EmbyTV.cs 43 KB

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