EmbyTV.cs 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net.Http;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using System.Xml;
  15. using Emby.Server.Implementations.Library;
  16. using Jellyfin.Data.Enums;
  17. using Jellyfin.Data.Events;
  18. using Jellyfin.Extensions;
  19. using MediaBrowser.Common.Configuration;
  20. using MediaBrowser.Common.Extensions;
  21. using MediaBrowser.Common.Progress;
  22. using MediaBrowser.Controller;
  23. using MediaBrowser.Controller.Configuration;
  24. using MediaBrowser.Controller.Dto;
  25. using MediaBrowser.Controller.Entities;
  26. using MediaBrowser.Controller.Entities.TV;
  27. using MediaBrowser.Controller.Library;
  28. using MediaBrowser.Controller.LiveTv;
  29. using MediaBrowser.Controller.MediaEncoding;
  30. using MediaBrowser.Controller.Providers;
  31. using MediaBrowser.Model.Configuration;
  32. using MediaBrowser.Model.Dto;
  33. using MediaBrowser.Model.Entities;
  34. using MediaBrowser.Model.IO;
  35. using MediaBrowser.Model.LiveTv;
  36. using MediaBrowser.Model.MediaInfo;
  37. using MediaBrowser.Model.Providers;
  38. using Microsoft.Extensions.Logging;
  39. namespace Emby.Server.Implementations.LiveTv.EmbyTV
  40. {
  41. public sealed class EmbyTV : ILiveTvService, ISupportsDirectStreamProvider, ISupportsNewTimerIds, IDisposable
  42. {
  43. public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
  44. private const int TunerDiscoveryDurationMs = 3000;
  45. private readonly IServerApplicationHost _appHost;
  46. private readonly ILogger<EmbyTV> _logger;
  47. private readonly IHttpClientFactory _httpClientFactory;
  48. private readonly IServerConfigurationManager _config;
  49. private readonly ItemDataProvider<SeriesTimerInfo> _seriesTimerProvider;
  50. private readonly TimerManager _timerProvider;
  51. private readonly LiveTvManager _liveTvManager;
  52. private readonly IFileSystem _fileSystem;
  53. private readonly ILibraryMonitor _libraryMonitor;
  54. private readonly ILibraryManager _libraryManager;
  55. private readonly IProviderManager _providerManager;
  56. private readonly IMediaEncoder _mediaEncoder;
  57. private readonly IMediaSourceManager _mediaSourceManager;
  58. private readonly IStreamHelper _streamHelper;
  59. private readonly ConcurrentDictionary<string, ActiveRecordingInfo> _activeRecordings =
  60. new ConcurrentDictionary<string, ActiveRecordingInfo>(StringComparer.OrdinalIgnoreCase);
  61. private readonly ConcurrentDictionary<string, EpgChannelData> _epgChannels =
  62. new ConcurrentDictionary<string, EpgChannelData>(StringComparer.OrdinalIgnoreCase);
  63. private readonly SemaphoreSlim _recordingDeleteSemaphore = new SemaphoreSlim(1, 1);
  64. private bool _disposed;
  65. public EmbyTV(
  66. IServerApplicationHost appHost,
  67. IStreamHelper streamHelper,
  68. IMediaSourceManager mediaSourceManager,
  69. ILogger<EmbyTV> logger,
  70. IHttpClientFactory httpClientFactory,
  71. IServerConfigurationManager config,
  72. ILiveTvManager liveTvManager,
  73. IFileSystem fileSystem,
  74. ILibraryManager libraryManager,
  75. ILibraryMonitor libraryMonitor,
  76. IProviderManager providerManager,
  77. IMediaEncoder mediaEncoder)
  78. {
  79. Current = this;
  80. _appHost = appHost;
  81. _logger = logger;
  82. _httpClientFactory = httpClientFactory;
  83. _config = config;
  84. _fileSystem = fileSystem;
  85. _libraryManager = libraryManager;
  86. _libraryMonitor = libraryMonitor;
  87. _providerManager = providerManager;
  88. _mediaEncoder = mediaEncoder;
  89. _liveTvManager = (LiveTvManager)liveTvManager;
  90. _mediaSourceManager = mediaSourceManager;
  91. _streamHelper = streamHelper;
  92. _seriesTimerProvider = new SeriesTimerManager(_logger, Path.Combine(DataPath, "seriestimers.json"));
  93. _timerProvider = new TimerManager(_logger, Path.Combine(DataPath, "timers.json"));
  94. _timerProvider.TimerFired += OnTimerProviderTimerFired;
  95. _config.NamedConfigurationUpdated += OnNamedConfigurationUpdated;
  96. }
  97. public event EventHandler<GenericEventArgs<TimerInfo>> TimerCreated;
  98. public event EventHandler<GenericEventArgs<string>> TimerCancelled;
  99. public static EmbyTV Current { get; private set; }
  100. /// <inheritdoc />
  101. public string Name => "Emby";
  102. public string DataPath => Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv");
  103. /// <inheritdoc />
  104. public string HomePageUrl => "https://github.com/jellyfin/jellyfin";
  105. private string DefaultRecordingPath => Path.Combine(DataPath, "recordings");
  106. private string RecordingPath
  107. {
  108. get
  109. {
  110. var path = GetConfiguration().RecordingPath;
  111. return string.IsNullOrWhiteSpace(path)
  112. ? DefaultRecordingPath
  113. : path;
  114. }
  115. }
  116. private async void OnNamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
  117. {
  118. if (string.Equals(e.Key, "livetv", StringComparison.OrdinalIgnoreCase))
  119. {
  120. await CreateRecordingFolders().ConfigureAwait(false);
  121. }
  122. }
  123. public Task Start()
  124. {
  125. _timerProvider.RestartTimers();
  126. return CreateRecordingFolders();
  127. }
  128. internal async Task CreateRecordingFolders()
  129. {
  130. try
  131. {
  132. var recordingFolders = GetRecordingFolders().ToArray();
  133. var virtualFolders = _libraryManager.GetVirtualFolders();
  134. var allExistingPaths = virtualFolders.SelectMany(i => i.Locations).ToList();
  135. var pathsAdded = new List<string>();
  136. foreach (var recordingFolder in recordingFolders)
  137. {
  138. var pathsToCreate = recordingFolder.Locations
  139. .Where(i => !allExistingPaths.Any(p => _fileSystem.AreEqual(p, i)))
  140. .ToList();
  141. if (pathsToCreate.Count == 0)
  142. {
  143. continue;
  144. }
  145. var mediaPathInfos = pathsToCreate.Select(i => new MediaPathInfo(i)).ToArray();
  146. var libraryOptions = new LibraryOptions
  147. {
  148. PathInfos = mediaPathInfos
  149. };
  150. try
  151. {
  152. await _libraryManager.AddVirtualFolder(recordingFolder.Name, recordingFolder.CollectionType, libraryOptions, true).ConfigureAwait(false);
  153. }
  154. catch (Exception ex)
  155. {
  156. _logger.LogError(ex, "Error creating virtual folder");
  157. }
  158. pathsAdded.AddRange(pathsToCreate);
  159. }
  160. var config = GetConfiguration();
  161. var pathsToRemove = config.MediaLocationsCreated
  162. .Except(recordingFolders.SelectMany(i => i.Locations))
  163. .ToList();
  164. if (pathsAdded.Count > 0 || pathsToRemove.Count > 0)
  165. {
  166. pathsAdded.InsertRange(0, config.MediaLocationsCreated);
  167. config.MediaLocationsCreated = pathsAdded.Except(pathsToRemove).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
  168. _config.SaveConfiguration("livetv", config);
  169. }
  170. foreach (var path in pathsToRemove)
  171. {
  172. await RemovePathFromLibraryAsync(path).ConfigureAwait(false);
  173. }
  174. }
  175. catch (Exception ex)
  176. {
  177. _logger.LogError(ex, "Error creating recording folders");
  178. }
  179. }
  180. private async Task RemovePathFromLibraryAsync(string path)
  181. {
  182. _logger.LogDebug("Removing path from library: {0}", path);
  183. var requiresRefresh = false;
  184. var virtualFolders = _libraryManager.GetVirtualFolders();
  185. foreach (var virtualFolder in virtualFolders)
  186. {
  187. if (!virtualFolder.Locations.Contains(path, StringComparison.OrdinalIgnoreCase))
  188. {
  189. continue;
  190. }
  191. if (virtualFolder.Locations.Length == 1)
  192. {
  193. // remove entire virtual folder
  194. try
  195. {
  196. await _libraryManager.RemoveVirtualFolder(virtualFolder.Name, true).ConfigureAwait(false);
  197. }
  198. catch (Exception ex)
  199. {
  200. _logger.LogError(ex, "Error removing virtual folder");
  201. }
  202. }
  203. else
  204. {
  205. try
  206. {
  207. _libraryManager.RemoveMediaPath(virtualFolder.Name, path);
  208. requiresRefresh = true;
  209. }
  210. catch (Exception ex)
  211. {
  212. _logger.LogError(ex, "Error removing media path");
  213. }
  214. }
  215. }
  216. if (requiresRefresh)
  217. {
  218. await _libraryManager.ValidateMediaLibrary(new SimpleProgress<double>(), CancellationToken.None).ConfigureAwait(false);
  219. }
  220. }
  221. public async Task RefreshSeriesTimers(CancellationToken cancellationToken)
  222. {
  223. var seriesTimers = await GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  224. foreach (var timer in seriesTimers)
  225. {
  226. UpdateTimersForSeriesTimer(timer, false, true);
  227. }
  228. }
  229. public async Task RefreshTimers(CancellationToken cancellationToken)
  230. {
  231. var timers = await GetTimersAsync(cancellationToken).ConfigureAwait(false);
  232. var tempChannelCache = new Dictionary<Guid, LiveTvChannel>();
  233. foreach (var timer in timers)
  234. {
  235. if (DateTime.UtcNow > timer.EndDate && !_activeRecordings.ContainsKey(timer.Id))
  236. {
  237. OnTimerOutOfDate(timer);
  238. continue;
  239. }
  240. if (string.IsNullOrWhiteSpace(timer.ProgramId) || string.IsNullOrWhiteSpace(timer.ChannelId))
  241. {
  242. continue;
  243. }
  244. var program = GetProgramInfoFromCache(timer);
  245. if (program is null)
  246. {
  247. OnTimerOutOfDate(timer);
  248. continue;
  249. }
  250. CopyProgramInfoToTimerInfo(program, timer, tempChannelCache);
  251. _timerProvider.Update(timer);
  252. }
  253. }
  254. private void OnTimerOutOfDate(TimerInfo timer)
  255. {
  256. _timerProvider.Delete(timer);
  257. }
  258. private async Task<IEnumerable<ChannelInfo>> GetChannelsAsync(bool enableCache, CancellationToken cancellationToken)
  259. {
  260. var list = new List<ChannelInfo>();
  261. foreach (var hostInstance in _liveTvManager.TunerHosts)
  262. {
  263. try
  264. {
  265. var channels = await hostInstance.GetChannels(enableCache, cancellationToken).ConfigureAwait(false);
  266. list.AddRange(channels);
  267. }
  268. catch (Exception ex)
  269. {
  270. _logger.LogError(ex, "Error getting channels");
  271. }
  272. }
  273. foreach (var provider in GetListingProviders())
  274. {
  275. var enabledChannels = list
  276. .Where(i => IsListingProviderEnabledForTuner(provider.Item2, i.TunerHostId))
  277. .ToList();
  278. if (enabledChannels.Count > 0)
  279. {
  280. try
  281. {
  282. await AddMetadata(provider.Item1, provider.Item2, enabledChannels, enableCache, cancellationToken).ConfigureAwait(false);
  283. }
  284. catch (NotSupportedException)
  285. {
  286. }
  287. catch (Exception ex)
  288. {
  289. _logger.LogError(ex, "Error adding metadata");
  290. }
  291. }
  292. }
  293. return list;
  294. }
  295. private async Task AddMetadata(
  296. IListingsProvider provider,
  297. ListingsProviderInfo info,
  298. IEnumerable<ChannelInfo> tunerChannels,
  299. bool enableCache,
  300. CancellationToken cancellationToken)
  301. {
  302. var epgChannels = await GetEpgChannels(provider, info, enableCache, cancellationToken).ConfigureAwait(false);
  303. foreach (var tunerChannel in tunerChannels)
  304. {
  305. var epgChannel = GetEpgChannelFromTunerChannel(info, tunerChannel, epgChannels);
  306. if (epgChannel is not null)
  307. {
  308. if (!string.IsNullOrWhiteSpace(epgChannel.Name))
  309. {
  310. // tunerChannel.Name = epgChannel.Name;
  311. }
  312. if (!string.IsNullOrWhiteSpace(epgChannel.ImageUrl))
  313. {
  314. tunerChannel.ImageUrl = epgChannel.ImageUrl;
  315. }
  316. }
  317. }
  318. }
  319. private async Task<EpgChannelData> GetEpgChannels(
  320. IListingsProvider provider,
  321. ListingsProviderInfo info,
  322. bool enableCache,
  323. CancellationToken cancellationToken)
  324. {
  325. if (!enableCache || !_epgChannels.TryGetValue(info.Id, out var result))
  326. {
  327. var channels = await provider.GetChannels(info, cancellationToken).ConfigureAwait(false);
  328. foreach (var channel in channels)
  329. {
  330. _logger.LogInformation("Found epg channel in {0} {1} {2} {3}", provider.Name, info.ListingsId, channel.Name, channel.Id);
  331. }
  332. result = new EpgChannelData(channels);
  333. _epgChannels.AddOrUpdate(info.Id, result, (_, _) => result);
  334. }
  335. return result;
  336. }
  337. private async Task<ChannelInfo> GetEpgChannelFromTunerChannel(IListingsProvider provider, ListingsProviderInfo info, ChannelInfo tunerChannel, CancellationToken cancellationToken)
  338. {
  339. var epgChannels = await GetEpgChannels(provider, info, true, cancellationToken).ConfigureAwait(false);
  340. return GetEpgChannelFromTunerChannel(info, tunerChannel, epgChannels);
  341. }
  342. private static string GetMappedChannel(string channelId, NameValuePair[] mappings)
  343. {
  344. foreach (NameValuePair mapping in mappings)
  345. {
  346. if (string.Equals(mapping.Name, channelId, StringComparison.OrdinalIgnoreCase))
  347. {
  348. return mapping.Value;
  349. }
  350. }
  351. return channelId;
  352. }
  353. internal ChannelInfo GetEpgChannelFromTunerChannel(NameValuePair[] mappings, ChannelInfo tunerChannel, List<ChannelInfo> epgChannels)
  354. {
  355. return GetEpgChannelFromTunerChannel(mappings, tunerChannel, new EpgChannelData(epgChannels));
  356. }
  357. private ChannelInfo GetEpgChannelFromTunerChannel(ListingsProviderInfo info, ChannelInfo tunerChannel, EpgChannelData epgChannels)
  358. {
  359. return GetEpgChannelFromTunerChannel(info.ChannelMappings, tunerChannel, epgChannels);
  360. }
  361. private ChannelInfo GetEpgChannelFromTunerChannel(
  362. NameValuePair[] mappings,
  363. ChannelInfo tunerChannel,
  364. EpgChannelData epgChannelData)
  365. {
  366. if (!string.IsNullOrWhiteSpace(tunerChannel.Id))
  367. {
  368. var mappedTunerChannelId = GetMappedChannel(tunerChannel.Id, mappings);
  369. if (string.IsNullOrWhiteSpace(mappedTunerChannelId))
  370. {
  371. mappedTunerChannelId = tunerChannel.Id;
  372. }
  373. var channel = epgChannelData.GetChannelById(mappedTunerChannelId);
  374. if (channel is not null)
  375. {
  376. return channel;
  377. }
  378. }
  379. if (!string.IsNullOrWhiteSpace(tunerChannel.TunerChannelId))
  380. {
  381. var tunerChannelId = tunerChannel.TunerChannelId;
  382. if (tunerChannelId.Contains(".json.schedulesdirect.org", StringComparison.OrdinalIgnoreCase))
  383. {
  384. tunerChannelId = tunerChannelId.Replace(".json.schedulesdirect.org", string.Empty, StringComparison.OrdinalIgnoreCase).TrimStart('I');
  385. }
  386. var mappedTunerChannelId = GetMappedChannel(tunerChannelId, mappings);
  387. if (string.IsNullOrWhiteSpace(mappedTunerChannelId))
  388. {
  389. mappedTunerChannelId = tunerChannelId;
  390. }
  391. var channel = epgChannelData.GetChannelById(mappedTunerChannelId);
  392. if (channel is not null)
  393. {
  394. return channel;
  395. }
  396. }
  397. if (!string.IsNullOrWhiteSpace(tunerChannel.Number))
  398. {
  399. var tunerChannelNumber = GetMappedChannel(tunerChannel.Number, mappings);
  400. if (string.IsNullOrWhiteSpace(tunerChannelNumber))
  401. {
  402. tunerChannelNumber = tunerChannel.Number;
  403. }
  404. var channel = epgChannelData.GetChannelByNumber(tunerChannelNumber);
  405. if (channel is not null)
  406. {
  407. return channel;
  408. }
  409. }
  410. if (!string.IsNullOrWhiteSpace(tunerChannel.Name))
  411. {
  412. var normalizedName = EpgChannelData.NormalizeName(tunerChannel.Name);
  413. var channel = epgChannelData.GetChannelByName(normalizedName);
  414. if (channel is not null)
  415. {
  416. return channel;
  417. }
  418. }
  419. return null;
  420. }
  421. public async Task<List<ChannelInfo>> GetChannelsForListingsProvider(ListingsProviderInfo listingsProvider, CancellationToken cancellationToken)
  422. {
  423. var list = new List<ChannelInfo>();
  424. foreach (var hostInstance in _liveTvManager.TunerHosts)
  425. {
  426. try
  427. {
  428. var channels = await hostInstance.GetChannels(false, cancellationToken).ConfigureAwait(false);
  429. list.AddRange(channels);
  430. }
  431. catch (Exception ex)
  432. {
  433. _logger.LogError(ex, "Error getting channels");
  434. }
  435. }
  436. return list
  437. .Where(i => IsListingProviderEnabledForTuner(listingsProvider, i.TunerHostId))
  438. .ToList();
  439. }
  440. public Task<IEnumerable<ChannelInfo>> GetChannelsAsync(CancellationToken cancellationToken)
  441. {
  442. return GetChannelsAsync(false, cancellationToken);
  443. }
  444. public Task CancelSeriesTimerAsync(string timerId, CancellationToken cancellationToken)
  445. {
  446. var timers = _timerProvider
  447. .GetAll()
  448. .Where(i => string.Equals(i.SeriesTimerId, timerId, StringComparison.OrdinalIgnoreCase))
  449. .ToList();
  450. foreach (var timer in timers)
  451. {
  452. CancelTimerInternal(timer.Id, true, true);
  453. }
  454. var remove = _seriesTimerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
  455. if (remove is not null)
  456. {
  457. _seriesTimerProvider.Delete(remove);
  458. }
  459. return Task.CompletedTask;
  460. }
  461. private void CancelTimerInternal(string timerId, bool isSeriesCancelled, bool isManualCancellation)
  462. {
  463. var timer = _timerProvider.GetTimer(timerId);
  464. if (timer is not null)
  465. {
  466. var statusChanging = timer.Status != RecordingStatus.Cancelled;
  467. timer.Status = RecordingStatus.Cancelled;
  468. if (isManualCancellation)
  469. {
  470. timer.IsManual = true;
  471. }
  472. if (string.IsNullOrWhiteSpace(timer.SeriesTimerId) || isSeriesCancelled)
  473. {
  474. _timerProvider.Delete(timer);
  475. }
  476. else
  477. {
  478. _timerProvider.AddOrUpdate(timer, false);
  479. }
  480. if (statusChanging && TimerCancelled is not null)
  481. {
  482. TimerCancelled(this, new GenericEventArgs<string>(timerId));
  483. }
  484. }
  485. if (_activeRecordings.TryGetValue(timerId, out var activeRecordingInfo))
  486. {
  487. activeRecordingInfo.Timer = timer;
  488. activeRecordingInfo.CancellationTokenSource.Cancel();
  489. }
  490. }
  491. public Task CancelTimerAsync(string timerId, CancellationToken cancellationToken)
  492. {
  493. CancelTimerInternal(timerId, false, true);
  494. return Task.CompletedTask;
  495. }
  496. public Task CreateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  497. {
  498. throw new NotImplementedException();
  499. }
  500. public Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
  501. {
  502. throw new NotImplementedException();
  503. }
  504. public Task<string> CreateTimer(TimerInfo info, CancellationToken cancellationToken)
  505. {
  506. var existingTimer = string.IsNullOrWhiteSpace(info.ProgramId) ?
  507. null :
  508. _timerProvider.GetTimerByProgramId(info.ProgramId);
  509. if (existingTimer is not null)
  510. {
  511. if (existingTimer.Status == RecordingStatus.Cancelled
  512. || existingTimer.Status == RecordingStatus.Completed)
  513. {
  514. existingTimer.Status = RecordingStatus.New;
  515. existingTimer.IsManual = true;
  516. _timerProvider.Update(existingTimer);
  517. return Task.FromResult(existingTimer.Id);
  518. }
  519. throw new ArgumentException("A scheduled recording already exists for this program.");
  520. }
  521. info.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
  522. LiveTvProgram programInfo = null;
  523. if (!string.IsNullOrWhiteSpace(info.ProgramId))
  524. {
  525. programInfo = GetProgramInfoFromCache(info);
  526. }
  527. if (programInfo is null)
  528. {
  529. _logger.LogInformation("Unable to find program with Id {0}. Will search using start date", info.ProgramId);
  530. programInfo = GetProgramInfoFromCache(info.ChannelId, info.StartDate);
  531. }
  532. if (programInfo is not null)
  533. {
  534. CopyProgramInfoToTimerInfo(programInfo, info);
  535. }
  536. info.IsManual = true;
  537. _timerProvider.Add(info);
  538. TimerCreated?.Invoke(this, new GenericEventArgs<TimerInfo>(info));
  539. return Task.FromResult(info.Id);
  540. }
  541. public async Task<string> CreateSeriesTimer(SeriesTimerInfo info, CancellationToken cancellationToken)
  542. {
  543. info.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
  544. // populate info.seriesID
  545. var program = GetProgramInfoFromCache(info.ProgramId);
  546. if (program is not null)
  547. {
  548. info.SeriesId = program.ExternalSeriesId;
  549. }
  550. else
  551. {
  552. throw new InvalidOperationException("SeriesId for program not found");
  553. }
  554. // If any timers have already been manually created, make sure they don't get cancelled
  555. var existingTimers = (await GetTimersAsync(CancellationToken.None).ConfigureAwait(false))
  556. .Where(i =>
  557. {
  558. if (string.Equals(i.ProgramId, info.ProgramId, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(info.ProgramId))
  559. {
  560. return true;
  561. }
  562. if (string.Equals(i.SeriesId, info.SeriesId, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(info.SeriesId))
  563. {
  564. return true;
  565. }
  566. return false;
  567. })
  568. .ToList();
  569. _seriesTimerProvider.Add(info);
  570. foreach (var timer in existingTimers)
  571. {
  572. timer.SeriesTimerId = info.Id;
  573. timer.IsManual = true;
  574. _timerProvider.AddOrUpdate(timer, false);
  575. }
  576. UpdateTimersForSeriesTimer(info, true, false);
  577. return info.Id;
  578. }
  579. public Task UpdateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  580. {
  581. var instance = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  582. if (instance is not null)
  583. {
  584. instance.ChannelId = info.ChannelId;
  585. instance.Days = info.Days;
  586. instance.EndDate = info.EndDate;
  587. instance.IsPostPaddingRequired = info.IsPostPaddingRequired;
  588. instance.IsPrePaddingRequired = info.IsPrePaddingRequired;
  589. instance.PostPaddingSeconds = info.PostPaddingSeconds;
  590. instance.PrePaddingSeconds = info.PrePaddingSeconds;
  591. instance.Priority = info.Priority;
  592. instance.RecordAnyChannel = info.RecordAnyChannel;
  593. instance.RecordAnyTime = info.RecordAnyTime;
  594. instance.RecordNewOnly = info.RecordNewOnly;
  595. instance.SkipEpisodesInLibrary = info.SkipEpisodesInLibrary;
  596. instance.KeepUpTo = info.KeepUpTo;
  597. instance.KeepUntil = info.KeepUntil;
  598. instance.StartDate = info.StartDate;
  599. _seriesTimerProvider.Update(instance);
  600. UpdateTimersForSeriesTimer(instance, true, true);
  601. }
  602. return Task.CompletedTask;
  603. }
  604. public Task UpdateTimerAsync(TimerInfo updatedTimer, CancellationToken cancellationToken)
  605. {
  606. var existingTimer = _timerProvider.GetTimer(updatedTimer.Id);
  607. if (existingTimer is null)
  608. {
  609. throw new ResourceNotFoundException();
  610. }
  611. // Only update if not currently active
  612. if (!_activeRecordings.TryGetValue(updatedTimer.Id, out _))
  613. {
  614. existingTimer.PrePaddingSeconds = updatedTimer.PrePaddingSeconds;
  615. existingTimer.PostPaddingSeconds = updatedTimer.PostPaddingSeconds;
  616. existingTimer.IsPostPaddingRequired = updatedTimer.IsPostPaddingRequired;
  617. existingTimer.IsPrePaddingRequired = updatedTimer.IsPrePaddingRequired;
  618. _timerProvider.Update(existingTimer);
  619. }
  620. return Task.CompletedTask;
  621. }
  622. private static void UpdateExistingTimerWithNewMetadata(TimerInfo existingTimer, TimerInfo updatedTimer)
  623. {
  624. // Update the program info but retain the status
  625. existingTimer.ChannelId = updatedTimer.ChannelId;
  626. existingTimer.CommunityRating = updatedTimer.CommunityRating;
  627. existingTimer.EndDate = updatedTimer.EndDate;
  628. existingTimer.EpisodeNumber = updatedTimer.EpisodeNumber;
  629. existingTimer.EpisodeTitle = updatedTimer.EpisodeTitle;
  630. existingTimer.Genres = updatedTimer.Genres;
  631. existingTimer.IsMovie = updatedTimer.IsMovie;
  632. existingTimer.IsSeries = updatedTimer.IsSeries;
  633. existingTimer.Tags = updatedTimer.Tags;
  634. existingTimer.IsProgramSeries = updatedTimer.IsProgramSeries;
  635. existingTimer.IsRepeat = updatedTimer.IsRepeat;
  636. existingTimer.Name = updatedTimer.Name;
  637. existingTimer.OfficialRating = updatedTimer.OfficialRating;
  638. existingTimer.OriginalAirDate = updatedTimer.OriginalAirDate;
  639. existingTimer.Overview = updatedTimer.Overview;
  640. existingTimer.ProductionYear = updatedTimer.ProductionYear;
  641. existingTimer.ProgramId = updatedTimer.ProgramId;
  642. existingTimer.SeasonNumber = updatedTimer.SeasonNumber;
  643. existingTimer.StartDate = updatedTimer.StartDate;
  644. existingTimer.ShowId = updatedTimer.ShowId;
  645. existingTimer.ProviderIds = updatedTimer.ProviderIds;
  646. existingTimer.SeriesProviderIds = updatedTimer.SeriesProviderIds;
  647. }
  648. public string GetActiveRecordingPath(string id)
  649. {
  650. if (_activeRecordings.TryGetValue(id, out var info))
  651. {
  652. return info.Path;
  653. }
  654. return null;
  655. }
  656. public ActiveRecordingInfo GetActiveRecordingInfo(string path)
  657. {
  658. if (string.IsNullOrWhiteSpace(path) || _activeRecordings.IsEmpty)
  659. {
  660. return null;
  661. }
  662. foreach (var (_, recordingInfo) in _activeRecordings)
  663. {
  664. if (string.Equals(recordingInfo.Path, path, StringComparison.Ordinal) && !recordingInfo.CancellationTokenSource.IsCancellationRequested)
  665. {
  666. var timer = recordingInfo.Timer;
  667. if (timer.Status != RecordingStatus.InProgress)
  668. {
  669. return null;
  670. }
  671. return recordingInfo;
  672. }
  673. }
  674. return null;
  675. }
  676. public Task<IEnumerable<TimerInfo>> GetTimersAsync(CancellationToken cancellationToken)
  677. {
  678. var excludeStatues = new List<RecordingStatus>
  679. {
  680. RecordingStatus.Completed
  681. };
  682. var timers = _timerProvider.GetAll()
  683. .Where(i => !excludeStatues.Contains(i.Status));
  684. return Task.FromResult(timers);
  685. }
  686. public Task<SeriesTimerInfo> GetNewTimerDefaultsAsync(CancellationToken cancellationToken, ProgramInfo program = null)
  687. {
  688. var config = GetConfiguration();
  689. var defaults = new SeriesTimerInfo()
  690. {
  691. PostPaddingSeconds = Math.Max(config.PostPaddingSeconds, 0),
  692. PrePaddingSeconds = Math.Max(config.PrePaddingSeconds, 0),
  693. RecordAnyChannel = false,
  694. RecordAnyTime = true,
  695. RecordNewOnly = true,
  696. Days = new List<DayOfWeek>
  697. {
  698. DayOfWeek.Sunday,
  699. DayOfWeek.Monday,
  700. DayOfWeek.Tuesday,
  701. DayOfWeek.Wednesday,
  702. DayOfWeek.Thursday,
  703. DayOfWeek.Friday,
  704. DayOfWeek.Saturday
  705. }
  706. };
  707. if (program is not null)
  708. {
  709. defaults.SeriesId = program.SeriesId;
  710. defaults.ProgramId = program.Id;
  711. defaults.RecordNewOnly = !program.IsRepeat;
  712. defaults.Name = program.Name;
  713. }
  714. defaults.SkipEpisodesInLibrary = defaults.RecordNewOnly;
  715. defaults.KeepUntil = KeepUntil.UntilDeleted;
  716. return Task.FromResult(defaults);
  717. }
  718. public Task<IEnumerable<SeriesTimerInfo>> GetSeriesTimersAsync(CancellationToken cancellationToken)
  719. {
  720. return Task.FromResult((IEnumerable<SeriesTimerInfo>)_seriesTimerProvider.GetAll());
  721. }
  722. private bool IsListingProviderEnabledForTuner(ListingsProviderInfo info, string tunerHostId)
  723. {
  724. if (info.EnableAllTuners)
  725. {
  726. return true;
  727. }
  728. if (string.IsNullOrWhiteSpace(tunerHostId))
  729. {
  730. throw new ArgumentNullException(nameof(tunerHostId));
  731. }
  732. return info.EnabledTuners.Contains(tunerHostId, StringComparison.OrdinalIgnoreCase);
  733. }
  734. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  735. {
  736. var channels = await GetChannelsAsync(true, cancellationToken).ConfigureAwait(false);
  737. var channel = channels.First(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  738. foreach (var provider in GetListingProviders())
  739. {
  740. if (!IsListingProviderEnabledForTuner(provider.Item2, channel.TunerHostId))
  741. {
  742. _logger.LogDebug("Skipping getting programs for channel {0}-{1} from {2}-{3}, because it's not enabled for this tuner.", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
  743. continue;
  744. }
  745. _logger.LogDebug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
  746. var epgChannel = await GetEpgChannelFromTunerChannel(provider.Item1, provider.Item2, channel, cancellationToken).ConfigureAwait(false);
  747. if (epgChannel is null)
  748. {
  749. _logger.LogDebug("EPG channel not found for tuner channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
  750. continue;
  751. }
  752. List<ProgramInfo> programs = (await provider.Item1.GetProgramsAsync(provider.Item2, epgChannel.Id, startDateUtc, endDateUtc, cancellationToken)
  753. .ConfigureAwait(false)).ToList();
  754. // Replace the value that came from the provider with a normalized value
  755. foreach (var program in programs)
  756. {
  757. program.ChannelId = channelId;
  758. program.Id += "_" + channelId;
  759. }
  760. if (programs.Count > 0)
  761. {
  762. return programs;
  763. }
  764. }
  765. return Enumerable.Empty<ProgramInfo>();
  766. }
  767. private List<Tuple<IListingsProvider, ListingsProviderInfo>> GetListingProviders()
  768. {
  769. return GetConfiguration().ListingProviders
  770. .Select(i =>
  771. {
  772. var provider = _liveTvManager.ListingProviders.FirstOrDefault(l => string.Equals(l.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  773. return provider is null ? null : new Tuple<IListingsProvider, ListingsProviderInfo>(provider, i);
  774. })
  775. .Where(i => i is not null)
  776. .ToList();
  777. }
  778. public Task<MediaSourceInfo> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
  779. {
  780. throw new NotImplementedException();
  781. }
  782. public async Task<ILiveStream> GetChannelStreamWithDirectStreamProvider(string channelId, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
  783. {
  784. _logger.LogInformation("Streaming Channel {Id}", channelId);
  785. var result = string.IsNullOrEmpty(streamId) ?
  786. null :
  787. currentLiveStreams.FirstOrDefault(i => string.Equals(i.OriginalStreamId, streamId, StringComparison.OrdinalIgnoreCase));
  788. if (result is not null && result.EnableStreamSharing)
  789. {
  790. result.ConsumerCount++;
  791. _logger.LogInformation("Live stream {0} consumer count is now {1}", streamId, result.ConsumerCount);
  792. return result;
  793. }
  794. foreach (var hostInstance in _liveTvManager.TunerHosts)
  795. {
  796. try
  797. {
  798. result = await hostInstance.GetChannelStream(channelId, streamId, currentLiveStreams, cancellationToken).ConfigureAwait(false);
  799. var openedMediaSource = result.MediaSource;
  800. result.OriginalStreamId = streamId;
  801. _logger.LogInformation("Returning mediasource streamId {0}, mediaSource.Id {1}, mediaSource.LiveStreamId {2}", streamId, openedMediaSource.Id, openedMediaSource.LiveStreamId);
  802. return result;
  803. }
  804. catch (FileNotFoundException)
  805. {
  806. }
  807. catch (OperationCanceledException)
  808. {
  809. }
  810. }
  811. throw new ResourceNotFoundException("Tuner not found.");
  812. }
  813. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  814. {
  815. if (string.IsNullOrWhiteSpace(channelId))
  816. {
  817. throw new ArgumentNullException(nameof(channelId));
  818. }
  819. foreach (var hostInstance in _liveTvManager.TunerHosts)
  820. {
  821. try
  822. {
  823. var sources = await hostInstance.GetChannelStreamMediaSources(channelId, cancellationToken).ConfigureAwait(false);
  824. if (sources.Count > 0)
  825. {
  826. return sources;
  827. }
  828. }
  829. catch (NotImplementedException)
  830. {
  831. }
  832. }
  833. throw new NotImplementedException();
  834. }
  835. public async Task<List<MediaSourceInfo>> GetRecordingStreamMediaSources(ActiveRecordingInfo info, CancellationToken cancellationToken)
  836. {
  837. var stream = new MediaSourceInfo
  838. {
  839. EncoderPath = _appHost.GetApiUrlForLocalAccess() + "/LiveTv/LiveRecordings/" + info.Id + "/stream",
  840. EncoderProtocol = MediaProtocol.Http,
  841. Path = info.Path,
  842. Protocol = MediaProtocol.File,
  843. Id = info.Id,
  844. SupportsDirectPlay = false,
  845. SupportsDirectStream = true,
  846. SupportsTranscoding = true,
  847. IsInfiniteStream = true,
  848. RequiresOpening = false,
  849. RequiresClosing = false,
  850. BufferMs = 0,
  851. IgnoreDts = true,
  852. IgnoreIndex = true
  853. };
  854. await new LiveStreamHelper(_mediaEncoder, _logger, _config.CommonApplicationPaths)
  855. .AddMediaInfoWithProbe(stream, false, false, cancellationToken).ConfigureAwait(false);
  856. return new List<MediaSourceInfo>
  857. {
  858. stream
  859. };
  860. }
  861. public Task CloseLiveStream(string id, CancellationToken cancellationToken)
  862. {
  863. return Task.CompletedTask;
  864. }
  865. public Task RecordLiveStream(string id, CancellationToken cancellationToken)
  866. {
  867. return Task.CompletedTask;
  868. }
  869. public Task ResetTuner(string id, CancellationToken cancellationToken)
  870. {
  871. return Task.CompletedTask;
  872. }
  873. private async void OnTimerProviderTimerFired(object sender, GenericEventArgs<TimerInfo> e)
  874. {
  875. var timer = e.Argument;
  876. _logger.LogInformation("Recording timer fired for {0}.", timer.Name);
  877. try
  878. {
  879. var recordingEndDate = timer.EndDate.AddSeconds(timer.PostPaddingSeconds);
  880. if (recordingEndDate <= DateTime.UtcNow)
  881. {
  882. _logger.LogWarning("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
  883. OnTimerOutOfDate(timer);
  884. return;
  885. }
  886. var activeRecordingInfo = new ActiveRecordingInfo
  887. {
  888. CancellationTokenSource = new CancellationTokenSource(),
  889. Timer = timer,
  890. Id = timer.Id
  891. };
  892. if (!_activeRecordings.ContainsKey(timer.Id))
  893. {
  894. await RecordStream(timer, recordingEndDate, activeRecordingInfo).ConfigureAwait(false);
  895. }
  896. else
  897. {
  898. _logger.LogInformation("Skipping RecordStream because it's already in progress.");
  899. }
  900. }
  901. catch (OperationCanceledException)
  902. {
  903. }
  904. catch (Exception ex)
  905. {
  906. _logger.LogError(ex, "Error recording stream");
  907. }
  908. }
  909. private string GetRecordingPath(TimerInfo timer, RemoteSearchResult metadata, out string seriesPath)
  910. {
  911. var recordPath = RecordingPath;
  912. var config = GetConfiguration();
  913. seriesPath = null;
  914. if (timer.IsProgramSeries)
  915. {
  916. var customRecordingPath = config.SeriesRecordingPath;
  917. var allowSubfolder = true;
  918. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  919. {
  920. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  921. recordPath = customRecordingPath;
  922. }
  923. if (allowSubfolder && config.EnableRecordingSubfolders)
  924. {
  925. recordPath = Path.Combine(recordPath, "Series");
  926. }
  927. // trim trailing period from the folder name
  928. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim().TrimEnd('.').Trim();
  929. if (metadata is not null && metadata.ProductionYear.HasValue)
  930. {
  931. folderName += " (" + metadata.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  932. }
  933. // Can't use the year here in the folder name because it is the year of the episode, not the series.
  934. recordPath = Path.Combine(recordPath, folderName);
  935. seriesPath = recordPath;
  936. if (timer.SeasonNumber.HasValue)
  937. {
  938. folderName = string.Format(
  939. CultureInfo.InvariantCulture,
  940. "Season {0}",
  941. timer.SeasonNumber.Value);
  942. recordPath = Path.Combine(recordPath, folderName);
  943. }
  944. }
  945. else if (timer.IsMovie)
  946. {
  947. var customRecordingPath = config.MovieRecordingPath;
  948. var allowSubfolder = true;
  949. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  950. {
  951. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  952. recordPath = customRecordingPath;
  953. }
  954. if (allowSubfolder && config.EnableRecordingSubfolders)
  955. {
  956. recordPath = Path.Combine(recordPath, "Movies");
  957. }
  958. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  959. if (timer.ProductionYear.HasValue)
  960. {
  961. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  962. }
  963. // trim trailing period from the folder name
  964. folderName = folderName.TrimEnd('.').Trim();
  965. recordPath = Path.Combine(recordPath, folderName);
  966. }
  967. else if (timer.IsKids)
  968. {
  969. if (config.EnableRecordingSubfolders)
  970. {
  971. recordPath = Path.Combine(recordPath, "Kids");
  972. }
  973. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  974. if (timer.ProductionYear.HasValue)
  975. {
  976. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  977. }
  978. // trim trailing period from the folder name
  979. folderName = folderName.TrimEnd('.').Trim();
  980. recordPath = Path.Combine(recordPath, folderName);
  981. }
  982. else if (timer.IsSports)
  983. {
  984. if (config.EnableRecordingSubfolders)
  985. {
  986. recordPath = Path.Combine(recordPath, "Sports");
  987. }
  988. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  989. }
  990. else
  991. {
  992. if (config.EnableRecordingSubfolders)
  993. {
  994. recordPath = Path.Combine(recordPath, "Other");
  995. }
  996. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  997. }
  998. var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer)).Trim() + ".ts";
  999. return Path.Combine(recordPath, recordingFileName);
  1000. }
  1001. private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate, ActiveRecordingInfo activeRecordingInfo)
  1002. {
  1003. ArgumentNullException.ThrowIfNull(timer);
  1004. LiveTvProgram programInfo = null;
  1005. if (!string.IsNullOrWhiteSpace(timer.ProgramId))
  1006. {
  1007. programInfo = GetProgramInfoFromCache(timer);
  1008. }
  1009. if (programInfo is null)
  1010. {
  1011. _logger.LogInformation("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  1012. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  1013. }
  1014. if (programInfo is not null)
  1015. {
  1016. CopyProgramInfoToTimerInfo(programInfo, timer);
  1017. }
  1018. var remoteMetadata = await FetchInternetMetadata(timer, CancellationToken.None).ConfigureAwait(false);
  1019. var recordPath = GetRecordingPath(timer, remoteMetadata, out string seriesPath);
  1020. var channelItem = _liveTvManager.GetLiveTvChannel(timer, this);
  1021. string liveStreamId = null;
  1022. RecordingStatus recordingStatus;
  1023. try
  1024. {
  1025. var allMediaSources = await _mediaSourceManager.GetPlaybackMediaSources(channelItem, null, true, false, CancellationToken.None).ConfigureAwait(false);
  1026. var mediaStreamInfo = allMediaSources[0];
  1027. IDirectStreamProvider directStreamProvider = null;
  1028. if (mediaStreamInfo.RequiresOpening)
  1029. {
  1030. var liveStreamResponse = await _mediaSourceManager.OpenLiveStreamInternal(
  1031. new LiveStreamRequest
  1032. {
  1033. ItemId = channelItem.Id,
  1034. OpenToken = mediaStreamInfo.OpenToken
  1035. },
  1036. CancellationToken.None).ConfigureAwait(false);
  1037. mediaStreamInfo = liveStreamResponse.Item1.MediaSource;
  1038. liveStreamId = mediaStreamInfo.LiveStreamId;
  1039. directStreamProvider = liveStreamResponse.Item2;
  1040. }
  1041. using var recorder = GetRecorder(mediaStreamInfo);
  1042. recordPath = recorder.GetOutputPath(mediaStreamInfo, recordPath);
  1043. recordPath = EnsureFileUnique(recordPath, timer.Id);
  1044. _libraryMonitor.ReportFileSystemChangeBeginning(recordPath);
  1045. var duration = recordingEndDate - DateTime.UtcNow;
  1046. _logger.LogInformation("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
  1047. _logger.LogInformation("Writing file to: {Path}", recordPath);
  1048. Action onStarted = async () =>
  1049. {
  1050. activeRecordingInfo.Path = recordPath;
  1051. _activeRecordings.TryAdd(timer.Id, activeRecordingInfo);
  1052. timer.Status = RecordingStatus.InProgress;
  1053. _timerProvider.AddOrUpdate(timer, false);
  1054. await SaveRecordingMetadata(timer, recordPath, seriesPath).ConfigureAwait(false);
  1055. await CreateRecordingFolders().ConfigureAwait(false);
  1056. TriggerRefresh(recordPath);
  1057. await EnforceKeepUpTo(timer, seriesPath).ConfigureAwait(false);
  1058. };
  1059. await recorder.Record(directStreamProvider, mediaStreamInfo, recordPath, duration, onStarted, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false);
  1060. recordingStatus = RecordingStatus.Completed;
  1061. _logger.LogInformation("Recording completed: {RecordPath}", recordPath);
  1062. }
  1063. catch (OperationCanceledException)
  1064. {
  1065. _logger.LogInformation("Recording stopped: {RecordPath}", recordPath);
  1066. recordingStatus = RecordingStatus.Completed;
  1067. }
  1068. catch (Exception ex)
  1069. {
  1070. _logger.LogError(ex, "Error recording to {RecordPath}", recordPath);
  1071. recordingStatus = RecordingStatus.Error;
  1072. }
  1073. if (!string.IsNullOrWhiteSpace(liveStreamId))
  1074. {
  1075. try
  1076. {
  1077. await _mediaSourceManager.CloseLiveStream(liveStreamId).ConfigureAwait(false);
  1078. }
  1079. catch (Exception ex)
  1080. {
  1081. _logger.LogError(ex, "Error closing live stream");
  1082. }
  1083. }
  1084. DeleteFileIfEmpty(recordPath);
  1085. TriggerRefresh(recordPath);
  1086. _libraryMonitor.ReportFileSystemChangeComplete(recordPath, false);
  1087. _activeRecordings.TryRemove(timer.Id, out _);
  1088. if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate && timer.RetryCount < 10)
  1089. {
  1090. const int RetryIntervalSeconds = 60;
  1091. _logger.LogInformation("Retrying recording in {0} seconds.", RetryIntervalSeconds);
  1092. timer.Status = RecordingStatus.New;
  1093. timer.PrePaddingSeconds = 0;
  1094. timer.StartDate = DateTime.UtcNow.AddSeconds(RetryIntervalSeconds);
  1095. timer.RetryCount++;
  1096. _timerProvider.AddOrUpdate(timer);
  1097. }
  1098. else if (File.Exists(recordPath))
  1099. {
  1100. timer.RecordingPath = recordPath;
  1101. timer.Status = RecordingStatus.Completed;
  1102. _timerProvider.AddOrUpdate(timer, false);
  1103. OnSuccessfulRecording(timer, recordPath);
  1104. }
  1105. else
  1106. {
  1107. _timerProvider.Delete(timer);
  1108. }
  1109. }
  1110. private async Task<RemoteSearchResult> FetchInternetMetadata(TimerInfo timer, CancellationToken cancellationToken)
  1111. {
  1112. if (timer.IsSeries)
  1113. {
  1114. if (timer.SeriesProviderIds.Count == 0)
  1115. {
  1116. return null;
  1117. }
  1118. var query = new RemoteSearchQuery<SeriesInfo>()
  1119. {
  1120. SearchInfo = new SeriesInfo
  1121. {
  1122. ProviderIds = timer.SeriesProviderIds,
  1123. Name = timer.Name,
  1124. MetadataCountryCode = _config.Configuration.MetadataCountryCode,
  1125. MetadataLanguage = _config.Configuration.PreferredMetadataLanguage
  1126. }
  1127. };
  1128. var results = await _providerManager.GetRemoteSearchResults<Series, SeriesInfo>(query, cancellationToken).ConfigureAwait(false);
  1129. return results.FirstOrDefault();
  1130. }
  1131. return null;
  1132. }
  1133. private void DeleteFileIfEmpty(string path)
  1134. {
  1135. var file = _fileSystem.GetFileInfo(path);
  1136. if (file.Exists && file.Length == 0)
  1137. {
  1138. try
  1139. {
  1140. _fileSystem.DeleteFile(path);
  1141. }
  1142. catch (Exception ex)
  1143. {
  1144. _logger.LogError(ex, "Error deleting 0-byte failed recording file {Path}", path);
  1145. }
  1146. }
  1147. }
  1148. private void TriggerRefresh(string path)
  1149. {
  1150. _logger.LogInformation("Triggering refresh on {Path}", path);
  1151. var item = GetAffectedBaseItem(Path.GetDirectoryName(path));
  1152. if (item is not null)
  1153. {
  1154. _logger.LogInformation("Refreshing recording parent {Path}", item.Path);
  1155. _providerManager.QueueRefresh(
  1156. item.Id,
  1157. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  1158. {
  1159. RefreshPaths = new string[]
  1160. {
  1161. path,
  1162. Path.GetDirectoryName(path),
  1163. Path.GetDirectoryName(Path.GetDirectoryName(path))
  1164. }
  1165. },
  1166. RefreshPriority.High);
  1167. }
  1168. }
  1169. private BaseItem GetAffectedBaseItem(string path)
  1170. {
  1171. BaseItem item = null;
  1172. var parentPath = Path.GetDirectoryName(path);
  1173. while (item is null && !string.IsNullOrEmpty(path))
  1174. {
  1175. item = _libraryManager.FindByPath(path, null);
  1176. path = Path.GetDirectoryName(path);
  1177. }
  1178. if (item is not null)
  1179. {
  1180. if (item.GetType() == typeof(Folder) && string.Equals(item.Path, parentPath, StringComparison.OrdinalIgnoreCase))
  1181. {
  1182. var parentItem = item.GetParent();
  1183. if (parentItem is not null && parentItem is not AggregateFolder)
  1184. {
  1185. item = parentItem;
  1186. }
  1187. }
  1188. }
  1189. return item;
  1190. }
  1191. private async Task EnforceKeepUpTo(TimerInfo timer, string seriesPath)
  1192. {
  1193. if (string.IsNullOrWhiteSpace(timer.SeriesTimerId))
  1194. {
  1195. return;
  1196. }
  1197. if (string.IsNullOrWhiteSpace(seriesPath))
  1198. {
  1199. return;
  1200. }
  1201. var seriesTimerId = timer.SeriesTimerId;
  1202. var seriesTimer = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, seriesTimerId, StringComparison.OrdinalIgnoreCase));
  1203. if (seriesTimer is null || seriesTimer.KeepUpTo <= 0)
  1204. {
  1205. return;
  1206. }
  1207. if (_disposed)
  1208. {
  1209. return;
  1210. }
  1211. await _recordingDeleteSemaphore.WaitAsync().ConfigureAwait(false);
  1212. try
  1213. {
  1214. if (_disposed)
  1215. {
  1216. return;
  1217. }
  1218. var timersToDelete = _timerProvider.GetAll()
  1219. .Where(i => i.Status == RecordingStatus.Completed && !string.IsNullOrWhiteSpace(i.RecordingPath))
  1220. .Where(i => string.Equals(i.SeriesTimerId, seriesTimerId, StringComparison.OrdinalIgnoreCase))
  1221. .OrderByDescending(i => i.EndDate)
  1222. .Where(i => File.Exists(i.RecordingPath))
  1223. .Skip(seriesTimer.KeepUpTo - 1)
  1224. .ToList();
  1225. DeleteLibraryItemsForTimers(timersToDelete);
  1226. if (_libraryManager.FindByPath(seriesPath, true) is not Folder librarySeries)
  1227. {
  1228. return;
  1229. }
  1230. var episodesToDelete = librarySeries.GetItemList(
  1231. new InternalItemsQuery
  1232. {
  1233. OrderBy = new[] { (ItemSortBy.DateCreated, SortOrder.Descending) },
  1234. IsVirtualItem = false,
  1235. IsFolder = false,
  1236. Recursive = true,
  1237. DtoOptions = new DtoOptions(true)
  1238. })
  1239. .Where(i => i.IsFileProtocol && File.Exists(i.Path))
  1240. .Skip(seriesTimer.KeepUpTo - 1)
  1241. .ToList();
  1242. foreach (var item in episodesToDelete)
  1243. {
  1244. try
  1245. {
  1246. _libraryManager.DeleteItem(
  1247. item,
  1248. new DeleteOptions
  1249. {
  1250. DeleteFileLocation = true
  1251. },
  1252. true);
  1253. }
  1254. catch (Exception ex)
  1255. {
  1256. _logger.LogError(ex, "Error deleting item");
  1257. }
  1258. }
  1259. }
  1260. finally
  1261. {
  1262. _recordingDeleteSemaphore.Release();
  1263. }
  1264. }
  1265. private void DeleteLibraryItemsForTimers(List<TimerInfo> timers)
  1266. {
  1267. foreach (var timer in timers)
  1268. {
  1269. if (_disposed)
  1270. {
  1271. return;
  1272. }
  1273. try
  1274. {
  1275. DeleteLibraryItemForTimer(timer);
  1276. }
  1277. catch (Exception ex)
  1278. {
  1279. _logger.LogError(ex, "Error deleting recording");
  1280. }
  1281. }
  1282. }
  1283. private void DeleteLibraryItemForTimer(TimerInfo timer)
  1284. {
  1285. var libraryItem = _libraryManager.FindByPath(timer.RecordingPath, false);
  1286. if (libraryItem is not null)
  1287. {
  1288. _libraryManager.DeleteItem(
  1289. libraryItem,
  1290. new DeleteOptions
  1291. {
  1292. DeleteFileLocation = true
  1293. },
  1294. true);
  1295. }
  1296. else if (File.Exists(timer.RecordingPath))
  1297. {
  1298. _fileSystem.DeleteFile(timer.RecordingPath);
  1299. }
  1300. _timerProvider.Delete(timer);
  1301. }
  1302. private string EnsureFileUnique(string path, string timerId)
  1303. {
  1304. var originalPath = path;
  1305. var index = 1;
  1306. while (FileExists(path, timerId))
  1307. {
  1308. var parent = Path.GetDirectoryName(originalPath);
  1309. var name = Path.GetFileNameWithoutExtension(originalPath);
  1310. name += " - " + index.ToString(CultureInfo.InvariantCulture);
  1311. path = Path.ChangeExtension(Path.Combine(parent, name), Path.GetExtension(originalPath));
  1312. index++;
  1313. }
  1314. return path;
  1315. }
  1316. private bool FileExists(string path, string timerId)
  1317. {
  1318. if (File.Exists(path))
  1319. {
  1320. return true;
  1321. }
  1322. return _activeRecordings
  1323. .Any(i => string.Equals(i.Value.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.Value.Timer.Id, timerId, StringComparison.OrdinalIgnoreCase));
  1324. }
  1325. private IRecorder GetRecorder(MediaSourceInfo mediaSource)
  1326. {
  1327. if (mediaSource.RequiresLooping || !(mediaSource.Container ?? string.Empty).EndsWith("ts", StringComparison.OrdinalIgnoreCase) || (mediaSource.Protocol != MediaProtocol.File && mediaSource.Protocol != MediaProtocol.Http))
  1328. {
  1329. return new EncodedRecorder(_logger, _mediaEncoder, _config.ApplicationPaths, _config);
  1330. }
  1331. return new DirectRecorder(_logger, _httpClientFactory, _streamHelper);
  1332. }
  1333. private void OnSuccessfulRecording(TimerInfo timer, string path)
  1334. {
  1335. PostProcessRecording(timer, path);
  1336. }
  1337. private void PostProcessRecording(TimerInfo timer, string path)
  1338. {
  1339. var options = GetConfiguration();
  1340. if (string.IsNullOrWhiteSpace(options.RecordingPostProcessor))
  1341. {
  1342. return;
  1343. }
  1344. try
  1345. {
  1346. var process = new Process
  1347. {
  1348. StartInfo = new ProcessStartInfo
  1349. {
  1350. Arguments = GetPostProcessArguments(path, options.RecordingPostProcessorArguments),
  1351. CreateNoWindow = true,
  1352. ErrorDialog = false,
  1353. FileName = options.RecordingPostProcessor,
  1354. WindowStyle = ProcessWindowStyle.Hidden,
  1355. UseShellExecute = false
  1356. },
  1357. EnableRaisingEvents = true
  1358. };
  1359. _logger.LogInformation("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  1360. process.Exited += OnProcessExited;
  1361. process.Start();
  1362. }
  1363. catch (Exception ex)
  1364. {
  1365. _logger.LogError(ex, "Error running recording post processor");
  1366. }
  1367. }
  1368. private static string GetPostProcessArguments(string path, string arguments)
  1369. {
  1370. return arguments.Replace("{path}", path, StringComparison.OrdinalIgnoreCase);
  1371. }
  1372. private void OnProcessExited(object sender, EventArgs e)
  1373. {
  1374. using (var process = (Process)sender)
  1375. {
  1376. _logger.LogInformation("Recording post-processing script completed with exit code {ExitCode}", process.ExitCode);
  1377. }
  1378. }
  1379. private async Task SaveRecordingImage(string recordingPath, LiveTvProgram program, ItemImageInfo image)
  1380. {
  1381. if (!image.IsLocalFile)
  1382. {
  1383. image = await _libraryManager.ConvertImageToLocal(program, image, 0).ConfigureAwait(false);
  1384. }
  1385. string imageSaveFilenameWithoutExtension = image.Type switch
  1386. {
  1387. ImageType.Primary => program.IsSeries ? Path.GetFileNameWithoutExtension(recordingPath) + "-thumb" : "poster",
  1388. ImageType.Logo => "logo",
  1389. ImageType.Thumb => program.IsSeries ? Path.GetFileNameWithoutExtension(recordingPath) + "-thumb" : "landscape",
  1390. ImageType.Backdrop => "fanart",
  1391. _ => null
  1392. };
  1393. if (imageSaveFilenameWithoutExtension is null)
  1394. {
  1395. return;
  1396. }
  1397. var imageSavePath = Path.Combine(Path.GetDirectoryName(recordingPath), imageSaveFilenameWithoutExtension);
  1398. // preserve original image extension
  1399. imageSavePath = Path.ChangeExtension(imageSavePath, Path.GetExtension(image.Path));
  1400. File.Copy(image.Path, imageSavePath, true);
  1401. }
  1402. private async Task SaveRecordingImages(string recordingPath, LiveTvProgram program)
  1403. {
  1404. var image = program.IsSeries ?
  1405. (program.GetImageInfo(ImageType.Thumb, 0) ?? program.GetImageInfo(ImageType.Primary, 0)) :
  1406. (program.GetImageInfo(ImageType.Primary, 0) ?? program.GetImageInfo(ImageType.Thumb, 0));
  1407. if (image is not null)
  1408. {
  1409. try
  1410. {
  1411. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1412. }
  1413. catch (Exception ex)
  1414. {
  1415. _logger.LogError(ex, "Error saving recording image");
  1416. }
  1417. }
  1418. if (!program.IsSeries)
  1419. {
  1420. image = program.GetImageInfo(ImageType.Backdrop, 0);
  1421. if (image is not null)
  1422. {
  1423. try
  1424. {
  1425. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1426. }
  1427. catch (Exception ex)
  1428. {
  1429. _logger.LogError(ex, "Error saving recording image");
  1430. }
  1431. }
  1432. image = program.GetImageInfo(ImageType.Thumb, 0);
  1433. if (image is not null)
  1434. {
  1435. try
  1436. {
  1437. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1438. }
  1439. catch (Exception ex)
  1440. {
  1441. _logger.LogError(ex, "Error saving recording image");
  1442. }
  1443. }
  1444. image = program.GetImageInfo(ImageType.Logo, 0);
  1445. if (image is not null)
  1446. {
  1447. try
  1448. {
  1449. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1450. }
  1451. catch (Exception ex)
  1452. {
  1453. _logger.LogError(ex, "Error saving recording image");
  1454. }
  1455. }
  1456. }
  1457. }
  1458. private async Task SaveRecordingMetadata(TimerInfo timer, string recordingPath, string seriesPath)
  1459. {
  1460. try
  1461. {
  1462. var program = string.IsNullOrWhiteSpace(timer.ProgramId) ? null : _libraryManager.GetItemList(new InternalItemsQuery
  1463. {
  1464. IncludeItemTypes = new[] { BaseItemKind.LiveTvProgram },
  1465. Limit = 1,
  1466. ExternalId = timer.ProgramId,
  1467. DtoOptions = new DtoOptions(true)
  1468. }).FirstOrDefault() as LiveTvProgram;
  1469. // dummy this up
  1470. if (program is null)
  1471. {
  1472. program = new LiveTvProgram
  1473. {
  1474. Name = timer.Name,
  1475. Overview = timer.Overview,
  1476. Genres = timer.Genres,
  1477. CommunityRating = timer.CommunityRating,
  1478. OfficialRating = timer.OfficialRating,
  1479. ProductionYear = timer.ProductionYear,
  1480. PremiereDate = timer.OriginalAirDate,
  1481. IndexNumber = timer.EpisodeNumber,
  1482. ParentIndexNumber = timer.SeasonNumber
  1483. };
  1484. }
  1485. if (timer.IsSports)
  1486. {
  1487. program.AddGenre("Sports");
  1488. }
  1489. if (timer.IsKids)
  1490. {
  1491. program.AddGenre("Kids");
  1492. program.AddGenre("Children");
  1493. }
  1494. if (timer.IsNews)
  1495. {
  1496. program.AddGenre("News");
  1497. }
  1498. var config = GetConfiguration();
  1499. if (config.SaveRecordingNFO)
  1500. {
  1501. if (timer.IsProgramSeries)
  1502. {
  1503. await SaveSeriesNfoAsync(timer, seriesPath).ConfigureAwait(false);
  1504. await SaveVideoNfoAsync(timer, recordingPath, program, false).ConfigureAwait(false);
  1505. }
  1506. else if (!timer.IsMovie || timer.IsSports || timer.IsNews)
  1507. {
  1508. await SaveVideoNfoAsync(timer, recordingPath, program, true).ConfigureAwait(false);
  1509. }
  1510. else
  1511. {
  1512. await SaveVideoNfoAsync(timer, recordingPath, program, false).ConfigureAwait(false);
  1513. }
  1514. }
  1515. if (config.SaveRecordingImages)
  1516. {
  1517. await SaveRecordingImages(recordingPath, program).ConfigureAwait(false);
  1518. }
  1519. }
  1520. catch (Exception ex)
  1521. {
  1522. _logger.LogError(ex, "Error saving nfo");
  1523. }
  1524. }
  1525. private async Task SaveSeriesNfoAsync(TimerInfo timer, string seriesPath)
  1526. {
  1527. var nfoPath = Path.Combine(seriesPath, "tvshow.nfo");
  1528. if (File.Exists(nfoPath))
  1529. {
  1530. return;
  1531. }
  1532. var stream = new FileStream(nfoPath, FileMode.CreateNew, FileAccess.Write, FileShare.None);
  1533. await using (stream.ConfigureAwait(false))
  1534. {
  1535. var settings = new XmlWriterSettings
  1536. {
  1537. Indent = true,
  1538. Encoding = Encoding.UTF8,
  1539. Async = true
  1540. };
  1541. var writer = XmlWriter.Create(stream, settings);
  1542. await using (writer.ConfigureAwait(false))
  1543. {
  1544. await writer.WriteStartDocumentAsync(true).ConfigureAwait(false);
  1545. await writer.WriteStartElementAsync(null, "tvshow", null).ConfigureAwait(false);
  1546. if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Tvdb.ToString(), out var id))
  1547. {
  1548. await writer.WriteElementStringAsync(null, "id", null, id).ConfigureAwait(false);
  1549. }
  1550. if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Imdb.ToString(), out id))
  1551. {
  1552. await writer.WriteElementStringAsync(null, "imdb_id", null, id).ConfigureAwait(false);
  1553. }
  1554. if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Tmdb.ToString(), out id))
  1555. {
  1556. await writer.WriteElementStringAsync(null, "tmdbid", null, id).ConfigureAwait(false);
  1557. }
  1558. if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Zap2It.ToString(), out id))
  1559. {
  1560. await writer.WriteElementStringAsync(null, "zap2itid", null, id).ConfigureAwait(false);
  1561. }
  1562. if (!string.IsNullOrWhiteSpace(timer.Name))
  1563. {
  1564. await writer.WriteElementStringAsync(null, "title", null, timer.Name).ConfigureAwait(false);
  1565. }
  1566. if (!string.IsNullOrWhiteSpace(timer.OfficialRating))
  1567. {
  1568. await writer.WriteElementStringAsync(null, "mpaa", null, timer.OfficialRating).ConfigureAwait(false);
  1569. }
  1570. foreach (var genre in timer.Genres)
  1571. {
  1572. await writer.WriteElementStringAsync(null, "genre", null, genre).ConfigureAwait(false);
  1573. }
  1574. await writer.WriteEndElementAsync().ConfigureAwait(false);
  1575. await writer.WriteEndDocumentAsync().ConfigureAwait(false);
  1576. }
  1577. }
  1578. }
  1579. private async Task SaveVideoNfoAsync(TimerInfo timer, string recordingPath, BaseItem item, bool lockData)
  1580. {
  1581. var nfoPath = Path.ChangeExtension(recordingPath, ".nfo");
  1582. if (File.Exists(nfoPath))
  1583. {
  1584. return;
  1585. }
  1586. var stream = new FileStream(nfoPath, FileMode.CreateNew, FileAccess.Write, FileShare.None);
  1587. await using (stream.ConfigureAwait(false))
  1588. {
  1589. var settings = new XmlWriterSettings
  1590. {
  1591. Indent = true,
  1592. Encoding = Encoding.UTF8,
  1593. Async = true
  1594. };
  1595. var options = _config.GetNfoConfiguration();
  1596. var isSeriesEpisode = timer.IsProgramSeries;
  1597. var writer = XmlWriter.Create(stream, settings);
  1598. await using (writer.ConfigureAwait(false))
  1599. {
  1600. await writer.WriteStartDocumentAsync(true).ConfigureAwait(false);
  1601. if (isSeriesEpisode)
  1602. {
  1603. await writer.WriteStartElementAsync(null, "episodedetails", null).ConfigureAwait(false);
  1604. if (!string.IsNullOrWhiteSpace(timer.EpisodeTitle))
  1605. {
  1606. await writer.WriteElementStringAsync(null, "title", null, timer.EpisodeTitle).ConfigureAwait(false);
  1607. }
  1608. var premiereDate = item.PremiereDate ?? (!timer.IsRepeat ? DateTime.UtcNow : null);
  1609. if (premiereDate.HasValue)
  1610. {
  1611. var formatString = options.ReleaseDateFormat;
  1612. await writer.WriteElementStringAsync(
  1613. null,
  1614. "aired",
  1615. null,
  1616. premiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1617. }
  1618. if (item.IndexNumber.HasValue)
  1619. {
  1620. await writer.WriteElementStringAsync(null, "episode", null, item.IndexNumber.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1621. }
  1622. if (item.ParentIndexNumber.HasValue)
  1623. {
  1624. await writer.WriteElementStringAsync(null, "season", null, item.ParentIndexNumber.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1625. }
  1626. }
  1627. else
  1628. {
  1629. await writer.WriteStartElementAsync(null, "movie", null).ConfigureAwait(false);
  1630. if (!string.IsNullOrWhiteSpace(item.Name))
  1631. {
  1632. await writer.WriteElementStringAsync(null, "title", null, item.Name).ConfigureAwait(false);
  1633. }
  1634. if (!string.IsNullOrWhiteSpace(item.OriginalTitle))
  1635. {
  1636. await writer.WriteElementStringAsync(null, "originaltitle", null, item.OriginalTitle).ConfigureAwait(false);
  1637. }
  1638. if (item.PremiereDate.HasValue)
  1639. {
  1640. var formatString = options.ReleaseDateFormat;
  1641. await writer.WriteElementStringAsync(
  1642. null,
  1643. "premiered",
  1644. null,
  1645. item.PremiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1646. await writer.WriteElementStringAsync(
  1647. null,
  1648. "releasedate",
  1649. null,
  1650. item.PremiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1651. }
  1652. }
  1653. await writer.WriteElementStringAsync(
  1654. null,
  1655. "dateadded",
  1656. null,
  1657. DateTime.Now.ToString(DateAddedFormat, CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1658. if (item.ProductionYear.HasValue)
  1659. {
  1660. await writer.WriteElementStringAsync(null, "year", null, item.ProductionYear.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1661. }
  1662. if (!string.IsNullOrEmpty(item.OfficialRating))
  1663. {
  1664. await writer.WriteElementStringAsync(null, "mpaa", null, item.OfficialRating).ConfigureAwait(false);
  1665. }
  1666. var overview = (item.Overview ?? string.Empty)
  1667. .StripHtml()
  1668. .Replace("&quot;", "'", StringComparison.Ordinal);
  1669. await writer.WriteElementStringAsync(null, "plot", null, overview).ConfigureAwait(false);
  1670. if (item.CommunityRating.HasValue)
  1671. {
  1672. await writer.WriteElementStringAsync(null, "rating", null, item.CommunityRating.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1673. }
  1674. foreach (var genre in item.Genres)
  1675. {
  1676. await writer.WriteElementStringAsync(null, "genre", null, genre).ConfigureAwait(false);
  1677. }
  1678. var people = item.Id.Equals(default) ? new List<PersonInfo>() : _libraryManager.GetPeople(item);
  1679. var directors = people
  1680. .Where(i => i.IsType(PersonKind.Director))
  1681. .Select(i => i.Name)
  1682. .ToList();
  1683. foreach (var person in directors)
  1684. {
  1685. await writer.WriteElementStringAsync(null, "director", null, person).ConfigureAwait(false);
  1686. }
  1687. var writers = people
  1688. .Where(i => i.IsType(PersonKind.Writer))
  1689. .Select(i => i.Name)
  1690. .Distinct(StringComparer.OrdinalIgnoreCase)
  1691. .ToList();
  1692. foreach (var person in writers)
  1693. {
  1694. await writer.WriteElementStringAsync(null, "writer", null, person).ConfigureAwait(false);
  1695. }
  1696. foreach (var person in writers)
  1697. {
  1698. await writer.WriteElementStringAsync(null, "credits", null, person).ConfigureAwait(false);
  1699. }
  1700. var tmdbCollection = item.GetProviderId(MetadataProvider.TmdbCollection);
  1701. if (!string.IsNullOrEmpty(tmdbCollection))
  1702. {
  1703. await writer.WriteElementStringAsync(null, "collectionnumber", null, tmdbCollection).ConfigureAwait(false);
  1704. }
  1705. var imdb = item.GetProviderId(MetadataProvider.Imdb);
  1706. if (!string.IsNullOrEmpty(imdb))
  1707. {
  1708. if (!isSeriesEpisode)
  1709. {
  1710. await writer.WriteElementStringAsync(null, "id", null, imdb).ConfigureAwait(false);
  1711. }
  1712. await writer.WriteElementStringAsync(null, "imdbid", null, imdb).ConfigureAwait(false);
  1713. // No need to lock if we have identified the content already
  1714. lockData = false;
  1715. }
  1716. var tvdb = item.GetProviderId(MetadataProvider.Tvdb);
  1717. if (!string.IsNullOrEmpty(tvdb))
  1718. {
  1719. await writer.WriteElementStringAsync(null, "tvdbid", null, tvdb).ConfigureAwait(false);
  1720. // No need to lock if we have identified the content already
  1721. lockData = false;
  1722. }
  1723. var tmdb = item.GetProviderId(MetadataProvider.Tmdb);
  1724. if (!string.IsNullOrEmpty(tmdb))
  1725. {
  1726. await writer.WriteElementStringAsync(null, "tmdbid", null, tmdb).ConfigureAwait(false);
  1727. // No need to lock if we have identified the content already
  1728. lockData = false;
  1729. }
  1730. if (lockData)
  1731. {
  1732. await writer.WriteElementStringAsync(null, "lockdata", null, "true").ConfigureAwait(false);
  1733. }
  1734. if (item.CriticRating.HasValue)
  1735. {
  1736. await writer.WriteElementStringAsync(null, "criticrating", null, item.CriticRating.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1737. }
  1738. if (!string.IsNullOrWhiteSpace(item.Tagline))
  1739. {
  1740. await writer.WriteElementStringAsync(null, "tagline", null, item.Tagline).ConfigureAwait(false);
  1741. }
  1742. foreach (var studio in item.Studios)
  1743. {
  1744. await writer.WriteElementStringAsync(null, "studio", null, studio).ConfigureAwait(false);
  1745. }
  1746. await writer.WriteEndElementAsync().ConfigureAwait(false);
  1747. await writer.WriteEndDocumentAsync().ConfigureAwait(false);
  1748. }
  1749. }
  1750. }
  1751. private LiveTvProgram GetProgramInfoFromCache(string programId)
  1752. {
  1753. var query = new InternalItemsQuery
  1754. {
  1755. ItemIds = new[] { _liveTvManager.GetInternalProgramId(programId) },
  1756. Limit = 1,
  1757. DtoOptions = new DtoOptions()
  1758. };
  1759. return _libraryManager.GetItemList(query).Cast<LiveTvProgram>().FirstOrDefault();
  1760. }
  1761. private LiveTvProgram GetProgramInfoFromCache(TimerInfo timer)
  1762. {
  1763. return GetProgramInfoFromCache(timer.ProgramId);
  1764. }
  1765. private LiveTvProgram GetProgramInfoFromCache(string channelId, DateTime startDateUtc)
  1766. {
  1767. var query = new InternalItemsQuery
  1768. {
  1769. IncludeItemTypes = new[] { BaseItemKind.LiveTvProgram },
  1770. Limit = 1,
  1771. DtoOptions = new DtoOptions(true)
  1772. {
  1773. EnableImages = false
  1774. },
  1775. MinStartDate = startDateUtc.AddMinutes(-3),
  1776. MaxStartDate = startDateUtc.AddMinutes(3),
  1777. OrderBy = new[] { (ItemSortBy.StartDate, SortOrder.Ascending) }
  1778. };
  1779. if (!string.IsNullOrWhiteSpace(channelId))
  1780. {
  1781. query.ChannelIds = new[] { _liveTvManager.GetInternalChannelId(Name, channelId) };
  1782. }
  1783. return _libraryManager.GetItemList(query).Cast<LiveTvProgram>().FirstOrDefault();
  1784. }
  1785. private LiveTvOptions GetConfiguration()
  1786. {
  1787. return _config.GetConfiguration<LiveTvOptions>("livetv");
  1788. }
  1789. private bool ShouldCancelTimerForSeriesTimer(SeriesTimerInfo seriesTimer, TimerInfo timer)
  1790. {
  1791. if (timer.IsManual)
  1792. {
  1793. return false;
  1794. }
  1795. if (!seriesTimer.RecordAnyTime
  1796. && Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - timer.StartDate.TimeOfDay.Ticks) >= TimeSpan.FromMinutes(10).Ticks)
  1797. {
  1798. return true;
  1799. }
  1800. if (seriesTimer.RecordNewOnly && timer.IsRepeat)
  1801. {
  1802. return true;
  1803. }
  1804. if (!seriesTimer.RecordAnyChannel
  1805. && !string.Equals(timer.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase))
  1806. {
  1807. return true;
  1808. }
  1809. return seriesTimer.SkipEpisodesInLibrary && IsProgramAlreadyInLibrary(timer);
  1810. }
  1811. private void HandleDuplicateShowIds(List<TimerInfo> timers)
  1812. {
  1813. // sort showings by HD channels first, then by startDate, record earliest showing possible
  1814. foreach (var timer in timers.OrderByDescending(t => _liveTvManager.GetLiveTvChannel(t, this).IsHD).ThenBy(t => t.StartDate).Skip(1))
  1815. {
  1816. timer.Status = RecordingStatus.Cancelled;
  1817. _timerProvider.Update(timer);
  1818. }
  1819. }
  1820. private void SearchForDuplicateShowIds(IEnumerable<TimerInfo> timers)
  1821. {
  1822. var groups = timers.ToLookup(i => i.ShowId ?? string.Empty).ToList();
  1823. foreach (var group in groups)
  1824. {
  1825. if (string.IsNullOrWhiteSpace(group.Key))
  1826. {
  1827. continue;
  1828. }
  1829. var groupTimers = group.ToList();
  1830. if (groupTimers.Count < 2)
  1831. {
  1832. continue;
  1833. }
  1834. // Skip ShowId without SubKey from duplicate removal actions - https://github.com/jellyfin/jellyfin/issues/5856
  1835. if (group.Key.EndsWith("0000", StringComparison.Ordinal))
  1836. {
  1837. continue;
  1838. }
  1839. HandleDuplicateShowIds(groupTimers);
  1840. }
  1841. }
  1842. private void UpdateTimersForSeriesTimer(SeriesTimerInfo seriesTimer, bool updateTimerSettings, bool deleteInvalidTimers)
  1843. {
  1844. var allTimers = GetTimersForSeries(seriesTimer).ToList();
  1845. var enabledTimersForSeries = new List<TimerInfo>();
  1846. foreach (var timer in allTimers)
  1847. {
  1848. var existingTimer = _timerProvider.GetTimer(timer.Id)
  1849. ?? (string.IsNullOrWhiteSpace(timer.ProgramId)
  1850. ? null
  1851. : _timerProvider.GetTimerByProgramId(timer.ProgramId));
  1852. if (existingTimer is null)
  1853. {
  1854. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1855. {
  1856. timer.Status = RecordingStatus.Cancelled;
  1857. }
  1858. else
  1859. {
  1860. enabledTimersForSeries.Add(timer);
  1861. }
  1862. _timerProvider.Add(timer);
  1863. TimerCreated?.Invoke(this, new GenericEventArgs<TimerInfo>(timer));
  1864. }
  1865. // Only update if not currently active - test both new timer and existing in case Id's are different
  1866. // Id's could be different if the timer was created manually prior to series timer creation
  1867. else if (!_activeRecordings.TryGetValue(timer.Id, out _) && !_activeRecordings.TryGetValue(existingTimer.Id, out _))
  1868. {
  1869. UpdateExistingTimerWithNewMetadata(existingTimer, timer);
  1870. // Needed by ShouldCancelTimerForSeriesTimer
  1871. timer.IsManual = existingTimer.IsManual;
  1872. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1873. {
  1874. existingTimer.Status = RecordingStatus.Cancelled;
  1875. }
  1876. else if (!existingTimer.IsManual)
  1877. {
  1878. existingTimer.Status = RecordingStatus.New;
  1879. }
  1880. if (existingTimer.Status != RecordingStatus.Cancelled)
  1881. {
  1882. enabledTimersForSeries.Add(existingTimer);
  1883. }
  1884. if (updateTimerSettings)
  1885. {
  1886. existingTimer.KeepUntil = seriesTimer.KeepUntil;
  1887. existingTimer.IsPostPaddingRequired = seriesTimer.IsPostPaddingRequired;
  1888. existingTimer.IsPrePaddingRequired = seriesTimer.IsPrePaddingRequired;
  1889. existingTimer.PostPaddingSeconds = seriesTimer.PostPaddingSeconds;
  1890. existingTimer.PrePaddingSeconds = seriesTimer.PrePaddingSeconds;
  1891. existingTimer.Priority = seriesTimer.Priority;
  1892. existingTimer.SeriesTimerId = seriesTimer.Id;
  1893. }
  1894. existingTimer.SeriesTimerId = seriesTimer.Id;
  1895. _timerProvider.Update(existingTimer);
  1896. }
  1897. }
  1898. SearchForDuplicateShowIds(enabledTimersForSeries);
  1899. if (deleteInvalidTimers)
  1900. {
  1901. var allTimerIds = allTimers
  1902. .Select(i => i.Id)
  1903. .ToList();
  1904. var deleteStatuses = new[]
  1905. {
  1906. RecordingStatus.New
  1907. };
  1908. var deletes = _timerProvider.GetAll()
  1909. .Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
  1910. .Where(i => !allTimerIds.Contains(i.Id, StringComparison.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
  1911. .Where(i => deleteStatuses.Contains(i.Status))
  1912. .ToList();
  1913. foreach (var timer in deletes)
  1914. {
  1915. CancelTimerInternal(timer.Id, false, false);
  1916. }
  1917. }
  1918. }
  1919. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer)
  1920. {
  1921. ArgumentNullException.ThrowIfNull(seriesTimer);
  1922. var query = new InternalItemsQuery
  1923. {
  1924. IncludeItemTypes = new[] { BaseItemKind.LiveTvProgram },
  1925. ExternalSeriesId = seriesTimer.SeriesId,
  1926. DtoOptions = new DtoOptions(true)
  1927. {
  1928. EnableImages = false
  1929. },
  1930. MinEndDate = DateTime.UtcNow
  1931. };
  1932. if (string.IsNullOrEmpty(seriesTimer.SeriesId))
  1933. {
  1934. query.Name = seriesTimer.Name;
  1935. }
  1936. if (!seriesTimer.RecordAnyChannel)
  1937. {
  1938. query.ChannelIds = new[] { _liveTvManager.GetInternalChannelId(Name, seriesTimer.ChannelId) };
  1939. }
  1940. var tempChannelCache = new Dictionary<Guid, LiveTvChannel>();
  1941. return _libraryManager.GetItemList(query).Cast<LiveTvProgram>().Select(i => CreateTimer(i, seriesTimer, tempChannelCache));
  1942. }
  1943. private TimerInfo CreateTimer(LiveTvProgram parent, SeriesTimerInfo seriesTimer, Dictionary<Guid, LiveTvChannel> tempChannelCache)
  1944. {
  1945. string channelId = seriesTimer.RecordAnyChannel ? null : seriesTimer.ChannelId;
  1946. if (string.IsNullOrWhiteSpace(channelId) && !parent.ChannelId.Equals(default))
  1947. {
  1948. if (!tempChannelCache.TryGetValue(parent.ChannelId, out LiveTvChannel channel))
  1949. {
  1950. channel = _libraryManager.GetItemList(
  1951. new InternalItemsQuery
  1952. {
  1953. IncludeItemTypes = new[] { BaseItemKind.LiveTvChannel },
  1954. ItemIds = new[] { parent.ChannelId },
  1955. DtoOptions = new DtoOptions()
  1956. }).FirstOrDefault() as LiveTvChannel;
  1957. if (channel is not null && !string.IsNullOrWhiteSpace(channel.ExternalId))
  1958. {
  1959. tempChannelCache[parent.ChannelId] = channel;
  1960. }
  1961. }
  1962. if (channel is not null || tempChannelCache.TryGetValue(parent.ChannelId, out channel))
  1963. {
  1964. channelId = channel.ExternalId;
  1965. }
  1966. }
  1967. var timer = new TimerInfo
  1968. {
  1969. ChannelId = channelId,
  1970. Id = (seriesTimer.Id + parent.ExternalId).GetMD5().ToString("N", CultureInfo.InvariantCulture),
  1971. StartDate = parent.StartDate,
  1972. EndDate = parent.EndDate.Value,
  1973. ProgramId = parent.ExternalId,
  1974. PrePaddingSeconds = seriesTimer.PrePaddingSeconds,
  1975. PostPaddingSeconds = seriesTimer.PostPaddingSeconds,
  1976. IsPostPaddingRequired = seriesTimer.IsPostPaddingRequired,
  1977. IsPrePaddingRequired = seriesTimer.IsPrePaddingRequired,
  1978. KeepUntil = seriesTimer.KeepUntil,
  1979. Priority = seriesTimer.Priority,
  1980. Name = parent.Name,
  1981. Overview = parent.Overview,
  1982. SeriesId = parent.ExternalSeriesId,
  1983. SeriesTimerId = seriesTimer.Id,
  1984. ShowId = parent.ShowId
  1985. };
  1986. CopyProgramInfoToTimerInfo(parent, timer, tempChannelCache);
  1987. return timer;
  1988. }
  1989. private void CopyProgramInfoToTimerInfo(LiveTvProgram programInfo, TimerInfo timerInfo)
  1990. {
  1991. var tempChannelCache = new Dictionary<Guid, LiveTvChannel>();
  1992. CopyProgramInfoToTimerInfo(programInfo, timerInfo, tempChannelCache);
  1993. }
  1994. private void CopyProgramInfoToTimerInfo(LiveTvProgram programInfo, TimerInfo timerInfo, Dictionary<Guid, LiveTvChannel> tempChannelCache)
  1995. {
  1996. string channelId = null;
  1997. if (!programInfo.ChannelId.Equals(default))
  1998. {
  1999. if (!tempChannelCache.TryGetValue(programInfo.ChannelId, out LiveTvChannel channel))
  2000. {
  2001. channel = _libraryManager.GetItemList(
  2002. new InternalItemsQuery
  2003. {
  2004. IncludeItemTypes = new[] { BaseItemKind.LiveTvChannel },
  2005. ItemIds = new[] { programInfo.ChannelId },
  2006. DtoOptions = new DtoOptions()
  2007. }).FirstOrDefault() as LiveTvChannel;
  2008. if (channel is not null && !string.IsNullOrWhiteSpace(channel.ExternalId))
  2009. {
  2010. tempChannelCache[programInfo.ChannelId] = channel;
  2011. }
  2012. }
  2013. if (channel is not null || tempChannelCache.TryGetValue(programInfo.ChannelId, out channel))
  2014. {
  2015. channelId = channel.ExternalId;
  2016. }
  2017. }
  2018. timerInfo.Name = programInfo.Name;
  2019. timerInfo.StartDate = programInfo.StartDate;
  2020. timerInfo.EndDate = programInfo.EndDate.Value;
  2021. if (!string.IsNullOrWhiteSpace(channelId))
  2022. {
  2023. timerInfo.ChannelId = channelId;
  2024. }
  2025. timerInfo.SeasonNumber = programInfo.ParentIndexNumber;
  2026. timerInfo.EpisodeNumber = programInfo.IndexNumber;
  2027. timerInfo.IsMovie = programInfo.IsMovie;
  2028. timerInfo.ProductionYear = programInfo.ProductionYear;
  2029. timerInfo.EpisodeTitle = programInfo.EpisodeTitle;
  2030. timerInfo.OriginalAirDate = programInfo.PremiereDate;
  2031. timerInfo.IsProgramSeries = programInfo.IsSeries;
  2032. timerInfo.IsSeries = programInfo.IsSeries;
  2033. timerInfo.CommunityRating = programInfo.CommunityRating;
  2034. timerInfo.Overview = programInfo.Overview;
  2035. timerInfo.OfficialRating = programInfo.OfficialRating;
  2036. timerInfo.IsRepeat = programInfo.IsRepeat;
  2037. timerInfo.SeriesId = programInfo.ExternalSeriesId;
  2038. timerInfo.ProviderIds = programInfo.ProviderIds;
  2039. timerInfo.Tags = programInfo.Tags;
  2040. var seriesProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  2041. foreach (var providerId in timerInfo.ProviderIds)
  2042. {
  2043. const string Search = "Series";
  2044. if (providerId.Key.StartsWith(Search, StringComparison.OrdinalIgnoreCase))
  2045. {
  2046. seriesProviderIds[providerId.Key.Substring(Search.Length)] = providerId.Value;
  2047. }
  2048. }
  2049. timerInfo.SeriesProviderIds = seriesProviderIds;
  2050. }
  2051. private bool IsProgramAlreadyInLibrary(TimerInfo program)
  2052. {
  2053. if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle))
  2054. {
  2055. var seriesIds = _libraryManager.GetItemIds(
  2056. new InternalItemsQuery
  2057. {
  2058. IncludeItemTypes = new[] { BaseItemKind.Series },
  2059. Name = program.Name
  2060. }).ToArray();
  2061. if (seriesIds.Length == 0)
  2062. {
  2063. return false;
  2064. }
  2065. if (program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue)
  2066. {
  2067. var result = _libraryManager.GetItemIds(new InternalItemsQuery
  2068. {
  2069. IncludeItemTypes = new[] { BaseItemKind.Episode },
  2070. ParentIndexNumber = program.SeasonNumber.Value,
  2071. IndexNumber = program.EpisodeNumber.Value,
  2072. AncestorIds = seriesIds,
  2073. IsVirtualItem = false,
  2074. Limit = 1
  2075. });
  2076. if (result.Count > 0)
  2077. {
  2078. return true;
  2079. }
  2080. }
  2081. }
  2082. return false;
  2083. }
  2084. /// <inheritdoc />
  2085. public void Dispose()
  2086. {
  2087. if (_disposed)
  2088. {
  2089. return;
  2090. }
  2091. _recordingDeleteSemaphore.Dispose();
  2092. foreach (var pair in _activeRecordings.ToList())
  2093. {
  2094. pair.Value.CancellationTokenSource.Cancel();
  2095. }
  2096. _disposed = true;
  2097. }
  2098. public IEnumerable<VirtualFolderInfo> GetRecordingFolders()
  2099. {
  2100. var defaultFolder = RecordingPath;
  2101. var defaultName = "Recordings";
  2102. if (Directory.Exists(defaultFolder))
  2103. {
  2104. yield return new VirtualFolderInfo
  2105. {
  2106. Locations = new string[] { defaultFolder },
  2107. Name = defaultName
  2108. };
  2109. }
  2110. var customPath = GetConfiguration().MovieRecordingPath;
  2111. if (!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase) && Directory.Exists(customPath))
  2112. {
  2113. yield return new VirtualFolderInfo
  2114. {
  2115. Locations = new string[] { customPath },
  2116. Name = "Recorded Movies",
  2117. CollectionType = CollectionTypeOptions.Movies
  2118. };
  2119. }
  2120. customPath = GetConfiguration().SeriesRecordingPath;
  2121. if (!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase) && Directory.Exists(customPath))
  2122. {
  2123. yield return new VirtualFolderInfo
  2124. {
  2125. Locations = new string[] { customPath },
  2126. Name = "Recorded Shows",
  2127. CollectionType = CollectionTypeOptions.TvShows
  2128. };
  2129. }
  2130. }
  2131. public async Task<List<TunerHostInfo>> DiscoverTuners(bool newDevicesOnly, CancellationToken cancellationToken)
  2132. {
  2133. var list = new List<TunerHostInfo>();
  2134. var configuredDeviceIds = GetConfiguration().TunerHosts
  2135. .Where(i => !string.IsNullOrWhiteSpace(i.DeviceId))
  2136. .Select(i => i.DeviceId)
  2137. .ToList();
  2138. foreach (var host in _liveTvManager.TunerHosts)
  2139. {
  2140. var discoveredDevices = await DiscoverDevices(host, TunerDiscoveryDurationMs, cancellationToken).ConfigureAwait(false);
  2141. if (newDevicesOnly)
  2142. {
  2143. discoveredDevices = discoveredDevices.Where(d => !configuredDeviceIds.Contains(d.DeviceId, StringComparison.OrdinalIgnoreCase))
  2144. .ToList();
  2145. }
  2146. list.AddRange(discoveredDevices);
  2147. }
  2148. return list;
  2149. }
  2150. public async Task ScanForTunerDeviceChanges(CancellationToken cancellationToken)
  2151. {
  2152. foreach (var host in _liveTvManager.TunerHosts)
  2153. {
  2154. await ScanForTunerDeviceChanges(host, cancellationToken).ConfigureAwait(false);
  2155. }
  2156. }
  2157. private async Task ScanForTunerDeviceChanges(ITunerHost host, CancellationToken cancellationToken)
  2158. {
  2159. var discoveredDevices = await DiscoverDevices(host, TunerDiscoveryDurationMs, cancellationToken).ConfigureAwait(false);
  2160. var configuredDevices = GetConfiguration().TunerHosts
  2161. .Where(i => string.Equals(i.Type, host.Type, StringComparison.OrdinalIgnoreCase))
  2162. .ToList();
  2163. foreach (var device in discoveredDevices)
  2164. {
  2165. var configuredDevice = configuredDevices.FirstOrDefault(i => string.Equals(i.DeviceId, device.DeviceId, StringComparison.OrdinalIgnoreCase));
  2166. if (configuredDevice is not null && !string.Equals(device.Url, configuredDevice.Url, StringComparison.OrdinalIgnoreCase))
  2167. {
  2168. _logger.LogInformation("Tuner url has changed from {PreviousUrl} to {NewUrl}", configuredDevice.Url, device.Url);
  2169. configuredDevice.Url = device.Url;
  2170. await _liveTvManager.SaveTunerHost(configuredDevice).ConfigureAwait(false);
  2171. }
  2172. }
  2173. }
  2174. private async Task<List<TunerHostInfo>> DiscoverDevices(ITunerHost host, int discoveryDurationMs, CancellationToken cancellationToken)
  2175. {
  2176. try
  2177. {
  2178. var discoveredDevices = await host.DiscoverDevices(discoveryDurationMs, cancellationToken).ConfigureAwait(false);
  2179. foreach (var device in discoveredDevices)
  2180. {
  2181. _logger.LogInformation("Discovered tuner device {0} at {1}", host.Name, device.Url);
  2182. }
  2183. return discoveredDevices;
  2184. }
  2185. catch (Exception ex)
  2186. {
  2187. _logger.LogError(ex, "Error discovering tuner devices");
  2188. return new List<TunerHostInfo>();
  2189. }
  2190. }
  2191. }
  2192. }