EmbyTV.cs 100 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net.Http;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using System.Xml;
  15. using Emby.Server.Implementations.Library;
  16. using Jellyfin.Data.Enums;
  17. using Jellyfin.Data.Events;
  18. using MediaBrowser.Common.Configuration;
  19. using MediaBrowser.Common.Extensions;
  20. using MediaBrowser.Common.Progress;
  21. using MediaBrowser.Controller;
  22. using MediaBrowser.Controller.Configuration;
  23. using MediaBrowser.Controller.Dto;
  24. using MediaBrowser.Controller.Entities;
  25. using MediaBrowser.Controller.Entities.TV;
  26. using MediaBrowser.Controller.Library;
  27. using MediaBrowser.Controller.LiveTv;
  28. using MediaBrowser.Controller.MediaEncoding;
  29. using MediaBrowser.Controller.Providers;
  30. using MediaBrowser.Model.Configuration;
  31. using MediaBrowser.Model.Dto;
  32. using MediaBrowser.Model.Entities;
  33. using MediaBrowser.Model.IO;
  34. using MediaBrowser.Model.LiveTv;
  35. using MediaBrowser.Model.MediaInfo;
  36. using MediaBrowser.Model.Providers;
  37. using MediaBrowser.Model.Querying;
  38. using Microsoft.Extensions.Logging;
  39. namespace Emby.Server.Implementations.LiveTv.EmbyTV
  40. {
  41. public class EmbyTV : ILiveTvService, ISupportsDirectStreamProvider, ISupportsNewTimerIds, IDisposable
  42. {
  43. public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
  44. private const int TunerDiscoveryDurationMs = 3000;
  45. private readonly IServerApplicationHost _appHost;
  46. private readonly ILogger<EmbyTV> _logger;
  47. private readonly IHttpClientFactory _httpClientFactory;
  48. private readonly IServerConfigurationManager _config;
  49. private readonly ItemDataProvider<SeriesTimerInfo> _seriesTimerProvider;
  50. private readonly TimerManager _timerProvider;
  51. private readonly LiveTvManager _liveTvManager;
  52. private readonly IFileSystem _fileSystem;
  53. private readonly ILibraryMonitor _libraryMonitor;
  54. private readonly ILibraryManager _libraryManager;
  55. private readonly IProviderManager _providerManager;
  56. private readonly IMediaEncoder _mediaEncoder;
  57. private readonly IMediaSourceManager _mediaSourceManager;
  58. private readonly IStreamHelper _streamHelper;
  59. private readonly ConcurrentDictionary<string, ActiveRecordingInfo> _activeRecordings =
  60. new ConcurrentDictionary<string, ActiveRecordingInfo>(StringComparer.OrdinalIgnoreCase);
  61. private readonly ConcurrentDictionary<string, EpgChannelData> _epgChannels =
  62. new ConcurrentDictionary<string, EpgChannelData>(StringComparer.OrdinalIgnoreCase);
  63. private readonly SemaphoreSlim _recordingDeleteSemaphore = new SemaphoreSlim(1, 1);
  64. private bool _disposed = false;
  65. public EmbyTV(
  66. IServerApplicationHost appHost,
  67. IStreamHelper streamHelper,
  68. IMediaSourceManager mediaSourceManager,
  69. ILogger<EmbyTV> logger,
  70. IHttpClientFactory httpClientFactory,
  71. IServerConfigurationManager config,
  72. ILiveTvManager liveTvManager,
  73. IFileSystem fileSystem,
  74. ILibraryManager libraryManager,
  75. ILibraryMonitor libraryMonitor,
  76. IProviderManager providerManager,
  77. IMediaEncoder mediaEncoder)
  78. {
  79. Current = this;
  80. _appHost = appHost;
  81. _logger = logger;
  82. _httpClientFactory = httpClientFactory;
  83. _config = config;
  84. _fileSystem = fileSystem;
  85. _libraryManager = libraryManager;
  86. _libraryMonitor = libraryMonitor;
  87. _providerManager = providerManager;
  88. _mediaEncoder = mediaEncoder;
  89. _liveTvManager = (LiveTvManager)liveTvManager;
  90. _mediaSourceManager = mediaSourceManager;
  91. _streamHelper = streamHelper;
  92. _seriesTimerProvider = new SeriesTimerManager(_logger, Path.Combine(DataPath, "seriestimers.json"));
  93. _timerProvider = new TimerManager(_logger, Path.Combine(DataPath, "timers.json"));
  94. _timerProvider.TimerFired += OnTimerProviderTimerFired;
  95. _config.NamedConfigurationUpdated += OnNamedConfigurationUpdated;
  96. }
  97. public event EventHandler<GenericEventArgs<TimerInfo>> TimerCreated;
  98. public event EventHandler<GenericEventArgs<string>> TimerCancelled;
  99. public static EmbyTV Current { get; private set; }
  100. /// <inheritdoc />
  101. public string Name => "Emby";
  102. public string DataPath => Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv");
  103. /// <inheritdoc />
  104. public string HomePageUrl => "https://github.com/jellyfin/jellyfin";
  105. private string DefaultRecordingPath => Path.Combine(DataPath, "recordings");
  106. private string RecordingPath
  107. {
  108. get
  109. {
  110. var path = GetConfiguration().RecordingPath;
  111. return string.IsNullOrWhiteSpace(path)
  112. ? DefaultRecordingPath
  113. : path;
  114. }
  115. }
  116. private async void OnNamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
  117. {
  118. if (string.Equals(e.Key, "livetv", StringComparison.OrdinalIgnoreCase))
  119. {
  120. await CreateRecordingFolders().ConfigureAwait(false);
  121. }
  122. }
  123. public Task Start()
  124. {
  125. _timerProvider.RestartTimers();
  126. return CreateRecordingFolders();
  127. }
  128. internal async Task CreateRecordingFolders()
  129. {
  130. try
  131. {
  132. var recordingFolders = GetRecordingFolders().ToArray();
  133. var virtualFolders = _libraryManager.GetVirtualFolders()
  134. .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) || _activeRecordings.IsEmpty)
  664. {
  665. return null;
  666. }
  667. foreach (var (_, recordingInfo) in _activeRecordings)
  668. {
  669. if (string.Equals(recordingInfo.Path, path, StringComparison.Ordinal) && !recordingInfo.CancellationTokenSource.IsCancellationRequested)
  670. {
  671. var timer = recordingInfo.Timer;
  672. if (timer.Status != RecordingStatus.InProgress)
  673. {
  674. return null;
  675. }
  676. return recordingInfo;
  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. .Any(i => string.Equals(i.Value.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.Value.Timer.Id, timerId, StringComparison.OrdinalIgnoreCase));
  1337. }
  1338. private IRecorder GetRecorder(MediaSourceInfo mediaSource)
  1339. {
  1340. if (mediaSource.RequiresLooping || !(mediaSource.Container ?? string.Empty).EndsWith("ts", StringComparison.OrdinalIgnoreCase) || (mediaSource.Protocol != MediaProtocol.File && mediaSource.Protocol != MediaProtocol.Http))
  1341. {
  1342. return new EncodedRecorder(_logger, _mediaEncoder, _config.ApplicationPaths, _config);
  1343. }
  1344. return new DirectRecorder(_logger, _httpClientFactory, _streamHelper);
  1345. }
  1346. private void OnSuccessfulRecording(TimerInfo timer, string path)
  1347. {
  1348. PostProcessRecording(timer, path);
  1349. }
  1350. private void PostProcessRecording(TimerInfo timer, string path)
  1351. {
  1352. var options = GetConfiguration();
  1353. if (string.IsNullOrWhiteSpace(options.RecordingPostProcessor))
  1354. {
  1355. return;
  1356. }
  1357. try
  1358. {
  1359. var process = new Process
  1360. {
  1361. StartInfo = new ProcessStartInfo
  1362. {
  1363. Arguments = GetPostProcessArguments(path, options.RecordingPostProcessorArguments),
  1364. CreateNoWindow = true,
  1365. ErrorDialog = false,
  1366. FileName = options.RecordingPostProcessor,
  1367. WindowStyle = ProcessWindowStyle.Hidden,
  1368. UseShellExecute = false
  1369. },
  1370. EnableRaisingEvents = true
  1371. };
  1372. _logger.LogInformation("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  1373. process.Exited += Process_Exited;
  1374. process.Start();
  1375. }
  1376. catch (Exception ex)
  1377. {
  1378. _logger.LogError(ex, "Error running recording post processor");
  1379. }
  1380. }
  1381. private static string GetPostProcessArguments(string path, string arguments)
  1382. {
  1383. return arguments.Replace("{path}", path, StringComparison.OrdinalIgnoreCase);
  1384. }
  1385. private void Process_Exited(object sender, EventArgs e)
  1386. {
  1387. using (var process = (Process)sender)
  1388. {
  1389. _logger.LogInformation("Recording post-processing script completed with exit code {ExitCode}", process.ExitCode);
  1390. }
  1391. }
  1392. private async Task SaveRecordingImage(string recordingPath, LiveTvProgram program, ItemImageInfo image)
  1393. {
  1394. if (!image.IsLocalFile)
  1395. {
  1396. image = await _libraryManager.ConvertImageToLocal(program, image, 0).ConfigureAwait(false);
  1397. }
  1398. string imageSaveFilenameWithoutExtension = image.Type switch
  1399. {
  1400. ImageType.Primary => program.IsSeries ? Path.GetFileNameWithoutExtension(recordingPath) + "-thumb" : "poster",
  1401. ImageType.Logo => "logo",
  1402. ImageType.Thumb => program.IsSeries ? Path.GetFileNameWithoutExtension(recordingPath) + "-thumb" : "landscape",
  1403. ImageType.Backdrop => "fanart",
  1404. _ => null
  1405. };
  1406. if (imageSaveFilenameWithoutExtension == null)
  1407. {
  1408. return;
  1409. }
  1410. var imageSavePath = Path.Combine(Path.GetDirectoryName(recordingPath), imageSaveFilenameWithoutExtension);
  1411. // preserve original image extension
  1412. imageSavePath = Path.ChangeExtension(imageSavePath, Path.GetExtension(image.Path));
  1413. File.Copy(image.Path, imageSavePath, true);
  1414. }
  1415. private async Task SaveRecordingImages(string recordingPath, LiveTvProgram program)
  1416. {
  1417. var image = program.IsSeries ?
  1418. (program.GetImageInfo(ImageType.Thumb, 0) ?? program.GetImageInfo(ImageType.Primary, 0)) :
  1419. (program.GetImageInfo(ImageType.Primary, 0) ?? program.GetImageInfo(ImageType.Thumb, 0));
  1420. if (image != null)
  1421. {
  1422. try
  1423. {
  1424. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1425. }
  1426. catch (Exception ex)
  1427. {
  1428. _logger.LogError(ex, "Error saving recording image");
  1429. }
  1430. }
  1431. if (!program.IsSeries)
  1432. {
  1433. image = program.GetImageInfo(ImageType.Backdrop, 0);
  1434. if (image != null)
  1435. {
  1436. try
  1437. {
  1438. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1439. }
  1440. catch (Exception ex)
  1441. {
  1442. _logger.LogError(ex, "Error saving recording image");
  1443. }
  1444. }
  1445. image = program.GetImageInfo(ImageType.Thumb, 0);
  1446. if (image != null)
  1447. {
  1448. try
  1449. {
  1450. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1451. }
  1452. catch (Exception ex)
  1453. {
  1454. _logger.LogError(ex, "Error saving recording image");
  1455. }
  1456. }
  1457. image = program.GetImageInfo(ImageType.Logo, 0);
  1458. if (image != null)
  1459. {
  1460. try
  1461. {
  1462. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1463. }
  1464. catch (Exception ex)
  1465. {
  1466. _logger.LogError(ex, "Error saving recording image");
  1467. }
  1468. }
  1469. }
  1470. }
  1471. private async Task SaveRecordingMetadata(TimerInfo timer, string recordingPath, string seriesPath)
  1472. {
  1473. try
  1474. {
  1475. var program = string.IsNullOrWhiteSpace(timer.ProgramId) ? null : _libraryManager.GetItemList(new InternalItemsQuery
  1476. {
  1477. IncludeItemTypes = new[] { nameof(LiveTvProgram) },
  1478. Limit = 1,
  1479. ExternalId = timer.ProgramId,
  1480. DtoOptions = new DtoOptions(true)
  1481. }).FirstOrDefault() as LiveTvProgram;
  1482. // dummy this up
  1483. if (program == null)
  1484. {
  1485. program = new LiveTvProgram
  1486. {
  1487. Name = timer.Name,
  1488. Overview = timer.Overview,
  1489. Genres = timer.Genres,
  1490. CommunityRating = timer.CommunityRating,
  1491. OfficialRating = timer.OfficialRating,
  1492. ProductionYear = timer.ProductionYear,
  1493. PremiereDate = timer.OriginalAirDate,
  1494. IndexNumber = timer.EpisodeNumber,
  1495. ParentIndexNumber = timer.SeasonNumber
  1496. };
  1497. }
  1498. if (timer.IsSports)
  1499. {
  1500. program.AddGenre("Sports");
  1501. }
  1502. if (timer.IsKids)
  1503. {
  1504. program.AddGenre("Kids");
  1505. program.AddGenre("Children");
  1506. }
  1507. if (timer.IsNews)
  1508. {
  1509. program.AddGenre("News");
  1510. }
  1511. if (timer.IsProgramSeries)
  1512. {
  1513. SaveSeriesNfo(timer, seriesPath);
  1514. SaveVideoNfo(timer, recordingPath, program, false);
  1515. }
  1516. else if (!timer.IsMovie || timer.IsSports || timer.IsNews)
  1517. {
  1518. SaveVideoNfo(timer, recordingPath, program, true);
  1519. }
  1520. else
  1521. {
  1522. SaveVideoNfo(timer, recordingPath, program, false);
  1523. }
  1524. await SaveRecordingImages(recordingPath, program).ConfigureAwait(false);
  1525. }
  1526. catch (Exception ex)
  1527. {
  1528. _logger.LogError(ex, "Error saving nfo");
  1529. }
  1530. }
  1531. private void SaveSeriesNfo(TimerInfo timer, string seriesPath)
  1532. {
  1533. var nfoPath = Path.Combine(seriesPath, "tvshow.nfo");
  1534. if (File.Exists(nfoPath))
  1535. {
  1536. return;
  1537. }
  1538. // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 .
  1539. using (var stream = new FileStream(nfoPath, FileMode.Create, FileAccess.Write, FileShare.None))
  1540. {
  1541. var settings = new XmlWriterSettings
  1542. {
  1543. Indent = true,
  1544. Encoding = Encoding.UTF8,
  1545. CloseOutput = false
  1546. };
  1547. using (var writer = XmlWriter.Create(stream, settings))
  1548. {
  1549. writer.WriteStartDocument(true);
  1550. writer.WriteStartElement("tvshow");
  1551. string id;
  1552. if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Tvdb.ToString(), out id))
  1553. {
  1554. writer.WriteElementString("id", id);
  1555. }
  1556. if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Imdb.ToString(), out id))
  1557. {
  1558. writer.WriteElementString("imdb_id", id);
  1559. }
  1560. if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Tmdb.ToString(), out id))
  1561. {
  1562. writer.WriteElementString("tmdbid", id);
  1563. }
  1564. if (timer.SeriesProviderIds.TryGetValue(MetadataProvider.Zap2It.ToString(), out id))
  1565. {
  1566. writer.WriteElementString("zap2itid", id);
  1567. }
  1568. if (!string.IsNullOrWhiteSpace(timer.Name))
  1569. {
  1570. writer.WriteElementString("title", timer.Name);
  1571. }
  1572. if (!string.IsNullOrWhiteSpace(timer.OfficialRating))
  1573. {
  1574. writer.WriteElementString("mpaa", timer.OfficialRating);
  1575. }
  1576. foreach (var genre in timer.Genres)
  1577. {
  1578. writer.WriteElementString("genre", genre);
  1579. }
  1580. writer.WriteEndElement();
  1581. writer.WriteEndDocument();
  1582. }
  1583. }
  1584. }
  1585. private void SaveVideoNfo(TimerInfo timer, string recordingPath, BaseItem item, bool lockData)
  1586. {
  1587. var nfoPath = Path.ChangeExtension(recordingPath, ".nfo");
  1588. if (File.Exists(nfoPath))
  1589. {
  1590. return;
  1591. }
  1592. // use FileShare.None as this bypasses dotnet bug dotnet/runtime#42790 .
  1593. using (var stream = new FileStream(nfoPath, FileMode.Create, FileAccess.Write, FileShare.None))
  1594. {
  1595. var settings = new XmlWriterSettings
  1596. {
  1597. Indent = true,
  1598. Encoding = Encoding.UTF8,
  1599. CloseOutput = false
  1600. };
  1601. var options = _config.GetNfoConfiguration();
  1602. var isSeriesEpisode = timer.IsProgramSeries;
  1603. using (var writer = XmlWriter.Create(stream, settings))
  1604. {
  1605. writer.WriteStartDocument(true);
  1606. if (isSeriesEpisode)
  1607. {
  1608. writer.WriteStartElement("episodedetails");
  1609. if (!string.IsNullOrWhiteSpace(timer.EpisodeTitle))
  1610. {
  1611. writer.WriteElementString("title", timer.EpisodeTitle);
  1612. }
  1613. var premiereDate = item.PremiereDate ?? (!timer.IsRepeat ? DateTime.UtcNow : (DateTime?)null);
  1614. if (premiereDate.HasValue)
  1615. {
  1616. var formatString = options.ReleaseDateFormat;
  1617. writer.WriteElementString(
  1618. "aired",
  1619. premiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture));
  1620. }
  1621. if (item.IndexNumber.HasValue)
  1622. {
  1623. writer.WriteElementString("episode", item.IndexNumber.Value.ToString(CultureInfo.InvariantCulture));
  1624. }
  1625. if (item.ParentIndexNumber.HasValue)
  1626. {
  1627. writer.WriteElementString("season", item.ParentIndexNumber.Value.ToString(CultureInfo.InvariantCulture));
  1628. }
  1629. }
  1630. else
  1631. {
  1632. writer.WriteStartElement("movie");
  1633. if (!string.IsNullOrWhiteSpace(item.Name))
  1634. {
  1635. writer.WriteElementString("title", item.Name);
  1636. }
  1637. if (!string.IsNullOrWhiteSpace(item.OriginalTitle))
  1638. {
  1639. writer.WriteElementString("originaltitle", item.OriginalTitle);
  1640. }
  1641. if (item.PremiereDate.HasValue)
  1642. {
  1643. var formatString = options.ReleaseDateFormat;
  1644. writer.WriteElementString(
  1645. "premiered",
  1646. item.PremiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture));
  1647. writer.WriteElementString(
  1648. "releasedate",
  1649. item.PremiereDate.Value.ToLocalTime().ToString(formatString, CultureInfo.InvariantCulture));
  1650. }
  1651. }
  1652. writer.WriteElementString(
  1653. "dateadded",
  1654. DateTime.UtcNow.ToLocalTime().ToString(DateAddedFormat, CultureInfo.InvariantCulture));
  1655. if (item.ProductionYear.HasValue)
  1656. {
  1657. writer.WriteElementString("year", item.ProductionYear.Value.ToString(CultureInfo.InvariantCulture));
  1658. }
  1659. if (!string.IsNullOrEmpty(item.OfficialRating))
  1660. {
  1661. writer.WriteElementString("mpaa", item.OfficialRating);
  1662. }
  1663. var overview = (item.Overview ?? string.Empty)
  1664. .StripHtml()
  1665. .Replace("&quot;", "'", StringComparison.Ordinal);
  1666. writer.WriteElementString("plot", overview);
  1667. if (item.CommunityRating.HasValue)
  1668. {
  1669. writer.WriteElementString("rating", item.CommunityRating.Value.ToString(CultureInfo.InvariantCulture));
  1670. }
  1671. foreach (var genre in item.Genres)
  1672. {
  1673. writer.WriteElementString("genre", genre);
  1674. }
  1675. var people = item.Id.Equals(Guid.Empty) ? new List<PersonInfo>() : _libraryManager.GetPeople(item);
  1676. var directors = people
  1677. .Where(i => IsPersonType(i, PersonType.Director))
  1678. .Select(i => i.Name)
  1679. .ToList();
  1680. foreach (var person in directors)
  1681. {
  1682. writer.WriteElementString("director", person);
  1683. }
  1684. var writers = people
  1685. .Where(i => IsPersonType(i, PersonType.Writer))
  1686. .Select(i => i.Name)
  1687. .Distinct(StringComparer.OrdinalIgnoreCase)
  1688. .ToList();
  1689. foreach (var person in writers)
  1690. {
  1691. writer.WriteElementString("writer", person);
  1692. }
  1693. foreach (var person in writers)
  1694. {
  1695. writer.WriteElementString("credits", person);
  1696. }
  1697. var tmdbCollection = item.GetProviderId(MetadataProvider.TmdbCollection);
  1698. if (!string.IsNullOrEmpty(tmdbCollection))
  1699. {
  1700. writer.WriteElementString("collectionnumber", tmdbCollection);
  1701. }
  1702. var imdb = item.GetProviderId(MetadataProvider.Imdb);
  1703. if (!string.IsNullOrEmpty(imdb))
  1704. {
  1705. if (!isSeriesEpisode)
  1706. {
  1707. writer.WriteElementString("id", imdb);
  1708. }
  1709. writer.WriteElementString("imdbid", imdb);
  1710. // No need to lock if we have identified the content already
  1711. lockData = false;
  1712. }
  1713. var tvdb = item.GetProviderId(MetadataProvider.Tvdb);
  1714. if (!string.IsNullOrEmpty(tvdb))
  1715. {
  1716. writer.WriteElementString("tvdbid", tvdb);
  1717. // No need to lock if we have identified the content already
  1718. lockData = false;
  1719. }
  1720. var tmdb = item.GetProviderId(MetadataProvider.Tmdb);
  1721. if (!string.IsNullOrEmpty(tmdb))
  1722. {
  1723. writer.WriteElementString("tmdbid", tmdb);
  1724. // No need to lock if we have identified the content already
  1725. lockData = false;
  1726. }
  1727. if (lockData)
  1728. {
  1729. writer.WriteElementString("lockdata", true.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
  1730. }
  1731. if (item.CriticRating.HasValue)
  1732. {
  1733. writer.WriteElementString("criticrating", item.CriticRating.Value.ToString(CultureInfo.InvariantCulture));
  1734. }
  1735. if (!string.IsNullOrWhiteSpace(item.Tagline))
  1736. {
  1737. writer.WriteElementString("tagline", item.Tagline);
  1738. }
  1739. foreach (var studio in item.Studios)
  1740. {
  1741. writer.WriteElementString("studio", studio);
  1742. }
  1743. writer.WriteEndElement();
  1744. writer.WriteEndDocument();
  1745. }
  1746. }
  1747. }
  1748. private static bool IsPersonType(PersonInfo person, string type)
  1749. => string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase)
  1750. || string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase);
  1751. private LiveTvProgram GetProgramInfoFromCache(string programId)
  1752. {
  1753. var query = new InternalItemsQuery
  1754. {
  1755. ItemIds = new[] { _liveTvManager.GetInternalProgramId(programId) },
  1756. Limit = 1,
  1757. DtoOptions = new DtoOptions()
  1758. };
  1759. return _libraryManager.GetItemList(query).Cast<LiveTvProgram>().FirstOrDefault();
  1760. }
  1761. private LiveTvProgram GetProgramInfoFromCache(TimerInfo timer)
  1762. {
  1763. return GetProgramInfoFromCache(timer.ProgramId, timer.ChannelId);
  1764. }
  1765. private LiveTvProgram GetProgramInfoFromCache(string programId, string channelId)
  1766. {
  1767. return GetProgramInfoFromCache(programId);
  1768. }
  1769. private LiveTvProgram GetProgramInfoFromCache(string channelId, DateTime startDateUtc)
  1770. {
  1771. var query = new InternalItemsQuery
  1772. {
  1773. IncludeItemTypes = new string[] { nameof(LiveTvProgram) },
  1774. Limit = 1,
  1775. DtoOptions = new DtoOptions(true)
  1776. {
  1777. EnableImages = false
  1778. },
  1779. MinStartDate = startDateUtc.AddMinutes(-3),
  1780. MaxStartDate = startDateUtc.AddMinutes(3),
  1781. OrderBy = new[] { (ItemSortBy.StartDate, SortOrder.Ascending) }
  1782. };
  1783. if (!string.IsNullOrWhiteSpace(channelId))
  1784. {
  1785. query.ChannelIds = new[] { _liveTvManager.GetInternalChannelId(Name, channelId) };
  1786. }
  1787. return _libraryManager.GetItemList(query).Cast<LiveTvProgram>().FirstOrDefault();
  1788. }
  1789. private LiveTvOptions GetConfiguration()
  1790. {
  1791. return _config.GetConfiguration<LiveTvOptions>("livetv");
  1792. }
  1793. private bool ShouldCancelTimerForSeriesTimer(SeriesTimerInfo seriesTimer, TimerInfo timer)
  1794. {
  1795. if (timer.IsManual)
  1796. {
  1797. return false;
  1798. }
  1799. if (!seriesTimer.RecordAnyTime
  1800. && Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - timer.StartDate.TimeOfDay.Ticks) >= TimeSpan.FromMinutes(10).Ticks)
  1801. {
  1802. return true;
  1803. }
  1804. if (seriesTimer.RecordNewOnly && timer.IsRepeat)
  1805. {
  1806. return true;
  1807. }
  1808. if (!seriesTimer.RecordAnyChannel
  1809. && !string.Equals(timer.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase))
  1810. {
  1811. return true;
  1812. }
  1813. return seriesTimer.SkipEpisodesInLibrary && IsProgramAlreadyInLibrary(timer);
  1814. }
  1815. private void HandleDuplicateShowIds(List<TimerInfo> timers)
  1816. {
  1817. foreach (var timer in timers.Skip(1))
  1818. {
  1819. // TODO: Get smarter, prefer HD, etc
  1820. timer.Status = RecordingStatus.Cancelled;
  1821. _timerProvider.Update(timer);
  1822. }
  1823. }
  1824. private void SearchForDuplicateShowIds(List<TimerInfo> timers)
  1825. {
  1826. var groups = timers.ToLookup(i => i.ShowId ?? string.Empty).ToList();
  1827. foreach (var group in groups)
  1828. {
  1829. if (string.IsNullOrWhiteSpace(group.Key))
  1830. {
  1831. continue;
  1832. }
  1833. var groupTimers = group.ToList();
  1834. if (groupTimers.Count < 2)
  1835. {
  1836. continue;
  1837. }
  1838. HandleDuplicateShowIds(groupTimers);
  1839. }
  1840. }
  1841. private void UpdateTimersForSeriesTimer(SeriesTimerInfo seriesTimer, bool updateTimerSettings, bool deleteInvalidTimers)
  1842. {
  1843. var allTimers = GetTimersForSeries(seriesTimer).ToList();
  1844. var enabledTimersForSeries = new List<TimerInfo>();
  1845. foreach (var timer in allTimers)
  1846. {
  1847. var existingTimer = _timerProvider.GetTimer(timer.Id)
  1848. ?? (string.IsNullOrWhiteSpace(timer.ProgramId)
  1849. ? null
  1850. : _timerProvider.GetTimerByProgramId(timer.ProgramId));
  1851. if (existingTimer == null)
  1852. {
  1853. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1854. {
  1855. timer.Status = RecordingStatus.Cancelled;
  1856. }
  1857. else
  1858. {
  1859. enabledTimersForSeries.Add(timer);
  1860. }
  1861. _timerProvider.Add(timer);
  1862. TimerCreated?.Invoke(this, new GenericEventArgs<TimerInfo>(timer));
  1863. }
  1864. // Only update if not currently active - test both new timer and existing in case Id's are different
  1865. // Id's could be different if the timer was created manually prior to series timer creation
  1866. else if (!_activeRecordings.TryGetValue(timer.Id, out _) && !_activeRecordings.TryGetValue(existingTimer.Id, out _))
  1867. {
  1868. UpdateExistingTimerWithNewMetadata(existingTimer, timer);
  1869. // Needed by ShouldCancelTimerForSeriesTimer
  1870. timer.IsManual = existingTimer.IsManual;
  1871. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1872. {
  1873. existingTimer.Status = RecordingStatus.Cancelled;
  1874. }
  1875. else if (!existingTimer.IsManual)
  1876. {
  1877. existingTimer.Status = RecordingStatus.New;
  1878. }
  1879. if (existingTimer.Status != RecordingStatus.Cancelled)
  1880. {
  1881. enabledTimersForSeries.Add(existingTimer);
  1882. }
  1883. if (updateTimerSettings)
  1884. {
  1885. // Only update if not currently active - test both new timer and existing in case Id's are different
  1886. // Id's could be different if the timer was created manually prior to series timer creation
  1887. if (!_activeRecordings.TryGetValue(timer.Id, out var activeRecordingInfo) && !_activeRecordings.TryGetValue(existingTimer.Id, out activeRecordingInfo))
  1888. {
  1889. UpdateExistingTimerWithNewMetadata(existingTimer, timer);
  1890. // Needed by ShouldCancelTimerForSeriesTimer
  1891. timer.IsManual = existingTimer.IsManual;
  1892. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1893. {
  1894. existingTimer.Status = RecordingStatus.Cancelled;
  1895. }
  1896. else if (!existingTimer.IsManual)
  1897. {
  1898. existingTimer.Status = RecordingStatus.New;
  1899. }
  1900. if (existingTimer.Status != RecordingStatus.Cancelled)
  1901. {
  1902. enabledTimersForSeries.Add(existingTimer);
  1903. }
  1904. if (updateTimerSettings)
  1905. {
  1906. existingTimer.KeepUntil = seriesTimer.KeepUntil;
  1907. existingTimer.IsPostPaddingRequired = seriesTimer.IsPostPaddingRequired;
  1908. existingTimer.IsPrePaddingRequired = seriesTimer.IsPrePaddingRequired;
  1909. existingTimer.PostPaddingSeconds = seriesTimer.PostPaddingSeconds;
  1910. existingTimer.PrePaddingSeconds = seriesTimer.PrePaddingSeconds;
  1911. existingTimer.Priority = seriesTimer.Priority;
  1912. }
  1913. existingTimer.SeriesTimerId = seriesTimer.Id;
  1914. _timerProvider.Update(existingTimer);
  1915. }
  1916. }
  1917. existingTimer.SeriesTimerId = seriesTimer.Id;
  1918. _timerProvider.Update(existingTimer);
  1919. }
  1920. }
  1921. SearchForDuplicateShowIds(enabledTimersForSeries);
  1922. if (deleteInvalidTimers)
  1923. {
  1924. var allTimerIds = allTimers
  1925. .Select(i => i.Id)
  1926. .ToList();
  1927. var deleteStatuses = new[]
  1928. {
  1929. RecordingStatus.New
  1930. };
  1931. var deletes = _timerProvider.GetAll()
  1932. .Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
  1933. .Where(i => !allTimerIds.Contains(i.Id, StringComparer.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
  1934. .Where(i => deleteStatuses.Contains(i.Status))
  1935. .ToList();
  1936. foreach (var timer in deletes)
  1937. {
  1938. CancelTimerInternal(timer.Id, false, false);
  1939. }
  1940. }
  1941. }
  1942. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer)
  1943. {
  1944. if (seriesTimer == null)
  1945. {
  1946. throw new ArgumentNullException(nameof(seriesTimer));
  1947. }
  1948. var query = new InternalItemsQuery
  1949. {
  1950. IncludeItemTypes = new string[] { nameof(LiveTvProgram) },
  1951. ExternalSeriesId = seriesTimer.SeriesId,
  1952. DtoOptions = new DtoOptions(true)
  1953. {
  1954. EnableImages = false
  1955. },
  1956. MinEndDate = DateTime.UtcNow
  1957. };
  1958. if (string.IsNullOrEmpty(seriesTimer.SeriesId))
  1959. {
  1960. query.Name = seriesTimer.Name;
  1961. }
  1962. if (!seriesTimer.RecordAnyChannel)
  1963. {
  1964. query.ChannelIds = new[] { _liveTvManager.GetInternalChannelId(Name, seriesTimer.ChannelId) };
  1965. }
  1966. var tempChannelCache = new Dictionary<Guid, LiveTvChannel>();
  1967. return _libraryManager.GetItemList(query).Cast<LiveTvProgram>().Select(i => CreateTimer(i, seriesTimer, tempChannelCache));
  1968. }
  1969. private TimerInfo CreateTimer(LiveTvProgram parent, SeriesTimerInfo seriesTimer, Dictionary<Guid, LiveTvChannel> tempChannelCache)
  1970. {
  1971. string channelId = seriesTimer.RecordAnyChannel ? null : seriesTimer.ChannelId;
  1972. if (string.IsNullOrWhiteSpace(channelId) && !parent.ChannelId.Equals(Guid.Empty))
  1973. {
  1974. if (!tempChannelCache.TryGetValue(parent.ChannelId, out LiveTvChannel channel))
  1975. {
  1976. channel = _libraryManager.GetItemList(
  1977. new InternalItemsQuery
  1978. {
  1979. IncludeItemTypes = new string[] { nameof(LiveTvChannel) },
  1980. ItemIds = new[] { parent.ChannelId },
  1981. DtoOptions = new DtoOptions()
  1982. }).FirstOrDefault() as LiveTvChannel;
  1983. if (channel != null && !string.IsNullOrWhiteSpace(channel.ExternalId))
  1984. {
  1985. tempChannelCache[parent.ChannelId] = channel;
  1986. }
  1987. }
  1988. if (channel != null || tempChannelCache.TryGetValue(parent.ChannelId, out channel))
  1989. {
  1990. channelId = channel.ExternalId;
  1991. }
  1992. }
  1993. var timer = new TimerInfo
  1994. {
  1995. ChannelId = channelId,
  1996. Id = (seriesTimer.Id + parent.ExternalId).GetMD5().ToString("N", CultureInfo.InvariantCulture),
  1997. StartDate = parent.StartDate,
  1998. EndDate = parent.EndDate.Value,
  1999. ProgramId = parent.ExternalId,
  2000. PrePaddingSeconds = seriesTimer.PrePaddingSeconds,
  2001. PostPaddingSeconds = seriesTimer.PostPaddingSeconds,
  2002. IsPostPaddingRequired = seriesTimer.IsPostPaddingRequired,
  2003. IsPrePaddingRequired = seriesTimer.IsPrePaddingRequired,
  2004. KeepUntil = seriesTimer.KeepUntil,
  2005. Priority = seriesTimer.Priority,
  2006. Name = parent.Name,
  2007. Overview = parent.Overview,
  2008. SeriesId = parent.ExternalSeriesId,
  2009. SeriesTimerId = seriesTimer.Id,
  2010. ShowId = parent.ShowId
  2011. };
  2012. CopyProgramInfoToTimerInfo(parent, timer, tempChannelCache);
  2013. return timer;
  2014. }
  2015. private void CopyProgramInfoToTimerInfo(LiveTvProgram programInfo, TimerInfo timerInfo)
  2016. {
  2017. var tempChannelCache = new Dictionary<Guid, LiveTvChannel>();
  2018. CopyProgramInfoToTimerInfo(programInfo, timerInfo, tempChannelCache);
  2019. }
  2020. private void CopyProgramInfoToTimerInfo(LiveTvProgram programInfo, TimerInfo timerInfo, Dictionary<Guid, LiveTvChannel> tempChannelCache)
  2021. {
  2022. string channelId = null;
  2023. if (!programInfo.ChannelId.Equals(Guid.Empty))
  2024. {
  2025. if (!tempChannelCache.TryGetValue(programInfo.ChannelId, out LiveTvChannel channel))
  2026. {
  2027. channel = _libraryManager.GetItemList(
  2028. new InternalItemsQuery
  2029. {
  2030. IncludeItemTypes = new string[] { nameof(LiveTvChannel) },
  2031. ItemIds = new[] { programInfo.ChannelId },
  2032. DtoOptions = new DtoOptions()
  2033. }).FirstOrDefault() as LiveTvChannel;
  2034. if (channel != null && !string.IsNullOrWhiteSpace(channel.ExternalId))
  2035. {
  2036. tempChannelCache[programInfo.ChannelId] = channel;
  2037. }
  2038. }
  2039. if (channel != null || tempChannelCache.TryGetValue(programInfo.ChannelId, out channel))
  2040. {
  2041. channelId = channel.ExternalId;
  2042. }
  2043. }
  2044. timerInfo.Name = programInfo.Name;
  2045. timerInfo.StartDate = programInfo.StartDate;
  2046. timerInfo.EndDate = programInfo.EndDate.Value;
  2047. if (!string.IsNullOrWhiteSpace(channelId))
  2048. {
  2049. timerInfo.ChannelId = channelId;
  2050. }
  2051. timerInfo.SeasonNumber = programInfo.ParentIndexNumber;
  2052. timerInfo.EpisodeNumber = programInfo.IndexNumber;
  2053. timerInfo.IsMovie = programInfo.IsMovie;
  2054. timerInfo.ProductionYear = programInfo.ProductionYear;
  2055. timerInfo.EpisodeTitle = programInfo.EpisodeTitle;
  2056. timerInfo.OriginalAirDate = programInfo.PremiereDate;
  2057. timerInfo.IsProgramSeries = programInfo.IsSeries;
  2058. timerInfo.IsSeries = programInfo.IsSeries;
  2059. timerInfo.CommunityRating = programInfo.CommunityRating;
  2060. timerInfo.Overview = programInfo.Overview;
  2061. timerInfo.OfficialRating = programInfo.OfficialRating;
  2062. timerInfo.IsRepeat = programInfo.IsRepeat;
  2063. timerInfo.SeriesId = programInfo.ExternalSeriesId;
  2064. timerInfo.ProviderIds = programInfo.ProviderIds;
  2065. timerInfo.Tags = programInfo.Tags;
  2066. var seriesProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  2067. foreach (var providerId in timerInfo.ProviderIds)
  2068. {
  2069. const string Search = "Series";
  2070. if (providerId.Key.StartsWith(Search, StringComparison.OrdinalIgnoreCase))
  2071. {
  2072. seriesProviderIds[providerId.Key.Substring(Search.Length)] = providerId.Value;
  2073. }
  2074. }
  2075. timerInfo.SeriesProviderIds = seriesProviderIds;
  2076. }
  2077. private bool IsProgramAlreadyInLibrary(TimerInfo program)
  2078. {
  2079. if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle))
  2080. {
  2081. var seriesIds = _libraryManager.GetItemIds(
  2082. new InternalItemsQuery
  2083. {
  2084. IncludeItemTypes = new[] { nameof(Series) },
  2085. Name = program.Name
  2086. }).ToArray();
  2087. if (seriesIds.Length == 0)
  2088. {
  2089. return false;
  2090. }
  2091. if (program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue)
  2092. {
  2093. var result = _libraryManager.GetItemIds(new InternalItemsQuery
  2094. {
  2095. IncludeItemTypes = new[] { nameof(Episode) },
  2096. ParentIndexNumber = program.SeasonNumber.Value,
  2097. IndexNumber = program.EpisodeNumber.Value,
  2098. AncestorIds = seriesIds,
  2099. IsVirtualItem = false,
  2100. Limit = 1
  2101. });
  2102. if (result.Count > 0)
  2103. {
  2104. return true;
  2105. }
  2106. }
  2107. }
  2108. return false;
  2109. }
  2110. /// <inheritdoc />
  2111. public void Dispose()
  2112. {
  2113. Dispose(true);
  2114. GC.SuppressFinalize(this);
  2115. }
  2116. protected virtual void Dispose(bool disposing)
  2117. {
  2118. if (_disposed)
  2119. {
  2120. return;
  2121. }
  2122. if (disposing)
  2123. {
  2124. _recordingDeleteSemaphore.Dispose();
  2125. }
  2126. foreach (var pair in _activeRecordings.ToList())
  2127. {
  2128. pair.Value.CancellationTokenSource.Cancel();
  2129. }
  2130. _disposed = true;
  2131. }
  2132. public IEnumerable<VirtualFolderInfo> GetRecordingFolders()
  2133. {
  2134. var defaultFolder = RecordingPath;
  2135. var defaultName = "Recordings";
  2136. if (Directory.Exists(defaultFolder))
  2137. {
  2138. yield return new VirtualFolderInfo
  2139. {
  2140. Locations = new string[] { defaultFolder },
  2141. Name = defaultName
  2142. };
  2143. }
  2144. var customPath = GetConfiguration().MovieRecordingPath;
  2145. if (!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase) && Directory.Exists(customPath))
  2146. {
  2147. yield return new VirtualFolderInfo
  2148. {
  2149. Locations = new string[] { customPath },
  2150. Name = "Recorded Movies",
  2151. CollectionType = CollectionTypeOptions.Movies
  2152. };
  2153. }
  2154. customPath = GetConfiguration().SeriesRecordingPath;
  2155. if (!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase) && Directory.Exists(customPath))
  2156. {
  2157. yield return new VirtualFolderInfo
  2158. {
  2159. Locations = new string[] { customPath },
  2160. Name = "Recorded Shows",
  2161. CollectionType = CollectionTypeOptions.TvShows
  2162. };
  2163. }
  2164. }
  2165. public async Task<List<TunerHostInfo>> DiscoverTuners(bool newDevicesOnly, CancellationToken cancellationToken)
  2166. {
  2167. var list = new List<TunerHostInfo>();
  2168. var configuredDeviceIds = GetConfiguration().TunerHosts
  2169. .Where(i => !string.IsNullOrWhiteSpace(i.DeviceId))
  2170. .Select(i => i.DeviceId)
  2171. .ToList();
  2172. foreach (var host in _liveTvManager.TunerHosts)
  2173. {
  2174. var discoveredDevices = await DiscoverDevices(host, TunerDiscoveryDurationMs, cancellationToken).ConfigureAwait(false);
  2175. if (newDevicesOnly)
  2176. {
  2177. discoveredDevices = discoveredDevices.Where(d => !configuredDeviceIds.Contains(d.DeviceId, StringComparer.OrdinalIgnoreCase))
  2178. .ToList();
  2179. }
  2180. list.AddRange(discoveredDevices);
  2181. }
  2182. return list;
  2183. }
  2184. public async Task ScanForTunerDeviceChanges(CancellationToken cancellationToken)
  2185. {
  2186. foreach (var host in _liveTvManager.TunerHosts)
  2187. {
  2188. await ScanForTunerDeviceChanges(host, cancellationToken).ConfigureAwait(false);
  2189. }
  2190. }
  2191. private async Task ScanForTunerDeviceChanges(ITunerHost host, CancellationToken cancellationToken)
  2192. {
  2193. var discoveredDevices = await DiscoverDevices(host, TunerDiscoveryDurationMs, cancellationToken).ConfigureAwait(false);
  2194. var configuredDevices = GetConfiguration().TunerHosts
  2195. .Where(i => string.Equals(i.Type, host.Type, StringComparison.OrdinalIgnoreCase))
  2196. .ToList();
  2197. foreach (var device in discoveredDevices)
  2198. {
  2199. var configuredDevice = configuredDevices.FirstOrDefault(i => string.Equals(i.DeviceId, device.DeviceId, StringComparison.OrdinalIgnoreCase));
  2200. if (configuredDevice != null && !string.Equals(device.Url, configuredDevice.Url, StringComparison.OrdinalIgnoreCase))
  2201. {
  2202. _logger.LogInformation("Tuner url has changed from {PreviousUrl} to {NewUrl}", configuredDevice.Url, device.Url);
  2203. configuredDevice.Url = device.Url;
  2204. await _liveTvManager.SaveTunerHost(configuredDevice).ConfigureAwait(false);
  2205. }
  2206. }
  2207. }
  2208. private async Task<List<TunerHostInfo>> DiscoverDevices(ITunerHost host, int discoveryDurationMs, CancellationToken cancellationToken)
  2209. {
  2210. try
  2211. {
  2212. var discoveredDevices = await host.DiscoverDevices(discoveryDurationMs, cancellationToken).ConfigureAwait(false);
  2213. foreach (var device in discoveredDevices)
  2214. {
  2215. _logger.LogInformation("Discovered tuner device {0} at {1}", host.Name, device.Url);
  2216. }
  2217. return discoveredDevices;
  2218. }
  2219. catch (Exception ex)
  2220. {
  2221. _logger.LogError(ex, "Error discovering tuner devices");
  2222. return new List<TunerHostInfo>();
  2223. }
  2224. }
  2225. }
  2226. }