EmbyTV.cs 100 KB

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