EmbyTV.cs 101 KB

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