EmbyTV.cs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316
  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.FileOrganization;
  16. using MediaBrowser.Model.LiveTv;
  17. using MediaBrowser.Model.Logging;
  18. using MediaBrowser.Model.Serialization;
  19. using MediaBrowser.Server.Implementations.FileOrganization;
  20. using System;
  21. using System.Collections.Concurrent;
  22. using System.Collections.Generic;
  23. using System.Globalization;
  24. using System.IO;
  25. using System.Linq;
  26. using System.Threading;
  27. using System.Threading.Tasks;
  28. using CommonIO;
  29. using MediaBrowser.Common.Events;
  30. using MediaBrowser.Common.Extensions;
  31. using MediaBrowser.Controller.Entities;
  32. using MediaBrowser.Controller.Entities.TV;
  33. using MediaBrowser.Controller.Power;
  34. using Microsoft.Win32;
  35. namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
  36. {
  37. public class EmbyTV : ILiveTvService, IHasRegistrationInfo, IDisposable
  38. {
  39. private readonly IApplicationHost _appHpst;
  40. private readonly ILogger _logger;
  41. private readonly IHttpClient _httpClient;
  42. private readonly IServerConfigurationManager _config;
  43. private readonly IJsonSerializer _jsonSerializer;
  44. private readonly ItemDataProvider<SeriesTimerInfo> _seriesTimerProvider;
  45. private readonly TimerManager _timerProvider;
  46. private readonly LiveTvManager _liveTvManager;
  47. private readonly IFileSystem _fileSystem;
  48. private readonly ISecurityManager _security;
  49. private readonly ILibraryMonitor _libraryMonitor;
  50. private readonly ILibraryManager _libraryManager;
  51. private readonly IProviderManager _providerManager;
  52. private readonly IFileOrganizationService _organizationService;
  53. private readonly IMediaEncoder _mediaEncoder;
  54. public static EmbyTV Current;
  55. public event EventHandler DataSourceChanged;
  56. public event EventHandler<RecordingStatusChangedEventArgs> RecordingStatusChanged;
  57. private readonly ConcurrentDictionary<string, ActiveRecordingInfo> _activeRecordings =
  58. new ConcurrentDictionary<string, ActiveRecordingInfo>(StringComparer.OrdinalIgnoreCase);
  59. public EmbyTV(IApplicationHost appHost, ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IServerConfigurationManager config, ILiveTvManager liveTvManager, IFileSystem fileSystem, ISecurityManager security, ILibraryManager libraryManager, ILibraryMonitor libraryMonitor, IProviderManager providerManager, IFileOrganizationService organizationService, IMediaEncoder mediaEncoder, IPowerManagement powerManagement)
  60. {
  61. Current = this;
  62. _appHpst = appHost;
  63. _logger = logger;
  64. _httpClient = httpClient;
  65. _config = config;
  66. _fileSystem = fileSystem;
  67. _security = security;
  68. _libraryManager = libraryManager;
  69. _libraryMonitor = libraryMonitor;
  70. _providerManager = providerManager;
  71. _organizationService = organizationService;
  72. _mediaEncoder = mediaEncoder;
  73. _liveTvManager = (LiveTvManager)liveTvManager;
  74. _jsonSerializer = jsonSerializer;
  75. _seriesTimerProvider = new SeriesTimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers"));
  76. _timerProvider = new TimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "timers"), powerManagement, _logger);
  77. _timerProvider.TimerFired += _timerProvider_TimerFired;
  78. _config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
  79. }
  80. private void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
  81. {
  82. if (string.Equals(e.Key, "livetv", StringComparison.OrdinalIgnoreCase))
  83. {
  84. OnRecordingFoldersChanged();
  85. }
  86. }
  87. public void Start()
  88. {
  89. _timerProvider.RestartTimers();
  90. SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
  91. CreateRecordingFolders();
  92. }
  93. private void OnRecordingFoldersChanged()
  94. {
  95. CreateRecordingFolders();
  96. }
  97. private void CreateRecordingFolders()
  98. {
  99. var recordingFolders = GetRecordingFolders();
  100. var defaultRecordingPath = DefaultRecordingPath;
  101. if (!recordingFolders.Any(i => i.Locations.Contains(defaultRecordingPath, StringComparer.OrdinalIgnoreCase)))
  102. {
  103. RemovePathFromLibrary(defaultRecordingPath);
  104. }
  105. var virtualFolders = _libraryManager.GetVirtualFolders()
  106. .ToList();
  107. var allExistingPaths = virtualFolders.SelectMany(i => i.Locations).ToList();
  108. foreach (var recordingFolder in recordingFolders)
  109. {
  110. var pathsToCreate = recordingFolder.Locations
  111. .Where(i => !allExistingPaths.Contains(i, StringComparer.OrdinalIgnoreCase))
  112. .ToList();
  113. if (pathsToCreate.Count == 0)
  114. {
  115. continue;
  116. }
  117. try
  118. {
  119. _libraryManager.AddVirtualFolder(recordingFolder.Name, recordingFolder.CollectionType, pathsToCreate.ToArray(), true);
  120. }
  121. catch (Exception ex)
  122. {
  123. _logger.ErrorException("Error creating virtual folder", ex);
  124. }
  125. }
  126. }
  127. private void RemovePathFromLibrary(string path)
  128. {
  129. var requiresRefresh = false;
  130. var virtualFolders = _libraryManager.GetVirtualFolders()
  131. .ToList();
  132. foreach (var virtualFolder in virtualFolders)
  133. {
  134. if (!virtualFolder.Locations.Contains(path, StringComparer.OrdinalIgnoreCase))
  135. {
  136. continue;
  137. }
  138. if (virtualFolder.Locations.Count == 1)
  139. {
  140. // remove entire virtual folder
  141. try
  142. {
  143. _libraryManager.RemoveVirtualFolder(virtualFolder.Name, true);
  144. }
  145. catch (Exception ex)
  146. {
  147. _logger.ErrorException("Error removing virtual folder", ex);
  148. }
  149. }
  150. else
  151. {
  152. try
  153. {
  154. _libraryManager.RemoveMediaPath(virtualFolder.Name, path);
  155. requiresRefresh = true;
  156. }
  157. catch (Exception ex)
  158. {
  159. _logger.ErrorException("Error removing media path", ex);
  160. }
  161. }
  162. }
  163. if (requiresRefresh)
  164. {
  165. _libraryManager.ValidateMediaLibrary(new Progress<Double>(), CancellationToken.None);
  166. }
  167. }
  168. void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
  169. {
  170. _logger.Info("Power mode changed to {0}", e.Mode);
  171. if (e.Mode == PowerModes.Resume)
  172. {
  173. _timerProvider.RestartTimers();
  174. }
  175. }
  176. public string Name
  177. {
  178. get { return "Emby"; }
  179. }
  180. public string DataPath
  181. {
  182. get { return Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv"); }
  183. }
  184. private string DefaultRecordingPath
  185. {
  186. get
  187. {
  188. return Path.Combine(DataPath, "recordings");
  189. }
  190. }
  191. private string RecordingPath
  192. {
  193. get
  194. {
  195. var path = GetConfiguration().RecordingPath;
  196. return string.IsNullOrWhiteSpace(path)
  197. ? DefaultRecordingPath
  198. : path;
  199. }
  200. }
  201. public string HomePageUrl
  202. {
  203. get { return "http://emby.media"; }
  204. }
  205. public async Task<LiveTvServiceStatusInfo> GetStatusInfoAsync(CancellationToken cancellationToken)
  206. {
  207. var status = new LiveTvServiceStatusInfo();
  208. var list = new List<LiveTvTunerInfo>();
  209. foreach (var hostInstance in _liveTvManager.TunerHosts)
  210. {
  211. try
  212. {
  213. var tuners = await hostInstance.GetTunerInfos(cancellationToken).ConfigureAwait(false);
  214. list.AddRange(tuners);
  215. }
  216. catch (Exception ex)
  217. {
  218. _logger.ErrorException("Error getting tuners", ex);
  219. }
  220. }
  221. status.Tuners = list;
  222. status.Status = LiveTvServiceStatus.Ok;
  223. status.Version = _appHpst.ApplicationVersion.ToString();
  224. status.IsVisible = false;
  225. return status;
  226. }
  227. public async Task RefreshSeriesTimers(CancellationToken cancellationToken, IProgress<double> progress)
  228. {
  229. var seriesTimers = await GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  230. List<ChannelInfo> channels = null;
  231. foreach (var timer in seriesTimers)
  232. {
  233. List<ProgramInfo> epgData;
  234. if (timer.RecordAnyChannel)
  235. {
  236. if (channels == null)
  237. {
  238. channels = (await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false)).ToList();
  239. }
  240. var channelIds = channels.Select(i => i.Id).ToList();
  241. epgData = GetEpgDataForChannels(channelIds);
  242. }
  243. else
  244. {
  245. epgData = GetEpgDataForChannel(timer.ChannelId);
  246. }
  247. await UpdateTimersForSeriesTimer(epgData, timer, true).ConfigureAwait(false);
  248. }
  249. var timers = await GetTimersAsync(cancellationToken).ConfigureAwait(false);
  250. foreach (var timer in timers.ToList())
  251. {
  252. if (DateTime.UtcNow > timer.EndDate && !_activeRecordings.ContainsKey(timer.Id))
  253. {
  254. _timerProvider.Delete(timer);
  255. }
  256. }
  257. }
  258. private List<ChannelInfo> _channelCache = null;
  259. private async Task<IEnumerable<ChannelInfo>> GetChannelsAsync(bool enableCache, CancellationToken cancellationToken)
  260. {
  261. if (enableCache && _channelCache != null)
  262. {
  263. return _channelCache.ToList();
  264. }
  265. var list = new List<ChannelInfo>();
  266. foreach (var hostInstance in _liveTvManager.TunerHosts)
  267. {
  268. try
  269. {
  270. var channels = await hostInstance.GetChannels(cancellationToken).ConfigureAwait(false);
  271. list.AddRange(channels);
  272. }
  273. catch (Exception ex)
  274. {
  275. _logger.ErrorException("Error getting channels", ex);
  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 provider.Item1.AddMetadata(provider.Item2, enabledChannels, cancellationToken).ConfigureAwait(false);
  288. }
  289. catch (NotSupportedException)
  290. {
  291. }
  292. catch (Exception ex)
  293. {
  294. _logger.ErrorException("Error adding metadata", ex);
  295. }
  296. }
  297. }
  298. _channelCache = list.ToList();
  299. return list;
  300. }
  301. public Task<IEnumerable<ChannelInfo>> GetChannelsAsync(CancellationToken cancellationToken)
  302. {
  303. return GetChannelsAsync(false, cancellationToken);
  304. }
  305. public Task CancelSeriesTimerAsync(string timerId, CancellationToken cancellationToken)
  306. {
  307. var timers = _timerProvider
  308. .GetAll()
  309. .Where(i => string.Equals(i.SeriesTimerId, timerId, StringComparison.OrdinalIgnoreCase))
  310. .ToList();
  311. foreach (var timer in timers)
  312. {
  313. CancelTimerInternal(timer.Id);
  314. }
  315. var remove = _seriesTimerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
  316. if (remove != null)
  317. {
  318. _seriesTimerProvider.Delete(remove);
  319. }
  320. return Task.FromResult(true);
  321. }
  322. private void CancelTimerInternal(string timerId)
  323. {
  324. var remove = _timerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
  325. if (remove != null)
  326. {
  327. _timerProvider.Delete(remove);
  328. }
  329. ActiveRecordingInfo activeRecordingInfo;
  330. if (_activeRecordings.TryGetValue(timerId, out activeRecordingInfo))
  331. {
  332. activeRecordingInfo.CancellationTokenSource.Cancel();
  333. }
  334. }
  335. public Task CancelTimerAsync(string timerId, CancellationToken cancellationToken)
  336. {
  337. CancelTimerInternal(timerId);
  338. return Task.FromResult(true);
  339. }
  340. public Task DeleteRecordingAsync(string recordingId, CancellationToken cancellationToken)
  341. {
  342. return Task.FromResult(true);
  343. }
  344. public Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
  345. {
  346. info.Id = Guid.NewGuid().ToString("N");
  347. _timerProvider.Add(info);
  348. return Task.FromResult(0);
  349. }
  350. public async Task CreateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  351. {
  352. info.Id = Guid.NewGuid().ToString("N");
  353. List<ProgramInfo> epgData;
  354. if (info.RecordAnyChannel)
  355. {
  356. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  357. var channelIds = channels.Select(i => i.Id).ToList();
  358. epgData = GetEpgDataForChannels(channelIds);
  359. }
  360. else
  361. {
  362. epgData = GetEpgDataForChannel(info.ChannelId);
  363. }
  364. // populate info.seriesID
  365. var program = epgData.FirstOrDefault(i => string.Equals(i.Id, info.ProgramId, StringComparison.OrdinalIgnoreCase));
  366. if (program != null)
  367. {
  368. info.SeriesId = program.SeriesId;
  369. }
  370. else
  371. {
  372. throw new InvalidOperationException("SeriesId for program not found");
  373. }
  374. _seriesTimerProvider.Add(info);
  375. await UpdateTimersForSeriesTimer(epgData, info, false).ConfigureAwait(false);
  376. }
  377. public async Task UpdateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  378. {
  379. var instance = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  380. if (instance != null)
  381. {
  382. instance.ChannelId = info.ChannelId;
  383. instance.Days = info.Days;
  384. instance.EndDate = info.EndDate;
  385. instance.IsPostPaddingRequired = info.IsPostPaddingRequired;
  386. instance.IsPrePaddingRequired = info.IsPrePaddingRequired;
  387. instance.PostPaddingSeconds = info.PostPaddingSeconds;
  388. instance.PrePaddingSeconds = info.PrePaddingSeconds;
  389. instance.Priority = info.Priority;
  390. instance.RecordAnyChannel = info.RecordAnyChannel;
  391. instance.RecordAnyTime = info.RecordAnyTime;
  392. instance.RecordNewOnly = info.RecordNewOnly;
  393. instance.StartDate = info.StartDate;
  394. _seriesTimerProvider.Update(instance);
  395. List<ProgramInfo> epgData;
  396. if (instance.RecordAnyChannel)
  397. {
  398. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  399. var channelIds = channels.Select(i => i.Id).ToList();
  400. epgData = GetEpgDataForChannels(channelIds);
  401. }
  402. else
  403. {
  404. epgData = GetEpgDataForChannel(instance.ChannelId);
  405. }
  406. await UpdateTimersForSeriesTimer(epgData, instance, true).ConfigureAwait(false);
  407. }
  408. }
  409. public Task UpdateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
  410. {
  411. _timerProvider.Update(info);
  412. return Task.FromResult(true);
  413. }
  414. public Task<ImageStream> GetChannelImageAsync(string channelId, CancellationToken cancellationToken)
  415. {
  416. throw new NotImplementedException();
  417. }
  418. public Task<ImageStream> GetRecordingImageAsync(string recordingId, CancellationToken cancellationToken)
  419. {
  420. throw new NotImplementedException();
  421. }
  422. public Task<ImageStream> GetProgramImageAsync(string programId, string channelId, CancellationToken cancellationToken)
  423. {
  424. throw new NotImplementedException();
  425. }
  426. public async Task<IEnumerable<RecordingInfo>> GetRecordingsAsync(CancellationToken cancellationToken)
  427. {
  428. return new List<RecordingInfo>();
  429. }
  430. public Task<IEnumerable<TimerInfo>> GetTimersAsync(CancellationToken cancellationToken)
  431. {
  432. return Task.FromResult((IEnumerable<TimerInfo>)_timerProvider.GetAll());
  433. }
  434. public Task<SeriesTimerInfo> GetNewTimerDefaultsAsync(CancellationToken cancellationToken, ProgramInfo program = null)
  435. {
  436. var config = GetConfiguration();
  437. var defaults = new SeriesTimerInfo()
  438. {
  439. PostPaddingSeconds = Math.Max(config.PostPaddingSeconds, 0),
  440. PrePaddingSeconds = Math.Max(config.PrePaddingSeconds, 0),
  441. RecordAnyChannel = false,
  442. RecordAnyTime = false,
  443. RecordNewOnly = false
  444. };
  445. if (program != null)
  446. {
  447. defaults.SeriesId = program.SeriesId;
  448. defaults.ProgramId = program.Id;
  449. }
  450. return Task.FromResult(defaults);
  451. }
  452. public Task<IEnumerable<SeriesTimerInfo>> GetSeriesTimersAsync(CancellationToken cancellationToken)
  453. {
  454. return Task.FromResult((IEnumerable<SeriesTimerInfo>)_seriesTimerProvider.GetAll());
  455. }
  456. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  457. {
  458. try
  459. {
  460. return await GetProgramsAsyncInternal(channelId, startDateUtc, endDateUtc, cancellationToken).ConfigureAwait(false);
  461. }
  462. catch (OperationCanceledException)
  463. {
  464. throw;
  465. }
  466. catch (Exception ex)
  467. {
  468. _logger.ErrorException("Error getting programs", ex);
  469. return GetEpgDataForChannel(channelId).Where(i => i.StartDate <= endDateUtc && i.EndDate >= startDateUtc);
  470. }
  471. }
  472. private bool IsListingProviderEnabledForTuner(ListingsProviderInfo info, string tunerHostId)
  473. {
  474. if (info.EnableAllTuners)
  475. {
  476. return true;
  477. }
  478. if (string.IsNullOrWhiteSpace(tunerHostId))
  479. {
  480. throw new ArgumentNullException("tunerHostId");
  481. }
  482. return info.EnabledTuners.Contains(tunerHostId, StringComparer.OrdinalIgnoreCase);
  483. }
  484. private async Task<IEnumerable<ProgramInfo>> GetProgramsAsyncInternal(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  485. {
  486. var channels = await GetChannelsAsync(true, cancellationToken).ConfigureAwait(false);
  487. var channel = channels.First(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  488. foreach (var provider in GetListingProviders())
  489. {
  490. if (!IsListingProviderEnabledForTuner(provider.Item2, channel.TunerHostId))
  491. {
  492. _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);
  493. continue;
  494. }
  495. _logger.Debug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
  496. var programs = await provider.Item1.GetProgramsAsync(provider.Item2, channel.Number, channel.Name, startDateUtc, endDateUtc, cancellationToken)
  497. .ConfigureAwait(false);
  498. var list = programs.ToList();
  499. // Replace the value that came from the provider with a normalized value
  500. foreach (var program in list)
  501. {
  502. program.ChannelId = channelId;
  503. }
  504. if (list.Count > 0)
  505. {
  506. SaveEpgDataForChannel(channelId, list);
  507. return list;
  508. }
  509. }
  510. return new List<ProgramInfo>();
  511. }
  512. private List<Tuple<IListingsProvider, ListingsProviderInfo>> GetListingProviders()
  513. {
  514. return GetConfiguration().ListingProviders
  515. .Select(i =>
  516. {
  517. var provider = _liveTvManager.ListingProviders.FirstOrDefault(l => string.Equals(l.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  518. return provider == null ? null : new Tuple<IListingsProvider, ListingsProviderInfo>(provider, i);
  519. })
  520. .Where(i => i != null)
  521. .ToList();
  522. }
  523. public Task<MediaSourceInfo> GetRecordingStream(string recordingId, string streamId, CancellationToken cancellationToken)
  524. {
  525. throw new NotImplementedException();
  526. }
  527. public async Task<MediaSourceInfo> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
  528. {
  529. _logger.Info("Streaming Channel " + channelId);
  530. foreach (var hostInstance in _liveTvManager.TunerHosts)
  531. {
  532. try
  533. {
  534. var result = await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
  535. result.Item2.Release();
  536. return result.Item1;
  537. }
  538. catch (Exception e)
  539. {
  540. _logger.ErrorException("Error getting channel stream", e);
  541. }
  542. }
  543. throw new ApplicationException("Tuner not found.");
  544. }
  545. private async Task<Tuple<MediaSourceInfo, ITunerHost, SemaphoreSlim>> GetChannelStreamInternal(string channelId, string streamId, CancellationToken cancellationToken)
  546. {
  547. _logger.Info("Streaming Channel " + channelId);
  548. foreach (var hostInstance in _liveTvManager.TunerHosts)
  549. {
  550. try
  551. {
  552. var result = await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
  553. return new Tuple<MediaSourceInfo, ITunerHost, SemaphoreSlim>(result.Item1, hostInstance, result.Item2);
  554. }
  555. catch (Exception e)
  556. {
  557. _logger.ErrorException("Error getting channel stream", e);
  558. }
  559. }
  560. throw new ApplicationException("Tuner not found.");
  561. }
  562. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  563. {
  564. foreach (var hostInstance in _liveTvManager.TunerHosts)
  565. {
  566. try
  567. {
  568. var sources = await hostInstance.GetChannelStreamMediaSources(channelId, cancellationToken).ConfigureAwait(false);
  569. if (sources.Count > 0)
  570. {
  571. return sources;
  572. }
  573. }
  574. catch (NotImplementedException)
  575. {
  576. }
  577. }
  578. throw new NotImplementedException();
  579. }
  580. public Task<List<MediaSourceInfo>> GetRecordingStreamMediaSources(string recordingId, CancellationToken cancellationToken)
  581. {
  582. throw new NotImplementedException();
  583. }
  584. public Task CloseLiveStream(string id, CancellationToken cancellationToken)
  585. {
  586. return Task.FromResult(0);
  587. }
  588. public Task RecordLiveStream(string id, CancellationToken cancellationToken)
  589. {
  590. return Task.FromResult(0);
  591. }
  592. public Task ResetTuner(string id, CancellationToken cancellationToken)
  593. {
  594. return Task.FromResult(0);
  595. }
  596. async void _timerProvider_TimerFired(object sender, GenericEventArgs<TimerInfo> e)
  597. {
  598. var timer = e.Argument;
  599. _logger.Info("Recording timer fired.");
  600. try
  601. {
  602. var recordingEndDate = timer.EndDate.AddSeconds(timer.PostPaddingSeconds);
  603. if (recordingEndDate <= DateTime.UtcNow)
  604. {
  605. _logger.Warn("Recording timer fired for timer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
  606. return;
  607. }
  608. var activeRecordingInfo = new ActiveRecordingInfo
  609. {
  610. CancellationTokenSource = new CancellationTokenSource(),
  611. TimerId = timer.Id
  612. };
  613. if (_activeRecordings.TryAdd(timer.Id, activeRecordingInfo))
  614. {
  615. await RecordStream(timer, recordingEndDate, activeRecordingInfo, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false);
  616. }
  617. else
  618. {
  619. _logger.Info("Skipping RecordStream because it's already in progress.");
  620. }
  621. }
  622. catch (OperationCanceledException)
  623. {
  624. }
  625. catch (Exception ex)
  626. {
  627. _logger.ErrorException("Error recording stream", ex);
  628. }
  629. }
  630. private string GetRecordingPath(TimerInfo timer, ProgramInfo info)
  631. {
  632. var recordPath = RecordingPath;
  633. var config = GetConfiguration();
  634. if (info.IsMovie)
  635. {
  636. var customRecordingPath = config.MovieRecordingPath;
  637. var allowSubfolder = true;
  638. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  639. {
  640. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  641. recordPath = customRecordingPath;
  642. }
  643. if (allowSubfolder && config.EnableRecordingSubfolders)
  644. {
  645. recordPath = Path.Combine(recordPath, "Movies");
  646. }
  647. var folderName = _fileSystem.GetValidFilename(info.Name).Trim();
  648. if (info.ProductionYear.HasValue)
  649. {
  650. folderName += " (" + info.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  651. }
  652. recordPath = Path.Combine(recordPath, folderName);
  653. }
  654. else if (info.IsSeries)
  655. {
  656. var customRecordingPath = config.SeriesRecordingPath;
  657. var allowSubfolder = true;
  658. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  659. {
  660. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  661. recordPath = customRecordingPath;
  662. }
  663. if (allowSubfolder && config.EnableRecordingSubfolders)
  664. {
  665. recordPath = Path.Combine(recordPath, "Series");
  666. }
  667. var folderName = _fileSystem.GetValidFilename(info.Name).Trim();
  668. var folderNameWithYear = folderName;
  669. if (info.ProductionYear.HasValue)
  670. {
  671. folderNameWithYear += " (" + info.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  672. }
  673. if (Directory.Exists(Path.Combine(recordPath, folderName)))
  674. {
  675. recordPath = Path.Combine(recordPath, folderName);
  676. }
  677. else
  678. {
  679. recordPath = Path.Combine(recordPath, folderNameWithYear);
  680. }
  681. if (info.SeasonNumber.HasValue)
  682. {
  683. folderName = string.Format("Season {0}", info.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture));
  684. recordPath = Path.Combine(recordPath, folderName);
  685. }
  686. }
  687. else if (info.IsKids)
  688. {
  689. if (config.EnableRecordingSubfolders)
  690. {
  691. recordPath = Path.Combine(recordPath, "Kids");
  692. }
  693. var folderName = _fileSystem.GetValidFilename(info.Name).Trim();
  694. if (info.ProductionYear.HasValue)
  695. {
  696. folderName += " (" + info.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  697. }
  698. recordPath = Path.Combine(recordPath, folderName);
  699. }
  700. else if (info.IsSports)
  701. {
  702. if (config.EnableRecordingSubfolders)
  703. {
  704. recordPath = Path.Combine(recordPath, "Sports");
  705. }
  706. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(info.Name).Trim());
  707. }
  708. else
  709. {
  710. if (config.EnableRecordingSubfolders)
  711. {
  712. recordPath = Path.Combine(recordPath, "Other");
  713. }
  714. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(info.Name).Trim());
  715. }
  716. var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer, info)).Trim() + ".ts";
  717. return Path.Combine(recordPath, recordingFileName);
  718. }
  719. private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate, ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken)
  720. {
  721. if (timer == null)
  722. {
  723. throw new ArgumentNullException("timer");
  724. }
  725. ProgramInfo info = null;
  726. if (string.IsNullOrWhiteSpace(timer.ProgramId))
  727. {
  728. _logger.Info("Timer {0} has null programId", timer.Id);
  729. }
  730. else
  731. {
  732. info = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  733. }
  734. if (info == null)
  735. {
  736. _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  737. info = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  738. }
  739. if (info == null)
  740. {
  741. throw new InvalidOperationException(string.Format("Program with Id {0} not found", timer.ProgramId));
  742. }
  743. var recordPath = GetRecordingPath(timer, info);
  744. var recordingStatus = RecordingStatus.New;
  745. try
  746. {
  747. var result = await GetChannelStreamInternal(timer.ChannelId, null, CancellationToken.None).ConfigureAwait(false);
  748. var mediaStreamInfo = result.Item1;
  749. var isResourceOpen = true;
  750. // Unfortunately due to the semaphore we have to have a nested try/finally
  751. try
  752. {
  753. // HDHR doesn't seem to release the tuner right away after first probing with ffmpeg
  754. //await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  755. var recorder = await GetRecorder().ConfigureAwait(false);
  756. recordPath = recorder.GetOutputPath(mediaStreamInfo, recordPath);
  757. recordPath = EnsureFileUnique(recordPath, timer.Id);
  758. _fileSystem.CreateDirectory(Path.GetDirectoryName(recordPath));
  759. activeRecordingInfo.Path = recordPath;
  760. _libraryMonitor.ReportFileSystemChangeBeginning(recordPath);
  761. var duration = recordingEndDate - DateTime.UtcNow;
  762. _logger.Info("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
  763. _logger.Info("Writing file to path: " + recordPath);
  764. _logger.Info("Opening recording stream from tuner provider");
  765. Action onStarted = () =>
  766. {
  767. result.Item3.Release();
  768. isResourceOpen = false;
  769. };
  770. var pathWithDuration = result.Item2.ApplyDuration(mediaStreamInfo.Path, duration);
  771. // If it supports supplying duration via url
  772. if (!string.Equals(pathWithDuration, mediaStreamInfo.Path, StringComparison.OrdinalIgnoreCase))
  773. {
  774. mediaStreamInfo.Path = pathWithDuration;
  775. mediaStreamInfo.RunTimeTicks = duration.Ticks;
  776. }
  777. await recorder.Record(mediaStreamInfo, recordPath, duration, onStarted, cancellationToken).ConfigureAwait(false);
  778. recordingStatus = RecordingStatus.Completed;
  779. _logger.Info("Recording completed: {0}", recordPath);
  780. }
  781. finally
  782. {
  783. if (isResourceOpen)
  784. {
  785. result.Item3.Release();
  786. }
  787. _libraryMonitor.ReportFileSystemChangeComplete(recordPath, false);
  788. }
  789. }
  790. catch (OperationCanceledException)
  791. {
  792. _logger.Info("Recording stopped: {0}", recordPath);
  793. recordingStatus = RecordingStatus.Completed;
  794. }
  795. catch (Exception ex)
  796. {
  797. _logger.ErrorException("Error recording to {0}", ex, recordPath);
  798. recordingStatus = RecordingStatus.Error;
  799. }
  800. finally
  801. {
  802. ActiveRecordingInfo removed;
  803. _activeRecordings.TryRemove(timer.Id, out removed);
  804. }
  805. if (recordingStatus == RecordingStatus.Completed)
  806. {
  807. OnSuccessfulRecording(info.IsSeries, recordPath);
  808. _timerProvider.Delete(timer);
  809. }
  810. else if (DateTime.UtcNow < timer.EndDate)
  811. {
  812. const int retryIntervalSeconds = 60;
  813. _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds);
  814. _timerProvider.StartTimer(timer, TimeSpan.FromSeconds(retryIntervalSeconds));
  815. }
  816. else
  817. {
  818. _timerProvider.Delete(timer);
  819. }
  820. }
  821. private string EnsureFileUnique(string path, string timerId)
  822. {
  823. var originalPath = path;
  824. var index = 1;
  825. while (FileExists(path, timerId))
  826. {
  827. var parent = Path.GetDirectoryName(originalPath);
  828. var name = Path.GetFileNameWithoutExtension(originalPath);
  829. name += "-" + index.ToString(CultureInfo.InvariantCulture);
  830. path = Path.ChangeExtension(Path.Combine(parent, name), Path.GetExtension(originalPath));
  831. index++;
  832. }
  833. return path;
  834. }
  835. private bool FileExists(string path, string timerId)
  836. {
  837. if (_fileSystem.FileExists(path))
  838. {
  839. return true;
  840. }
  841. var hasRecordingAtPath = _activeRecordings.Values.ToList().Any(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.TimerId, timerId, StringComparison.OrdinalIgnoreCase));
  842. if (hasRecordingAtPath)
  843. {
  844. return true;
  845. }
  846. return false;
  847. }
  848. private async Task<IRecorder> GetRecorder()
  849. {
  850. var config = GetConfiguration();
  851. if (config.EnableRecordingEncoding)
  852. {
  853. var regInfo = await _security.GetRegistrationStatus("embytvrecordingconversion").ConfigureAwait(false);
  854. if (regInfo.IsValid)
  855. {
  856. return new EncodedRecorder(_logger, _fileSystem, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, config);
  857. }
  858. }
  859. return new DirectRecorder(_logger, _httpClient, _fileSystem);
  860. }
  861. private async void OnSuccessfulRecording(bool isSeries, string path)
  862. {
  863. if (GetConfiguration().EnableAutoOrganize)
  864. {
  865. if (isSeries)
  866. {
  867. try
  868. {
  869. // this is to account for the library monitor holding a lock for additional time after the change is complete.
  870. // ideally this shouldn't be hard-coded
  871. await Task.Delay(30000).ConfigureAwait(false);
  872. var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager);
  873. var result = await organize.OrganizeEpisodeFile(path, CancellationToken.None).ConfigureAwait(false);
  874. }
  875. catch (Exception ex)
  876. {
  877. _logger.ErrorException("Error processing new recording", ex);
  878. }
  879. }
  880. }
  881. }
  882. private ProgramInfo GetProgramInfoFromCache(string channelId, string programId)
  883. {
  884. var epgData = GetEpgDataForChannel(channelId);
  885. return epgData.FirstOrDefault(p => string.Equals(p.Id, programId, StringComparison.OrdinalIgnoreCase));
  886. }
  887. private ProgramInfo GetProgramInfoFromCache(string channelId, DateTime startDateUtc)
  888. {
  889. var epgData = GetEpgDataForChannel(channelId);
  890. var startDateTicks = startDateUtc.Ticks;
  891. // Find the first program that starts within 3 minutes
  892. return epgData.FirstOrDefault(p => Math.Abs(startDateTicks - p.StartDate.Ticks) <= TimeSpan.FromMinutes(3).Ticks);
  893. }
  894. private LiveTvOptions GetConfiguration()
  895. {
  896. return _config.GetConfiguration<LiveTvOptions>("livetv");
  897. }
  898. private async Task UpdateTimersForSeriesTimer(List<ProgramInfo> epgData, SeriesTimerInfo seriesTimer, bool deleteInvalidTimers)
  899. {
  900. var newTimers = GetTimersForSeries(seriesTimer, epgData, true).ToList();
  901. var registration = await GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
  902. if (registration.IsValid)
  903. {
  904. foreach (var timer in newTimers)
  905. {
  906. _timerProvider.AddOrUpdate(timer);
  907. }
  908. }
  909. if (deleteInvalidTimers)
  910. {
  911. var allTimers = GetTimersForSeries(seriesTimer, epgData, false)
  912. .Select(i => i.Id)
  913. .ToList();
  914. var deletes = _timerProvider.GetAll()
  915. .Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
  916. .Where(i => !allTimers.Contains(i.Id, StringComparer.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
  917. .ToList();
  918. foreach (var timer in deletes)
  919. {
  920. await CancelTimerAsync(timer.Id, CancellationToken.None).ConfigureAwait(false);
  921. }
  922. }
  923. }
  924. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer,
  925. IEnumerable<ProgramInfo> allPrograms,
  926. bool filterByCurrentRecordings)
  927. {
  928. if (seriesTimer == null)
  929. {
  930. throw new ArgumentNullException("seriesTimer");
  931. }
  932. if (allPrograms == null)
  933. {
  934. throw new ArgumentNullException("allPrograms");
  935. }
  936. // Exclude programs that have already ended
  937. allPrograms = allPrograms.Where(i => i.EndDate > DateTime.UtcNow && i.StartDate > DateTime.UtcNow);
  938. allPrograms = GetProgramsForSeries(seriesTimer, allPrograms);
  939. if (filterByCurrentRecordings)
  940. {
  941. allPrograms = allPrograms.Where(i => !IsProgramAlreadyInLibrary(i));
  942. }
  943. return allPrograms.Select(i => RecordingHelper.CreateTimer(i, seriesTimer));
  944. }
  945. private bool IsProgramAlreadyInLibrary(ProgramInfo program)
  946. {
  947. if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle))
  948. {
  949. var seriesIds = _libraryManager.GetItemIds(new InternalItemsQuery
  950. {
  951. IncludeItemTypes = new[] { typeof(Series).Name },
  952. Name = program.Name
  953. }).Select(i => i.ToString("N")).ToArray();
  954. if (seriesIds.Length == 0)
  955. {
  956. return false;
  957. }
  958. if (program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue)
  959. {
  960. var result = _libraryManager.GetItemsResult(new InternalItemsQuery
  961. {
  962. IncludeItemTypes = new[] { typeof(Episode).Name },
  963. ParentIndexNumber = program.SeasonNumber.Value,
  964. IndexNumber = program.EpisodeNumber.Value,
  965. AncestorIds = seriesIds,
  966. ExcludeLocationTypes = new[] { LocationType.Virtual }
  967. });
  968. if (result.TotalRecordCount > 0)
  969. {
  970. return true;
  971. }
  972. }
  973. if (!string.IsNullOrWhiteSpace(program.EpisodeTitle))
  974. {
  975. var result = _libraryManager.GetItemsResult(new InternalItemsQuery
  976. {
  977. IncludeItemTypes = new[] { typeof(Episode).Name },
  978. Name = program.EpisodeTitle,
  979. AncestorIds = seriesIds,
  980. ExcludeLocationTypes = new[] { LocationType.Virtual }
  981. });
  982. if (result.TotalRecordCount > 0)
  983. {
  984. return true;
  985. }
  986. }
  987. }
  988. return false;
  989. }
  990. private IEnumerable<ProgramInfo> GetProgramsForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  991. {
  992. if (!seriesTimer.RecordAnyTime)
  993. {
  994. allPrograms = allPrograms.Where(epg => Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - epg.StartDate.TimeOfDay.Ticks) < TimeSpan.FromMinutes(5).Ticks);
  995. }
  996. if (seriesTimer.RecordNewOnly)
  997. {
  998. allPrograms = allPrograms.Where(epg => !epg.IsRepeat);
  999. }
  1000. if (!seriesTimer.RecordAnyChannel)
  1001. {
  1002. allPrograms = allPrograms.Where(epg => string.Equals(epg.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase));
  1003. }
  1004. allPrograms = allPrograms.Where(i => seriesTimer.Days.Contains(i.StartDate.ToLocalTime().DayOfWeek));
  1005. if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
  1006. {
  1007. _logger.Error("seriesTimer.SeriesId is null. Cannot find programs for series");
  1008. return new List<ProgramInfo>();
  1009. }
  1010. return allPrograms.Where(i => string.Equals(i.SeriesId, seriesTimer.SeriesId, StringComparison.OrdinalIgnoreCase));
  1011. }
  1012. private string GetChannelEpgCachePath(string channelId)
  1013. {
  1014. return Path.Combine(_config.CommonApplicationPaths.CachePath, "embytvepg", channelId + ".json");
  1015. }
  1016. private readonly object _epgLock = new object();
  1017. private void SaveEpgDataForChannel(string channelId, List<ProgramInfo> epgData)
  1018. {
  1019. var path = GetChannelEpgCachePath(channelId);
  1020. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  1021. lock (_epgLock)
  1022. {
  1023. _jsonSerializer.SerializeToFile(epgData, path);
  1024. }
  1025. }
  1026. private List<ProgramInfo> GetEpgDataForChannel(string channelId)
  1027. {
  1028. try
  1029. {
  1030. lock (_epgLock)
  1031. {
  1032. return _jsonSerializer.DeserializeFromFile<List<ProgramInfo>>(GetChannelEpgCachePath(channelId));
  1033. }
  1034. }
  1035. catch
  1036. {
  1037. return new List<ProgramInfo>();
  1038. }
  1039. }
  1040. private List<ProgramInfo> GetEpgDataForChannels(List<string> channelIds)
  1041. {
  1042. return channelIds.SelectMany(GetEpgDataForChannel).ToList();
  1043. }
  1044. public void Dispose()
  1045. {
  1046. foreach (var pair in _activeRecordings.ToList())
  1047. {
  1048. pair.Value.CancellationTokenSource.Cancel();
  1049. }
  1050. }
  1051. public Task<MBRegistrationRecord> GetRegistrationInfo(string feature)
  1052. {
  1053. if (string.Equals(feature, "seriesrecordings", StringComparison.OrdinalIgnoreCase))
  1054. {
  1055. return _security.GetRegistrationStatus("embytvseriesrecordings");
  1056. }
  1057. return Task.FromResult(new MBRegistrationRecord
  1058. {
  1059. IsValid = true,
  1060. IsRegistered = true
  1061. });
  1062. }
  1063. public List<VirtualFolderInfo> GetRecordingFolders()
  1064. {
  1065. var list = new List<VirtualFolderInfo>();
  1066. var defaultFolder = RecordingPath;
  1067. var defaultName = "Recordings";
  1068. if (Directory.Exists(defaultFolder))
  1069. {
  1070. list.Add(new VirtualFolderInfo
  1071. {
  1072. Locations = new List<string> { defaultFolder },
  1073. Name = defaultName
  1074. });
  1075. }
  1076. var customPath = GetConfiguration().MovieRecordingPath;
  1077. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath))
  1078. {
  1079. list.Add(new VirtualFolderInfo
  1080. {
  1081. Locations = new List<string> { customPath },
  1082. Name = "Recorded Movies",
  1083. CollectionType = CollectionType.Movies
  1084. });
  1085. }
  1086. customPath = GetConfiguration().SeriesRecordingPath;
  1087. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath))
  1088. {
  1089. list.Add(new VirtualFolderInfo
  1090. {
  1091. Locations = new List<string> { customPath },
  1092. Name = "Recorded Series",
  1093. CollectionType = CollectionType.TvShows
  1094. });
  1095. }
  1096. return list;
  1097. }
  1098. class ActiveRecordingInfo
  1099. {
  1100. public string Path { get; set; }
  1101. public string TimerId { get; set; }
  1102. public CancellationTokenSource CancellationTokenSource { get; set; }
  1103. }
  1104. }
  1105. }