EmbyTV.cs 38 KB

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