EmbyTV.cs 101 KB

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