EmbyTV.cs 51 KB

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