EmbyTV.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Common.Net;
  5. using MediaBrowser.Common.Security;
  6. using MediaBrowser.Controller.Configuration;
  7. using MediaBrowser.Controller.Drawing;
  8. using MediaBrowser.Controller.FileOrganization;
  9. using MediaBrowser.Controller.Library;
  10. using MediaBrowser.Controller.LiveTv;
  11. using MediaBrowser.Controller.MediaEncoding;
  12. using MediaBrowser.Controller.Providers;
  13. using MediaBrowser.Model.Dlna;
  14. using MediaBrowser.Model.Dto;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.Events;
  17. using MediaBrowser.Model.FileOrganization;
  18. using MediaBrowser.Model.LiveTv;
  19. using MediaBrowser.Model.Logging;
  20. using MediaBrowser.Model.Serialization;
  21. using MediaBrowser.Server.Implementations.FileOrganization;
  22. using System;
  23. using System.Collections.Concurrent;
  24. using System.Collections.Generic;
  25. using System.IO;
  26. using System.Linq;
  27. using System.Threading;
  28. using System.Threading.Tasks;
  29. using CommonIO;
  30. using MediaBrowser.Common.Extensions;
  31. namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
  32. {
  33. public class EmbyTV : ILiveTvService, IHasRegistrationInfo, IDisposable
  34. {
  35. private readonly IApplicationHost _appHpst;
  36. private readonly ILogger _logger;
  37. private readonly IHttpClient _httpClient;
  38. private readonly IServerConfigurationManager _config;
  39. private readonly IJsonSerializer _jsonSerializer;
  40. private readonly ItemDataProvider<RecordingInfo> _recordingProvider;
  41. private readonly ItemDataProvider<SeriesTimerInfo> _seriesTimerProvider;
  42. private readonly TimerManager _timerProvider;
  43. private readonly LiveTvManager _liveTvManager;
  44. private readonly IFileSystem _fileSystem;
  45. private readonly ISecurityManager _security;
  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 EmbyTV(IApplicationHost appHost, ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IServerConfigurationManager config, ILiveTvManager liveTvManager, IFileSystem fileSystem, ISecurityManager security, ILibraryManager libraryManager, ILibraryMonitor libraryMonitor, IProviderManager providerManager, IFileOrganizationService organizationService, IMediaEncoder mediaEncoder)
  53. {
  54. Current = this;
  55. _appHpst = appHost;
  56. _logger = logger;
  57. _httpClient = httpClient;
  58. _config = config;
  59. _fileSystem = fileSystem;
  60. _security = security;
  61. _libraryManager = libraryManager;
  62. _libraryMonitor = libraryMonitor;
  63. _providerManager = providerManager;
  64. _organizationService = organizationService;
  65. _mediaEncoder = mediaEncoder;
  66. _liveTvManager = (LiveTvManager)liveTvManager;
  67. _jsonSerializer = jsonSerializer;
  68. _recordingProvider = new ItemDataProvider<RecordingInfo>(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "recordings"), (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase));
  69. _seriesTimerProvider = new SeriesTimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers"));
  70. _timerProvider = new TimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "timers"));
  71. _timerProvider.TimerFired += _timerProvider_TimerFired;
  72. }
  73. public void Start()
  74. {
  75. _timerProvider.RestartTimers();
  76. }
  77. public event EventHandler DataSourceChanged;
  78. public event EventHandler<RecordingStatusChangedEventArgs> RecordingStatusChanged;
  79. private readonly ConcurrentDictionary<string, CancellationTokenSource> _activeRecordings =
  80. new ConcurrentDictionary<string, CancellationTokenSource>(StringComparer.OrdinalIgnoreCase);
  81. public string Name
  82. {
  83. get { return "Emby"; }
  84. }
  85. public string DataPath
  86. {
  87. get { return Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv"); }
  88. }
  89. public string HomePageUrl
  90. {
  91. get { return "http://emby.media"; }
  92. }
  93. public async Task<LiveTvServiceStatusInfo> GetStatusInfoAsync(CancellationToken cancellationToken)
  94. {
  95. var status = new LiveTvServiceStatusInfo();
  96. var list = new List<LiveTvTunerInfo>();
  97. foreach (var hostInstance in _liveTvManager.TunerHosts)
  98. {
  99. try
  100. {
  101. var tuners = await hostInstance.GetTunerInfos(cancellationToken).ConfigureAwait(false);
  102. list.AddRange(tuners);
  103. }
  104. catch (Exception ex)
  105. {
  106. _logger.ErrorException("Error getting tuners", ex);
  107. }
  108. }
  109. status.Tuners = list;
  110. status.Status = LiveTvServiceStatus.Ok;
  111. status.Version = _appHpst.ApplicationVersion.ToString();
  112. status.IsVisible = false;
  113. return status;
  114. }
  115. public async Task RefreshSeriesTimers(CancellationToken cancellationToken, IProgress<double> progress)
  116. {
  117. var timers = await GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  118. List<ChannelInfo> channels = null;
  119. foreach (var timer in timers)
  120. {
  121. List<ProgramInfo> epgData;
  122. if (timer.RecordAnyChannel)
  123. {
  124. if (channels == null)
  125. {
  126. channels = (await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false)).ToList();
  127. }
  128. var channelIds = channels.Select(i => i.Id).ToList();
  129. epgData = GetEpgDataForChannels(channelIds);
  130. }
  131. else
  132. {
  133. epgData = GetEpgDataForChannel(timer.ChannelId);
  134. }
  135. await UpdateTimersForSeriesTimer(epgData, timer).ConfigureAwait(false);
  136. }
  137. }
  138. private List<ChannelInfo> _channelCache = null;
  139. private async Task<IEnumerable<ChannelInfo>> GetChannelsAsync(bool enableCache, CancellationToken cancellationToken)
  140. {
  141. if (enableCache && _channelCache != null)
  142. {
  143. return _channelCache.ToList();
  144. }
  145. var list = new List<ChannelInfo>();
  146. foreach (var hostInstance in _liveTvManager.TunerHosts)
  147. {
  148. try
  149. {
  150. var channels = await hostInstance.GetChannels(cancellationToken).ConfigureAwait(false);
  151. list.AddRange(channels);
  152. }
  153. catch (Exception ex)
  154. {
  155. _logger.ErrorException("Error getting channels", ex);
  156. }
  157. }
  158. if (list.Count > 0)
  159. {
  160. foreach (var provider in GetListingProviders())
  161. {
  162. try
  163. {
  164. await provider.Item1.AddMetadata(provider.Item2, list, cancellationToken).ConfigureAwait(false);
  165. }
  166. catch (NotSupportedException)
  167. {
  168. }
  169. catch (Exception ex)
  170. {
  171. _logger.ErrorException("Error adding metadata", ex);
  172. }
  173. }
  174. }
  175. _channelCache = list;
  176. return list;
  177. }
  178. public Task<IEnumerable<ChannelInfo>> GetChannelsAsync(CancellationToken cancellationToken)
  179. {
  180. return GetChannelsAsync(false, cancellationToken);
  181. }
  182. public Task CancelSeriesTimerAsync(string timerId, CancellationToken cancellationToken)
  183. {
  184. var timers = _timerProvider.GetAll().Where(i => string.Equals(i.SeriesTimerId, timerId, StringComparison.OrdinalIgnoreCase));
  185. foreach (var timer in timers)
  186. {
  187. CancelTimerInternal(timer.Id);
  188. }
  189. var remove = _seriesTimerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
  190. if (remove != null)
  191. {
  192. _seriesTimerProvider.Delete(remove);
  193. }
  194. return Task.FromResult(true);
  195. }
  196. private void CancelTimerInternal(string timerId)
  197. {
  198. var remove = _timerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
  199. if (remove != null)
  200. {
  201. _timerProvider.Delete(remove);
  202. }
  203. CancellationTokenSource cancellationTokenSource;
  204. if (_activeRecordings.TryGetValue(timerId, out cancellationTokenSource))
  205. {
  206. cancellationTokenSource.Cancel();
  207. }
  208. }
  209. public Task CancelTimerAsync(string timerId, CancellationToken cancellationToken)
  210. {
  211. CancelTimerInternal(timerId);
  212. return Task.FromResult(true);
  213. }
  214. public async Task DeleteRecordingAsync(string recordingId, CancellationToken cancellationToken)
  215. {
  216. var remove = _recordingProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, recordingId, StringComparison.OrdinalIgnoreCase));
  217. if (remove != null)
  218. {
  219. if (!string.IsNullOrWhiteSpace(remove.TimerId))
  220. {
  221. var enableDelay = _activeRecordings.ContainsKey(remove.TimerId);
  222. CancelTimerInternal(remove.TimerId);
  223. if (enableDelay)
  224. {
  225. // A hack yes, but need to make sure the file is closed before attempting to delete it
  226. await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  227. }
  228. }
  229. try
  230. {
  231. _fileSystem.DeleteFile(remove.Path);
  232. }
  233. catch (DirectoryNotFoundException)
  234. {
  235. }
  236. catch (FileNotFoundException)
  237. {
  238. }
  239. _recordingProvider.Delete(remove);
  240. }
  241. else
  242. {
  243. throw new ResourceNotFoundException("Recording not found: " + recordingId);
  244. }
  245. }
  246. public Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
  247. {
  248. info.Id = Guid.NewGuid().ToString("N");
  249. _timerProvider.Add(info);
  250. return Task.FromResult(0);
  251. }
  252. public async Task CreateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  253. {
  254. info.Id = Guid.NewGuid().ToString("N");
  255. List<ProgramInfo> epgData;
  256. if (info.RecordAnyChannel)
  257. {
  258. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  259. var channelIds = channels.Select(i => i.Id).ToList();
  260. epgData = GetEpgDataForChannels(channelIds);
  261. }
  262. else
  263. {
  264. epgData = GetEpgDataForChannel(info.ChannelId);
  265. }
  266. // populate info.seriesID
  267. var program = epgData.FirstOrDefault(i => string.Equals(i.Id, info.ProgramId, StringComparison.OrdinalIgnoreCase));
  268. if (program != null)
  269. {
  270. info.SeriesId = program.SeriesId;
  271. }
  272. else
  273. {
  274. throw new InvalidOperationException("SeriesId for program not found");
  275. }
  276. _seriesTimerProvider.Add(info);
  277. await UpdateTimersForSeriesTimer(epgData, info).ConfigureAwait(false);
  278. }
  279. public async Task UpdateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  280. {
  281. _seriesTimerProvider.Update(info);
  282. List<ProgramInfo> epgData;
  283. if (info.RecordAnyChannel)
  284. {
  285. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  286. var channelIds = channels.Select(i => i.Id).ToList();
  287. epgData = GetEpgDataForChannels(channelIds);
  288. }
  289. else
  290. {
  291. epgData = GetEpgDataForChannel(info.ChannelId);
  292. }
  293. await UpdateTimersForSeriesTimer(epgData, info).ConfigureAwait(false);
  294. }
  295. public Task UpdateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
  296. {
  297. _timerProvider.Update(info);
  298. return Task.FromResult(true);
  299. }
  300. public Task<ImageStream> GetChannelImageAsync(string channelId, CancellationToken cancellationToken)
  301. {
  302. throw new NotImplementedException();
  303. }
  304. public Task<ImageStream> GetRecordingImageAsync(string recordingId, CancellationToken cancellationToken)
  305. {
  306. throw new NotImplementedException();
  307. }
  308. public Task<ImageStream> GetProgramImageAsync(string programId, string channelId, CancellationToken cancellationToken)
  309. {
  310. throw new NotImplementedException();
  311. }
  312. public async Task<IEnumerable<RecordingInfo>> GetRecordingsAsync(CancellationToken cancellationToken)
  313. {
  314. var recordings = _recordingProvider.GetAll().ToList();
  315. var updated = false;
  316. foreach (var recording in recordings)
  317. {
  318. if (recording.Status == RecordingStatus.InProgress)
  319. {
  320. if (string.IsNullOrWhiteSpace(recording.TimerId) || !_activeRecordings.ContainsKey(recording.TimerId))
  321. {
  322. recording.Status = RecordingStatus.Cancelled;
  323. recording.DateLastUpdated = DateTime.UtcNow;
  324. _recordingProvider.Update(recording);
  325. updated = true;
  326. }
  327. }
  328. }
  329. if (updated)
  330. {
  331. recordings = _recordingProvider.GetAll().ToList();
  332. }
  333. return recordings;
  334. }
  335. public Task<IEnumerable<TimerInfo>> GetTimersAsync(CancellationToken cancellationToken)
  336. {
  337. return Task.FromResult((IEnumerable<TimerInfo>)_timerProvider.GetAll());
  338. }
  339. public Task<SeriesTimerInfo> GetNewTimerDefaultsAsync(CancellationToken cancellationToken, ProgramInfo program = null)
  340. {
  341. var config = GetConfiguration();
  342. var defaults = new SeriesTimerInfo()
  343. {
  344. PostPaddingSeconds = Math.Max(config.PostPaddingSeconds, 0),
  345. PrePaddingSeconds = Math.Max(config.PrePaddingSeconds, 0),
  346. RecordAnyChannel = false,
  347. RecordAnyTime = false,
  348. RecordNewOnly = false
  349. };
  350. if (program != null)
  351. {
  352. defaults.SeriesId = program.SeriesId;
  353. defaults.ProgramId = program.Id;
  354. }
  355. return Task.FromResult(defaults);
  356. }
  357. public Task<IEnumerable<SeriesTimerInfo>> GetSeriesTimersAsync(CancellationToken cancellationToken)
  358. {
  359. return Task.FromResult((IEnumerable<SeriesTimerInfo>)_seriesTimerProvider.GetAll());
  360. }
  361. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  362. {
  363. try
  364. {
  365. return await GetProgramsAsyncInternal(channelId, startDateUtc, endDateUtc, cancellationToken).ConfigureAwait(false);
  366. }
  367. catch (Exception ex)
  368. {
  369. _logger.ErrorException("Error getting programs", ex);
  370. return GetEpgDataForChannel(channelId).Where(i => i.StartDate <= endDateUtc && i.EndDate >= startDateUtc);
  371. }
  372. }
  373. private async Task<IEnumerable<ProgramInfo>> GetProgramsAsyncInternal(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  374. {
  375. var channels = await GetChannelsAsync(true, cancellationToken).ConfigureAwait(false);
  376. var channel = channels.First(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  377. foreach (var provider in GetListingProviders())
  378. {
  379. var programs = await provider.Item1.GetProgramsAsync(provider.Item2, channel.Number, channel.Name, startDateUtc, endDateUtc, cancellationToken)
  380. .ConfigureAwait(false);
  381. var list = programs.ToList();
  382. // Replace the value that came from the provider with a normalized value
  383. foreach (var program in list)
  384. {
  385. program.ChannelId = channelId;
  386. }
  387. if (list.Count > 0)
  388. {
  389. SaveEpgDataForChannel(channelId, list);
  390. return list;
  391. }
  392. }
  393. return new List<ProgramInfo>();
  394. }
  395. private List<Tuple<IListingsProvider, ListingsProviderInfo>> GetListingProviders()
  396. {
  397. return GetConfiguration().ListingProviders
  398. .Select(i =>
  399. {
  400. var provider = _liveTvManager.ListingProviders.FirstOrDefault(l => string.Equals(l.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  401. return provider == null ? null : new Tuple<IListingsProvider, ListingsProviderInfo>(provider, i);
  402. })
  403. .Where(i => i != null)
  404. .ToList();
  405. }
  406. public Task<MediaSourceInfo> GetRecordingStream(string recordingId, string streamId, CancellationToken cancellationToken)
  407. {
  408. throw new NotImplementedException();
  409. }
  410. public async Task<MediaSourceInfo> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
  411. {
  412. _logger.Info("Streaming Channel " + channelId);
  413. foreach (var hostInstance in _liveTvManager.TunerHosts)
  414. {
  415. try
  416. {
  417. return await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
  418. }
  419. catch (Exception e)
  420. {
  421. _logger.ErrorException("Error getting channel stream", e);
  422. }
  423. }
  424. throw new ApplicationException("Tuner not found.");
  425. }
  426. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  427. {
  428. foreach (var hostInstance in _liveTvManager.TunerHosts)
  429. {
  430. try
  431. {
  432. var sources = await hostInstance.GetChannelStreamMediaSources(channelId, cancellationToken).ConfigureAwait(false);
  433. if (sources.Count > 0)
  434. {
  435. return sources;
  436. }
  437. }
  438. catch (NotImplementedException)
  439. {
  440. }
  441. }
  442. throw new NotImplementedException();
  443. }
  444. public Task<List<MediaSourceInfo>> GetRecordingStreamMediaSources(string recordingId, CancellationToken cancellationToken)
  445. {
  446. throw new NotImplementedException();
  447. }
  448. public Task CloseLiveStream(string id, CancellationToken cancellationToken)
  449. {
  450. return Task.FromResult(0);
  451. }
  452. public Task RecordLiveStream(string id, CancellationToken cancellationToken)
  453. {
  454. return Task.FromResult(0);
  455. }
  456. public Task ResetTuner(string id, CancellationToken cancellationToken)
  457. {
  458. return Task.FromResult(0);
  459. }
  460. async void _timerProvider_TimerFired(object sender, GenericEventArgs<TimerInfo> e)
  461. {
  462. var timer = e.Argument;
  463. _logger.Info("Recording timer fired.");
  464. try
  465. {
  466. var recordingEndDate = timer.EndDate.AddSeconds(timer.PostPaddingSeconds);
  467. if (recordingEndDate <= DateTime.UtcNow)
  468. {
  469. _logger.Warn("Recording timer fired for timer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
  470. return;
  471. }
  472. var cancellationTokenSource = new CancellationTokenSource();
  473. if (_activeRecordings.TryAdd(timer.Id, cancellationTokenSource))
  474. {
  475. await RecordStream(timer, recordingEndDate, cancellationTokenSource.Token).ConfigureAwait(false);
  476. }
  477. }
  478. catch (OperationCanceledException)
  479. {
  480. }
  481. catch (Exception ex)
  482. {
  483. _logger.ErrorException("Error recording stream", ex);
  484. }
  485. }
  486. private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate, CancellationToken cancellationToken)
  487. {
  488. if (timer == null)
  489. {
  490. throw new ArgumentNullException("timer");
  491. }
  492. var info = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  493. var recordPath = RecordingPath;
  494. if (info.IsMovie)
  495. {
  496. recordPath = Path.Combine(recordPath, "Movies", _fileSystem.GetValidFilename(info.Name).Trim());
  497. }
  498. else if (info.IsSeries)
  499. {
  500. recordPath = Path.Combine(recordPath, "Series", _fileSystem.GetValidFilename(info.Name).Trim());
  501. }
  502. else if (info.IsKids)
  503. {
  504. recordPath = Path.Combine(recordPath, "Kids", _fileSystem.GetValidFilename(info.Name).Trim());
  505. }
  506. else if (info.IsSports)
  507. {
  508. recordPath = Path.Combine(recordPath, "Sports", _fileSystem.GetValidFilename(info.Name).Trim());
  509. }
  510. else
  511. {
  512. recordPath = Path.Combine(recordPath, "Other", _fileSystem.GetValidFilename(info.Name).Trim());
  513. }
  514. var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer, info)).Trim() + ".ts";
  515. recordPath = Path.Combine(recordPath, recordingFileName);
  516. _fileSystem.CreateDirectory(Path.GetDirectoryName(recordPath));
  517. var recordingId = info.Id.GetMD5().ToString("N");
  518. var recording = _recordingProvider.GetAll().FirstOrDefault(x => string.Equals(x.Id, recordingId, StringComparison.OrdinalIgnoreCase));
  519. if (recording == null)
  520. {
  521. recording = new RecordingInfo
  522. {
  523. ChannelId = info.ChannelId,
  524. Id = recordingId,
  525. StartDate = info.StartDate,
  526. EndDate = info.EndDate,
  527. Genres = info.Genres,
  528. IsKids = info.IsKids,
  529. IsLive = info.IsLive,
  530. IsMovie = info.IsMovie,
  531. IsHD = info.IsHD,
  532. IsNews = info.IsNews,
  533. IsPremiere = info.IsPremiere,
  534. IsSeries = info.IsSeries,
  535. IsSports = info.IsSports,
  536. IsRepeat = !info.IsPremiere,
  537. Name = info.Name,
  538. EpisodeTitle = info.EpisodeTitle,
  539. ProgramId = info.Id,
  540. HasImage = info.HasImage,
  541. ImagePath = info.ImagePath,
  542. ImageUrl = info.ImageUrl,
  543. OriginalAirDate = info.OriginalAirDate,
  544. Status = RecordingStatus.Scheduled,
  545. Overview = info.Overview,
  546. SeriesTimerId = timer.SeriesTimerId,
  547. TimerId = timer.Id,
  548. ShowId = info.ShowId
  549. };
  550. _recordingProvider.Add(recording);
  551. }
  552. try
  553. {
  554. var mediaStreamInfo = await GetChannelStream(timer.ChannelId, null, CancellationToken.None);
  555. // HDHR doesn't seem to release the tuner right away after first probing with ffmpeg
  556. await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  557. var duration = recordingEndDate - DateTime.UtcNow;
  558. HttpRequestOptions httpRequestOptions = new HttpRequestOptions()
  559. {
  560. Url = mediaStreamInfo.Path
  561. };
  562. recording.Path = recordPath;
  563. recording.Status = RecordingStatus.InProgress;
  564. recording.DateLastUpdated = DateTime.UtcNow;
  565. _recordingProvider.Update(recording);
  566. _logger.Info("Beginning recording.");
  567. httpRequestOptions.BufferContent = false;
  568. var durationToken = new CancellationTokenSource(duration);
  569. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
  570. httpRequestOptions.CancellationToken = linkedToken;
  571. _logger.Info("Writing file to path: " + recordPath);
  572. using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET"))
  573. {
  574. using (var output = _fileSystem.GetFileStream(recordPath, FileMode.Create, FileAccess.Write, FileShare.Read))
  575. {
  576. await response.Content.CopyToAsync(output, StreamDefaults.DefaultCopyToBufferSize, linkedToken);
  577. }
  578. }
  579. recording.Status = RecordingStatus.Completed;
  580. _logger.Info("Recording completed");
  581. }
  582. catch (OperationCanceledException)
  583. {
  584. _logger.Info("Recording stopped");
  585. recording.Status = RecordingStatus.Completed;
  586. }
  587. catch (Exception ex)
  588. {
  589. _logger.ErrorException("Error recording", ex);
  590. recording.Status = RecordingStatus.Error;
  591. }
  592. finally
  593. {
  594. CancellationTokenSource removed;
  595. _activeRecordings.TryRemove(timer.Id, out removed);
  596. }
  597. recording.DateLastUpdated = DateTime.UtcNow;
  598. _recordingProvider.Update(recording);
  599. if (recording.Status == RecordingStatus.Completed)
  600. {
  601. OnSuccessfulRecording(recording);
  602. _timerProvider.Delete(timer);
  603. }
  604. else if (DateTime.UtcNow < timer.EndDate)
  605. {
  606. const int retryIntervalSeconds = 60;
  607. _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds);
  608. _timerProvider.StartTimer(timer, TimeSpan.FromSeconds(retryIntervalSeconds));
  609. }
  610. else
  611. {
  612. _timerProvider.Delete(timer);
  613. _recordingProvider.Delete(recording);
  614. }
  615. }
  616. private async void OnSuccessfulRecording(RecordingInfo recording)
  617. {
  618. if (GetConfiguration().EnableAutoOrganize)
  619. {
  620. if (recording.IsSeries)
  621. {
  622. try
  623. {
  624. var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager);
  625. var result = await organize.OrganizeEpisodeFile(recording.Path, CancellationToken.None).ConfigureAwait(false);
  626. if (result.Status == FileSortingStatus.Success)
  627. {
  628. _recordingProvider.Delete(recording);
  629. }
  630. }
  631. catch (Exception ex)
  632. {
  633. _logger.ErrorException("Error processing new recording", ex);
  634. }
  635. }
  636. }
  637. }
  638. private ProgramInfo GetProgramInfoFromCache(string channelId, string programId)
  639. {
  640. var epgData = GetEpgDataForChannel(channelId);
  641. return epgData.FirstOrDefault(p => string.Equals(p.Id, programId, StringComparison.OrdinalIgnoreCase));
  642. }
  643. private string RecordingPath
  644. {
  645. get
  646. {
  647. var path = GetConfiguration().RecordingPath;
  648. return string.IsNullOrWhiteSpace(path)
  649. ? Path.Combine(DataPath, "recordings")
  650. : path;
  651. }
  652. }
  653. private LiveTvOptions GetConfiguration()
  654. {
  655. return _config.GetConfiguration<LiveTvOptions>("livetv");
  656. }
  657. private async Task UpdateTimersForSeriesTimer(List<ProgramInfo> epgData, SeriesTimerInfo seriesTimer)
  658. {
  659. var registration = await GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
  660. if (registration.IsValid)
  661. {
  662. var newTimers = GetTimersForSeries(seriesTimer, epgData, _recordingProvider.GetAll()).ToList();
  663. foreach (var timer in newTimers)
  664. {
  665. _timerProvider.AddOrUpdate(timer);
  666. }
  667. }
  668. }
  669. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms, IReadOnlyList<RecordingInfo> currentRecordings)
  670. {
  671. // Exclude programs that have already ended
  672. allPrograms = allPrograms.Where(i => i.EndDate > DateTime.UtcNow);
  673. allPrograms = GetProgramsForSeries(seriesTimer, allPrograms);
  674. var recordingShowIds = currentRecordings.Select(i => i.ProgramId).Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  675. allPrograms = allPrograms.Where(i => !recordingShowIds.Contains(i.Id, StringComparer.OrdinalIgnoreCase));
  676. return allPrograms.Select(i => RecordingHelper.CreateTimer(i, seriesTimer));
  677. }
  678. private IEnumerable<ProgramInfo> GetProgramsForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  679. {
  680. if (!seriesTimer.RecordAnyTime)
  681. {
  682. allPrograms = allPrograms.Where(epg => (seriesTimer.StartDate.TimeOfDay == epg.StartDate.TimeOfDay));
  683. }
  684. if (seriesTimer.RecordNewOnly)
  685. {
  686. allPrograms = allPrograms.Where(epg => !epg.IsRepeat);
  687. }
  688. if (!seriesTimer.RecordAnyChannel)
  689. {
  690. allPrograms = allPrograms.Where(epg => string.Equals(epg.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase));
  691. }
  692. allPrograms = allPrograms.Where(i => seriesTimer.Days.Contains(i.StartDate.ToLocalTime().DayOfWeek));
  693. if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
  694. {
  695. _logger.Error("seriesTimer.SeriesId is null. Cannot find programs for series");
  696. return new List<ProgramInfo>();
  697. }
  698. return allPrograms.Where(i => string.Equals(i.SeriesId, seriesTimer.SeriesId, StringComparison.OrdinalIgnoreCase));
  699. }
  700. private string GetChannelEpgCachePath(string channelId)
  701. {
  702. return Path.Combine(DataPath, "epg", channelId + ".json");
  703. }
  704. private readonly object _epgLock = new object();
  705. private void SaveEpgDataForChannel(string channelId, List<ProgramInfo> epgData)
  706. {
  707. var path = GetChannelEpgCachePath(channelId);
  708. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  709. lock (_epgLock)
  710. {
  711. _jsonSerializer.SerializeToFile(epgData, path);
  712. }
  713. }
  714. private List<ProgramInfo> GetEpgDataForChannel(string channelId)
  715. {
  716. try
  717. {
  718. lock (_epgLock)
  719. {
  720. return _jsonSerializer.DeserializeFromFile<List<ProgramInfo>>(GetChannelEpgCachePath(channelId));
  721. }
  722. }
  723. catch
  724. {
  725. return new List<ProgramInfo>();
  726. }
  727. }
  728. private List<ProgramInfo> GetEpgDataForChannels(List<string> channelIds)
  729. {
  730. return channelIds.SelectMany(GetEpgDataForChannel).ToList();
  731. }
  732. public void Dispose()
  733. {
  734. foreach (var pair in _activeRecordings.ToList())
  735. {
  736. pair.Value.Cancel();
  737. }
  738. }
  739. public Task<MBRegistrationRecord> GetRegistrationInfo(string feature)
  740. {
  741. if (string.Equals(feature, "seriesrecordings", StringComparison.OrdinalIgnoreCase))
  742. {
  743. return _security.GetRegistrationStatus("embytvseriesrecordings");
  744. }
  745. return Task.FromResult(new MBRegistrationRecord
  746. {
  747. IsValid = true,
  748. IsRegistered = true
  749. });
  750. }
  751. }
  752. }