EmbyTV.cs 26 KB

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