EmbyTV.cs 101 KB

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