EmbyTV.cs 100 KB

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