EmbyTV.cs 100 KB

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