EmbyTV.cs 101 KB

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