EmbyTV.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035
  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, false).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
  205. .GetAll()
  206. .Where(i => string.Equals(i.SeriesTimerId, timerId, StringComparison.OrdinalIgnoreCase))
  207. .ToList();
  208. foreach (var timer in timers)
  209. {
  210. CancelTimerInternal(timer.Id);
  211. }
  212. var remove = _seriesTimerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
  213. if (remove != null)
  214. {
  215. _seriesTimerProvider.Delete(remove);
  216. }
  217. return Task.FromResult(true);
  218. }
  219. private void CancelTimerInternal(string timerId)
  220. {
  221. var remove = _timerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
  222. if (remove != null)
  223. {
  224. _timerProvider.Delete(remove);
  225. }
  226. CancellationTokenSource cancellationTokenSource;
  227. if (_activeRecordings.TryGetValue(timerId, out cancellationTokenSource))
  228. {
  229. cancellationTokenSource.Cancel();
  230. }
  231. }
  232. public Task CancelTimerAsync(string timerId, CancellationToken cancellationToken)
  233. {
  234. CancelTimerInternal(timerId);
  235. return Task.FromResult(true);
  236. }
  237. public async Task DeleteRecordingAsync(string recordingId, CancellationToken cancellationToken)
  238. {
  239. var remove = _recordingProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, recordingId, StringComparison.OrdinalIgnoreCase));
  240. if (remove != null)
  241. {
  242. if (!string.IsNullOrWhiteSpace(remove.TimerId))
  243. {
  244. var enableDelay = _activeRecordings.ContainsKey(remove.TimerId);
  245. CancelTimerInternal(remove.TimerId);
  246. if (enableDelay)
  247. {
  248. // A hack yes, but need to make sure the file is closed before attempting to delete it
  249. await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  250. }
  251. }
  252. try
  253. {
  254. _fileSystem.DeleteFile(remove.Path);
  255. }
  256. catch (DirectoryNotFoundException)
  257. {
  258. }
  259. catch (FileNotFoundException)
  260. {
  261. }
  262. _recordingProvider.Delete(remove);
  263. }
  264. else
  265. {
  266. throw new ResourceNotFoundException("Recording not found: " + recordingId);
  267. }
  268. }
  269. public Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
  270. {
  271. info.Id = Guid.NewGuid().ToString("N");
  272. _timerProvider.Add(info);
  273. return Task.FromResult(0);
  274. }
  275. public async Task CreateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  276. {
  277. info.Id = Guid.NewGuid().ToString("N");
  278. List<ProgramInfo> epgData;
  279. if (info.RecordAnyChannel)
  280. {
  281. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  282. var channelIds = channels.Select(i => i.Id).ToList();
  283. epgData = GetEpgDataForChannels(channelIds);
  284. }
  285. else
  286. {
  287. epgData = GetEpgDataForChannel(info.ChannelId);
  288. }
  289. // populate info.seriesID
  290. var program = epgData.FirstOrDefault(i => string.Equals(i.Id, info.ProgramId, StringComparison.OrdinalIgnoreCase));
  291. if (program != null)
  292. {
  293. info.SeriesId = program.SeriesId;
  294. }
  295. else
  296. {
  297. throw new InvalidOperationException("SeriesId for program not found");
  298. }
  299. _seriesTimerProvider.Add(info);
  300. await UpdateTimersForSeriesTimer(epgData, info, false).ConfigureAwait(false);
  301. }
  302. public async Task UpdateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  303. {
  304. var instance = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  305. if (instance != null)
  306. {
  307. instance.ChannelId = info.ChannelId;
  308. instance.Days = info.Days;
  309. instance.EndDate = info.EndDate;
  310. instance.IsPostPaddingRequired = info.IsPostPaddingRequired;
  311. instance.IsPrePaddingRequired = info.IsPrePaddingRequired;
  312. instance.PostPaddingSeconds = info.PostPaddingSeconds;
  313. instance.PrePaddingSeconds = info.PrePaddingSeconds;
  314. instance.Priority = info.Priority;
  315. instance.RecordAnyChannel = info.RecordAnyChannel;
  316. instance.RecordAnyTime = info.RecordAnyTime;
  317. instance.RecordNewOnly = info.RecordNewOnly;
  318. instance.StartDate = info.StartDate;
  319. _seriesTimerProvider.Update(instance);
  320. List<ProgramInfo> epgData;
  321. if (instance.RecordAnyChannel)
  322. {
  323. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  324. var channelIds = channels.Select(i => i.Id).ToList();
  325. epgData = GetEpgDataForChannels(channelIds);
  326. }
  327. else
  328. {
  329. epgData = GetEpgDataForChannel(instance.ChannelId);
  330. }
  331. await UpdateTimersForSeriesTimer(epgData, instance, true).ConfigureAwait(false);
  332. }
  333. }
  334. public Task UpdateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
  335. {
  336. _timerProvider.Update(info);
  337. return Task.FromResult(true);
  338. }
  339. public Task<ImageStream> GetChannelImageAsync(string channelId, CancellationToken cancellationToken)
  340. {
  341. throw new NotImplementedException();
  342. }
  343. public Task<ImageStream> GetRecordingImageAsync(string recordingId, CancellationToken cancellationToken)
  344. {
  345. throw new NotImplementedException();
  346. }
  347. public Task<ImageStream> GetProgramImageAsync(string programId, string channelId, CancellationToken cancellationToken)
  348. {
  349. throw new NotImplementedException();
  350. }
  351. public async Task<IEnumerable<RecordingInfo>> GetRecordingsAsync(CancellationToken cancellationToken)
  352. {
  353. var recordings = _recordingProvider.GetAll().ToList();
  354. var updated = false;
  355. foreach (var recording in recordings)
  356. {
  357. if (recording.Status == RecordingStatus.InProgress)
  358. {
  359. if (string.IsNullOrWhiteSpace(recording.TimerId) || !_activeRecordings.ContainsKey(recording.TimerId))
  360. {
  361. recording.Status = RecordingStatus.Cancelled;
  362. recording.DateLastUpdated = DateTime.UtcNow;
  363. _recordingProvider.Update(recording);
  364. updated = true;
  365. }
  366. }
  367. }
  368. if (updated)
  369. {
  370. recordings = _recordingProvider.GetAll().ToList();
  371. }
  372. return recordings;
  373. }
  374. public Task<IEnumerable<TimerInfo>> GetTimersAsync(CancellationToken cancellationToken)
  375. {
  376. return Task.FromResult((IEnumerable<TimerInfo>)_timerProvider.GetAll());
  377. }
  378. public Task<SeriesTimerInfo> GetNewTimerDefaultsAsync(CancellationToken cancellationToken, ProgramInfo program = null)
  379. {
  380. var config = GetConfiguration();
  381. var defaults = new SeriesTimerInfo()
  382. {
  383. PostPaddingSeconds = Math.Max(config.PostPaddingSeconds, 0),
  384. PrePaddingSeconds = Math.Max(config.PrePaddingSeconds, 0),
  385. RecordAnyChannel = false,
  386. RecordAnyTime = false,
  387. RecordNewOnly = false
  388. };
  389. if (program != null)
  390. {
  391. defaults.SeriesId = program.SeriesId;
  392. defaults.ProgramId = program.Id;
  393. }
  394. return Task.FromResult(defaults);
  395. }
  396. public Task<IEnumerable<SeriesTimerInfo>> GetSeriesTimersAsync(CancellationToken cancellationToken)
  397. {
  398. return Task.FromResult((IEnumerable<SeriesTimerInfo>)_seriesTimerProvider.GetAll());
  399. }
  400. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  401. {
  402. try
  403. {
  404. return await GetProgramsAsyncInternal(channelId, startDateUtc, endDateUtc, cancellationToken).ConfigureAwait(false);
  405. }
  406. catch (OperationCanceledException)
  407. {
  408. throw;
  409. }
  410. catch (Exception ex)
  411. {
  412. _logger.ErrorException("Error getting programs", ex);
  413. return GetEpgDataForChannel(channelId).Where(i => i.StartDate <= endDateUtc && i.EndDate >= startDateUtc);
  414. }
  415. }
  416. private async Task<IEnumerable<ProgramInfo>> GetProgramsAsyncInternal(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  417. {
  418. var channels = await GetChannelsAsync(true, cancellationToken).ConfigureAwait(false);
  419. var channel = channels.First(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  420. foreach (var provider in GetListingProviders())
  421. {
  422. var programs = await provider.Item1.GetProgramsAsync(provider.Item2, channel.Number, channel.Name, startDateUtc, endDateUtc, cancellationToken)
  423. .ConfigureAwait(false);
  424. var list = programs.ToList();
  425. // Replace the value that came from the provider with a normalized value
  426. foreach (var program in list)
  427. {
  428. program.ChannelId = channelId;
  429. }
  430. if (list.Count > 0)
  431. {
  432. SaveEpgDataForChannel(channelId, list);
  433. return list;
  434. }
  435. }
  436. return new List<ProgramInfo>();
  437. }
  438. private List<Tuple<IListingsProvider, ListingsProviderInfo>> GetListingProviders()
  439. {
  440. return GetConfiguration().ListingProviders
  441. .Select(i =>
  442. {
  443. var provider = _liveTvManager.ListingProviders.FirstOrDefault(l => string.Equals(l.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  444. return provider == null ? null : new Tuple<IListingsProvider, ListingsProviderInfo>(provider, i);
  445. })
  446. .Where(i => i != null)
  447. .ToList();
  448. }
  449. public Task<MediaSourceInfo> GetRecordingStream(string recordingId, string streamId, CancellationToken cancellationToken)
  450. {
  451. throw new NotImplementedException();
  452. }
  453. public async Task<MediaSourceInfo> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
  454. {
  455. _logger.Info("Streaming Channel " + channelId);
  456. foreach (var hostInstance in _liveTvManager.TunerHosts)
  457. {
  458. try
  459. {
  460. var result = await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
  461. result.Item2.Release();
  462. return result.Item1;
  463. }
  464. catch (Exception e)
  465. {
  466. _logger.ErrorException("Error getting channel stream", e);
  467. }
  468. }
  469. throw new ApplicationException("Tuner not found.");
  470. }
  471. private async Task<Tuple<MediaSourceInfo, SemaphoreSlim>> GetChannelStreamInternal(string channelId, string streamId, CancellationToken cancellationToken)
  472. {
  473. _logger.Info("Streaming Channel " + channelId);
  474. foreach (var hostInstance in _liveTvManager.TunerHosts)
  475. {
  476. try
  477. {
  478. return await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
  479. }
  480. catch (Exception e)
  481. {
  482. _logger.ErrorException("Error getting channel stream", e);
  483. }
  484. }
  485. throw new ApplicationException("Tuner not found.");
  486. }
  487. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  488. {
  489. foreach (var hostInstance in _liveTvManager.TunerHosts)
  490. {
  491. try
  492. {
  493. var sources = await hostInstance.GetChannelStreamMediaSources(channelId, cancellationToken).ConfigureAwait(false);
  494. if (sources.Count > 0)
  495. {
  496. return sources;
  497. }
  498. }
  499. catch (NotImplementedException)
  500. {
  501. }
  502. }
  503. throw new NotImplementedException();
  504. }
  505. public Task<List<MediaSourceInfo>> GetRecordingStreamMediaSources(string recordingId, CancellationToken cancellationToken)
  506. {
  507. throw new NotImplementedException();
  508. }
  509. public Task CloseLiveStream(string id, CancellationToken cancellationToken)
  510. {
  511. return Task.FromResult(0);
  512. }
  513. public Task RecordLiveStream(string id, CancellationToken cancellationToken)
  514. {
  515. return Task.FromResult(0);
  516. }
  517. public Task ResetTuner(string id, CancellationToken cancellationToken)
  518. {
  519. return Task.FromResult(0);
  520. }
  521. async void _timerProvider_TimerFired(object sender, GenericEventArgs<TimerInfo> e)
  522. {
  523. var timer = e.Argument;
  524. _logger.Info("Recording timer fired.");
  525. try
  526. {
  527. var recordingEndDate = timer.EndDate.AddSeconds(timer.PostPaddingSeconds);
  528. if (recordingEndDate <= DateTime.UtcNow)
  529. {
  530. _logger.Warn("Recording timer fired for timer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
  531. return;
  532. }
  533. var cancellationTokenSource = new CancellationTokenSource();
  534. if (_activeRecordings.TryAdd(timer.Id, cancellationTokenSource))
  535. {
  536. await RecordStream(timer, recordingEndDate, cancellationTokenSource.Token).ConfigureAwait(false);
  537. }
  538. else
  539. {
  540. _logger.Info("Skipping RecordStream because it's already in progress.");
  541. }
  542. }
  543. catch (OperationCanceledException)
  544. {
  545. }
  546. catch (Exception ex)
  547. {
  548. _logger.ErrorException("Error recording stream", ex);
  549. }
  550. }
  551. private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate, CancellationToken cancellationToken)
  552. {
  553. if (timer == null)
  554. {
  555. throw new ArgumentNullException("timer");
  556. }
  557. ProgramInfo info = null;
  558. if (string.IsNullOrWhiteSpace(timer.ProgramId))
  559. {
  560. _logger.Info("Timer {0} has null programId", timer.Id);
  561. }
  562. else
  563. {
  564. info = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  565. }
  566. if (info == null)
  567. {
  568. _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  569. info = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  570. }
  571. if (info == null)
  572. {
  573. throw new InvalidOperationException(string.Format("Program with Id {0} not found", timer.ProgramId));
  574. }
  575. var recordPath = RecordingPath;
  576. if (info.IsMovie)
  577. {
  578. recordPath = Path.Combine(recordPath, "Movies", _fileSystem.GetValidFilename(info.Name).Trim());
  579. }
  580. else if (info.IsSeries)
  581. {
  582. recordPath = Path.Combine(recordPath, "Series", _fileSystem.GetValidFilename(info.Name).Trim());
  583. }
  584. else if (info.IsKids)
  585. {
  586. recordPath = Path.Combine(recordPath, "Kids", _fileSystem.GetValidFilename(info.Name).Trim());
  587. }
  588. else if (info.IsSports)
  589. {
  590. recordPath = Path.Combine(recordPath, "Sports", _fileSystem.GetValidFilename(info.Name).Trim());
  591. }
  592. else
  593. {
  594. recordPath = Path.Combine(recordPath, "Other", _fileSystem.GetValidFilename(info.Name).Trim());
  595. }
  596. var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer, info)).Trim() + ".ts";
  597. recordPath = Path.Combine(recordPath, recordingFileName);
  598. _fileSystem.CreateDirectory(Path.GetDirectoryName(recordPath));
  599. var recordingId = info.Id.GetMD5().ToString("N");
  600. var recording = _recordingProvider.GetAll().FirstOrDefault(x => string.Equals(x.Id, recordingId, StringComparison.OrdinalIgnoreCase));
  601. if (recording == null)
  602. {
  603. recording = new RecordingInfo
  604. {
  605. ChannelId = info.ChannelId,
  606. Id = recordingId,
  607. StartDate = info.StartDate,
  608. EndDate = info.EndDate,
  609. Genres = info.Genres,
  610. IsKids = info.IsKids,
  611. IsLive = info.IsLive,
  612. IsMovie = info.IsMovie,
  613. IsHD = info.IsHD,
  614. IsNews = info.IsNews,
  615. IsPremiere = info.IsPremiere,
  616. IsSeries = info.IsSeries,
  617. IsSports = info.IsSports,
  618. IsRepeat = !info.IsPremiere,
  619. Name = info.Name,
  620. EpisodeTitle = info.EpisodeTitle,
  621. ProgramId = info.Id,
  622. ImagePath = info.ImagePath,
  623. ImageUrl = info.ImageUrl,
  624. OriginalAirDate = info.OriginalAirDate,
  625. Status = RecordingStatus.Scheduled,
  626. Overview = info.Overview,
  627. SeriesTimerId = timer.SeriesTimerId,
  628. TimerId = timer.Id,
  629. ShowId = info.ShowId
  630. };
  631. _recordingProvider.AddOrUpdate(recording);
  632. }
  633. try
  634. {
  635. var result = await GetChannelStreamInternal(timer.ChannelId, null, CancellationToken.None).ConfigureAwait(false);
  636. var mediaStreamInfo = result.Item1;
  637. var isResourceOpen = true;
  638. // Unfortunately due to the semaphore we have to have a nested try/finally
  639. try
  640. {
  641. // HDHR doesn't seem to release the tuner right away after first probing with ffmpeg
  642. await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  643. var duration = recordingEndDate - DateTime.UtcNow;
  644. HttpRequestOptions httpRequestOptions = new HttpRequestOptions()
  645. {
  646. Url = mediaStreamInfo.Path
  647. };
  648. recording.Path = recordPath;
  649. recording.Status = RecordingStatus.InProgress;
  650. recording.DateLastUpdated = DateTime.UtcNow;
  651. _recordingProvider.AddOrUpdate(recording);
  652. _logger.Info("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
  653. httpRequestOptions.BufferContent = false;
  654. var durationToken = new CancellationTokenSource(duration);
  655. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
  656. httpRequestOptions.CancellationToken = linkedToken;
  657. _logger.Info("Writing file to path: " + recordPath);
  658. _logger.Info("Opening recording stream from tuner provider");
  659. using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET").ConfigureAwait(false))
  660. {
  661. _logger.Info("Opened recording stream from tuner provider");
  662. using (var output = _fileSystem.GetFileStream(recordPath, FileMode.Create, FileAccess.Write, FileShare.Read))
  663. {
  664. result.Item2.Release();
  665. isResourceOpen = false;
  666. _logger.Info("Copying recording stream to file stream");
  667. await response.Content.CopyToAsync(output, StreamDefaults.DefaultCopyToBufferSize, linkedToken).ConfigureAwait(false);
  668. }
  669. }
  670. recording.Status = RecordingStatus.Completed;
  671. _logger.Info("Recording completed");
  672. }
  673. finally
  674. {
  675. if (isResourceOpen)
  676. {
  677. result.Item2.Release();
  678. }
  679. }
  680. }
  681. catch (OperationCanceledException)
  682. {
  683. _logger.Info("Recording stopped");
  684. recording.Status = RecordingStatus.Completed;
  685. }
  686. catch (Exception ex)
  687. {
  688. _logger.ErrorException("Error recording", ex);
  689. recording.Status = RecordingStatus.Error;
  690. }
  691. finally
  692. {
  693. CancellationTokenSource removed;
  694. _activeRecordings.TryRemove(timer.Id, out removed);
  695. }
  696. recording.DateLastUpdated = DateTime.UtcNow;
  697. _recordingProvider.AddOrUpdate(recording);
  698. if (recording.Status == RecordingStatus.Completed)
  699. {
  700. OnSuccessfulRecording(recording);
  701. _timerProvider.Delete(timer);
  702. }
  703. else if (DateTime.UtcNow < timer.EndDate)
  704. {
  705. const int retryIntervalSeconds = 60;
  706. _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds);
  707. _timerProvider.StartTimer(timer, TimeSpan.FromSeconds(retryIntervalSeconds));
  708. }
  709. else
  710. {
  711. _timerProvider.Delete(timer);
  712. _recordingProvider.Delete(recording);
  713. }
  714. }
  715. private async void OnSuccessfulRecording(RecordingInfo recording)
  716. {
  717. if (GetConfiguration().EnableAutoOrganize)
  718. {
  719. if (recording.IsSeries)
  720. {
  721. try
  722. {
  723. var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager);
  724. var result = await organize.OrganizeEpisodeFile(recording.Path, CancellationToken.None).ConfigureAwait(false);
  725. if (result.Status == FileSortingStatus.Success)
  726. {
  727. _recordingProvider.Delete(recording);
  728. }
  729. }
  730. catch (Exception ex)
  731. {
  732. _logger.ErrorException("Error processing new recording", ex);
  733. }
  734. }
  735. }
  736. }
  737. private ProgramInfo GetProgramInfoFromCache(string channelId, string programId)
  738. {
  739. var epgData = GetEpgDataForChannel(channelId);
  740. return epgData.FirstOrDefault(p => string.Equals(p.Id, programId, StringComparison.OrdinalIgnoreCase));
  741. }
  742. private ProgramInfo GetProgramInfoFromCache(string channelId, DateTime startDateUtc)
  743. {
  744. var epgData = GetEpgDataForChannel(channelId);
  745. var startDateTicks = startDateUtc.Ticks;
  746. // Find the first program that starts within 3 minutes
  747. return epgData.FirstOrDefault(p => Math.Abs(startDateTicks - p.StartDate.Ticks) <= TimeSpan.FromMinutes(3).Ticks);
  748. }
  749. private string RecordingPath
  750. {
  751. get
  752. {
  753. var path = GetConfiguration().RecordingPath;
  754. return string.IsNullOrWhiteSpace(path)
  755. ? Path.Combine(DataPath, "recordings")
  756. : path;
  757. }
  758. }
  759. private LiveTvOptions GetConfiguration()
  760. {
  761. return _config.GetConfiguration<LiveTvOptions>("livetv");
  762. }
  763. private async Task UpdateTimersForSeriesTimer(List<ProgramInfo> epgData, SeriesTimerInfo seriesTimer, bool deleteInvalidTimers)
  764. {
  765. var newTimers = GetTimersForSeries(seriesTimer, epgData, _recordingProvider.GetAll()).ToList();
  766. var registration = await GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
  767. if (registration.IsValid)
  768. {
  769. foreach (var timer in newTimers)
  770. {
  771. _timerProvider.AddOrUpdate(timer);
  772. }
  773. }
  774. if (deleteInvalidTimers)
  775. {
  776. var allTimers = GetTimersForSeries(seriesTimer, epgData, new List<RecordingInfo>())
  777. .Select(i => i.Id)
  778. .ToList();
  779. var deletes = _timerProvider.GetAll()
  780. .Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
  781. .Where(i => !allTimers.Contains(i.Id, StringComparer.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
  782. .ToList();
  783. foreach (var timer in deletes)
  784. {
  785. await CancelTimerAsync(timer.Id, CancellationToken.None).ConfigureAwait(false);
  786. }
  787. }
  788. }
  789. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms, IReadOnlyList<RecordingInfo> currentRecordings)
  790. {
  791. // Exclude programs that have already ended
  792. allPrograms = allPrograms.Where(i => i.EndDate > DateTime.UtcNow && i.StartDate > DateTime.UtcNow);
  793. allPrograms = GetProgramsForSeries(seriesTimer, allPrograms);
  794. var recordingShowIds = currentRecordings.Select(i => i.ProgramId).Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  795. allPrograms = allPrograms.Where(i => !recordingShowIds.Contains(i.Id, StringComparer.OrdinalIgnoreCase));
  796. return allPrograms.Select(i => RecordingHelper.CreateTimer(i, seriesTimer));
  797. }
  798. private IEnumerable<ProgramInfo> GetProgramsForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  799. {
  800. if (!seriesTimer.RecordAnyTime)
  801. {
  802. allPrograms = allPrograms.Where(epg => Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - epg.StartDate.TimeOfDay.Ticks) < TimeSpan.FromMinutes(5).Ticks);
  803. }
  804. if (seriesTimer.RecordNewOnly)
  805. {
  806. allPrograms = allPrograms.Where(epg => !epg.IsRepeat);
  807. }
  808. if (!seriesTimer.RecordAnyChannel)
  809. {
  810. allPrograms = allPrograms.Where(epg => string.Equals(epg.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase));
  811. }
  812. allPrograms = allPrograms.Where(i => seriesTimer.Days.Contains(i.StartDate.ToLocalTime().DayOfWeek));
  813. if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
  814. {
  815. _logger.Error("seriesTimer.SeriesId is null. Cannot find programs for series");
  816. return new List<ProgramInfo>();
  817. }
  818. return allPrograms.Where(i => string.Equals(i.SeriesId, seriesTimer.SeriesId, StringComparison.OrdinalIgnoreCase));
  819. }
  820. private string GetChannelEpgCachePath(string channelId)
  821. {
  822. return Path.Combine(_config.CommonApplicationPaths.CachePath, "embytvepg", channelId + ".json");
  823. }
  824. private readonly object _epgLock = new object();
  825. private void SaveEpgDataForChannel(string channelId, List<ProgramInfo> epgData)
  826. {
  827. var path = GetChannelEpgCachePath(channelId);
  828. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  829. lock (_epgLock)
  830. {
  831. _jsonSerializer.SerializeToFile(epgData, path);
  832. }
  833. }
  834. private List<ProgramInfo> GetEpgDataForChannel(string channelId)
  835. {
  836. try
  837. {
  838. lock (_epgLock)
  839. {
  840. return _jsonSerializer.DeserializeFromFile<List<ProgramInfo>>(GetChannelEpgCachePath(channelId));
  841. }
  842. }
  843. catch
  844. {
  845. return new List<ProgramInfo>();
  846. }
  847. }
  848. private List<ProgramInfo> GetEpgDataForChannels(List<string> channelIds)
  849. {
  850. return channelIds.SelectMany(GetEpgDataForChannel).ToList();
  851. }
  852. public void Dispose()
  853. {
  854. foreach (var pair in _activeRecordings.ToList())
  855. {
  856. pair.Value.Cancel();
  857. }
  858. }
  859. public Task<MBRegistrationRecord> GetRegistrationInfo(string feature)
  860. {
  861. if (string.Equals(feature, "seriesrecordings", StringComparison.OrdinalIgnoreCase))
  862. {
  863. return _security.GetRegistrationStatus("embytvseriesrecordings");
  864. }
  865. return Task.FromResult(new MBRegistrationRecord
  866. {
  867. IsValid = true,
  868. IsRegistered = true
  869. });
  870. }
  871. }
  872. }