EmbyTV.cs 37 KB

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