EmbyTV.cs 100 KB

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