EmbyTV.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  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, enabledChannels, 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.ToList();
  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. _logger.Debug("Skipping getting programs for channel {0}-{1} from {2}-{3}, because it's not enabled for this tuner.", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
  443. continue;
  444. }
  445. _logger.Debug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
  446. var programs = await provider.Item1.GetProgramsAsync(provider.Item2, channel.Number, channel.Name, startDateUtc, endDateUtc, cancellationToken)
  447. .ConfigureAwait(false);
  448. var list = programs.ToList();
  449. // Replace the value that came from the provider with a normalized value
  450. foreach (var program in list)
  451. {
  452. program.ChannelId = channelId;
  453. }
  454. if (list.Count > 0)
  455. {
  456. SaveEpgDataForChannel(channelId, list);
  457. return list;
  458. }
  459. }
  460. return new List<ProgramInfo>();
  461. }
  462. private List<Tuple<IListingsProvider, ListingsProviderInfo>> GetListingProviders()
  463. {
  464. return GetConfiguration().ListingProviders
  465. .Select(i =>
  466. {
  467. var provider = _liveTvManager.ListingProviders.FirstOrDefault(l => string.Equals(l.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  468. return provider == null ? null : new Tuple<IListingsProvider, ListingsProviderInfo>(provider, i);
  469. })
  470. .Where(i => i != null)
  471. .ToList();
  472. }
  473. public Task<MediaSourceInfo> GetRecordingStream(string recordingId, string streamId, CancellationToken cancellationToken)
  474. {
  475. throw new NotImplementedException();
  476. }
  477. public async Task<MediaSourceInfo> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
  478. {
  479. _logger.Info("Streaming Channel " + channelId);
  480. foreach (var hostInstance in _liveTvManager.TunerHosts)
  481. {
  482. try
  483. {
  484. var result = await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
  485. result.Item2.Release();
  486. return result.Item1;
  487. }
  488. catch (Exception e)
  489. {
  490. _logger.ErrorException("Error getting channel stream", e);
  491. }
  492. }
  493. throw new ApplicationException("Tuner not found.");
  494. }
  495. private async Task<Tuple<MediaSourceInfo, SemaphoreSlim>> GetChannelStreamInternal(string channelId, string streamId, CancellationToken cancellationToken)
  496. {
  497. _logger.Info("Streaming Channel " + channelId);
  498. foreach (var hostInstance in _liveTvManager.TunerHosts)
  499. {
  500. try
  501. {
  502. return await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
  503. }
  504. catch (Exception e)
  505. {
  506. _logger.ErrorException("Error getting channel stream", e);
  507. }
  508. }
  509. throw new ApplicationException("Tuner not found.");
  510. }
  511. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  512. {
  513. foreach (var hostInstance in _liveTvManager.TunerHosts)
  514. {
  515. try
  516. {
  517. var sources = await hostInstance.GetChannelStreamMediaSources(channelId, cancellationToken).ConfigureAwait(false);
  518. if (sources.Count > 0)
  519. {
  520. return sources;
  521. }
  522. }
  523. catch (NotImplementedException)
  524. {
  525. }
  526. }
  527. throw new NotImplementedException();
  528. }
  529. public Task<List<MediaSourceInfo>> GetRecordingStreamMediaSources(string recordingId, CancellationToken cancellationToken)
  530. {
  531. throw new NotImplementedException();
  532. }
  533. public Task CloseLiveStream(string id, CancellationToken cancellationToken)
  534. {
  535. return Task.FromResult(0);
  536. }
  537. public Task RecordLiveStream(string id, CancellationToken cancellationToken)
  538. {
  539. return Task.FromResult(0);
  540. }
  541. public Task ResetTuner(string id, CancellationToken cancellationToken)
  542. {
  543. return Task.FromResult(0);
  544. }
  545. async void _timerProvider_TimerFired(object sender, GenericEventArgs<TimerInfo> e)
  546. {
  547. var timer = e.Argument;
  548. _logger.Info("Recording timer fired.");
  549. try
  550. {
  551. var recordingEndDate = timer.EndDate.AddSeconds(timer.PostPaddingSeconds);
  552. if (recordingEndDate <= DateTime.UtcNow)
  553. {
  554. _logger.Warn("Recording timer fired for timer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
  555. return;
  556. }
  557. var activeRecordingInfo = new ActiveRecordingInfo
  558. {
  559. CancellationTokenSource = new CancellationTokenSource(),
  560. TimerId = timer.Id
  561. };
  562. if (_activeRecordings.TryAdd(timer.Id, activeRecordingInfo))
  563. {
  564. await RecordStream(timer, recordingEndDate, activeRecordingInfo, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false);
  565. }
  566. else
  567. {
  568. _logger.Info("Skipping RecordStream because it's already in progress.");
  569. }
  570. }
  571. catch (OperationCanceledException)
  572. {
  573. }
  574. catch (Exception ex)
  575. {
  576. _logger.ErrorException("Error recording stream", ex);
  577. }
  578. }
  579. private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate, ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken)
  580. {
  581. if (timer == null)
  582. {
  583. throw new ArgumentNullException("timer");
  584. }
  585. ProgramInfo info = null;
  586. if (string.IsNullOrWhiteSpace(timer.ProgramId))
  587. {
  588. _logger.Info("Timer {0} has null programId", timer.Id);
  589. }
  590. else
  591. {
  592. info = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  593. }
  594. if (info == null)
  595. {
  596. _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  597. info = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  598. }
  599. if (info == null)
  600. {
  601. throw new InvalidOperationException(string.Format("Program with Id {0} not found", timer.ProgramId));
  602. }
  603. var recordPath = RecordingPath;
  604. if (info.IsMovie)
  605. {
  606. recordPath = Path.Combine(recordPath, "Movies", _fileSystem.GetValidFilename(info.Name).Trim());
  607. }
  608. else if (info.IsSeries)
  609. {
  610. recordPath = Path.Combine(recordPath, "Series", _fileSystem.GetValidFilename(info.Name).Trim());
  611. }
  612. else if (info.IsKids)
  613. {
  614. recordPath = Path.Combine(recordPath, "Kids", _fileSystem.GetValidFilename(info.Name).Trim());
  615. }
  616. else if (info.IsSports)
  617. {
  618. recordPath = Path.Combine(recordPath, "Sports", _fileSystem.GetValidFilename(info.Name).Trim());
  619. }
  620. else
  621. {
  622. recordPath = Path.Combine(recordPath, "Other", _fileSystem.GetValidFilename(info.Name).Trim());
  623. }
  624. var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer, info)).Trim() + ".ts";
  625. recordPath = Path.Combine(recordPath, recordingFileName);
  626. var recordingId = info.Id.GetMD5().ToString("N");
  627. var recording = _recordingProvider.GetAll().FirstOrDefault(x => string.Equals(x.Id, recordingId, StringComparison.OrdinalIgnoreCase));
  628. if (recording == null)
  629. {
  630. recording = new RecordingInfo
  631. {
  632. ChannelId = info.ChannelId,
  633. Id = recordingId,
  634. StartDate = info.StartDate,
  635. EndDate = info.EndDate,
  636. Genres = info.Genres,
  637. IsKids = info.IsKids,
  638. IsLive = info.IsLive,
  639. IsMovie = info.IsMovie,
  640. IsHD = info.IsHD,
  641. IsNews = info.IsNews,
  642. IsPremiere = info.IsPremiere,
  643. IsSeries = info.IsSeries,
  644. IsSports = info.IsSports,
  645. IsRepeat = !info.IsPremiere,
  646. Name = info.Name,
  647. EpisodeTitle = info.EpisodeTitle,
  648. ProgramId = info.Id,
  649. ImagePath = info.ImagePath,
  650. ImageUrl = info.ImageUrl,
  651. OriginalAirDate = info.OriginalAirDate,
  652. Status = RecordingStatus.Scheduled,
  653. Overview = info.Overview,
  654. SeriesTimerId = timer.SeriesTimerId,
  655. TimerId = timer.Id,
  656. ShowId = info.ShowId
  657. };
  658. _recordingProvider.AddOrUpdate(recording);
  659. }
  660. try
  661. {
  662. var result = await GetChannelStreamInternal(timer.ChannelId, null, CancellationToken.None).ConfigureAwait(false);
  663. var mediaStreamInfo = result.Item1;
  664. var isResourceOpen = true;
  665. // Unfortunately due to the semaphore we have to have a nested try/finally
  666. try
  667. {
  668. // HDHR doesn't seem to release the tuner right away after first probing with ffmpeg
  669. //await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  670. var duration = recordingEndDate - DateTime.UtcNow;
  671. var recorder = await GetRecorder().ConfigureAwait(false);
  672. if (recorder is EncodedRecorder)
  673. {
  674. recordPath = Path.ChangeExtension(recordPath, ".mp4");
  675. }
  676. recordPath = EnsureFileUnique(recordPath, timer.Id);
  677. _fileSystem.CreateDirectory(Path.GetDirectoryName(recordPath));
  678. activeRecordingInfo.Path = recordPath;
  679. _libraryMonitor.ReportFileSystemChangeBeginning(recordPath);
  680. recording.Path = recordPath;
  681. recording.Status = RecordingStatus.InProgress;
  682. recording.DateLastUpdated = DateTime.UtcNow;
  683. _recordingProvider.AddOrUpdate(recording);
  684. _logger.Info("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
  685. _logger.Info("Writing file to path: " + recordPath);
  686. _logger.Info("Opening recording stream from tuner provider");
  687. Action onStarted = () =>
  688. {
  689. result.Item2.Release();
  690. isResourceOpen = false;
  691. };
  692. await recorder.Record(mediaStreamInfo, recordPath, duration, onStarted, cancellationToken).ConfigureAwait(false);
  693. recording.Status = RecordingStatus.Completed;
  694. _logger.Info("Recording completed: {0}", recordPath);
  695. }
  696. finally
  697. {
  698. if (isResourceOpen)
  699. {
  700. result.Item2.Release();
  701. }
  702. _libraryMonitor.ReportFileSystemChangeComplete(recordPath, false);
  703. }
  704. }
  705. catch (OperationCanceledException)
  706. {
  707. _logger.Info("Recording stopped: {0}", recordPath);
  708. recording.Status = RecordingStatus.Completed;
  709. }
  710. catch (Exception ex)
  711. {
  712. _logger.ErrorException("Error recording to {0}", ex, recordPath);
  713. recording.Status = RecordingStatus.Error;
  714. }
  715. finally
  716. {
  717. ActiveRecordingInfo removed;
  718. _activeRecordings.TryRemove(timer.Id, out removed);
  719. }
  720. recording.DateLastUpdated = DateTime.UtcNow;
  721. _recordingProvider.AddOrUpdate(recording);
  722. if (recording.Status == RecordingStatus.Completed)
  723. {
  724. OnSuccessfulRecording(recording);
  725. _timerProvider.Delete(timer);
  726. }
  727. else if (DateTime.UtcNow < timer.EndDate)
  728. {
  729. const int retryIntervalSeconds = 60;
  730. _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds);
  731. _timerProvider.StartTimer(timer, TimeSpan.FromSeconds(retryIntervalSeconds));
  732. }
  733. else
  734. {
  735. _timerProvider.Delete(timer);
  736. _recordingProvider.Delete(recording);
  737. }
  738. }
  739. private string EnsureFileUnique(string path, string timerId)
  740. {
  741. var originalPath = path;
  742. var index = 1;
  743. while (FileExists(path, timerId))
  744. {
  745. var parent = Path.GetDirectoryName(originalPath);
  746. var name = Path.GetFileNameWithoutExtension(originalPath);
  747. name += "-" + index.ToString(CultureInfo.InvariantCulture);
  748. path = Path.ChangeExtension(Path.Combine(parent, name), Path.GetExtension(originalPath));
  749. index++;
  750. }
  751. return path;
  752. }
  753. private bool FileExists(string path, string timerId)
  754. {
  755. if (_fileSystem.FileExists(path))
  756. {
  757. return true;
  758. }
  759. var hasRecordingAtPath = _activeRecordings.Values.ToList().Any(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.TimerId, timerId, StringComparison.OrdinalIgnoreCase));
  760. if (hasRecordingAtPath)
  761. {
  762. return true;
  763. }
  764. return false;
  765. }
  766. private async Task<IRecorder> GetRecorder()
  767. {
  768. if (GetConfiguration().EnableRecordingEncoding)
  769. {
  770. var regInfo = await _security.GetRegistrationStatus("embytvrecordingconversion").ConfigureAwait(false);
  771. if (regInfo.IsValid)
  772. {
  773. return new EncodedRecorder(_logger, _fileSystem, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer);
  774. }
  775. }
  776. return new DirectRecorder(_logger, _httpClient, _fileSystem);
  777. }
  778. private async void OnSuccessfulRecording(RecordingInfo recording)
  779. {
  780. if (GetConfiguration().EnableAutoOrganize)
  781. {
  782. if (recording.IsSeries)
  783. {
  784. try
  785. {
  786. // this is to account for the library monitor holding a lock for additional time after the change is complete.
  787. // ideally this shouldn't be hard-coded
  788. await Task.Delay(30000).ConfigureAwait(false);
  789. var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager);
  790. var result = await organize.OrganizeEpisodeFile(recording.Path, CancellationToken.None).ConfigureAwait(false);
  791. if (result.Status == FileSortingStatus.Success)
  792. {
  793. _recordingProvider.Delete(recording);
  794. }
  795. }
  796. catch (Exception ex)
  797. {
  798. _logger.ErrorException("Error processing new recording", ex);
  799. }
  800. }
  801. }
  802. }
  803. private ProgramInfo GetProgramInfoFromCache(string channelId, string programId)
  804. {
  805. var epgData = GetEpgDataForChannel(channelId);
  806. return epgData.FirstOrDefault(p => string.Equals(p.Id, programId, StringComparison.OrdinalIgnoreCase));
  807. }
  808. private ProgramInfo GetProgramInfoFromCache(string channelId, DateTime startDateUtc)
  809. {
  810. var epgData = GetEpgDataForChannel(channelId);
  811. var startDateTicks = startDateUtc.Ticks;
  812. // Find the first program that starts within 3 minutes
  813. return epgData.FirstOrDefault(p => Math.Abs(startDateTicks - p.StartDate.Ticks) <= TimeSpan.FromMinutes(3).Ticks);
  814. }
  815. private string RecordingPath
  816. {
  817. get
  818. {
  819. var path = GetConfiguration().RecordingPath;
  820. return string.IsNullOrWhiteSpace(path)
  821. ? Path.Combine(DataPath, "recordings")
  822. : path;
  823. }
  824. }
  825. private LiveTvOptions GetConfiguration()
  826. {
  827. return _config.GetConfiguration<LiveTvOptions>("livetv");
  828. }
  829. private async Task UpdateTimersForSeriesTimer(List<ProgramInfo> epgData, SeriesTimerInfo seriesTimer, bool deleteInvalidTimers)
  830. {
  831. var newTimers = GetTimersForSeries(seriesTimer, epgData, _recordingProvider.GetAll()).ToList();
  832. var registration = await GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
  833. if (registration.IsValid)
  834. {
  835. foreach (var timer in newTimers)
  836. {
  837. _timerProvider.AddOrUpdate(timer);
  838. }
  839. }
  840. if (deleteInvalidTimers)
  841. {
  842. var allTimers = GetTimersForSeries(seriesTimer, epgData, new List<RecordingInfo>())
  843. .Select(i => i.Id)
  844. .ToList();
  845. var deletes = _timerProvider.GetAll()
  846. .Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
  847. .Where(i => !allTimers.Contains(i.Id, StringComparer.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
  848. .ToList();
  849. foreach (var timer in deletes)
  850. {
  851. await CancelTimerAsync(timer.Id, CancellationToken.None).ConfigureAwait(false);
  852. }
  853. }
  854. }
  855. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms, IReadOnlyList<RecordingInfo> currentRecordings)
  856. {
  857. if (seriesTimer == null)
  858. {
  859. throw new ArgumentNullException("seriesTimer");
  860. }
  861. if (allPrograms == null)
  862. {
  863. throw new ArgumentNullException("allPrograms");
  864. }
  865. if (currentRecordings == null)
  866. {
  867. throw new ArgumentNullException("currentRecordings");
  868. }
  869. // Exclude programs that have already ended
  870. allPrograms = allPrograms.Where(i => i.EndDate > DateTime.UtcNow && i.StartDate > DateTime.UtcNow);
  871. allPrograms = GetProgramsForSeries(seriesTimer, allPrograms);
  872. var recordingShowIds = currentRecordings.Select(i => i.ProgramId).Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  873. allPrograms = allPrograms.Where(i => !recordingShowIds.Contains(i.Id, StringComparer.OrdinalIgnoreCase));
  874. return allPrograms.Select(i => RecordingHelper.CreateTimer(i, seriesTimer));
  875. }
  876. private IEnumerable<ProgramInfo> GetProgramsForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  877. {
  878. if (!seriesTimer.RecordAnyTime)
  879. {
  880. allPrograms = allPrograms.Where(epg => Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - epg.StartDate.TimeOfDay.Ticks) < TimeSpan.FromMinutes(5).Ticks);
  881. }
  882. if (seriesTimer.RecordNewOnly)
  883. {
  884. allPrograms = allPrograms.Where(epg => !epg.IsRepeat);
  885. }
  886. if (!seriesTimer.RecordAnyChannel)
  887. {
  888. allPrograms = allPrograms.Where(epg => string.Equals(epg.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase));
  889. }
  890. allPrograms = allPrograms.Where(i => seriesTimer.Days.Contains(i.StartDate.ToLocalTime().DayOfWeek));
  891. if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
  892. {
  893. _logger.Error("seriesTimer.SeriesId is null. Cannot find programs for series");
  894. return new List<ProgramInfo>();
  895. }
  896. return allPrograms.Where(i => string.Equals(i.SeriesId, seriesTimer.SeriesId, StringComparison.OrdinalIgnoreCase));
  897. }
  898. private string GetChannelEpgCachePath(string channelId)
  899. {
  900. return Path.Combine(_config.CommonApplicationPaths.CachePath, "embytvepg", channelId + ".json");
  901. }
  902. private readonly object _epgLock = new object();
  903. private void SaveEpgDataForChannel(string channelId, List<ProgramInfo> epgData)
  904. {
  905. var path = GetChannelEpgCachePath(channelId);
  906. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  907. lock (_epgLock)
  908. {
  909. _jsonSerializer.SerializeToFile(epgData, path);
  910. }
  911. }
  912. private List<ProgramInfo> GetEpgDataForChannel(string channelId)
  913. {
  914. try
  915. {
  916. lock (_epgLock)
  917. {
  918. return _jsonSerializer.DeserializeFromFile<List<ProgramInfo>>(GetChannelEpgCachePath(channelId));
  919. }
  920. }
  921. catch
  922. {
  923. return new List<ProgramInfo>();
  924. }
  925. }
  926. private List<ProgramInfo> GetEpgDataForChannels(List<string> channelIds)
  927. {
  928. return channelIds.SelectMany(GetEpgDataForChannel).ToList();
  929. }
  930. public void Dispose()
  931. {
  932. foreach (var pair in _activeRecordings.ToList())
  933. {
  934. pair.Value.CancellationTokenSource.Cancel();
  935. }
  936. }
  937. public Task<MBRegistrationRecord> GetRegistrationInfo(string feature)
  938. {
  939. if (string.Equals(feature, "seriesrecordings", StringComparison.OrdinalIgnoreCase))
  940. {
  941. return _security.GetRegistrationStatus("embytvseriesrecordings");
  942. }
  943. return Task.FromResult(new MBRegistrationRecord
  944. {
  945. IsValid = true,
  946. IsRegistered = true
  947. });
  948. }
  949. class ActiveRecordingInfo
  950. {
  951. public string Path { get; set; }
  952. public string TimerId { get; set; }
  953. public CancellationTokenSource CancellationTokenSource { get; set; }
  954. }
  955. }
  956. }