EmbyTV.cs 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668
  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. else
  521. {
  522. throw new ArgumentException("A scheduled recording already exists for this program.");
  523. }
  524. }
  525. info.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
  526. LiveTvProgram programInfo = null;
  527. if (!string.IsNullOrWhiteSpace(info.ProgramId))
  528. {
  529. programInfo = GetProgramInfoFromCache(info);
  530. }
  531. if (programInfo is null)
  532. {
  533. _logger.LogInformation("Unable to find program with Id {0}. Will search using start date", info.ProgramId);
  534. programInfo = GetProgramInfoFromCache(info.ChannelId, info.StartDate);
  535. }
  536. if (programInfo is not null)
  537. {
  538. CopyProgramInfoToTimerInfo(programInfo, info);
  539. }
  540. info.IsManual = true;
  541. _timerProvider.Add(info);
  542. TimerCreated?.Invoke(this, new GenericEventArgs<TimerInfo>(info));
  543. return Task.FromResult(info.Id);
  544. }
  545. public async Task<string> CreateSeriesTimer(SeriesTimerInfo info, CancellationToken cancellationToken)
  546. {
  547. info.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
  548. // populate info.seriesID
  549. var program = GetProgramInfoFromCache(info.ProgramId);
  550. if (program is not null)
  551. {
  552. info.SeriesId = program.ExternalSeriesId;
  553. }
  554. else
  555. {
  556. throw new InvalidOperationException("SeriesId for program not found");
  557. }
  558. // If any timers have already been manually created, make sure they don't get cancelled
  559. var existingTimers = (await GetTimersAsync(CancellationToken.None).ConfigureAwait(false))
  560. .Where(i =>
  561. {
  562. if (string.Equals(i.ProgramId, info.ProgramId, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(info.ProgramId))
  563. {
  564. return true;
  565. }
  566. if (string.Equals(i.SeriesId, info.SeriesId, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(info.SeriesId))
  567. {
  568. return true;
  569. }
  570. return false;
  571. })
  572. .ToList();
  573. _seriesTimerProvider.Add(info);
  574. foreach (var timer in existingTimers)
  575. {
  576. timer.SeriesTimerId = info.Id;
  577. timer.IsManual = true;
  578. _timerProvider.AddOrUpdate(timer, false);
  579. }
  580. UpdateTimersForSeriesTimer(info, true, false);
  581. return info.Id;
  582. }
  583. public Task UpdateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  584. {
  585. var instance = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  586. if (instance is not null)
  587. {
  588. instance.ChannelId = info.ChannelId;
  589. instance.Days = info.Days;
  590. instance.EndDate = info.EndDate;
  591. instance.IsPostPaddingRequired = info.IsPostPaddingRequired;
  592. instance.IsPrePaddingRequired = info.IsPrePaddingRequired;
  593. instance.PostPaddingSeconds = info.PostPaddingSeconds;
  594. instance.PrePaddingSeconds = info.PrePaddingSeconds;
  595. instance.Priority = info.Priority;
  596. instance.RecordAnyChannel = info.RecordAnyChannel;
  597. instance.RecordAnyTime = info.RecordAnyTime;
  598. instance.RecordNewOnly = info.RecordNewOnly;
  599. instance.SkipEpisodesInLibrary = info.SkipEpisodesInLibrary;
  600. instance.KeepUpTo = info.KeepUpTo;
  601. instance.KeepUntil = info.KeepUntil;
  602. instance.StartDate = info.StartDate;
  603. _seriesTimerProvider.Update(instance);
  604. UpdateTimersForSeriesTimer(instance, true, true);
  605. }
  606. return Task.CompletedTask;
  607. }
  608. public Task UpdateTimerAsync(TimerInfo updatedTimer, CancellationToken cancellationToken)
  609. {
  610. var existingTimer = _timerProvider.GetTimer(updatedTimer.Id);
  611. if (existingTimer is null)
  612. {
  613. throw new ResourceNotFoundException();
  614. }
  615. // Only update if not currently active
  616. if (!_activeRecordings.TryGetValue(updatedTimer.Id, out _))
  617. {
  618. existingTimer.PrePaddingSeconds = updatedTimer.PrePaddingSeconds;
  619. existingTimer.PostPaddingSeconds = updatedTimer.PostPaddingSeconds;
  620. existingTimer.IsPostPaddingRequired = updatedTimer.IsPostPaddingRequired;
  621. existingTimer.IsPrePaddingRequired = updatedTimer.IsPrePaddingRequired;
  622. _timerProvider.Update(existingTimer);
  623. }
  624. return Task.CompletedTask;
  625. }
  626. private static void UpdateExistingTimerWithNewMetadata(TimerInfo existingTimer, TimerInfo updatedTimer)
  627. {
  628. // Update the program info but retain the status
  629. existingTimer.ChannelId = updatedTimer.ChannelId;
  630. existingTimer.CommunityRating = updatedTimer.CommunityRating;
  631. existingTimer.EndDate = updatedTimer.EndDate;
  632. existingTimer.EpisodeNumber = updatedTimer.EpisodeNumber;
  633. existingTimer.EpisodeTitle = updatedTimer.EpisodeTitle;
  634. existingTimer.Genres = updatedTimer.Genres;
  635. existingTimer.IsMovie = updatedTimer.IsMovie;
  636. existingTimer.IsSeries = updatedTimer.IsSeries;
  637. existingTimer.Tags = updatedTimer.Tags;
  638. existingTimer.IsProgramSeries = updatedTimer.IsProgramSeries;
  639. existingTimer.IsRepeat = updatedTimer.IsRepeat;
  640. existingTimer.Name = updatedTimer.Name;
  641. existingTimer.OfficialRating = updatedTimer.OfficialRating;
  642. existingTimer.OriginalAirDate = updatedTimer.OriginalAirDate;
  643. existingTimer.Overview = updatedTimer.Overview;
  644. existingTimer.ProductionYear = updatedTimer.ProductionYear;
  645. existingTimer.ProgramId = updatedTimer.ProgramId;
  646. existingTimer.SeasonNumber = updatedTimer.SeasonNumber;
  647. existingTimer.StartDate = updatedTimer.StartDate;
  648. existingTimer.ShowId = updatedTimer.ShowId;
  649. existingTimer.ProviderIds = updatedTimer.ProviderIds;
  650. existingTimer.SeriesProviderIds = updatedTimer.SeriesProviderIds;
  651. }
  652. public string GetActiveRecordingPath(string id)
  653. {
  654. if (_activeRecordings.TryGetValue(id, out var info))
  655. {
  656. return info.Path;
  657. }
  658. return null;
  659. }
  660. public ActiveRecordingInfo GetActiveRecordingInfo(string path)
  661. {
  662. if (string.IsNullOrWhiteSpace(path) || _activeRecordings.IsEmpty)
  663. {
  664. return null;
  665. }
  666. foreach (var (_, recordingInfo) in _activeRecordings)
  667. {
  668. if (string.Equals(recordingInfo.Path, path, StringComparison.Ordinal) && !recordingInfo.CancellationTokenSource.IsCancellationRequested)
  669. {
  670. var timer = recordingInfo.Timer;
  671. if (timer.Status != RecordingStatus.InProgress)
  672. {
  673. return null;
  674. }
  675. return recordingInfo;
  676. }
  677. }
  678. return null;
  679. }
  680. public Task<IEnumerable<TimerInfo>> GetTimersAsync(CancellationToken cancellationToken)
  681. {
  682. var excludeStatues = new List<RecordingStatus>
  683. {
  684. RecordingStatus.Completed
  685. };
  686. var timers = _timerProvider.GetAll()
  687. .Where(i => !excludeStatues.Contains(i.Status));
  688. return Task.FromResult(timers);
  689. }
  690. public Task<SeriesTimerInfo> GetNewTimerDefaultsAsync(CancellationToken cancellationToken, ProgramInfo program = null)
  691. {
  692. var config = GetConfiguration();
  693. var defaults = new SeriesTimerInfo()
  694. {
  695. PostPaddingSeconds = Math.Max(config.PostPaddingSeconds, 0),
  696. PrePaddingSeconds = Math.Max(config.PrePaddingSeconds, 0),
  697. RecordAnyChannel = false,
  698. RecordAnyTime = true,
  699. RecordNewOnly = true,
  700. Days = new List<DayOfWeek>
  701. {
  702. DayOfWeek.Sunday,
  703. DayOfWeek.Monday,
  704. DayOfWeek.Tuesday,
  705. DayOfWeek.Wednesday,
  706. DayOfWeek.Thursday,
  707. DayOfWeek.Friday,
  708. DayOfWeek.Saturday
  709. }
  710. };
  711. if (program is not null)
  712. {
  713. defaults.SeriesId = program.SeriesId;
  714. defaults.ProgramId = program.Id;
  715. defaults.RecordNewOnly = !program.IsRepeat;
  716. defaults.Name = program.Name;
  717. }
  718. defaults.SkipEpisodesInLibrary = defaults.RecordNewOnly;
  719. defaults.KeepUntil = KeepUntil.UntilDeleted;
  720. return Task.FromResult(defaults);
  721. }
  722. public Task<IEnumerable<SeriesTimerInfo>> GetSeriesTimersAsync(CancellationToken cancellationToken)
  723. {
  724. return Task.FromResult((IEnumerable<SeriesTimerInfo>)_seriesTimerProvider.GetAll());
  725. }
  726. private bool IsListingProviderEnabledForTuner(ListingsProviderInfo info, string tunerHostId)
  727. {
  728. if (info.EnableAllTuners)
  729. {
  730. return true;
  731. }
  732. if (string.IsNullOrWhiteSpace(tunerHostId))
  733. {
  734. throw new ArgumentNullException(nameof(tunerHostId));
  735. }
  736. return info.EnabledTuners.Contains(tunerHostId, StringComparison.OrdinalIgnoreCase);
  737. }
  738. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  739. {
  740. var channels = await GetChannelsAsync(true, cancellationToken).ConfigureAwait(false);
  741. var channel = channels.First(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  742. foreach (var provider in GetListingProviders())
  743. {
  744. if (!IsListingProviderEnabledForTuner(provider.Item2, channel.TunerHostId))
  745. {
  746. _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);
  747. continue;
  748. }
  749. _logger.LogDebug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
  750. var epgChannel = await GetEpgChannelFromTunerChannel(provider.Item1, provider.Item2, channel, cancellationToken).ConfigureAwait(false);
  751. if (epgChannel is null)
  752. {
  753. _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);
  754. continue;
  755. }
  756. List<ProgramInfo> programs = (await provider.Item1.GetProgramsAsync(provider.Item2, epgChannel.Id, startDateUtc, endDateUtc, cancellationToken)
  757. .ConfigureAwait(false)).ToList();
  758. // Replace the value that came from the provider with a normalized value
  759. foreach (var program in programs)
  760. {
  761. program.ChannelId = channelId;
  762. program.Id += "_" + channelId;
  763. }
  764. if (programs.Count > 0)
  765. {
  766. return programs;
  767. }
  768. }
  769. return Enumerable.Empty<ProgramInfo>();
  770. }
  771. private List<Tuple<IListingsProvider, ListingsProviderInfo>> GetListingProviders()
  772. {
  773. return GetConfiguration().ListingProviders
  774. .Select(i =>
  775. {
  776. var provider = _liveTvManager.ListingProviders.FirstOrDefault(l => string.Equals(l.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  777. return provider is null ? null : new Tuple<IListingsProvider, ListingsProviderInfo>(provider, i);
  778. })
  779. .Where(i => i is not null)
  780. .ToList();
  781. }
  782. public Task<MediaSourceInfo> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
  783. {
  784. throw new NotImplementedException();
  785. }
  786. public async Task<ILiveStream> GetChannelStreamWithDirectStreamProvider(string channelId, string streamId, List<ILiveStream> currentLiveStreams, CancellationToken cancellationToken)
  787. {
  788. _logger.LogInformation("Streaming Channel {Id}", channelId);
  789. var result = string.IsNullOrEmpty(streamId) ?
  790. null :
  791. currentLiveStreams.FirstOrDefault(i => string.Equals(i.OriginalStreamId, streamId, StringComparison.OrdinalIgnoreCase));
  792. if (result is not null && result.EnableStreamSharing)
  793. {
  794. result.ConsumerCount++;
  795. _logger.LogInformation("Live stream {0} consumer count is now {1}", streamId, result.ConsumerCount);
  796. return result;
  797. }
  798. foreach (var hostInstance in _liveTvManager.TunerHosts)
  799. {
  800. try
  801. {
  802. result = await hostInstance.GetChannelStream(channelId, streamId, currentLiveStreams, cancellationToken).ConfigureAwait(false);
  803. var openedMediaSource = result.MediaSource;
  804. result.OriginalStreamId = streamId;
  805. _logger.LogInformation("Returning mediasource streamId {0}, mediaSource.Id {1}, mediaSource.LiveStreamId {2}", streamId, openedMediaSource.Id, openedMediaSource.LiveStreamId);
  806. return result;
  807. }
  808. catch (FileNotFoundException)
  809. {
  810. }
  811. catch (OperationCanceledException)
  812. {
  813. }
  814. }
  815. throw new ResourceNotFoundException("Tuner not found.");
  816. }
  817. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  818. {
  819. if (string.IsNullOrWhiteSpace(channelId))
  820. {
  821. throw new ArgumentNullException(nameof(channelId));
  822. }
  823. foreach (var hostInstance in _liveTvManager.TunerHosts)
  824. {
  825. try
  826. {
  827. var sources = await hostInstance.GetChannelStreamMediaSources(channelId, cancellationToken).ConfigureAwait(false);
  828. if (sources.Count > 0)
  829. {
  830. return sources;
  831. }
  832. }
  833. catch (NotImplementedException)
  834. {
  835. }
  836. }
  837. throw new NotImplementedException();
  838. }
  839. public async Task<List<MediaSourceInfo>> GetRecordingStreamMediaSources(ActiveRecordingInfo info, CancellationToken cancellationToken)
  840. {
  841. var stream = new MediaSourceInfo
  842. {
  843. EncoderPath = _appHost.GetApiUrlForLocalAccess() + "/LiveTv/LiveRecordings/" + info.Id + "/stream",
  844. EncoderProtocol = MediaProtocol.Http,
  845. Path = info.Path,
  846. Protocol = MediaProtocol.File,
  847. Id = info.Id,
  848. SupportsDirectPlay = false,
  849. SupportsDirectStream = true,
  850. SupportsTranscoding = true,
  851. IsInfiniteStream = true,
  852. RequiresOpening = false,
  853. RequiresClosing = false,
  854. BufferMs = 0,
  855. IgnoreDts = true,
  856. IgnoreIndex = true
  857. };
  858. await new LiveStreamHelper(_mediaEncoder, _logger, _config.CommonApplicationPaths)
  859. .AddMediaInfoWithProbe(stream, false, false, cancellationToken).ConfigureAwait(false);
  860. return new List<MediaSourceInfo>
  861. {
  862. stream
  863. };
  864. }
  865. public Task CloseLiveStream(string id, CancellationToken cancellationToken)
  866. {
  867. return Task.CompletedTask;
  868. }
  869. public Task RecordLiveStream(string id, CancellationToken cancellationToken)
  870. {
  871. return Task.CompletedTask;
  872. }
  873. public Task ResetTuner(string id, CancellationToken cancellationToken)
  874. {
  875. return Task.CompletedTask;
  876. }
  877. private async void OnTimerProviderTimerFired(object sender, GenericEventArgs<TimerInfo> e)
  878. {
  879. var timer = e.Argument;
  880. _logger.LogInformation("Recording timer fired for {0}.", timer.Name);
  881. try
  882. {
  883. var recordingEndDate = timer.EndDate.AddSeconds(timer.PostPaddingSeconds);
  884. if (recordingEndDate <= DateTime.UtcNow)
  885. {
  886. _logger.LogWarning("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
  887. OnTimerOutOfDate(timer);
  888. return;
  889. }
  890. var activeRecordingInfo = new ActiveRecordingInfo
  891. {
  892. CancellationTokenSource = new CancellationTokenSource(),
  893. Timer = timer,
  894. Id = timer.Id
  895. };
  896. if (!_activeRecordings.ContainsKey(timer.Id))
  897. {
  898. await RecordStream(timer, recordingEndDate, activeRecordingInfo).ConfigureAwait(false);
  899. }
  900. else
  901. {
  902. _logger.LogInformation("Skipping RecordStream because it's already in progress.");
  903. }
  904. }
  905. catch (OperationCanceledException)
  906. {
  907. }
  908. catch (Exception ex)
  909. {
  910. _logger.LogError(ex, "Error recording stream");
  911. }
  912. }
  913. private string GetRecordingPath(TimerInfo timer, RemoteSearchResult metadata, out string seriesPath)
  914. {
  915. var recordPath = RecordingPath;
  916. var config = GetConfiguration();
  917. seriesPath = null;
  918. if (timer.IsProgramSeries)
  919. {
  920. var customRecordingPath = config.SeriesRecordingPath;
  921. var allowSubfolder = true;
  922. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  923. {
  924. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  925. recordPath = customRecordingPath;
  926. }
  927. if (allowSubfolder && config.EnableRecordingSubfolders)
  928. {
  929. recordPath = Path.Combine(recordPath, "Series");
  930. }
  931. // trim trailing period from the folder name
  932. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim().TrimEnd('.').Trim();
  933. if (metadata is not null && metadata.ProductionYear.HasValue)
  934. {
  935. folderName += " (" + metadata.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  936. }
  937. // Can't use the year here in the folder name because it is the year of the episode, not the series.
  938. recordPath = Path.Combine(recordPath, folderName);
  939. seriesPath = recordPath;
  940. if (timer.SeasonNumber.HasValue)
  941. {
  942. folderName = string.Format(
  943. CultureInfo.InvariantCulture,
  944. "Season {0}",
  945. timer.SeasonNumber.Value);
  946. recordPath = Path.Combine(recordPath, folderName);
  947. }
  948. }
  949. else if (timer.IsMovie)
  950. {
  951. var customRecordingPath = config.MovieRecordingPath;
  952. var allowSubfolder = true;
  953. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  954. {
  955. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  956. recordPath = customRecordingPath;
  957. }
  958. if (allowSubfolder && config.EnableRecordingSubfolders)
  959. {
  960. recordPath = Path.Combine(recordPath, "Movies");
  961. }
  962. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  963. if (timer.ProductionYear.HasValue)
  964. {
  965. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  966. }
  967. // trim trailing period from the folder name
  968. folderName = folderName.TrimEnd('.').Trim();
  969. recordPath = Path.Combine(recordPath, folderName);
  970. }
  971. else if (timer.IsKids)
  972. {
  973. if (config.EnableRecordingSubfolders)
  974. {
  975. recordPath = Path.Combine(recordPath, "Kids");
  976. }
  977. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  978. if (timer.ProductionYear.HasValue)
  979. {
  980. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  981. }
  982. // trim trailing period from the folder name
  983. folderName = folderName.TrimEnd('.').Trim();
  984. recordPath = Path.Combine(recordPath, folderName);
  985. }
  986. else if (timer.IsSports)
  987. {
  988. if (config.EnableRecordingSubfolders)
  989. {
  990. recordPath = Path.Combine(recordPath, "Sports");
  991. }
  992. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  993. }
  994. else
  995. {
  996. if (config.EnableRecordingSubfolders)
  997. {
  998. recordPath = Path.Combine(recordPath, "Other");
  999. }
  1000. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  1001. }
  1002. var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer)).Trim() + ".ts";
  1003. return Path.Combine(recordPath, recordingFileName);
  1004. }
  1005. private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate, ActiveRecordingInfo activeRecordingInfo)
  1006. {
  1007. ArgumentNullException.ThrowIfNull(timer);
  1008. LiveTvProgram programInfo = null;
  1009. if (!string.IsNullOrWhiteSpace(timer.ProgramId))
  1010. {
  1011. programInfo = GetProgramInfoFromCache(timer);
  1012. }
  1013. if (programInfo is null)
  1014. {
  1015. _logger.LogInformation("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  1016. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  1017. }
  1018. if (programInfo is not null)
  1019. {
  1020. CopyProgramInfoToTimerInfo(programInfo, timer);
  1021. }
  1022. var remoteMetadata = await FetchInternetMetadata(timer, CancellationToken.None).ConfigureAwait(false);
  1023. var recordPath = GetRecordingPath(timer, remoteMetadata, out string seriesPath);
  1024. var channelItem = _liveTvManager.GetLiveTvChannel(timer, this);
  1025. string liveStreamId = null;
  1026. RecordingStatus recordingStatus;
  1027. try
  1028. {
  1029. var allMediaSources = await _mediaSourceManager.GetPlaybackMediaSources(channelItem, null, true, false, CancellationToken.None).ConfigureAwait(false);
  1030. var mediaStreamInfo = allMediaSources[0];
  1031. IDirectStreamProvider directStreamProvider = null;
  1032. if (mediaStreamInfo.RequiresOpening)
  1033. {
  1034. var liveStreamResponse = await _mediaSourceManager.OpenLiveStreamInternal(
  1035. new LiveStreamRequest
  1036. {
  1037. ItemId = channelItem.Id,
  1038. OpenToken = mediaStreamInfo.OpenToken
  1039. },
  1040. CancellationToken.None).ConfigureAwait(false);
  1041. mediaStreamInfo = liveStreamResponse.Item1.MediaSource;
  1042. liveStreamId = mediaStreamInfo.LiveStreamId;
  1043. directStreamProvider = liveStreamResponse.Item2;
  1044. }
  1045. var recorder = GetRecorder(mediaStreamInfo);
  1046. recordPath = recorder.GetOutputPath(mediaStreamInfo, recordPath);
  1047. recordPath = EnsureFileUnique(recordPath, timer.Id);
  1048. _libraryMonitor.ReportFileSystemChangeBeginning(recordPath);
  1049. var duration = recordingEndDate - DateTime.UtcNow;
  1050. _logger.LogInformation("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
  1051. _logger.LogInformation("Writing file to: {Path}", recordPath);
  1052. Action onStarted = async () =>
  1053. {
  1054. activeRecordingInfo.Path = recordPath;
  1055. _activeRecordings.TryAdd(timer.Id, activeRecordingInfo);
  1056. timer.Status = RecordingStatus.InProgress;
  1057. _timerProvider.AddOrUpdate(timer, false);
  1058. await SaveRecordingMetadata(timer, recordPath, seriesPath).ConfigureAwait(false);
  1059. await CreateRecordingFolders().ConfigureAwait(false);
  1060. TriggerRefresh(recordPath);
  1061. await EnforceKeepUpTo(timer, seriesPath).ConfigureAwait(false);
  1062. };
  1063. await recorder.Record(directStreamProvider, mediaStreamInfo, recordPath, duration, onStarted, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false);
  1064. recordingStatus = RecordingStatus.Completed;
  1065. _logger.LogInformation("Recording completed: {RecordPath}", recordPath);
  1066. }
  1067. catch (OperationCanceledException)
  1068. {
  1069. _logger.LogInformation("Recording stopped: {RecordPath}", recordPath);
  1070. recordingStatus = RecordingStatus.Completed;
  1071. }
  1072. catch (Exception ex)
  1073. {
  1074. _logger.LogError(ex, "Error recording to {RecordPath}", recordPath);
  1075. recordingStatus = RecordingStatus.Error;
  1076. }
  1077. if (!string.IsNullOrWhiteSpace(liveStreamId))
  1078. {
  1079. try
  1080. {
  1081. await _mediaSourceManager.CloseLiveStream(liveStreamId).ConfigureAwait(false);
  1082. }
  1083. catch (Exception ex)
  1084. {
  1085. _logger.LogError(ex, "Error closing live stream");
  1086. }
  1087. }
  1088. DeleteFileIfEmpty(recordPath);
  1089. TriggerRefresh(recordPath);
  1090. _libraryMonitor.ReportFileSystemChangeComplete(recordPath, false);
  1091. _activeRecordings.TryRemove(timer.Id, out _);
  1092. if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate && timer.RetryCount < 10)
  1093. {
  1094. const int RetryIntervalSeconds = 60;
  1095. _logger.LogInformation("Retrying recording in {0} seconds.", RetryIntervalSeconds);
  1096. timer.Status = RecordingStatus.New;
  1097. timer.PrePaddingSeconds = 0;
  1098. timer.StartDate = DateTime.UtcNow.AddSeconds(RetryIntervalSeconds);
  1099. timer.RetryCount++;
  1100. _timerProvider.AddOrUpdate(timer);
  1101. }
  1102. else if (File.Exists(recordPath))
  1103. {
  1104. timer.RecordingPath = recordPath;
  1105. timer.Status = RecordingStatus.Completed;
  1106. _timerProvider.AddOrUpdate(timer, false);
  1107. OnSuccessfulRecording(timer, recordPath);
  1108. }
  1109. else
  1110. {
  1111. _timerProvider.Delete(timer);
  1112. }
  1113. }
  1114. private async Task<RemoteSearchResult> FetchInternetMetadata(TimerInfo timer, CancellationToken cancellationToken)
  1115. {
  1116. if (timer.IsSeries)
  1117. {
  1118. if (timer.SeriesProviderIds.Count == 0)
  1119. {
  1120. return null;
  1121. }
  1122. var query = new RemoteSearchQuery<SeriesInfo>()
  1123. {
  1124. SearchInfo = new SeriesInfo
  1125. {
  1126. ProviderIds = timer.SeriesProviderIds,
  1127. Name = timer.Name,
  1128. MetadataCountryCode = _config.Configuration.MetadataCountryCode,
  1129. MetadataLanguage = _config.Configuration.PreferredMetadataLanguage
  1130. }
  1131. };
  1132. var results = await _providerManager.GetRemoteSearchResults<Series, SeriesInfo>(query, cancellationToken).ConfigureAwait(false);
  1133. return results.FirstOrDefault();
  1134. }
  1135. return null;
  1136. }
  1137. private void DeleteFileIfEmpty(string path)
  1138. {
  1139. var file = _fileSystem.GetFileInfo(path);
  1140. if (file.Exists && file.Length == 0)
  1141. {
  1142. try
  1143. {
  1144. _fileSystem.DeleteFile(path);
  1145. }
  1146. catch (Exception ex)
  1147. {
  1148. _logger.LogError(ex, "Error deleting 0-byte failed recording file {Path}", path);
  1149. }
  1150. }
  1151. }
  1152. private void TriggerRefresh(string path)
  1153. {
  1154. _logger.LogInformation("Triggering refresh on {Path}", path);
  1155. var item = GetAffectedBaseItem(Path.GetDirectoryName(path));
  1156. if (item is not null)
  1157. {
  1158. _logger.LogInformation("Refreshing recording parent {Path}", item.Path);
  1159. _providerManager.QueueRefresh(
  1160. item.Id,
  1161. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  1162. {
  1163. RefreshPaths = new string[]
  1164. {
  1165. path,
  1166. Path.GetDirectoryName(path),
  1167. Path.GetDirectoryName(Path.GetDirectoryName(path))
  1168. }
  1169. },
  1170. RefreshPriority.High);
  1171. }
  1172. }
  1173. private BaseItem GetAffectedBaseItem(string path)
  1174. {
  1175. BaseItem item = null;
  1176. var parentPath = Path.GetDirectoryName(path);
  1177. while (item is null && !string.IsNullOrEmpty(path))
  1178. {
  1179. item = _libraryManager.FindByPath(path, null);
  1180. path = Path.GetDirectoryName(path);
  1181. }
  1182. if (item is not null)
  1183. {
  1184. if (item.GetType() == typeof(Folder) && string.Equals(item.Path, parentPath, StringComparison.OrdinalIgnoreCase))
  1185. {
  1186. var parentItem = item.GetParent();
  1187. if (parentItem is not null && parentItem is not AggregateFolder)
  1188. {
  1189. item = parentItem;
  1190. }
  1191. }
  1192. }
  1193. return item;
  1194. }
  1195. private async Task EnforceKeepUpTo(TimerInfo timer, string seriesPath)
  1196. {
  1197. if (string.IsNullOrWhiteSpace(timer.SeriesTimerId))
  1198. {
  1199. return;
  1200. }
  1201. if (string.IsNullOrWhiteSpace(seriesPath))
  1202. {
  1203. return;
  1204. }
  1205. var seriesTimerId = timer.SeriesTimerId;
  1206. var seriesTimer = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, seriesTimerId, StringComparison.OrdinalIgnoreCase));
  1207. if (seriesTimer is null || seriesTimer.KeepUpTo <= 0)
  1208. {
  1209. return;
  1210. }
  1211. if (_disposed)
  1212. {
  1213. return;
  1214. }
  1215. await _recordingDeleteSemaphore.WaitAsync().ConfigureAwait(false);
  1216. try
  1217. {
  1218. if (_disposed)
  1219. {
  1220. return;
  1221. }
  1222. var timersToDelete = _timerProvider.GetAll()
  1223. .Where(i => i.Status == RecordingStatus.Completed && !string.IsNullOrWhiteSpace(i.RecordingPath))
  1224. .Where(i => string.Equals(i.SeriesTimerId, seriesTimerId, StringComparison.OrdinalIgnoreCase))
  1225. .OrderByDescending(i => i.EndDate)
  1226. .Where(i => File.Exists(i.RecordingPath))
  1227. .Skip(seriesTimer.KeepUpTo - 1)
  1228. .ToList();
  1229. DeleteLibraryItemsForTimers(timersToDelete);
  1230. if (_libraryManager.FindByPath(seriesPath, true) is not Folder librarySeries)
  1231. {
  1232. return;
  1233. }
  1234. var episodesToDelete = librarySeries.GetItemList(
  1235. new InternalItemsQuery
  1236. {
  1237. OrderBy = new[] { (ItemSortBy.DateCreated, SortOrder.Descending) },
  1238. IsVirtualItem = false,
  1239. IsFolder = false,
  1240. Recursive = true,
  1241. DtoOptions = new DtoOptions(true)
  1242. })
  1243. .Where(i => i.IsFileProtocol && File.Exists(i.Path))
  1244. .Skip(seriesTimer.KeepUpTo - 1)
  1245. .ToList();
  1246. foreach (var item in episodesToDelete)
  1247. {
  1248. try
  1249. {
  1250. _libraryManager.DeleteItem(
  1251. item,
  1252. new DeleteOptions
  1253. {
  1254. DeleteFileLocation = true
  1255. },
  1256. true);
  1257. }
  1258. catch (Exception ex)
  1259. {
  1260. _logger.LogError(ex, "Error deleting item");
  1261. }
  1262. }
  1263. }
  1264. finally
  1265. {
  1266. _recordingDeleteSemaphore.Release();
  1267. }
  1268. }
  1269. private void DeleteLibraryItemsForTimers(List<TimerInfo> timers)
  1270. {
  1271. foreach (var timer in timers)
  1272. {
  1273. if (_disposed)
  1274. {
  1275. return;
  1276. }
  1277. try
  1278. {
  1279. DeleteLibraryItemForTimer(timer);
  1280. }
  1281. catch (Exception ex)
  1282. {
  1283. _logger.LogError(ex, "Error deleting recording");
  1284. }
  1285. }
  1286. }
  1287. private void DeleteLibraryItemForTimer(TimerInfo timer)
  1288. {
  1289. var libraryItem = _libraryManager.FindByPath(timer.RecordingPath, false);
  1290. if (libraryItem is not null)
  1291. {
  1292. _libraryManager.DeleteItem(
  1293. libraryItem,
  1294. new DeleteOptions
  1295. {
  1296. DeleteFileLocation = true
  1297. },
  1298. true);
  1299. }
  1300. else if (File.Exists(timer.RecordingPath))
  1301. {
  1302. _fileSystem.DeleteFile(timer.RecordingPath);
  1303. }
  1304. _timerProvider.Delete(timer);
  1305. }
  1306. private string EnsureFileUnique(string path, string timerId)
  1307. {
  1308. var originalPath = path;
  1309. var index = 1;
  1310. while (FileExists(path, timerId))
  1311. {
  1312. var parent = Path.GetDirectoryName(originalPath);
  1313. var name = Path.GetFileNameWithoutExtension(originalPath);
  1314. name += " - " + index.ToString(CultureInfo.InvariantCulture);
  1315. path = Path.ChangeExtension(Path.Combine(parent, name), Path.GetExtension(originalPath));
  1316. index++;
  1317. }
  1318. return path;
  1319. }
  1320. private bool FileExists(string path, string timerId)
  1321. {
  1322. if (File.Exists(path))
  1323. {
  1324. return true;
  1325. }
  1326. return _activeRecordings
  1327. .Any(i => string.Equals(i.Value.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.Value.Timer.Id, timerId, StringComparison.OrdinalIgnoreCase));
  1328. }
  1329. private IRecorder GetRecorder(MediaSourceInfo mediaSource)
  1330. {
  1331. if (mediaSource.RequiresLooping || !(mediaSource.Container ?? string.Empty).EndsWith("ts", StringComparison.OrdinalIgnoreCase) || (mediaSource.Protocol != MediaProtocol.File && mediaSource.Protocol != MediaProtocol.Http))
  1332. {
  1333. return new EncodedRecorder(_logger, _mediaEncoder, _config.ApplicationPaths, _config);
  1334. }
  1335. return new DirectRecorder(_logger, _httpClientFactory, _streamHelper);
  1336. }
  1337. private void OnSuccessfulRecording(TimerInfo timer, string path)
  1338. {
  1339. PostProcessRecording(timer, path);
  1340. }
  1341. private void PostProcessRecording(TimerInfo timer, string path)
  1342. {
  1343. var options = GetConfiguration();
  1344. if (string.IsNullOrWhiteSpace(options.RecordingPostProcessor))
  1345. {
  1346. return;
  1347. }
  1348. try
  1349. {
  1350. var process = new Process
  1351. {
  1352. StartInfo = new ProcessStartInfo
  1353. {
  1354. Arguments = GetPostProcessArguments(path, options.RecordingPostProcessorArguments),
  1355. CreateNoWindow = true,
  1356. ErrorDialog = false,
  1357. FileName = options.RecordingPostProcessor,
  1358. WindowStyle = ProcessWindowStyle.Hidden,
  1359. UseShellExecute = false
  1360. },
  1361. EnableRaisingEvents = true
  1362. };
  1363. _logger.LogInformation("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  1364. process.Exited += OnProcessExited;
  1365. process.Start();
  1366. }
  1367. catch (Exception ex)
  1368. {
  1369. _logger.LogError(ex, "Error running recording post processor");
  1370. }
  1371. }
  1372. private static string GetPostProcessArguments(string path, string arguments)
  1373. {
  1374. return arguments.Replace("{path}", path, StringComparison.OrdinalIgnoreCase);
  1375. }
  1376. private void OnProcessExited(object sender, EventArgs e)
  1377. {
  1378. using (var process = (Process)sender)
  1379. {
  1380. _logger.LogInformation("Recording post-processing script completed with exit code {ExitCode}", process.ExitCode);
  1381. }
  1382. }
  1383. private async Task SaveRecordingImage(string recordingPath, LiveTvProgram program, ItemImageInfo image)
  1384. {
  1385. if (!image.IsLocalFile)
  1386. {
  1387. image = await _libraryManager.ConvertImageToLocal(program, image, 0).ConfigureAwait(false);
  1388. }
  1389. string imageSaveFilenameWithoutExtension = image.Type switch
  1390. {
  1391. ImageType.Primary => program.IsSeries ? Path.GetFileNameWithoutExtension(recordingPath) + "-thumb" : "poster",
  1392. ImageType.Logo => "logo",
  1393. ImageType.Thumb => program.IsSeries ? Path.GetFileNameWithoutExtension(recordingPath) + "-thumb" : "landscape",
  1394. ImageType.Backdrop => "fanart",
  1395. _ => null
  1396. };
  1397. if (imageSaveFilenameWithoutExtension is null)
  1398. {
  1399. return;
  1400. }
  1401. var imageSavePath = Path.Combine(Path.GetDirectoryName(recordingPath), imageSaveFilenameWithoutExtension);
  1402. // preserve original image extension
  1403. imageSavePath = Path.ChangeExtension(imageSavePath, Path.GetExtension(image.Path));
  1404. File.Copy(image.Path, imageSavePath, true);
  1405. }
  1406. private async Task SaveRecordingImages(string recordingPath, LiveTvProgram program)
  1407. {
  1408. var image = program.IsSeries ?
  1409. (program.GetImageInfo(ImageType.Thumb, 0) ?? program.GetImageInfo(ImageType.Primary, 0)) :
  1410. (program.GetImageInfo(ImageType.Primary, 0) ?? program.GetImageInfo(ImageType.Thumb, 0));
  1411. if (image is not null)
  1412. {
  1413. try
  1414. {
  1415. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1416. }
  1417. catch (Exception ex)
  1418. {
  1419. _logger.LogError(ex, "Error saving recording image");
  1420. }
  1421. }
  1422. if (!program.IsSeries)
  1423. {
  1424. image = program.GetImageInfo(ImageType.Backdrop, 0);
  1425. if (image is not null)
  1426. {
  1427. try
  1428. {
  1429. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1430. }
  1431. catch (Exception ex)
  1432. {
  1433. _logger.LogError(ex, "Error saving recording image");
  1434. }
  1435. }
  1436. image = program.GetImageInfo(ImageType.Thumb, 0);
  1437. if (image is not null)
  1438. {
  1439. try
  1440. {
  1441. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1442. }
  1443. catch (Exception ex)
  1444. {
  1445. _logger.LogError(ex, "Error saving recording image");
  1446. }
  1447. }
  1448. image = program.GetImageInfo(ImageType.Logo, 0);
  1449. if (image is not null)
  1450. {
  1451. try
  1452. {
  1453. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1454. }
  1455. catch (Exception ex)
  1456. {
  1457. _logger.LogError(ex, "Error saving recording image");
  1458. }
  1459. }
  1460. }
  1461. }
  1462. private async Task SaveRecordingMetadata(TimerInfo timer, string recordingPath, string seriesPath)
  1463. {
  1464. try
  1465. {
  1466. var program = string.IsNullOrWhiteSpace(timer.ProgramId) ? null : _libraryManager.GetItemList(new InternalItemsQuery
  1467. {
  1468. IncludeItemTypes = new[] { BaseItemKind.LiveTvProgram },
  1469. Limit = 1,
  1470. ExternalId = timer.ProgramId,
  1471. DtoOptions = new DtoOptions(true)
  1472. }).FirstOrDefault() as LiveTvProgram;
  1473. // dummy this up
  1474. if (program is null)
  1475. {
  1476. program = new LiveTvProgram
  1477. {
  1478. Name = timer.Name,
  1479. Overview = timer.Overview,
  1480. Genres = timer.Genres,
  1481. CommunityRating = timer.CommunityRating,
  1482. OfficialRating = timer.OfficialRating,
  1483. ProductionYear = timer.ProductionYear,
  1484. PremiereDate = timer.OriginalAirDate,
  1485. IndexNumber = timer.EpisodeNumber,
  1486. ParentIndexNumber = timer.SeasonNumber
  1487. };
  1488. }
  1489. if (timer.IsSports)
  1490. {
  1491. program.AddGenre("Sports");
  1492. }
  1493. if (timer.IsKids)
  1494. {
  1495. program.AddGenre("Kids");
  1496. program.AddGenre("Children");
  1497. }
  1498. if (timer.IsNews)
  1499. {
  1500. program.AddGenre("News");
  1501. }
  1502. var config = GetConfiguration();
  1503. if (config.SaveRecordingNFO)
  1504. {
  1505. if (timer.IsProgramSeries)
  1506. {
  1507. await SaveSeriesNfoAsync(timer, seriesPath).ConfigureAwait(false);
  1508. await SaveVideoNfoAsync(timer, recordingPath, program, false).ConfigureAwait(false);
  1509. }
  1510. else if (!timer.IsMovie || timer.IsSports || timer.IsNews)
  1511. {
  1512. await SaveVideoNfoAsync(timer, recordingPath, program, true).ConfigureAwait(false);
  1513. }
  1514. else
  1515. {
  1516. await SaveVideoNfoAsync(timer, recordingPath, program, false).ConfigureAwait(false);
  1517. }
  1518. }
  1519. if (config.SaveRecordingImages)
  1520. {
  1521. await SaveRecordingImages(recordingPath, program).ConfigureAwait(false);
  1522. }
  1523. }
  1524. catch (Exception ex)
  1525. {
  1526. _logger.LogError(ex, "Error saving nfo");
  1527. }
  1528. }
  1529. private async Task SaveSeriesNfoAsync(TimerInfo timer, string seriesPath)
  1530. {
  1531. var nfoPath = Path.Combine(seriesPath, "tvshow.nfo");
  1532. if (File.Exists(nfoPath))
  1533. {
  1534. return;
  1535. }
  1536. await using (var stream = new FileStream(nfoPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
  1537. {
  1538. var settings = new XmlWriterSettings
  1539. {
  1540. Indent = true,
  1541. Encoding = Encoding.UTF8,
  1542. Async = true
  1543. };
  1544. await using (var writer = XmlWriter.Create(stream, settings))
  1545. {
  1546. await writer.WriteStartDocumentAsync(true).ConfigureAwait(false);
  1547. await writer.WriteStartElementAsync(null, "tvshow", null).ConfigureAwait(false);
  1548. string id;
  1549. if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Tvdb.ToString(), out id))
  1550. {
  1551. await writer.WriteElementStringAsync(null, "id", null, id).ConfigureAwait(false);
  1552. }
  1553. if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Imdb.ToString(), out id))
  1554. {
  1555. await writer.WriteElementStringAsync(null, "imdb_id", null, id).ConfigureAwait(false);
  1556. }
  1557. if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Tmdb.ToString(), out id))
  1558. {
  1559. await writer.WriteElementStringAsync(null, "tmdbid", null, id).ConfigureAwait(false);
  1560. }
  1561. if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Zap2It.ToString(), out id))
  1562. {
  1563. await writer.WriteElementStringAsync(null, "zap2itid", null, id).ConfigureAwait(false);
  1564. }
  1565. if (!string.IsNullOrWhiteSpace(timer.Name))
  1566. {
  1567. await writer.WriteElementStringAsync(null, "title", null, timer.Name).ConfigureAwait(false);
  1568. }
  1569. if (!string.IsNullOrWhiteSpace(timer.OfficialRating))
  1570. {
  1571. await writer.WriteElementStringAsync(null, "mpaa", null, timer.OfficialRating).ConfigureAwait(false);
  1572. }
  1573. foreach (var genre in timer.Genres)
  1574. {
  1575. await writer.WriteElementStringAsync(null, "genre", null, genre).ConfigureAwait(false);
  1576. }
  1577. await writer.WriteEndElementAsync().ConfigureAwait(false);
  1578. await writer.WriteEndDocumentAsync().ConfigureAwait(false);
  1579. }
  1580. }
  1581. }
  1582. private async Task SaveVideoNfoAsync(TimerInfo timer, string recordingPath, BaseItem item, bool lockData)
  1583. {
  1584. var nfoPath = Path.ChangeExtension(recordingPath, ".nfo");
  1585. if (File.Exists(nfoPath))
  1586. {
  1587. return;
  1588. }
  1589. await using (var stream = new FileStream(nfoPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
  1590. {
  1591. var settings = new XmlWriterSettings
  1592. {
  1593. Indent = true,
  1594. Encoding = Encoding.UTF8,
  1595. Async = true
  1596. };
  1597. var options = _config.GetNfoConfiguration();
  1598. var isSeriesEpisode = timer.IsProgramSeries;
  1599. await using (var writer = XmlWriter.Create(stream, settings))
  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);
  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 => IsPersonType(i, PersonType.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 => IsPersonType(i, PersonType.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 static bool IsPersonType(PersonInfo person, string type)
  1753. => string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase)
  1754. || string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase);
  1755. private LiveTvProgram GetProgramInfoFromCache(string programId)
  1756. {
  1757. var query = new InternalItemsQuery
  1758. {
  1759. ItemIds = new[] { _liveTvManager.GetInternalProgramId(programId) },
  1760. Limit = 1,
  1761. DtoOptions = new DtoOptions()
  1762. };
  1763. return _libraryManager.GetItemList(query).Cast<LiveTvProgram>().FirstOrDefault();
  1764. }
  1765. private LiveTvProgram GetProgramInfoFromCache(TimerInfo timer)
  1766. {
  1767. return GetProgramInfoFromCache(timer.ProgramId);
  1768. }
  1769. private LiveTvProgram GetProgramInfoFromCache(string channelId, DateTime startDateUtc)
  1770. {
  1771. var query = new InternalItemsQuery
  1772. {
  1773. IncludeItemTypes = new[] { BaseItemKind.LiveTvProgram },
  1774. Limit = 1,
  1775. DtoOptions = new DtoOptions(true)
  1776. {
  1777. EnableImages = false
  1778. },
  1779. MinStartDate = startDateUtc.AddMinutes(-3),
  1780. MaxStartDate = startDateUtc.AddMinutes(3),
  1781. OrderBy = new[] { (ItemSortBy.StartDate, SortOrder.Ascending) }
  1782. };
  1783. if (!string.IsNullOrWhiteSpace(channelId))
  1784. {
  1785. query.ChannelIds = new[] { _liveTvManager.GetInternalChannelId(Name, channelId) };
  1786. }
  1787. return _libraryManager.GetItemList(query).Cast<LiveTvProgram>().FirstOrDefault();
  1788. }
  1789. private LiveTvOptions GetConfiguration()
  1790. {
  1791. return _config.GetConfiguration<LiveTvOptions>("livetv");
  1792. }
  1793. private bool ShouldCancelTimerForSeriesTimer(SeriesTimerInfo seriesTimer, TimerInfo timer)
  1794. {
  1795. if (timer.IsManual)
  1796. {
  1797. return false;
  1798. }
  1799. if (!seriesTimer.RecordAnyTime
  1800. && Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - timer.StartDate.TimeOfDay.Ticks) >= TimeSpan.FromMinutes(10).Ticks)
  1801. {
  1802. return true;
  1803. }
  1804. if (seriesTimer.RecordNewOnly && timer.IsRepeat)
  1805. {
  1806. return true;
  1807. }
  1808. if (!seriesTimer.RecordAnyChannel
  1809. && !string.Equals(timer.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase))
  1810. {
  1811. return true;
  1812. }
  1813. return seriesTimer.SkipEpisodesInLibrary && IsProgramAlreadyInLibrary(timer);
  1814. }
  1815. private void HandleDuplicateShowIds(List<TimerInfo> timers)
  1816. {
  1817. // sort showings by HD channels first, then by startDate, record earliest showing possible
  1818. foreach (var timer in timers.OrderByDescending(t => _liveTvManager.GetLiveTvChannel(t, this).IsHD).ThenBy(t => t.StartDate).Skip(1))
  1819. {
  1820. timer.Status = RecordingStatus.Cancelled;
  1821. _timerProvider.Update(timer);
  1822. }
  1823. }
  1824. private void SearchForDuplicateShowIds(IEnumerable<TimerInfo> timers)
  1825. {
  1826. var groups = timers.ToLookup(i => i.ShowId ?? string.Empty).ToList();
  1827. foreach (var group in groups)
  1828. {
  1829. if (string.IsNullOrWhiteSpace(group.Key))
  1830. {
  1831. continue;
  1832. }
  1833. var groupTimers = group.ToList();
  1834. if (groupTimers.Count < 2)
  1835. {
  1836. continue;
  1837. }
  1838. // Skip ShowId without SubKey from duplicate removal actions - https://github.com/jellyfin/jellyfin/issues/5856
  1839. if (group.Key.EndsWith("0000", StringComparison.Ordinal))
  1840. {
  1841. continue;
  1842. }
  1843. HandleDuplicateShowIds(groupTimers);
  1844. }
  1845. }
  1846. private void UpdateTimersForSeriesTimer(SeriesTimerInfo seriesTimer, bool updateTimerSettings, bool deleteInvalidTimers)
  1847. {
  1848. var allTimers = GetTimersForSeries(seriesTimer).ToList();
  1849. var enabledTimersForSeries = new List<TimerInfo>();
  1850. foreach (var timer in allTimers)
  1851. {
  1852. var existingTimer = _timerProvider.GetTimer(timer.Id)
  1853. ?? (string.IsNullOrWhiteSpace(timer.ProgramId)
  1854. ? null
  1855. : _timerProvider.GetTimerByProgramId(timer.ProgramId));
  1856. if (existingTimer is null)
  1857. {
  1858. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1859. {
  1860. timer.Status = RecordingStatus.Cancelled;
  1861. }
  1862. else
  1863. {
  1864. enabledTimersForSeries.Add(timer);
  1865. }
  1866. _timerProvider.Add(timer);
  1867. TimerCreated?.Invoke(this, new GenericEventArgs<TimerInfo>(timer));
  1868. }
  1869. // Only update if not currently active - test both new timer and existing in case Id's are different
  1870. // Id's could be different if the timer was created manually prior to series timer creation
  1871. else if (!_activeRecordings.TryGetValue(timer.Id, out _) && !_activeRecordings.TryGetValue(existingTimer.Id, out _))
  1872. {
  1873. UpdateExistingTimerWithNewMetadata(existingTimer, timer);
  1874. // Needed by ShouldCancelTimerForSeriesTimer
  1875. timer.IsManual = existingTimer.IsManual;
  1876. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1877. {
  1878. existingTimer.Status = RecordingStatus.Cancelled;
  1879. }
  1880. else if (!existingTimer.IsManual)
  1881. {
  1882. existingTimer.Status = RecordingStatus.New;
  1883. }
  1884. if (existingTimer.Status != RecordingStatus.Cancelled)
  1885. {
  1886. enabledTimersForSeries.Add(existingTimer);
  1887. }
  1888. if (updateTimerSettings)
  1889. {
  1890. existingTimer.KeepUntil = seriesTimer.KeepUntil;
  1891. existingTimer.IsPostPaddingRequired = seriesTimer.IsPostPaddingRequired;
  1892. existingTimer.IsPrePaddingRequired = seriesTimer.IsPrePaddingRequired;
  1893. existingTimer.PostPaddingSeconds = seriesTimer.PostPaddingSeconds;
  1894. existingTimer.PrePaddingSeconds = seriesTimer.PrePaddingSeconds;
  1895. existingTimer.Priority = seriesTimer.Priority;
  1896. existingTimer.SeriesTimerId = seriesTimer.Id;
  1897. }
  1898. existingTimer.SeriesTimerId = seriesTimer.Id;
  1899. _timerProvider.Update(existingTimer);
  1900. }
  1901. }
  1902. SearchForDuplicateShowIds(enabledTimersForSeries);
  1903. if (deleteInvalidTimers)
  1904. {
  1905. var allTimerIds = allTimers
  1906. .Select(i => i.Id)
  1907. .ToList();
  1908. var deleteStatuses = new[]
  1909. {
  1910. RecordingStatus.New
  1911. };
  1912. var deletes = _timerProvider.GetAll()
  1913. .Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
  1914. .Where(i => !allTimerIds.Contains(i.Id, StringComparison.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
  1915. .Where(i => deleteStatuses.Contains(i.Status))
  1916. .ToList();
  1917. foreach (var timer in deletes)
  1918. {
  1919. CancelTimerInternal(timer.Id, false, false);
  1920. }
  1921. }
  1922. }
  1923. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer)
  1924. {
  1925. ArgumentNullException.ThrowIfNull(seriesTimer);
  1926. var query = new InternalItemsQuery
  1927. {
  1928. IncludeItemTypes = new[] { BaseItemKind.LiveTvProgram },
  1929. ExternalSeriesId = seriesTimer.SeriesId,
  1930. DtoOptions = new DtoOptions(true)
  1931. {
  1932. EnableImages = false
  1933. },
  1934. MinEndDate = DateTime.UtcNow
  1935. };
  1936. if (string.IsNullOrEmpty(seriesTimer.SeriesId))
  1937. {
  1938. query.Name = seriesTimer.Name;
  1939. }
  1940. if (!seriesTimer.RecordAnyChannel)
  1941. {
  1942. query.ChannelIds = new[] { _liveTvManager.GetInternalChannelId(Name, seriesTimer.ChannelId) };
  1943. }
  1944. var tempChannelCache = new Dictionary<Guid, LiveTvChannel>();
  1945. return _libraryManager.GetItemList(query).Cast<LiveTvProgram>().Select(i => CreateTimer(i, seriesTimer, tempChannelCache));
  1946. }
  1947. private TimerInfo CreateTimer(LiveTvProgram parent, SeriesTimerInfo seriesTimer, Dictionary<Guid, LiveTvChannel> tempChannelCache)
  1948. {
  1949. string channelId = seriesTimer.RecordAnyChannel ? null : seriesTimer.ChannelId;
  1950. if (string.IsNullOrWhiteSpace(channelId) && !parent.ChannelId.Equals(default))
  1951. {
  1952. if (!tempChannelCache.TryGetValue(parent.ChannelId, out LiveTvChannel channel))
  1953. {
  1954. channel = _libraryManager.GetItemList(
  1955. new InternalItemsQuery
  1956. {
  1957. IncludeItemTypes = new[] { BaseItemKind.LiveTvChannel },
  1958. ItemIds = new[] { parent.ChannelId },
  1959. DtoOptions = new DtoOptions()
  1960. }).FirstOrDefault() as LiveTvChannel;
  1961. if (channel is not null && !string.IsNullOrWhiteSpace(channel.ExternalId))
  1962. {
  1963. tempChannelCache[parent.ChannelId] = channel;
  1964. }
  1965. }
  1966. if (channel is not null || tempChannelCache.TryGetValue(parent.ChannelId, out channel))
  1967. {
  1968. channelId = channel.ExternalId;
  1969. }
  1970. }
  1971. var timer = new TimerInfo
  1972. {
  1973. ChannelId = channelId,
  1974. Id = (seriesTimer.Id + parent.ExternalId).GetMD5().ToString("N", CultureInfo.InvariantCulture),
  1975. StartDate = parent.StartDate,
  1976. EndDate = parent.EndDate.Value,
  1977. ProgramId = parent.ExternalId,
  1978. PrePaddingSeconds = seriesTimer.PrePaddingSeconds,
  1979. PostPaddingSeconds = seriesTimer.PostPaddingSeconds,
  1980. IsPostPaddingRequired = seriesTimer.IsPostPaddingRequired,
  1981. IsPrePaddingRequired = seriesTimer.IsPrePaddingRequired,
  1982. KeepUntil = seriesTimer.KeepUntil,
  1983. Priority = seriesTimer.Priority,
  1984. Name = parent.Name,
  1985. Overview = parent.Overview,
  1986. SeriesId = parent.ExternalSeriesId,
  1987. SeriesTimerId = seriesTimer.Id,
  1988. ShowId = parent.ShowId
  1989. };
  1990. CopyProgramInfoToTimerInfo(parent, timer, tempChannelCache);
  1991. return timer;
  1992. }
  1993. private void CopyProgramInfoToTimerInfo(LiveTvProgram programInfo, TimerInfo timerInfo)
  1994. {
  1995. var tempChannelCache = new Dictionary<Guid, LiveTvChannel>();
  1996. CopyProgramInfoToTimerInfo(programInfo, timerInfo, tempChannelCache);
  1997. }
  1998. private void CopyProgramInfoToTimerInfo(LiveTvProgram programInfo, TimerInfo timerInfo, Dictionary<Guid, LiveTvChannel> tempChannelCache)
  1999. {
  2000. string channelId = null;
  2001. if (!programInfo.ChannelId.Equals(default))
  2002. {
  2003. if (!tempChannelCache.TryGetValue(programInfo.ChannelId, out LiveTvChannel channel))
  2004. {
  2005. channel = _libraryManager.GetItemList(
  2006. new InternalItemsQuery
  2007. {
  2008. IncludeItemTypes = new[] { BaseItemKind.LiveTvChannel },
  2009. ItemIds = new[] { programInfo.ChannelId },
  2010. DtoOptions = new DtoOptions()
  2011. }).FirstOrDefault() as LiveTvChannel;
  2012. if (channel is not null && !string.IsNullOrWhiteSpace(channel.ExternalId))
  2013. {
  2014. tempChannelCache[programInfo.ChannelId] = channel;
  2015. }
  2016. }
  2017. if (channel is not null || tempChannelCache.TryGetValue(programInfo.ChannelId, out channel))
  2018. {
  2019. channelId = channel.ExternalId;
  2020. }
  2021. }
  2022. timerInfo.Name = programInfo.Name;
  2023. timerInfo.StartDate = programInfo.StartDate;
  2024. timerInfo.EndDate = programInfo.EndDate.Value;
  2025. if (!string.IsNullOrWhiteSpace(channelId))
  2026. {
  2027. timerInfo.ChannelId = channelId;
  2028. }
  2029. timerInfo.SeasonNumber = programInfo.ParentIndexNumber;
  2030. timerInfo.EpisodeNumber = programInfo.IndexNumber;
  2031. timerInfo.IsMovie = programInfo.IsMovie;
  2032. timerInfo.ProductionYear = programInfo.ProductionYear;
  2033. timerInfo.EpisodeTitle = programInfo.EpisodeTitle;
  2034. timerInfo.OriginalAirDate = programInfo.PremiereDate;
  2035. timerInfo.IsProgramSeries = programInfo.IsSeries;
  2036. timerInfo.IsSeries = programInfo.IsSeries;
  2037. timerInfo.CommunityRating = programInfo.CommunityRating;
  2038. timerInfo.Overview = programInfo.Overview;
  2039. timerInfo.OfficialRating = programInfo.OfficialRating;
  2040. timerInfo.IsRepeat = programInfo.IsRepeat;
  2041. timerInfo.SeriesId = programInfo.ExternalSeriesId;
  2042. timerInfo.ProviderIds = programInfo.ProviderIds;
  2043. timerInfo.Tags = programInfo.Tags;
  2044. var seriesProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  2045. foreach (var providerId in timerInfo.ProviderIds)
  2046. {
  2047. const string Search = "Series";
  2048. if (providerId.Key.StartsWith(Search, StringComparison.OrdinalIgnoreCase))
  2049. {
  2050. seriesProviderIds[providerId.Key.Substring(Search.Length)] = providerId.Value;
  2051. }
  2052. }
  2053. timerInfo.SeriesProviderIds = seriesProviderIds;
  2054. }
  2055. private bool IsProgramAlreadyInLibrary(TimerInfo program)
  2056. {
  2057. if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle))
  2058. {
  2059. var seriesIds = _libraryManager.GetItemIds(
  2060. new InternalItemsQuery
  2061. {
  2062. IncludeItemTypes = new[] { BaseItemKind.Series },
  2063. Name = program.Name
  2064. }).ToArray();
  2065. if (seriesIds.Length == 0)
  2066. {
  2067. return false;
  2068. }
  2069. if (program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue)
  2070. {
  2071. var result = _libraryManager.GetItemIds(new InternalItemsQuery
  2072. {
  2073. IncludeItemTypes = new[] { BaseItemKind.Episode },
  2074. ParentIndexNumber = program.SeasonNumber.Value,
  2075. IndexNumber = program.EpisodeNumber.Value,
  2076. AncestorIds = seriesIds,
  2077. IsVirtualItem = false,
  2078. Limit = 1
  2079. });
  2080. if (result.Count > 0)
  2081. {
  2082. return true;
  2083. }
  2084. }
  2085. }
  2086. return false;
  2087. }
  2088. /// <inheritdoc />
  2089. public void Dispose()
  2090. {
  2091. Dispose(true);
  2092. GC.SuppressFinalize(this);
  2093. }
  2094. protected virtual void Dispose(bool disposing)
  2095. {
  2096. if (_disposed)
  2097. {
  2098. return;
  2099. }
  2100. if (disposing)
  2101. {
  2102. _recordingDeleteSemaphore.Dispose();
  2103. }
  2104. foreach (var pair in _activeRecordings.ToList())
  2105. {
  2106. pair.Value.CancellationTokenSource.Cancel();
  2107. }
  2108. _disposed = true;
  2109. }
  2110. public IEnumerable<VirtualFolderInfo> GetRecordingFolders()
  2111. {
  2112. var defaultFolder = RecordingPath;
  2113. var defaultName = "Recordings";
  2114. if (Directory.Exists(defaultFolder))
  2115. {
  2116. yield return new VirtualFolderInfo
  2117. {
  2118. Locations = new string[] { defaultFolder },
  2119. Name = defaultName
  2120. };
  2121. }
  2122. var customPath = GetConfiguration().MovieRecordingPath;
  2123. if (!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase) && Directory.Exists(customPath))
  2124. {
  2125. yield return new VirtualFolderInfo
  2126. {
  2127. Locations = new string[] { customPath },
  2128. Name = "Recorded Movies",
  2129. CollectionType = CollectionTypeOptions.Movies
  2130. };
  2131. }
  2132. customPath = GetConfiguration().SeriesRecordingPath;
  2133. if (!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase) && Directory.Exists(customPath))
  2134. {
  2135. yield return new VirtualFolderInfo
  2136. {
  2137. Locations = new string[] { customPath },
  2138. Name = "Recorded Shows",
  2139. CollectionType = CollectionTypeOptions.TvShows
  2140. };
  2141. }
  2142. }
  2143. public async Task<List<TunerHostInfo>> DiscoverTuners(bool newDevicesOnly, CancellationToken cancellationToken)
  2144. {
  2145. var list = new List<TunerHostInfo>();
  2146. var configuredDeviceIds = GetConfiguration().TunerHosts
  2147. .Where(i => !string.IsNullOrWhiteSpace(i.DeviceId))
  2148. .Select(i => i.DeviceId)
  2149. .ToList();
  2150. foreach (var host in _liveTvManager.TunerHosts)
  2151. {
  2152. var discoveredDevices = await DiscoverDevices(host, TunerDiscoveryDurationMs, cancellationToken).ConfigureAwait(false);
  2153. if (newDevicesOnly)
  2154. {
  2155. discoveredDevices = discoveredDevices.Where(d => !configuredDeviceIds.Contains(d.DeviceId, StringComparison.OrdinalIgnoreCase))
  2156. .ToList();
  2157. }
  2158. list.AddRange(discoveredDevices);
  2159. }
  2160. return list;
  2161. }
  2162. public async Task ScanForTunerDeviceChanges(CancellationToken cancellationToken)
  2163. {
  2164. foreach (var host in _liveTvManager.TunerHosts)
  2165. {
  2166. await ScanForTunerDeviceChanges(host, cancellationToken).ConfigureAwait(false);
  2167. }
  2168. }
  2169. private async Task ScanForTunerDeviceChanges(ITunerHost host, CancellationToken cancellationToken)
  2170. {
  2171. var discoveredDevices = await DiscoverDevices(host, TunerDiscoveryDurationMs, cancellationToken).ConfigureAwait(false);
  2172. var configuredDevices = GetConfiguration().TunerHosts
  2173. .Where(i => string.Equals(i.Type, host.Type, StringComparison.OrdinalIgnoreCase))
  2174. .ToList();
  2175. foreach (var device in discoveredDevices)
  2176. {
  2177. var configuredDevice = configuredDevices.FirstOrDefault(i => string.Equals(i.DeviceId, device.DeviceId, StringComparison.OrdinalIgnoreCase));
  2178. if (configuredDevice is not null && !string.Equals(device.Url, configuredDevice.Url, StringComparison.OrdinalIgnoreCase))
  2179. {
  2180. _logger.LogInformation("Tuner url has changed from {PreviousUrl} to {NewUrl}", configuredDevice.Url, device.Url);
  2181. configuredDevice.Url = device.Url;
  2182. await _liveTvManager.SaveTunerHost(configuredDevice).ConfigureAwait(false);
  2183. }
  2184. }
  2185. }
  2186. private async Task<List<TunerHostInfo>> DiscoverDevices(ITunerHost host, int discoveryDurationMs, CancellationToken cancellationToken)
  2187. {
  2188. try
  2189. {
  2190. var discoveredDevices = await host.DiscoverDevices(discoveryDurationMs, cancellationToken).ConfigureAwait(false);
  2191. foreach (var device in discoveredDevices)
  2192. {
  2193. _logger.LogInformation("Discovered tuner device {0} at {1}", host.Name, device.Url);
  2194. }
  2195. return discoveredDevices;
  2196. }
  2197. catch (Exception ex)
  2198. {
  2199. _logger.LogError(ex, "Error discovering tuner devices");
  2200. return new List<TunerHostInfo>();
  2201. }
  2202. }
  2203. }
  2204. }