2
0

EmbyTV.cs 100 KB

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