EmbyTV.cs 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  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. if ((string.IsNullOrWhiteSpace(customRecordingPath) || string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase)) && config.EnableRecordingSubfolders)
  638. {
  639. recordPath = Path.Combine(recordPath, "Movies");
  640. }
  641. var folderName = _fileSystem.GetValidFilename(info.Name).Trim();
  642. if (info.ProductionYear.HasValue)
  643. {
  644. folderName += " (" + info.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  645. }
  646. recordPath = Path.Combine(recordPath, folderName);
  647. }
  648. else if (info.IsSeries)
  649. {
  650. var customRecordingPath = config.SeriesRecordingPath;
  651. if ((string.IsNullOrWhiteSpace(customRecordingPath) || string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase)) && config.EnableRecordingSubfolders)
  652. {
  653. recordPath = Path.Combine(recordPath, "Series");
  654. }
  655. var folderName = _fileSystem.GetValidFilename(info.Name).Trim();
  656. var folderNameWithYear = folderName;
  657. if (info.ProductionYear.HasValue)
  658. {
  659. folderNameWithYear += " (" + info.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  660. }
  661. if (Directory.Exists(Path.Combine(recordPath, folderName)))
  662. {
  663. recordPath = Path.Combine(recordPath, folderName);
  664. }
  665. else
  666. {
  667. recordPath = Path.Combine(recordPath, folderNameWithYear);
  668. }
  669. if (info.SeasonNumber.HasValue)
  670. {
  671. folderName = string.Format("Season {0}", info.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture));
  672. recordPath = Path.Combine(recordPath, folderName);
  673. }
  674. }
  675. else if (info.IsKids)
  676. {
  677. if (config.EnableRecordingSubfolders)
  678. {
  679. recordPath = Path.Combine(recordPath, "Kids");
  680. }
  681. var folderName = _fileSystem.GetValidFilename(info.Name).Trim();
  682. if (info.ProductionYear.HasValue)
  683. {
  684. folderName += " (" + info.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  685. }
  686. recordPath = Path.Combine(recordPath, folderName);
  687. }
  688. else if (info.IsSports)
  689. {
  690. if (config.EnableRecordingSubfolders)
  691. {
  692. recordPath = Path.Combine(recordPath, "Sports");
  693. }
  694. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(info.Name).Trim());
  695. }
  696. else
  697. {
  698. if (config.EnableRecordingSubfolders)
  699. {
  700. recordPath = Path.Combine(recordPath, "Other");
  701. }
  702. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(info.Name).Trim());
  703. }
  704. var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer, info)).Trim() + ".ts";
  705. return Path.Combine(recordPath, recordingFileName);
  706. }
  707. private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate, ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken)
  708. {
  709. if (timer == null)
  710. {
  711. throw new ArgumentNullException("timer");
  712. }
  713. ProgramInfo info = null;
  714. if (string.IsNullOrWhiteSpace(timer.ProgramId))
  715. {
  716. _logger.Info("Timer {0} has null programId", timer.Id);
  717. }
  718. else
  719. {
  720. info = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  721. }
  722. if (info == null)
  723. {
  724. _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  725. info = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  726. }
  727. if (info == null)
  728. {
  729. throw new InvalidOperationException(string.Format("Program with Id {0} not found", timer.ProgramId));
  730. }
  731. var recordPath = GetRecordingPath(timer, info);
  732. var recordingStatus = RecordingStatus.New;
  733. try
  734. {
  735. var result = await GetChannelStreamInternal(timer.ChannelId, null, CancellationToken.None).ConfigureAwait(false);
  736. var mediaStreamInfo = result.Item1;
  737. var isResourceOpen = true;
  738. // Unfortunately due to the semaphore we have to have a nested try/finally
  739. try
  740. {
  741. // HDHR doesn't seem to release the tuner right away after first probing with ffmpeg
  742. //await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  743. var recorder = await GetRecorder().ConfigureAwait(false);
  744. if (recorder is EncodedRecorder)
  745. {
  746. recordPath = Path.ChangeExtension(recordPath, ".mp4");
  747. }
  748. recordPath = EnsureFileUnique(recordPath, timer.Id);
  749. _fileSystem.CreateDirectory(Path.GetDirectoryName(recordPath));
  750. activeRecordingInfo.Path = recordPath;
  751. _libraryMonitor.ReportFileSystemChangeBeginning(recordPath);
  752. var duration = recordingEndDate - DateTime.UtcNow;
  753. _logger.Info("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
  754. _logger.Info("Writing file to path: " + recordPath);
  755. _logger.Info("Opening recording stream from tuner provider");
  756. Action onStarted = () =>
  757. {
  758. result.Item3.Release();
  759. isResourceOpen = false;
  760. };
  761. var pathWithDuration = result.Item2.ApplyDuration(mediaStreamInfo.Path, duration);
  762. // If it supports supplying duration via url
  763. if (!string.Equals(pathWithDuration, mediaStreamInfo.Path, StringComparison.OrdinalIgnoreCase))
  764. {
  765. mediaStreamInfo.Path = pathWithDuration;
  766. mediaStreamInfo.RunTimeTicks = duration.Ticks;
  767. }
  768. await recorder.Record(mediaStreamInfo, recordPath, duration, onStarted, cancellationToken).ConfigureAwait(false);
  769. recordingStatus = RecordingStatus.Completed;
  770. _logger.Info("Recording completed: {0}", recordPath);
  771. }
  772. finally
  773. {
  774. if (isResourceOpen)
  775. {
  776. result.Item3.Release();
  777. }
  778. _libraryMonitor.ReportFileSystemChangeComplete(recordPath, false);
  779. }
  780. }
  781. catch (OperationCanceledException)
  782. {
  783. _logger.Info("Recording stopped: {0}", recordPath);
  784. recordingStatus = RecordingStatus.Completed;
  785. }
  786. catch (Exception ex)
  787. {
  788. _logger.ErrorException("Error recording to {0}", ex, recordPath);
  789. recordingStatus = RecordingStatus.Error;
  790. }
  791. finally
  792. {
  793. ActiveRecordingInfo removed;
  794. _activeRecordings.TryRemove(timer.Id, out removed);
  795. }
  796. if (recordingStatus == RecordingStatus.Completed)
  797. {
  798. OnSuccessfulRecording(info.IsSeries, recordPath);
  799. _timerProvider.Delete(timer);
  800. }
  801. else if (DateTime.UtcNow < timer.EndDate)
  802. {
  803. const int retryIntervalSeconds = 60;
  804. _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds);
  805. _timerProvider.StartTimer(timer, TimeSpan.FromSeconds(retryIntervalSeconds));
  806. }
  807. else
  808. {
  809. _timerProvider.Delete(timer);
  810. }
  811. }
  812. private string EnsureFileUnique(string path, string timerId)
  813. {
  814. var originalPath = path;
  815. var index = 1;
  816. while (FileExists(path, timerId))
  817. {
  818. var parent = Path.GetDirectoryName(originalPath);
  819. var name = Path.GetFileNameWithoutExtension(originalPath);
  820. name += "-" + index.ToString(CultureInfo.InvariantCulture);
  821. path = Path.ChangeExtension(Path.Combine(parent, name), Path.GetExtension(originalPath));
  822. index++;
  823. }
  824. return path;
  825. }
  826. private bool FileExists(string path, string timerId)
  827. {
  828. if (_fileSystem.FileExists(path))
  829. {
  830. return true;
  831. }
  832. var hasRecordingAtPath = _activeRecordings.Values.ToList().Any(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.TimerId, timerId, StringComparison.OrdinalIgnoreCase));
  833. if (hasRecordingAtPath)
  834. {
  835. return true;
  836. }
  837. return false;
  838. }
  839. private async Task<IRecorder> GetRecorder()
  840. {
  841. var config = GetConfiguration();
  842. if (config.EnableRecordingEncoding)
  843. {
  844. var regInfo = await _security.GetRegistrationStatus("embytvrecordingconversion").ConfigureAwait(false);
  845. if (regInfo.IsValid)
  846. {
  847. return new EncodedRecorder(_logger, _fileSystem, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, config);
  848. }
  849. }
  850. return new DirectRecorder(_logger, _httpClient, _fileSystem);
  851. }
  852. private async void OnSuccessfulRecording(bool isSeries, string path)
  853. {
  854. if (GetConfiguration().EnableAutoOrganize)
  855. {
  856. if (isSeries)
  857. {
  858. try
  859. {
  860. // this is to account for the library monitor holding a lock for additional time after the change is complete.
  861. // ideally this shouldn't be hard-coded
  862. await Task.Delay(30000).ConfigureAwait(false);
  863. var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager);
  864. var result = await organize.OrganizeEpisodeFile(path, CancellationToken.None).ConfigureAwait(false);
  865. }
  866. catch (Exception ex)
  867. {
  868. _logger.ErrorException("Error processing new recording", ex);
  869. }
  870. }
  871. }
  872. }
  873. private ProgramInfo GetProgramInfoFromCache(string channelId, string programId)
  874. {
  875. var epgData = GetEpgDataForChannel(channelId);
  876. return epgData.FirstOrDefault(p => string.Equals(p.Id, programId, StringComparison.OrdinalIgnoreCase));
  877. }
  878. private ProgramInfo GetProgramInfoFromCache(string channelId, DateTime startDateUtc)
  879. {
  880. var epgData = GetEpgDataForChannel(channelId);
  881. var startDateTicks = startDateUtc.Ticks;
  882. // Find the first program that starts within 3 minutes
  883. return epgData.FirstOrDefault(p => Math.Abs(startDateTicks - p.StartDate.Ticks) <= TimeSpan.FromMinutes(3).Ticks);
  884. }
  885. private LiveTvOptions GetConfiguration()
  886. {
  887. return _config.GetConfiguration<LiveTvOptions>("livetv");
  888. }
  889. private async Task UpdateTimersForSeriesTimer(List<ProgramInfo> epgData, SeriesTimerInfo seriesTimer, bool deleteInvalidTimers)
  890. {
  891. var newTimers = GetTimersForSeries(seriesTimer, epgData, true).ToList();
  892. var registration = await GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
  893. if (registration.IsValid)
  894. {
  895. foreach (var timer in newTimers)
  896. {
  897. _timerProvider.AddOrUpdate(timer);
  898. }
  899. }
  900. if (deleteInvalidTimers)
  901. {
  902. var allTimers = GetTimersForSeries(seriesTimer, epgData, false)
  903. .Select(i => i.Id)
  904. .ToList();
  905. var deletes = _timerProvider.GetAll()
  906. .Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
  907. .Where(i => !allTimers.Contains(i.Id, StringComparer.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
  908. .ToList();
  909. foreach (var timer in deletes)
  910. {
  911. await CancelTimerAsync(timer.Id, CancellationToken.None).ConfigureAwait(false);
  912. }
  913. }
  914. }
  915. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer,
  916. IEnumerable<ProgramInfo> allPrograms,
  917. bool filterByCurrentRecordings)
  918. {
  919. if (seriesTimer == null)
  920. {
  921. throw new ArgumentNullException("seriesTimer");
  922. }
  923. if (allPrograms == null)
  924. {
  925. throw new ArgumentNullException("allPrograms");
  926. }
  927. // Exclude programs that have already ended
  928. allPrograms = allPrograms.Where(i => i.EndDate > DateTime.UtcNow && i.StartDate > DateTime.UtcNow);
  929. allPrograms = GetProgramsForSeries(seriesTimer, allPrograms);
  930. if (filterByCurrentRecordings)
  931. {
  932. allPrograms = allPrograms.Where(i => !IsProgramAlreadyInLibrary(i));
  933. }
  934. return allPrograms.Select(i => RecordingHelper.CreateTimer(i, seriesTimer));
  935. }
  936. private bool IsProgramAlreadyInLibrary(ProgramInfo program)
  937. {
  938. if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle))
  939. {
  940. var seriesIds = _libraryManager.GetItemIds(new InternalItemsQuery
  941. {
  942. IncludeItemTypes = new[] { typeof(Series).Name },
  943. Name = program.Name
  944. }).Select(i => i.ToString("N")).ToArray();
  945. if (seriesIds.Length == 0)
  946. {
  947. return false;
  948. }
  949. if (program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue)
  950. {
  951. var result = _libraryManager.GetItemsResult(new InternalItemsQuery
  952. {
  953. IncludeItemTypes = new[] { typeof(Episode).Name },
  954. ParentIndexNumber = program.SeasonNumber.Value,
  955. IndexNumber = program.EpisodeNumber.Value,
  956. AncestorIds = seriesIds
  957. });
  958. if (result.TotalRecordCount > 0)
  959. {
  960. return true;
  961. }
  962. }
  963. if (!string.IsNullOrWhiteSpace(program.EpisodeTitle))
  964. {
  965. var result = _libraryManager.GetItemsResult(new InternalItemsQuery
  966. {
  967. IncludeItemTypes = new[] { typeof(Episode).Name },
  968. Name = program.EpisodeTitle,
  969. AncestorIds = seriesIds
  970. });
  971. if (result.TotalRecordCount > 0)
  972. {
  973. return true;
  974. }
  975. }
  976. }
  977. return false;
  978. }
  979. private IEnumerable<ProgramInfo> GetProgramsForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  980. {
  981. if (!seriesTimer.RecordAnyTime)
  982. {
  983. allPrograms = allPrograms.Where(epg => Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - epg.StartDate.TimeOfDay.Ticks) < TimeSpan.FromMinutes(5).Ticks);
  984. }
  985. if (seriesTimer.RecordNewOnly)
  986. {
  987. allPrograms = allPrograms.Where(epg => !epg.IsRepeat);
  988. }
  989. if (!seriesTimer.RecordAnyChannel)
  990. {
  991. allPrograms = allPrograms.Where(epg => string.Equals(epg.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase));
  992. }
  993. allPrograms = allPrograms.Where(i => seriesTimer.Days.Contains(i.StartDate.ToLocalTime().DayOfWeek));
  994. if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
  995. {
  996. _logger.Error("seriesTimer.SeriesId is null. Cannot find programs for series");
  997. return new List<ProgramInfo>();
  998. }
  999. return allPrograms.Where(i => string.Equals(i.SeriesId, seriesTimer.SeriesId, StringComparison.OrdinalIgnoreCase));
  1000. }
  1001. private string GetChannelEpgCachePath(string channelId)
  1002. {
  1003. return Path.Combine(_config.CommonApplicationPaths.CachePath, "embytvepg", channelId + ".json");
  1004. }
  1005. private readonly object _epgLock = new object();
  1006. private void SaveEpgDataForChannel(string channelId, List<ProgramInfo> epgData)
  1007. {
  1008. var path = GetChannelEpgCachePath(channelId);
  1009. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  1010. lock (_epgLock)
  1011. {
  1012. _jsonSerializer.SerializeToFile(epgData, path);
  1013. }
  1014. }
  1015. private List<ProgramInfo> GetEpgDataForChannel(string channelId)
  1016. {
  1017. try
  1018. {
  1019. lock (_epgLock)
  1020. {
  1021. return _jsonSerializer.DeserializeFromFile<List<ProgramInfo>>(GetChannelEpgCachePath(channelId));
  1022. }
  1023. }
  1024. catch
  1025. {
  1026. return new List<ProgramInfo>();
  1027. }
  1028. }
  1029. private List<ProgramInfo> GetEpgDataForChannels(List<string> channelIds)
  1030. {
  1031. return channelIds.SelectMany(GetEpgDataForChannel).ToList();
  1032. }
  1033. public void Dispose()
  1034. {
  1035. foreach (var pair in _activeRecordings.ToList())
  1036. {
  1037. pair.Value.CancellationTokenSource.Cancel();
  1038. }
  1039. }
  1040. public Task<MBRegistrationRecord> GetRegistrationInfo(string feature)
  1041. {
  1042. if (string.Equals(feature, "seriesrecordings", StringComparison.OrdinalIgnoreCase))
  1043. {
  1044. return _security.GetRegistrationStatus("embytvseriesrecordings");
  1045. }
  1046. return Task.FromResult(new MBRegistrationRecord
  1047. {
  1048. IsValid = true,
  1049. IsRegistered = true
  1050. });
  1051. }
  1052. public List<VirtualFolderInfo> GetRecordingFolders()
  1053. {
  1054. var list = new List<VirtualFolderInfo>();
  1055. var defaultFolder = RecordingPath;
  1056. var defaultName = "Recordings";
  1057. if (Directory.Exists(defaultFolder))
  1058. {
  1059. list.Add(new VirtualFolderInfo
  1060. {
  1061. Locations = new List<string> { defaultFolder },
  1062. Name = defaultName
  1063. });
  1064. }
  1065. var customPath = GetConfiguration().MovieRecordingPath;
  1066. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath))
  1067. {
  1068. list.Add(new VirtualFolderInfo
  1069. {
  1070. Locations = new List<string> { customPath },
  1071. Name = "Recorded Movies",
  1072. CollectionType = CollectionType.Movies
  1073. });
  1074. }
  1075. customPath = GetConfiguration().SeriesRecordingPath;
  1076. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath))
  1077. {
  1078. list.Add(new VirtualFolderInfo
  1079. {
  1080. Locations = new List<string> { customPath },
  1081. Name = "Recorded Series",
  1082. CollectionType = CollectionType.TvShows
  1083. });
  1084. }
  1085. return list;
  1086. }
  1087. class ActiveRecordingInfo
  1088. {
  1089. public string Path { get; set; }
  1090. public string TimerId { get; set; }
  1091. public CancellationTokenSource CancellationTokenSource { get; set; }
  1092. }
  1093. }
  1094. }