EmbyTV.cs 36 KB

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