EmbyTV.cs 52 KB

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