EmbyTV.cs 100 KB

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