EmbyTV.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Common.IO;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Controller.Drawing;
  7. using MediaBrowser.Controller.LiveTv;
  8. using MediaBrowser.Model.Dto;
  9. using MediaBrowser.Model.Events;
  10. using MediaBrowser.Model.LiveTv;
  11. using MediaBrowser.Model.Logging;
  12. using MediaBrowser.Model.Serialization;
  13. using System;
  14. using System.Collections.Concurrent;
  15. using System.Collections.Generic;
  16. using System.Globalization;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  21. namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
  22. {
  23. public class EmbyTV : ILiveTvService, IDisposable
  24. {
  25. private readonly IApplicationHost _appHpst;
  26. private readonly ILogger _logger;
  27. private readonly IHttpClient _httpClient;
  28. private readonly IConfigurationManager _config;
  29. private readonly IJsonSerializer _jsonSerializer;
  30. private readonly ItemDataProvider<RecordingInfo> _recordingProvider;
  31. private readonly ItemDataProvider<SeriesTimerInfo> _seriesTimerProvider;
  32. private readonly TimerManager _timerProvider;
  33. private readonly LiveTvManager _liveTvManager;
  34. private readonly IFileSystem _fileSystem;
  35. public static EmbyTV Current;
  36. public EmbyTV(IApplicationHost appHost, ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IConfigurationManager config, ILiveTvManager liveTvManager, IFileSystem fileSystem)
  37. {
  38. Current = this;
  39. _appHpst = appHost;
  40. _logger = logger;
  41. _httpClient = httpClient;
  42. _config = config;
  43. _fileSystem = fileSystem;
  44. _liveTvManager = (LiveTvManager)liveTvManager;
  45. _jsonSerializer = jsonSerializer;
  46. _recordingProvider = new ItemDataProvider<RecordingInfo>(jsonSerializer, _logger, Path.Combine(DataPath, "recordings"), (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase));
  47. _seriesTimerProvider = new SeriesTimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers"));
  48. _timerProvider = new TimerManager(jsonSerializer, _logger, Path.Combine(DataPath, "timers"));
  49. _timerProvider.TimerFired += _timerProvider_TimerFired;
  50. }
  51. public void Start()
  52. {
  53. _timerProvider.RestartTimers();
  54. }
  55. public event EventHandler DataSourceChanged;
  56. public event EventHandler<RecordingStatusChangedEventArgs> RecordingStatusChanged;
  57. private readonly ConcurrentDictionary<string, CancellationTokenSource> _activeRecordings =
  58. new ConcurrentDictionary<string, CancellationTokenSource>(StringComparer.OrdinalIgnoreCase);
  59. public string Name
  60. {
  61. get { return "Emby"; }
  62. }
  63. public string DataPath
  64. {
  65. get { return Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv"); }
  66. }
  67. public string HomePageUrl
  68. {
  69. get { return "http://emby.media"; }
  70. }
  71. public async Task<LiveTvServiceStatusInfo> GetStatusInfoAsync(CancellationToken cancellationToken)
  72. {
  73. var status = new LiveTvServiceStatusInfo();
  74. var list = new List<LiveTvTunerInfo>();
  75. foreach (var hostInstance in GetTunerHosts())
  76. {
  77. try
  78. {
  79. var tuners = await hostInstance.Item1.GetTunerInfos(hostInstance.Item2, cancellationToken).ConfigureAwait(false);
  80. list.AddRange(tuners);
  81. }
  82. catch (Exception ex)
  83. {
  84. _logger.ErrorException("Error getting tuners", ex);
  85. }
  86. }
  87. status.Tuners = list;
  88. status.Status = LiveTvServiceStatus.Ok;
  89. status.Version = _appHpst.ApplicationVersion.ToString();
  90. status.IsVisible = false;
  91. return status;
  92. }
  93. private List<ChannelInfo> _channelCache = null;
  94. private async Task<IEnumerable<ChannelInfo>> GetChannelsAsync(bool enableCache, CancellationToken cancellationToken)
  95. {
  96. if (enableCache && _channelCache != null)
  97. {
  98. return _channelCache.ToList();
  99. }
  100. var list = new List<ChannelInfo>();
  101. foreach (var hostInstance in GetTunerHosts())
  102. {
  103. try
  104. {
  105. var channels = await hostInstance.Item1.GetChannels(hostInstance.Item2, cancellationToken).ConfigureAwait(false);
  106. list.AddRange(channels);
  107. }
  108. catch (Exception ex)
  109. {
  110. _logger.ErrorException("Error getting channels", ex);
  111. }
  112. }
  113. if (list.Count > 0)
  114. {
  115. foreach (var provider in GetListingProviders())
  116. {
  117. try
  118. {
  119. await provider.Item1.AddMetadata(provider.Item2, list, cancellationToken).ConfigureAwait(false);
  120. }
  121. catch (NotSupportedException)
  122. {
  123. }
  124. catch (Exception ex)
  125. {
  126. _logger.ErrorException("Error adding metadata", ex);
  127. }
  128. }
  129. }
  130. _channelCache = list;
  131. return list;
  132. }
  133. public Task<IEnumerable<ChannelInfo>> GetChannelsAsync(CancellationToken cancellationToken)
  134. {
  135. return GetChannelsAsync(false, cancellationToken);
  136. }
  137. private List<Tuple<ITunerHost, TunerHostInfo>> GetTunerHosts()
  138. {
  139. return GetConfiguration().TunerHosts
  140. .Where(i => i.IsEnabled)
  141. .Select(i =>
  142. {
  143. var provider = _liveTvManager.TunerHosts.FirstOrDefault(l => string.Equals(l.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  144. return provider == null ? null : new Tuple<ITunerHost, TunerHostInfo>(provider, i);
  145. })
  146. .Where(i => i != null)
  147. .ToList();
  148. }
  149. public Task CancelSeriesTimerAsync(string timerId, CancellationToken cancellationToken)
  150. {
  151. var remove = _seriesTimerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
  152. if (remove != null)
  153. {
  154. _seriesTimerProvider.Delete(remove);
  155. }
  156. return Task.FromResult(true);
  157. }
  158. private void CancelTimerInternal(string timerId)
  159. {
  160. var remove = _timerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
  161. if (remove != null)
  162. {
  163. _timerProvider.Delete(remove);
  164. }
  165. CancellationTokenSource cancellationTokenSource;
  166. if (_activeRecordings.TryGetValue(timerId, out cancellationTokenSource))
  167. {
  168. cancellationTokenSource.Cancel();
  169. }
  170. }
  171. public Task CancelTimerAsync(string timerId, CancellationToken cancellationToken)
  172. {
  173. CancelTimerInternal(timerId);
  174. return Task.FromResult(true);
  175. }
  176. public async Task DeleteRecordingAsync(string recordingId, CancellationToken cancellationToken)
  177. {
  178. var remove = _recordingProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, recordingId, StringComparison.OrdinalIgnoreCase));
  179. if (remove != null)
  180. {
  181. if (!string.IsNullOrWhiteSpace(remove.TimerId))
  182. {
  183. var enableDelay = _activeRecordings.ContainsKey(remove.TimerId);
  184. CancelTimerInternal(remove.TimerId);
  185. if (enableDelay)
  186. {
  187. // A hack yes, but need to make sure the file is closed before attempting to delete it
  188. await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  189. }
  190. }
  191. try
  192. {
  193. File.Delete(remove.Path);
  194. }
  195. catch (DirectoryNotFoundException)
  196. {
  197. }
  198. catch (FileNotFoundException)
  199. {
  200. }
  201. _recordingProvider.Delete(remove);
  202. }
  203. }
  204. public Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
  205. {
  206. info.Id = Guid.NewGuid().ToString("N");
  207. _timerProvider.Add(info);
  208. return Task.FromResult(0);
  209. }
  210. public async Task CreateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  211. {
  212. info.Id = Guid.NewGuid().ToString("N");
  213. await UpdateTimersForSeriesTimer(info).ConfigureAwait(false);
  214. _seriesTimerProvider.Add(info);
  215. }
  216. public async Task UpdateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  217. {
  218. _seriesTimerProvider.Update(info);
  219. await UpdateTimersForSeriesTimer(info).ConfigureAwait(false);
  220. }
  221. public Task UpdateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
  222. {
  223. _timerProvider.Update(info);
  224. return Task.FromResult(true);
  225. }
  226. public Task<ImageStream> GetChannelImageAsync(string channelId, CancellationToken cancellationToken)
  227. {
  228. throw new NotImplementedException();
  229. }
  230. public Task<ImageStream> GetRecordingImageAsync(string recordingId, CancellationToken cancellationToken)
  231. {
  232. throw new NotImplementedException();
  233. }
  234. public Task<ImageStream> GetProgramImageAsync(string programId, string channelId, CancellationToken cancellationToken)
  235. {
  236. throw new NotImplementedException();
  237. }
  238. public Task<IEnumerable<RecordingInfo>> GetRecordingsAsync(CancellationToken cancellationToken)
  239. {
  240. return Task.FromResult((IEnumerable<RecordingInfo>)_recordingProvider.GetAll());
  241. }
  242. public Task<IEnumerable<TimerInfo>> GetTimersAsync(CancellationToken cancellationToken)
  243. {
  244. return Task.FromResult((IEnumerable<TimerInfo>)_timerProvider.GetAll());
  245. }
  246. public Task<SeriesTimerInfo> GetNewTimerDefaultsAsync(CancellationToken cancellationToken, ProgramInfo program = null)
  247. {
  248. var defaults = new SeriesTimerInfo()
  249. {
  250. PostPaddingSeconds = 60,
  251. PrePaddingSeconds = 60,
  252. RecordAnyChannel = false,
  253. RecordAnyTime = false,
  254. RecordNewOnly = false
  255. };
  256. if (program != null)
  257. {
  258. defaults.SeriesId = program.SeriesId;
  259. defaults.ProgramId = program.Id;
  260. }
  261. return Task.FromResult(defaults);
  262. }
  263. public Task<IEnumerable<SeriesTimerInfo>> GetSeriesTimersAsync(CancellationToken cancellationToken)
  264. {
  265. return Task.FromResult((IEnumerable<SeriesTimerInfo>)_seriesTimerProvider.GetAll());
  266. }
  267. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  268. {
  269. var channels = await GetChannelsAsync(true, cancellationToken).ConfigureAwait(false);
  270. var channel = channels.First(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  271. foreach (var provider in GetListingProviders())
  272. {
  273. var programs = await provider.Item1.GetProgramsAsync(provider.Item2, channel.Number, startDateUtc, endDateUtc, cancellationToken)
  274. .ConfigureAwait(false);
  275. var list = programs.ToList();
  276. // Replace the value that came from the provider with a normalized value
  277. foreach (var program in list)
  278. {
  279. program.ChannelId = channelId;
  280. }
  281. if (list.Count > 0)
  282. {
  283. SaveEpgDataForChannel(channelId, list);
  284. return list;
  285. }
  286. }
  287. return new List<ProgramInfo>();
  288. }
  289. private List<Tuple<IListingsProvider, ListingsProviderInfo>> GetListingProviders()
  290. {
  291. return GetConfiguration().ListingProviders
  292. .Select(i =>
  293. {
  294. var provider = _liveTvManager.ListingProviders.FirstOrDefault(l => string.Equals(l.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  295. return provider == null ? null : new Tuple<IListingsProvider, ListingsProviderInfo>(provider, i);
  296. })
  297. .Where(i => i != null)
  298. .ToList();
  299. }
  300. public Task<MediaSourceInfo> GetRecordingStream(string recordingId, string streamId, CancellationToken cancellationToken)
  301. {
  302. throw new NotImplementedException();
  303. }
  304. public async Task<MediaSourceInfo> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
  305. {
  306. _logger.Info("Streaming Channel " + channelId);
  307. foreach (var hostInstance in GetTunerHosts())
  308. {
  309. if (!string.IsNullOrWhiteSpace(streamId))
  310. {
  311. var originalStreamId = string.Join("-", streamId.Split('-').Skip(1).ToArray());
  312. if (!string.Equals(hostInstance.Item2.Id, originalStreamId, StringComparison.OrdinalIgnoreCase))
  313. {
  314. continue;
  315. }
  316. }
  317. MediaSourceInfo mediaSourceInfo = null;
  318. try
  319. {
  320. mediaSourceInfo = await hostInstance.Item1.GetChannelStream(hostInstance.Item2, channelId, streamId, cancellationToken).ConfigureAwait(false);
  321. }
  322. catch (Exception e)
  323. {
  324. _logger.ErrorException("Error getting channel stream", e);
  325. }
  326. if (mediaSourceInfo != null)
  327. {
  328. mediaSourceInfo.Id = Guid.NewGuid().ToString("N");
  329. return mediaSourceInfo;
  330. }
  331. }
  332. throw new ApplicationException("Tuner not found.");
  333. }
  334. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  335. {
  336. foreach (var hostInstance in GetTunerHosts())
  337. {
  338. try
  339. {
  340. var sources = await hostInstance.Item1.GetChannelStreamMediaSources(hostInstance.Item2, channelId, cancellationToken).ConfigureAwait(false);
  341. foreach (var source in sources)
  342. {
  343. source.Id = hostInstance.Item2.Id + "-" + source.Id;
  344. }
  345. if (sources.Count > 0)
  346. {
  347. return sources;
  348. }
  349. }
  350. catch (NotImplementedException)
  351. {
  352. }
  353. }
  354. throw new ApplicationException("Tuner not found.");
  355. }
  356. public Task<List<MediaSourceInfo>> GetRecordingStreamMediaSources(string recordingId, CancellationToken cancellationToken)
  357. {
  358. throw new NotImplementedException();
  359. }
  360. public Task CloseLiveStream(string id, CancellationToken cancellationToken)
  361. {
  362. return Task.FromResult(0);
  363. }
  364. public Task RecordLiveStream(string id, CancellationToken cancellationToken)
  365. {
  366. return Task.FromResult(0);
  367. }
  368. public Task ResetTuner(string id, CancellationToken cancellationToken)
  369. {
  370. return Task.FromResult(0);
  371. }
  372. async void _timerProvider_TimerFired(object sender, GenericEventArgs<TimerInfo> e)
  373. {
  374. try
  375. {
  376. var cancellationTokenSource = new CancellationTokenSource();
  377. if (_activeRecordings.TryAdd(e.Argument.Id, cancellationTokenSource))
  378. {
  379. await RecordStream(e.Argument, cancellationTokenSource.Token).ConfigureAwait(false);
  380. }
  381. }
  382. catch (OperationCanceledException)
  383. {
  384. }
  385. catch (Exception ex)
  386. {
  387. _logger.ErrorException("Error recording stream", ex);
  388. }
  389. }
  390. private async Task RecordStream(TimerInfo timer, CancellationToken cancellationToken)
  391. {
  392. if (timer == null)
  393. {
  394. throw new ArgumentNullException("timer");
  395. }
  396. var mediaStreamInfo = await GetChannelStream(timer.ChannelId, null, CancellationToken.None);
  397. var duration = (timer.EndDate - DateTime.UtcNow).Add(TimeSpan.FromSeconds(timer.PostPaddingSeconds));
  398. HttpRequestOptions httpRequestOptions = new HttpRequestOptions()
  399. {
  400. Url = mediaStreamInfo.Path + "?duration=" + duration.TotalSeconds.ToString(CultureInfo.InvariantCulture)
  401. };
  402. var info = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  403. var recordPath = RecordingPath;
  404. if (info.IsMovie)
  405. {
  406. recordPath = Path.Combine(recordPath, "Movies", _fileSystem.GetValidFilename(info.Name));
  407. }
  408. else
  409. {
  410. recordPath = Path.Combine(recordPath, "TV", _fileSystem.GetValidFilename(info.Name));
  411. }
  412. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer, info)));
  413. Directory.CreateDirectory(Path.GetDirectoryName(recordPath));
  414. var recording = _recordingProvider.GetAll().FirstOrDefault(x => string.Equals(x.ProgramId, info.Id, StringComparison.OrdinalIgnoreCase));
  415. if (recording == null)
  416. {
  417. recording = new RecordingInfo
  418. {
  419. ChannelId = info.ChannelId,
  420. Id = Guid.NewGuid().ToString("N"),
  421. StartDate = info.StartDate,
  422. EndDate = info.EndDate,
  423. Genres = info.Genres,
  424. IsKids = info.IsKids,
  425. IsLive = info.IsLive,
  426. IsMovie = info.IsMovie,
  427. IsHD = info.IsHD,
  428. IsNews = info.IsNews,
  429. IsPremiere = info.IsPremiere,
  430. IsSeries = info.IsSeries,
  431. IsSports = info.IsSports,
  432. IsRepeat = !info.IsPremiere,
  433. Name = info.Name,
  434. EpisodeTitle = info.EpisodeTitle,
  435. ProgramId = info.Id,
  436. HasImage = info.HasImage,
  437. ImagePath = info.ImagePath,
  438. ImageUrl = info.ImageUrl,
  439. OriginalAirDate = info.OriginalAirDate,
  440. Status = RecordingStatus.Scheduled,
  441. Overview = info.Overview,
  442. SeriesTimerId = timer.SeriesTimerId,
  443. TimerId = timer.Id,
  444. ShowId = info.ShowId
  445. };
  446. _recordingProvider.Add(recording);
  447. }
  448. recording.Path = recordPath;
  449. recording.Status = RecordingStatus.InProgress;
  450. _recordingProvider.Update(recording);
  451. try
  452. {
  453. httpRequestOptions.BufferContent = false;
  454. var durationToken = new CancellationTokenSource(duration);
  455. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
  456. httpRequestOptions.CancellationToken = linkedToken;
  457. _logger.Info("Writing file to path: " + recordPath);
  458. using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET"))
  459. {
  460. using (var output = File.Open(recordPath, FileMode.Create, FileAccess.Write, FileShare.Read))
  461. {
  462. await response.Content.CopyToAsync(output, 131072, linkedToken);
  463. }
  464. }
  465. recording.Status = RecordingStatus.Completed;
  466. _logger.Info("Recording completed");
  467. }
  468. catch (OperationCanceledException)
  469. {
  470. _logger.Info("Recording cancelled");
  471. recording.Status = RecordingStatus.Completed;
  472. }
  473. catch (Exception ex)
  474. {
  475. _logger.ErrorException("Error recording", ex);
  476. recording.Status = RecordingStatus.Error;
  477. }
  478. _recordingProvider.Update(recording);
  479. _timerProvider.Delete(timer);
  480. _logger.Info("Recording was a success");
  481. }
  482. private ProgramInfo GetProgramInfoFromCache(string channelId, string programId)
  483. {
  484. var epgData = GetEpgDataForChannel(channelId);
  485. if (epgData.Any())
  486. {
  487. return epgData.FirstOrDefault(p => p.Id == programId);
  488. }
  489. return null;
  490. }
  491. private string RecordingPath
  492. {
  493. get
  494. {
  495. var path = GetConfiguration().RecordingPath;
  496. return string.IsNullOrWhiteSpace(path)
  497. ? Path.Combine(DataPath, "recordings")
  498. : path;
  499. }
  500. }
  501. private LiveTvOptions GetConfiguration()
  502. {
  503. return _config.GetConfiguration<LiveTvOptions>("livetv");
  504. }
  505. private async Task UpdateTimersForSeriesTimer(SeriesTimerInfo seriesTimer)
  506. {
  507. List<ProgramInfo> epgData;
  508. if (seriesTimer.RecordAnyChannel)
  509. {
  510. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  511. var channelIds = channels.Select(i => i.Id).ToList();
  512. epgData = GetEpgDataForChannels(channelIds);
  513. }
  514. else
  515. {
  516. epgData = GetEpgDataForChannel(seriesTimer.ChannelId);
  517. }
  518. var newTimers = GetTimersForSeries(seriesTimer, epgData, _recordingProvider.GetAll()).ToList();
  519. var existingTimers = _timerProvider.GetAll()
  520. .Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
  521. .ToList();
  522. foreach (var timer in newTimers)
  523. {
  524. _timerProvider.AddOrUpdate(timer);
  525. }
  526. var newTimerIds = newTimers.Select(i => i.Id).ToList();
  527. foreach (var timer in existingTimers)
  528. {
  529. if (!newTimerIds.Contains(timer.Id, StringComparer.OrdinalIgnoreCase))
  530. {
  531. CancelTimerInternal(timer.Id);
  532. }
  533. }
  534. }
  535. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms, IReadOnlyList<RecordingInfo> currentRecordings)
  536. {
  537. allPrograms = GetProgramsForSeries(seriesTimer, allPrograms);
  538. var recordingShowIds = currentRecordings.Select(i => i.ShowId).ToList();
  539. allPrograms = allPrograms.Where(epg => !recordingShowIds.Contains(epg.ShowId, StringComparer.OrdinalIgnoreCase));
  540. return allPrograms.Select(i => RecordingHelper.CreateTimer(i, seriesTimer));
  541. }
  542. private IEnumerable<ProgramInfo> GetProgramsForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  543. {
  544. if (!seriesTimer.RecordAnyTime)
  545. {
  546. allPrograms = allPrograms.Where(epg => (seriesTimer.StartDate.TimeOfDay == epg.StartDate.TimeOfDay));
  547. }
  548. if (seriesTimer.RecordNewOnly)
  549. {
  550. allPrograms = allPrograms.Where(epg => !epg.IsRepeat);
  551. }
  552. if (!seriesTimer.RecordAnyChannel)
  553. {
  554. allPrograms = allPrograms.Where(epg => string.Equals(epg.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase));
  555. }
  556. allPrograms = allPrograms.Where(i => seriesTimer.Days.Contains(i.StartDate.DayOfWeek));
  557. if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
  558. {
  559. _logger.Error("seriesTimer.SeriesId is null. Cannot find programs for series");
  560. return new List<ProgramInfo>();
  561. }
  562. return allPrograms.Where(i => string.Equals(i.SeriesId, seriesTimer.SeriesId, StringComparison.OrdinalIgnoreCase));
  563. }
  564. private string GetChannelEpgCachePath(string channelId)
  565. {
  566. return Path.Combine(DataPath, "epg", channelId + ".json");
  567. }
  568. private readonly object _epgLock = new object();
  569. private void SaveEpgDataForChannel(string channelId, List<ProgramInfo> epgData)
  570. {
  571. var path = GetChannelEpgCachePath(channelId);
  572. Directory.CreateDirectory(Path.GetDirectoryName(path));
  573. lock (_epgLock)
  574. {
  575. _jsonSerializer.SerializeToFile(epgData, path);
  576. }
  577. }
  578. private List<ProgramInfo> GetEpgDataForChannel(string channelId)
  579. {
  580. try
  581. {
  582. lock (_epgLock)
  583. {
  584. return _jsonSerializer.DeserializeFromFile<List<ProgramInfo>>(GetChannelEpgCachePath(channelId));
  585. }
  586. }
  587. catch
  588. {
  589. return new List<ProgramInfo>();
  590. }
  591. }
  592. private List<ProgramInfo> GetEpgDataForChannels(List<string> channelIds)
  593. {
  594. return channelIds.SelectMany(GetEpgDataForChannel).ToList();
  595. }
  596. public void Dispose()
  597. {
  598. foreach (var pair in _activeRecordings.ToList())
  599. {
  600. pair.Value.Cancel();
  601. }
  602. }
  603. }
  604. }