EmbyTV.cs 100 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665
  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. var stream = new FileStream(nfoPath, FileMode.CreateNew, FileAccess.Write, FileShare.None);
  1534. await using (stream.ConfigureAwait(false))
  1535. {
  1536. var settings = new XmlWriterSettings
  1537. {
  1538. Indent = true,
  1539. Encoding = Encoding.UTF8,
  1540. Async = true
  1541. };
  1542. var writer = XmlWriter.Create(stream, settings);
  1543. await using (writer.ConfigureAwait(false))
  1544. {
  1545. await writer.WriteStartDocumentAsync(true).ConfigureAwait(false);
  1546. await writer.WriteStartElementAsync(null, "tvshow", null).ConfigureAwait(false);
  1547. if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Tvdb.ToString(), out var id))
  1548. {
  1549. await writer.WriteElementStringAsync(null, "id", null, id).ConfigureAwait(false);
  1550. }
  1551. if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Imdb.ToString(), out id))
  1552. {
  1553. await writer.WriteElementStringAsync(null, "imdb_id", null, id).ConfigureAwait(false);
  1554. }
  1555. if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Tmdb.ToString(), out id))
  1556. {
  1557. await writer.WriteElementStringAsync(null, "tmdbid", null, id).ConfigureAwait(false);
  1558. }
  1559. if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Zap2It.ToString(), out id))
  1560. {
  1561. await writer.WriteElementStringAsync(null, "zap2itid", null, id).ConfigureAwait(false);
  1562. }
  1563. if (!string.IsNullOrWhiteSpace(timer.Name))
  1564. {
  1565. await writer.WriteElementStringAsync(null, "title", null, timer.Name).ConfigureAwait(false);
  1566. }
  1567. if (!string.IsNullOrWhiteSpace(timer.OfficialRating))
  1568. {
  1569. await writer.WriteElementStringAsync(null, "mpaa", null, timer.OfficialRating).ConfigureAwait(false);
  1570. }
  1571. foreach (var genre in timer.Genres)
  1572. {
  1573. await writer.WriteElementStringAsync(null, "genre", null, genre).ConfigureAwait(false);
  1574. }
  1575. await writer.WriteEndElementAsync().ConfigureAwait(false);
  1576. await writer.WriteEndDocumentAsync().ConfigureAwait(false);
  1577. }
  1578. }
  1579. }
  1580. private async Task SaveVideoNfoAsync(TimerInfo timer, string recordingPath, BaseItem item, bool lockData)
  1581. {
  1582. var nfoPath = Path.ChangeExtension(recordingPath, ".nfo");
  1583. if (File.Exists(nfoPath))
  1584. {
  1585. return;
  1586. }
  1587. var stream = new FileStream(nfoPath, FileMode.CreateNew, FileAccess.Write, FileShare.None);
  1588. await using (stream.ConfigureAwait(false))
  1589. {
  1590. var settings = new XmlWriterSettings
  1591. {
  1592. Indent = true,
  1593. Encoding = Encoding.UTF8,
  1594. Async = true
  1595. };
  1596. var options = _config.GetNfoConfiguration();
  1597. var isSeriesEpisode = timer.IsProgramSeries;
  1598. var writer = XmlWriter.Create(stream, settings);
  1599. await using (writer.ConfigureAwait(false))
  1600. {
  1601. await writer.WriteStartDocumentAsync(true).ConfigureAwait(false);
  1602. if (isSeriesEpisode)
  1603. {
  1604. await writer.WriteStartElementAsync(null, "episodedetails", null).ConfigureAwait(false);
  1605. if (!string.IsNullOrWhiteSpace(timer.EpisodeTitle))
  1606. {
  1607. await writer.WriteElementStringAsync(null, "title", null, timer.EpisodeTitle).ConfigureAwait(false);
  1608. }
  1609. var premiereDate = item.PremiereDate ?? (!timer.IsRepeat ? DateTime.UtcNow : null);
  1610. if (premiereDate.HasValue)
  1611. {
  1612. var formatString = options.ReleaseDateFormat;
  1613. await writer.WriteElementStringAsync(
  1614. null,
  1615. "aired",
  1616. null,
  1617. premiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1618. }
  1619. if (item.IndexNumber.HasValue)
  1620. {
  1621. await writer.WriteElementStringAsync(null, "episode", null, item.IndexNumber.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1622. }
  1623. if (item.ParentIndexNumber.HasValue)
  1624. {
  1625. await writer.WriteElementStringAsync(null, "season", null, item.ParentIndexNumber.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1626. }
  1627. }
  1628. else
  1629. {
  1630. await writer.WriteStartElementAsync(null, "movie", null).ConfigureAwait(false);
  1631. if (!string.IsNullOrWhiteSpace(item.Name))
  1632. {
  1633. await writer.WriteElementStringAsync(null, "title", null, item.Name).ConfigureAwait(false);
  1634. }
  1635. if (!string.IsNullOrWhiteSpace(item.OriginalTitle))
  1636. {
  1637. await writer.WriteElementStringAsync(null, "originaltitle", null, item.OriginalTitle).ConfigureAwait(false);
  1638. }
  1639. if (item.PremiereDate.HasValue)
  1640. {
  1641. var formatString = options.ReleaseDateFormat;
  1642. await writer.WriteElementStringAsync(
  1643. null,
  1644. "premiered",
  1645. null,
  1646. item.PremiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1647. await writer.WriteElementStringAsync(
  1648. null,
  1649. "releasedate",
  1650. null,
  1651. item.PremiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1652. }
  1653. }
  1654. await writer.WriteElementStringAsync(
  1655. null,
  1656. "dateadded",
  1657. null,
  1658. DateTime.Now.ToString(DateAddedFormat, CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1659. if (item.ProductionYear.HasValue)
  1660. {
  1661. await writer.WriteElementStringAsync(null, "year", null, item.ProductionYear.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1662. }
  1663. if (!string.IsNullOrEmpty(item.OfficialRating))
  1664. {
  1665. await writer.WriteElementStringAsync(null, "mpaa", null, item.OfficialRating).ConfigureAwait(false);
  1666. }
  1667. var overview = (item.Overview ?? string.Empty)
  1668. .StripHtml()
  1669. .Replace("&quot;", "'", StringComparison.Ordinal);
  1670. await writer.WriteElementStringAsync(null, "plot", null, overview).ConfigureAwait(false);
  1671. if (item.CommunityRating.HasValue)
  1672. {
  1673. await writer.WriteElementStringAsync(null, "rating", null, item.CommunityRating.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1674. }
  1675. foreach (var genre in item.Genres)
  1676. {
  1677. await writer.WriteElementStringAsync(null, "genre", null, genre).ConfigureAwait(false);
  1678. }
  1679. var people = item.Id.Equals(default) ? new List<PersonInfo>() : _libraryManager.GetPeople(item);
  1680. var directors = people
  1681. .Where(i => i.IsType(PersonKind.Director))
  1682. .Select(i => i.Name)
  1683. .ToList();
  1684. foreach (var person in directors)
  1685. {
  1686. await writer.WriteElementStringAsync(null, "director", null, person).ConfigureAwait(false);
  1687. }
  1688. var writers = people
  1689. .Where(i => i.IsType(PersonKind.Writer))
  1690. .Select(i => i.Name)
  1691. .Distinct(StringComparer.OrdinalIgnoreCase)
  1692. .ToList();
  1693. foreach (var person in writers)
  1694. {
  1695. await writer.WriteElementStringAsync(null, "writer", null, person).ConfigureAwait(false);
  1696. }
  1697. foreach (var person in writers)
  1698. {
  1699. await writer.WriteElementStringAsync(null, "credits", null, person).ConfigureAwait(false);
  1700. }
  1701. var tmdbCollection = item.GetProviderId(MetadataProvider.TmdbCollection);
  1702. if (!string.IsNullOrEmpty(tmdbCollection))
  1703. {
  1704. await writer.WriteElementStringAsync(null, "collectionnumber", null, tmdbCollection).ConfigureAwait(false);
  1705. }
  1706. var imdb = item.GetProviderId(MetadataProvider.Imdb);
  1707. if (!string.IsNullOrEmpty(imdb))
  1708. {
  1709. if (!isSeriesEpisode)
  1710. {
  1711. await writer.WriteElementStringAsync(null, "id", null, imdb).ConfigureAwait(false);
  1712. }
  1713. await writer.WriteElementStringAsync(null, "imdbid", null, imdb).ConfigureAwait(false);
  1714. // No need to lock if we have identified the content already
  1715. lockData = false;
  1716. }
  1717. var tvdb = item.GetProviderId(MetadataProvider.Tvdb);
  1718. if (!string.IsNullOrEmpty(tvdb))
  1719. {
  1720. await writer.WriteElementStringAsync(null, "tvdbid", null, tvdb).ConfigureAwait(false);
  1721. // No need to lock if we have identified the content already
  1722. lockData = false;
  1723. }
  1724. var tmdb = item.GetProviderId(MetadataProvider.Tmdb);
  1725. if (!string.IsNullOrEmpty(tmdb))
  1726. {
  1727. await writer.WriteElementStringAsync(null, "tmdbid", null, tmdb).ConfigureAwait(false);
  1728. // No need to lock if we have identified the content already
  1729. lockData = false;
  1730. }
  1731. if (lockData)
  1732. {
  1733. await writer.WriteElementStringAsync(null, "lockdata", null, "true").ConfigureAwait(false);
  1734. }
  1735. if (item.CriticRating.HasValue)
  1736. {
  1737. await writer.WriteElementStringAsync(null, "criticrating", null, item.CriticRating.Value.ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
  1738. }
  1739. if (!string.IsNullOrWhiteSpace(item.Tagline))
  1740. {
  1741. await writer.WriteElementStringAsync(null, "tagline", null, item.Tagline).ConfigureAwait(false);
  1742. }
  1743. foreach (var studio in item.Studios)
  1744. {
  1745. await writer.WriteElementStringAsync(null, "studio", null, studio).ConfigureAwait(false);
  1746. }
  1747. await writer.WriteEndElementAsync().ConfigureAwait(false);
  1748. await writer.WriteEndDocumentAsync().ConfigureAwait(false);
  1749. }
  1750. }
  1751. }
  1752. private LiveTvProgram GetProgramInfoFromCache(string programId)
  1753. {
  1754. var query = new InternalItemsQuery
  1755. {
  1756. ItemIds = new[] { _liveTvManager.GetInternalProgramId(programId) },
  1757. Limit = 1,
  1758. DtoOptions = new DtoOptions()
  1759. };
  1760. return _libraryManager.GetItemList(query).Cast<LiveTvProgram>().FirstOrDefault();
  1761. }
  1762. private LiveTvProgram GetProgramInfoFromCache(TimerInfo timer)
  1763. {
  1764. return GetProgramInfoFromCache(timer.ProgramId);
  1765. }
  1766. private LiveTvProgram GetProgramInfoFromCache(string channelId, DateTime startDateUtc)
  1767. {
  1768. var query = new InternalItemsQuery
  1769. {
  1770. IncludeItemTypes = new[] { BaseItemKind.LiveTvProgram },
  1771. Limit = 1,
  1772. DtoOptions = new DtoOptions(true)
  1773. {
  1774. EnableImages = false
  1775. },
  1776. MinStartDate = startDateUtc.AddMinutes(-3),
  1777. MaxStartDate = startDateUtc.AddMinutes(3),
  1778. OrderBy = new[] { (ItemSortBy.StartDate, SortOrder.Ascending) }
  1779. };
  1780. if (!string.IsNullOrWhiteSpace(channelId))
  1781. {
  1782. query.ChannelIds = new[] { _liveTvManager.GetInternalChannelId(Name, channelId) };
  1783. }
  1784. return _libraryManager.GetItemList(query).Cast<LiveTvProgram>().FirstOrDefault();
  1785. }
  1786. private LiveTvOptions GetConfiguration()
  1787. {
  1788. return _config.GetConfiguration<LiveTvOptions>("livetv");
  1789. }
  1790. private bool ShouldCancelTimerForSeriesTimer(SeriesTimerInfo seriesTimer, TimerInfo timer)
  1791. {
  1792. if (timer.IsManual)
  1793. {
  1794. return false;
  1795. }
  1796. if (!seriesTimer.RecordAnyTime
  1797. && Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - timer.StartDate.TimeOfDay.Ticks) >= TimeSpan.FromMinutes(10).Ticks)
  1798. {
  1799. return true;
  1800. }
  1801. if (seriesTimer.RecordNewOnly && timer.IsRepeat)
  1802. {
  1803. return true;
  1804. }
  1805. if (!seriesTimer.RecordAnyChannel
  1806. && !string.Equals(timer.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase))
  1807. {
  1808. return true;
  1809. }
  1810. return seriesTimer.SkipEpisodesInLibrary && IsProgramAlreadyInLibrary(timer);
  1811. }
  1812. private void HandleDuplicateShowIds(List<TimerInfo> timers)
  1813. {
  1814. // sort showings by HD channels first, then by startDate, record earliest showing possible
  1815. foreach (var timer in timers.OrderByDescending(t => _liveTvManager.GetLiveTvChannel(t, this).IsHD).ThenBy(t => t.StartDate).Skip(1))
  1816. {
  1817. timer.Status = RecordingStatus.Cancelled;
  1818. _timerProvider.Update(timer);
  1819. }
  1820. }
  1821. private void SearchForDuplicateShowIds(IEnumerable<TimerInfo> timers)
  1822. {
  1823. var groups = timers.ToLookup(i => i.ShowId ?? string.Empty).ToList();
  1824. foreach (var group in groups)
  1825. {
  1826. if (string.IsNullOrWhiteSpace(group.Key))
  1827. {
  1828. continue;
  1829. }
  1830. var groupTimers = group.ToList();
  1831. if (groupTimers.Count < 2)
  1832. {
  1833. continue;
  1834. }
  1835. // Skip ShowId without SubKey from duplicate removal actions - https://github.com/jellyfin/jellyfin/issues/5856
  1836. if (group.Key.EndsWith("0000", StringComparison.Ordinal))
  1837. {
  1838. continue;
  1839. }
  1840. HandleDuplicateShowIds(groupTimers);
  1841. }
  1842. }
  1843. private void UpdateTimersForSeriesTimer(SeriesTimerInfo seriesTimer, bool updateTimerSettings, bool deleteInvalidTimers)
  1844. {
  1845. var allTimers = GetTimersForSeries(seriesTimer).ToList();
  1846. var enabledTimersForSeries = new List<TimerInfo>();
  1847. foreach (var timer in allTimers)
  1848. {
  1849. var existingTimer = _timerProvider.GetTimer(timer.Id)
  1850. ?? (string.IsNullOrWhiteSpace(timer.ProgramId)
  1851. ? null
  1852. : _timerProvider.GetTimerByProgramId(timer.ProgramId));
  1853. if (existingTimer is null)
  1854. {
  1855. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1856. {
  1857. timer.Status = RecordingStatus.Cancelled;
  1858. }
  1859. else
  1860. {
  1861. enabledTimersForSeries.Add(timer);
  1862. }
  1863. _timerProvider.Add(timer);
  1864. TimerCreated?.Invoke(this, new GenericEventArgs<TimerInfo>(timer));
  1865. }
  1866. // Only update if not currently active - test both new timer and existing in case Id's are different
  1867. // Id's could be different if the timer was created manually prior to series timer creation
  1868. else if (!_activeRecordings.TryGetValue(timer.Id, out _) && !_activeRecordings.TryGetValue(existingTimer.Id, out _))
  1869. {
  1870. UpdateExistingTimerWithNewMetadata(existingTimer, timer);
  1871. // Needed by ShouldCancelTimerForSeriesTimer
  1872. timer.IsManual = existingTimer.IsManual;
  1873. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1874. {
  1875. existingTimer.Status = RecordingStatus.Cancelled;
  1876. }
  1877. else if (!existingTimer.IsManual)
  1878. {
  1879. existingTimer.Status = RecordingStatus.New;
  1880. }
  1881. if (existingTimer.Status != RecordingStatus.Cancelled)
  1882. {
  1883. enabledTimersForSeries.Add(existingTimer);
  1884. }
  1885. if (updateTimerSettings)
  1886. {
  1887. existingTimer.KeepUntil = seriesTimer.KeepUntil;
  1888. existingTimer.IsPostPaddingRequired = seriesTimer.IsPostPaddingRequired;
  1889. existingTimer.IsPrePaddingRequired = seriesTimer.IsPrePaddingRequired;
  1890. existingTimer.PostPaddingSeconds = seriesTimer.PostPaddingSeconds;
  1891. existingTimer.PrePaddingSeconds = seriesTimer.PrePaddingSeconds;
  1892. existingTimer.Priority = seriesTimer.Priority;
  1893. existingTimer.SeriesTimerId = seriesTimer.Id;
  1894. }
  1895. existingTimer.SeriesTimerId = seriesTimer.Id;
  1896. _timerProvider.Update(existingTimer);
  1897. }
  1898. }
  1899. SearchForDuplicateShowIds(enabledTimersForSeries);
  1900. if (deleteInvalidTimers)
  1901. {
  1902. var allTimerIds = allTimers
  1903. .Select(i => i.Id)
  1904. .ToList();
  1905. var deleteStatuses = new[]
  1906. {
  1907. RecordingStatus.New
  1908. };
  1909. var deletes = _timerProvider.GetAll()
  1910. .Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
  1911. .Where(i => !allTimerIds.Contains(i.Id, StringComparison.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
  1912. .Where(i => deleteStatuses.Contains(i.Status))
  1913. .ToList();
  1914. foreach (var timer in deletes)
  1915. {
  1916. CancelTimerInternal(timer.Id, false, false);
  1917. }
  1918. }
  1919. }
  1920. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer)
  1921. {
  1922. ArgumentNullException.ThrowIfNull(seriesTimer);
  1923. var query = new InternalItemsQuery
  1924. {
  1925. IncludeItemTypes = new[] { BaseItemKind.LiveTvProgram },
  1926. ExternalSeriesId = seriesTimer.SeriesId,
  1927. DtoOptions = new DtoOptions(true)
  1928. {
  1929. EnableImages = false
  1930. },
  1931. MinEndDate = DateTime.UtcNow
  1932. };
  1933. if (string.IsNullOrEmpty(seriesTimer.SeriesId))
  1934. {
  1935. query.Name = seriesTimer.Name;
  1936. }
  1937. if (!seriesTimer.RecordAnyChannel)
  1938. {
  1939. query.ChannelIds = new[] { _liveTvManager.GetInternalChannelId(Name, seriesTimer.ChannelId) };
  1940. }
  1941. var tempChannelCache = new Dictionary<Guid, LiveTvChannel>();
  1942. return _libraryManager.GetItemList(query).Cast<LiveTvProgram>().Select(i => CreateTimer(i, seriesTimer, tempChannelCache));
  1943. }
  1944. private TimerInfo CreateTimer(LiveTvProgram parent, SeriesTimerInfo seriesTimer, Dictionary<Guid, LiveTvChannel> tempChannelCache)
  1945. {
  1946. string channelId = seriesTimer.RecordAnyChannel ? null : seriesTimer.ChannelId;
  1947. if (string.IsNullOrWhiteSpace(channelId) && !parent.ChannelId.Equals(default))
  1948. {
  1949. if (!tempChannelCache.TryGetValue(parent.ChannelId, out LiveTvChannel channel))
  1950. {
  1951. channel = _libraryManager.GetItemList(
  1952. new InternalItemsQuery
  1953. {
  1954. IncludeItemTypes = new[] { BaseItemKind.LiveTvChannel },
  1955. ItemIds = new[] { parent.ChannelId },
  1956. DtoOptions = new DtoOptions()
  1957. }).FirstOrDefault() as LiveTvChannel;
  1958. if (channel is not null && !string.IsNullOrWhiteSpace(channel.ExternalId))
  1959. {
  1960. tempChannelCache[parent.ChannelId] = channel;
  1961. }
  1962. }
  1963. if (channel is not null || tempChannelCache.TryGetValue(parent.ChannelId, out channel))
  1964. {
  1965. channelId = channel.ExternalId;
  1966. }
  1967. }
  1968. var timer = new TimerInfo
  1969. {
  1970. ChannelId = channelId,
  1971. Id = (seriesTimer.Id + parent.ExternalId).GetMD5().ToString("N", CultureInfo.InvariantCulture),
  1972. StartDate = parent.StartDate,
  1973. EndDate = parent.EndDate.Value,
  1974. ProgramId = parent.ExternalId,
  1975. PrePaddingSeconds = seriesTimer.PrePaddingSeconds,
  1976. PostPaddingSeconds = seriesTimer.PostPaddingSeconds,
  1977. IsPostPaddingRequired = seriesTimer.IsPostPaddingRequired,
  1978. IsPrePaddingRequired = seriesTimer.IsPrePaddingRequired,
  1979. KeepUntil = seriesTimer.KeepUntil,
  1980. Priority = seriesTimer.Priority,
  1981. Name = parent.Name,
  1982. Overview = parent.Overview,
  1983. SeriesId = parent.ExternalSeriesId,
  1984. SeriesTimerId = seriesTimer.Id,
  1985. ShowId = parent.ShowId
  1986. };
  1987. CopyProgramInfoToTimerInfo(parent, timer, tempChannelCache);
  1988. return timer;
  1989. }
  1990. private void CopyProgramInfoToTimerInfo(LiveTvProgram programInfo, TimerInfo timerInfo)
  1991. {
  1992. var tempChannelCache = new Dictionary<Guid, LiveTvChannel>();
  1993. CopyProgramInfoToTimerInfo(programInfo, timerInfo, tempChannelCache);
  1994. }
  1995. private void CopyProgramInfoToTimerInfo(LiveTvProgram programInfo, TimerInfo timerInfo, Dictionary<Guid, LiveTvChannel> tempChannelCache)
  1996. {
  1997. string channelId = null;
  1998. if (!programInfo.ChannelId.Equals(default))
  1999. {
  2000. if (!tempChannelCache.TryGetValue(programInfo.ChannelId, out LiveTvChannel channel))
  2001. {
  2002. channel = _libraryManager.GetItemList(
  2003. new InternalItemsQuery
  2004. {
  2005. IncludeItemTypes = new[] { BaseItemKind.LiveTvChannel },
  2006. ItemIds = new[] { programInfo.ChannelId },
  2007. DtoOptions = new DtoOptions()
  2008. }).FirstOrDefault() as LiveTvChannel;
  2009. if (channel is not null && !string.IsNullOrWhiteSpace(channel.ExternalId))
  2010. {
  2011. tempChannelCache[programInfo.ChannelId] = channel;
  2012. }
  2013. }
  2014. if (channel is not null || tempChannelCache.TryGetValue(programInfo.ChannelId, out channel))
  2015. {
  2016. channelId = channel.ExternalId;
  2017. }
  2018. }
  2019. timerInfo.Name = programInfo.Name;
  2020. timerInfo.StartDate = programInfo.StartDate;
  2021. timerInfo.EndDate = programInfo.EndDate.Value;
  2022. if (!string.IsNullOrWhiteSpace(channelId))
  2023. {
  2024. timerInfo.ChannelId = channelId;
  2025. }
  2026. timerInfo.SeasonNumber = programInfo.ParentIndexNumber;
  2027. timerInfo.EpisodeNumber = programInfo.IndexNumber;
  2028. timerInfo.IsMovie = programInfo.IsMovie;
  2029. timerInfo.ProductionYear = programInfo.ProductionYear;
  2030. timerInfo.EpisodeTitle = programInfo.EpisodeTitle;
  2031. timerInfo.OriginalAirDate = programInfo.PremiereDate;
  2032. timerInfo.IsProgramSeries = programInfo.IsSeries;
  2033. timerInfo.IsSeries = programInfo.IsSeries;
  2034. timerInfo.CommunityRating = programInfo.CommunityRating;
  2035. timerInfo.Overview = programInfo.Overview;
  2036. timerInfo.OfficialRating = programInfo.OfficialRating;
  2037. timerInfo.IsRepeat = programInfo.IsRepeat;
  2038. timerInfo.SeriesId = programInfo.ExternalSeriesId;
  2039. timerInfo.ProviderIds = programInfo.ProviderIds;
  2040. timerInfo.Tags = programInfo.Tags;
  2041. var seriesProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  2042. foreach (var providerId in timerInfo.ProviderIds)
  2043. {
  2044. const string Search = "Series";
  2045. if (providerId.Key.StartsWith(Search, StringComparison.OrdinalIgnoreCase))
  2046. {
  2047. seriesProviderIds[providerId.Key.Substring(Search.Length)] = providerId.Value;
  2048. }
  2049. }
  2050. timerInfo.SeriesProviderIds = seriesProviderIds;
  2051. }
  2052. private bool IsProgramAlreadyInLibrary(TimerInfo program)
  2053. {
  2054. if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle))
  2055. {
  2056. var seriesIds = _libraryManager.GetItemIds(
  2057. new InternalItemsQuery
  2058. {
  2059. IncludeItemTypes = new[] { BaseItemKind.Series },
  2060. Name = program.Name
  2061. }).ToArray();
  2062. if (seriesIds.Length == 0)
  2063. {
  2064. return false;
  2065. }
  2066. if (program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue)
  2067. {
  2068. var result = _libraryManager.GetItemIds(new InternalItemsQuery
  2069. {
  2070. IncludeItemTypes = new[] { BaseItemKind.Episode },
  2071. ParentIndexNumber = program.SeasonNumber.Value,
  2072. IndexNumber = program.EpisodeNumber.Value,
  2073. AncestorIds = seriesIds,
  2074. IsVirtualItem = false,
  2075. Limit = 1
  2076. });
  2077. if (result.Count > 0)
  2078. {
  2079. return true;
  2080. }
  2081. }
  2082. }
  2083. return false;
  2084. }
  2085. /// <inheritdoc />
  2086. public void Dispose()
  2087. {
  2088. Dispose(true);
  2089. GC.SuppressFinalize(this);
  2090. }
  2091. protected virtual void Dispose(bool disposing)
  2092. {
  2093. if (_disposed)
  2094. {
  2095. return;
  2096. }
  2097. if (disposing)
  2098. {
  2099. _recordingDeleteSemaphore.Dispose();
  2100. }
  2101. foreach (var pair in _activeRecordings.ToList())
  2102. {
  2103. pair.Value.CancellationTokenSource.Cancel();
  2104. }
  2105. _disposed = true;
  2106. }
  2107. public IEnumerable<VirtualFolderInfo> GetRecordingFolders()
  2108. {
  2109. var defaultFolder = RecordingPath;
  2110. var defaultName = "Recordings";
  2111. if (Directory.Exists(defaultFolder))
  2112. {
  2113. yield return new VirtualFolderInfo
  2114. {
  2115. Locations = new string[] { defaultFolder },
  2116. Name = defaultName
  2117. };
  2118. }
  2119. var customPath = GetConfiguration().MovieRecordingPath;
  2120. if (!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase) && Directory.Exists(customPath))
  2121. {
  2122. yield return new VirtualFolderInfo
  2123. {
  2124. Locations = new string[] { customPath },
  2125. Name = "Recorded Movies",
  2126. CollectionType = CollectionTypeOptions.Movies
  2127. };
  2128. }
  2129. customPath = GetConfiguration().SeriesRecordingPath;
  2130. if (!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase) && Directory.Exists(customPath))
  2131. {
  2132. yield return new VirtualFolderInfo
  2133. {
  2134. Locations = new string[] { customPath },
  2135. Name = "Recorded Shows",
  2136. CollectionType = CollectionTypeOptions.TvShows
  2137. };
  2138. }
  2139. }
  2140. public async Task<List<TunerHostInfo>> DiscoverTuners(bool newDevicesOnly, CancellationToken cancellationToken)
  2141. {
  2142. var list = new List<TunerHostInfo>();
  2143. var configuredDeviceIds = GetConfiguration().TunerHosts
  2144. .Where(i => !string.IsNullOrWhiteSpace(i.DeviceId))
  2145. .Select(i => i.DeviceId)
  2146. .ToList();
  2147. foreach (var host in _liveTvManager.TunerHosts)
  2148. {
  2149. var discoveredDevices = await DiscoverDevices(host, TunerDiscoveryDurationMs, cancellationToken).ConfigureAwait(false);
  2150. if (newDevicesOnly)
  2151. {
  2152. discoveredDevices = discoveredDevices.Where(d => !configuredDeviceIds.Contains(d.DeviceId, StringComparison.OrdinalIgnoreCase))
  2153. .ToList();
  2154. }
  2155. list.AddRange(discoveredDevices);
  2156. }
  2157. return list;
  2158. }
  2159. public async Task ScanForTunerDeviceChanges(CancellationToken cancellationToken)
  2160. {
  2161. foreach (var host in _liveTvManager.TunerHosts)
  2162. {
  2163. await ScanForTunerDeviceChanges(host, cancellationToken).ConfigureAwait(false);
  2164. }
  2165. }
  2166. private async Task ScanForTunerDeviceChanges(ITunerHost host, CancellationToken cancellationToken)
  2167. {
  2168. var discoveredDevices = await DiscoverDevices(host, TunerDiscoveryDurationMs, cancellationToken).ConfigureAwait(false);
  2169. var configuredDevices = GetConfiguration().TunerHosts
  2170. .Where(i => string.Equals(i.Type, host.Type, StringComparison.OrdinalIgnoreCase))
  2171. .ToList();
  2172. foreach (var device in discoveredDevices)
  2173. {
  2174. var configuredDevice = configuredDevices.FirstOrDefault(i => string.Equals(i.DeviceId, device.DeviceId, StringComparison.OrdinalIgnoreCase));
  2175. if (configuredDevice is not null && !string.Equals(device.Url, configuredDevice.Url, StringComparison.OrdinalIgnoreCase))
  2176. {
  2177. _logger.LogInformation("Tuner url has changed from {PreviousUrl} to {NewUrl}", configuredDevice.Url, device.Url);
  2178. configuredDevice.Url = device.Url;
  2179. await _liveTvManager.SaveTunerHost(configuredDevice).ConfigureAwait(false);
  2180. }
  2181. }
  2182. }
  2183. private async Task<List<TunerHostInfo>> DiscoverDevices(ITunerHost host, int discoveryDurationMs, CancellationToken cancellationToken)
  2184. {
  2185. try
  2186. {
  2187. var discoveredDevices = await host.DiscoverDevices(discoveryDurationMs, cancellationToken).ConfigureAwait(false);
  2188. foreach (var device in discoveredDevices)
  2189. {
  2190. _logger.LogInformation("Discovered tuner device {0} at {1}", host.Name, device.Url);
  2191. }
  2192. return discoveredDevices;
  2193. }
  2194. catch (Exception ex)
  2195. {
  2196. _logger.LogError(ex, "Error discovering tuner devices");
  2197. return new List<TunerHostInfo>();
  2198. }
  2199. }
  2200. }
  2201. }