EmbyTV.cs 101 KB

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