EmbyTV.cs 40 KB

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