EmbyTV.cs 42 KB

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