EmbyTV.cs 93 KB

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