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