EmbyTV.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Common.Net;
  5. using MediaBrowser.Common.Security;
  6. using MediaBrowser.Controller.Configuration;
  7. using MediaBrowser.Controller.Drawing;
  8. using MediaBrowser.Controller.FileOrganization;
  9. using MediaBrowser.Controller.Library;
  10. using MediaBrowser.Controller.LiveTv;
  11. using MediaBrowser.Controller.MediaEncoding;
  12. using MediaBrowser.Controller.Providers;
  13. using MediaBrowser.Model.Dlna;
  14. using MediaBrowser.Model.Dto;
  15. using MediaBrowser.Model.Entities;
  16. using MediaBrowser.Model.Events;
  17. using MediaBrowser.Model.FileOrganization;
  18. using MediaBrowser.Model.LiveTv;
  19. using MediaBrowser.Model.Logging;
  20. using MediaBrowser.Model.Serialization;
  21. using MediaBrowser.Server.Implementations.FileOrganization;
  22. using System;
  23. using System.Collections.Concurrent;
  24. using System.Collections.Generic;
  25. using System.Globalization;
  26. using System.IO;
  27. using System.Linq;
  28. using System.Threading;
  29. using System.Threading.Tasks;
  30. using CommonIO;
  31. using MediaBrowser.Common.Extensions;
  32. using MediaBrowser.Controller.Power;
  33. using Microsoft.Win32;
  34. namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
  35. {
  36. public class EmbyTV : ILiveTvService, IHasRegistrationInfo, IDisposable
  37. {
  38. private readonly IApplicationHost _appHpst;
  39. private readonly ILogger _logger;
  40. private readonly IHttpClient _httpClient;
  41. private readonly IServerConfigurationManager _config;
  42. private readonly IJsonSerializer _jsonSerializer;
  43. private readonly ItemDataProvider<RecordingInfo> _recordingProvider;
  44. private readonly ItemDataProvider<SeriesTimerInfo> _seriesTimerProvider;
  45. private readonly TimerManager _timerProvider;
  46. private readonly LiveTvManager _liveTvManager;
  47. private readonly IFileSystem _fileSystem;
  48. private readonly ISecurityManager _security;
  49. private readonly ILibraryMonitor _libraryMonitor;
  50. private readonly ILibraryManager _libraryManager;
  51. private readonly IProviderManager _providerManager;
  52. private readonly IFileOrganizationService _organizationService;
  53. private readonly IMediaEncoder _mediaEncoder;
  54. public static EmbyTV Current;
  55. public EmbyTV(IApplicationHost appHost, ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IServerConfigurationManager config, ILiveTvManager liveTvManager, IFileSystem fileSystem, ISecurityManager security, ILibraryManager libraryManager, ILibraryMonitor libraryMonitor, IProviderManager providerManager, IFileOrganizationService organizationService, IMediaEncoder mediaEncoder, IPowerManagement powerManagement)
  56. {
  57. Current = this;
  58. _appHpst = appHost;
  59. _logger = logger;
  60. _httpClient = httpClient;
  61. _config = config;
  62. _fileSystem = fileSystem;
  63. _security = security;
  64. _libraryManager = libraryManager;
  65. _libraryMonitor = libraryMonitor;
  66. _providerManager = providerManager;
  67. _organizationService = organizationService;
  68. _mediaEncoder = mediaEncoder;
  69. _liveTvManager = (LiveTvManager)liveTvManager;
  70. _jsonSerializer = jsonSerializer;
  71. _recordingProvider = new ItemDataProvider<RecordingInfo>(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "recordings"), (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase));
  72. _seriesTimerProvider = new SeriesTimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers"));
  73. _timerProvider = new TimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "timers"), powerManagement, _logger);
  74. _timerProvider.TimerFired += _timerProvider_TimerFired;
  75. }
  76. public void Start()
  77. {
  78. _timerProvider.RestartTimers();
  79. SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
  80. }
  81. void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
  82. {
  83. _logger.Info("Power mode changed to {0}", e.Mode);
  84. if (e.Mode == PowerModes.Resume)
  85. {
  86. _timerProvider.RestartTimers();
  87. }
  88. }
  89. public event EventHandler DataSourceChanged;
  90. public event EventHandler<RecordingStatusChangedEventArgs> RecordingStatusChanged;
  91. private readonly ConcurrentDictionary<string, ActiveRecordingInfo> _activeRecordings =
  92. new ConcurrentDictionary<string, ActiveRecordingInfo>(StringComparer.OrdinalIgnoreCase);
  93. public string Name
  94. {
  95. get { return "Emby"; }
  96. }
  97. public string DataPath
  98. {
  99. get { return Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv"); }
  100. }
  101. public string HomePageUrl
  102. {
  103. get { return "http://emby.media"; }
  104. }
  105. public async Task<LiveTvServiceStatusInfo> GetStatusInfoAsync(CancellationToken cancellationToken)
  106. {
  107. var status = new LiveTvServiceStatusInfo();
  108. var list = new List<LiveTvTunerInfo>();
  109. foreach (var hostInstance in _liveTvManager.TunerHosts)
  110. {
  111. try
  112. {
  113. var tuners = await hostInstance.GetTunerInfos(cancellationToken).ConfigureAwait(false);
  114. list.AddRange(tuners);
  115. }
  116. catch (Exception ex)
  117. {
  118. _logger.ErrorException("Error getting tuners", ex);
  119. }
  120. }
  121. status.Tuners = list;
  122. status.Status = LiveTvServiceStatus.Ok;
  123. status.Version = _appHpst.ApplicationVersion.ToString();
  124. status.IsVisible = false;
  125. return status;
  126. }
  127. public async Task RefreshSeriesTimers(CancellationToken cancellationToken, IProgress<double> progress)
  128. {
  129. var seriesTimers = await GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  130. List<ChannelInfo> channels = null;
  131. foreach (var timer in seriesTimers)
  132. {
  133. List<ProgramInfo> epgData;
  134. if (timer.RecordAnyChannel)
  135. {
  136. if (channels == null)
  137. {
  138. channels = (await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false)).ToList();
  139. }
  140. var channelIds = channels.Select(i => i.Id).ToList();
  141. epgData = GetEpgDataForChannels(channelIds);
  142. }
  143. else
  144. {
  145. epgData = GetEpgDataForChannel(timer.ChannelId);
  146. }
  147. await UpdateTimersForSeriesTimer(epgData, timer, true).ConfigureAwait(false);
  148. }
  149. var timers = await GetTimersAsync(cancellationToken).ConfigureAwait(false);
  150. foreach (var timer in timers.ToList())
  151. {
  152. if (DateTime.UtcNow > timer.EndDate && !_activeRecordings.ContainsKey(timer.Id))
  153. {
  154. _timerProvider.Delete(timer);
  155. }
  156. }
  157. }
  158. private List<ChannelInfo> _channelCache = null;
  159. private async Task<IEnumerable<ChannelInfo>> GetChannelsAsync(bool enableCache, CancellationToken cancellationToken)
  160. {
  161. if (enableCache && _channelCache != null)
  162. {
  163. return _channelCache.ToList();
  164. }
  165. var list = new List<ChannelInfo>();
  166. foreach (var hostInstance in _liveTvManager.TunerHosts)
  167. {
  168. try
  169. {
  170. var channels = await hostInstance.GetChannels(cancellationToken).ConfigureAwait(false);
  171. list.AddRange(channels);
  172. }
  173. catch (Exception ex)
  174. {
  175. _logger.ErrorException("Error getting channels", ex);
  176. }
  177. }
  178. foreach (var provider in GetListingProviders())
  179. {
  180. var enabledChannels = list
  181. .Where(i => IsListingProviderEnabledForTuner(provider.Item2, i.TunerHostId))
  182. .ToList();
  183. if (enabledChannels.Count > 0)
  184. {
  185. try
  186. {
  187. await provider.Item1.AddMetadata(provider.Item2, list, cancellationToken).ConfigureAwait(false);
  188. }
  189. catch (NotSupportedException)
  190. {
  191. }
  192. catch (Exception ex)
  193. {
  194. _logger.ErrorException("Error adding metadata", ex);
  195. }
  196. }
  197. }
  198. _channelCache = list;
  199. return list;
  200. }
  201. public Task<IEnumerable<ChannelInfo>> GetChannelsAsync(CancellationToken cancellationToken)
  202. {
  203. return GetChannelsAsync(false, cancellationToken);
  204. }
  205. public Task CancelSeriesTimerAsync(string timerId, CancellationToken cancellationToken)
  206. {
  207. var timers = _timerProvider
  208. .GetAll()
  209. .Where(i => string.Equals(i.SeriesTimerId, timerId, StringComparison.OrdinalIgnoreCase))
  210. .ToList();
  211. foreach (var timer in timers)
  212. {
  213. CancelTimerInternal(timer.Id);
  214. }
  215. var remove = _seriesTimerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
  216. if (remove != null)
  217. {
  218. _seriesTimerProvider.Delete(remove);
  219. }
  220. return Task.FromResult(true);
  221. }
  222. private void CancelTimerInternal(string timerId)
  223. {
  224. var remove = _timerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
  225. if (remove != null)
  226. {
  227. _timerProvider.Delete(remove);
  228. }
  229. ActiveRecordingInfo activeRecordingInfo;
  230. if (_activeRecordings.TryGetValue(timerId, out activeRecordingInfo))
  231. {
  232. activeRecordingInfo.CancellationTokenSource.Cancel();
  233. }
  234. }
  235. public Task CancelTimerAsync(string timerId, CancellationToken cancellationToken)
  236. {
  237. CancelTimerInternal(timerId);
  238. return Task.FromResult(true);
  239. }
  240. public async Task DeleteRecordingAsync(string recordingId, CancellationToken cancellationToken)
  241. {
  242. var remove = _recordingProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, recordingId, StringComparison.OrdinalIgnoreCase));
  243. if (remove != null)
  244. {
  245. if (!string.IsNullOrWhiteSpace(remove.TimerId))
  246. {
  247. var enableDelay = _activeRecordings.ContainsKey(remove.TimerId);
  248. CancelTimerInternal(remove.TimerId);
  249. if (enableDelay)
  250. {
  251. // A hack yes, but need to make sure the file is closed before attempting to delete it
  252. await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  253. }
  254. }
  255. if (!string.IsNullOrWhiteSpace(remove.Path))
  256. {
  257. try
  258. {
  259. _fileSystem.DeleteFile(remove.Path);
  260. }
  261. catch (DirectoryNotFoundException)
  262. {
  263. }
  264. catch (FileNotFoundException)
  265. {
  266. }
  267. }
  268. _recordingProvider.Delete(remove);
  269. }
  270. else
  271. {
  272. throw new ResourceNotFoundException("Recording not found: " + recordingId);
  273. }
  274. }
  275. public Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
  276. {
  277. info.Id = Guid.NewGuid().ToString("N");
  278. _timerProvider.Add(info);
  279. return Task.FromResult(0);
  280. }
  281. public async Task CreateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  282. {
  283. info.Id = Guid.NewGuid().ToString("N");
  284. List<ProgramInfo> epgData;
  285. if (info.RecordAnyChannel)
  286. {
  287. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  288. var channelIds = channels.Select(i => i.Id).ToList();
  289. epgData = GetEpgDataForChannels(channelIds);
  290. }
  291. else
  292. {
  293. epgData = GetEpgDataForChannel(info.ChannelId);
  294. }
  295. // populate info.seriesID
  296. var program = epgData.FirstOrDefault(i => string.Equals(i.Id, info.ProgramId, StringComparison.OrdinalIgnoreCase));
  297. if (program != null)
  298. {
  299. info.SeriesId = program.SeriesId;
  300. }
  301. else
  302. {
  303. throw new InvalidOperationException("SeriesId for program not found");
  304. }
  305. _seriesTimerProvider.Add(info);
  306. await UpdateTimersForSeriesTimer(epgData, info, false).ConfigureAwait(false);
  307. }
  308. public async Task UpdateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  309. {
  310. var instance = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  311. if (instance != null)
  312. {
  313. instance.ChannelId = info.ChannelId;
  314. instance.Days = info.Days;
  315. instance.EndDate = info.EndDate;
  316. instance.IsPostPaddingRequired = info.IsPostPaddingRequired;
  317. instance.IsPrePaddingRequired = info.IsPrePaddingRequired;
  318. instance.PostPaddingSeconds = info.PostPaddingSeconds;
  319. instance.PrePaddingSeconds = info.PrePaddingSeconds;
  320. instance.Priority = info.Priority;
  321. instance.RecordAnyChannel = info.RecordAnyChannel;
  322. instance.RecordAnyTime = info.RecordAnyTime;
  323. instance.RecordNewOnly = info.RecordNewOnly;
  324. instance.StartDate = info.StartDate;
  325. _seriesTimerProvider.Update(instance);
  326. List<ProgramInfo> epgData;
  327. if (instance.RecordAnyChannel)
  328. {
  329. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  330. var channelIds = channels.Select(i => i.Id).ToList();
  331. epgData = GetEpgDataForChannels(channelIds);
  332. }
  333. else
  334. {
  335. epgData = GetEpgDataForChannel(instance.ChannelId);
  336. }
  337. await UpdateTimersForSeriesTimer(epgData, instance, true).ConfigureAwait(false);
  338. }
  339. }
  340. public Task UpdateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
  341. {
  342. _timerProvider.Update(info);
  343. return Task.FromResult(true);
  344. }
  345. public Task<ImageStream> GetChannelImageAsync(string channelId, CancellationToken cancellationToken)
  346. {
  347. throw new NotImplementedException();
  348. }
  349. public Task<ImageStream> GetRecordingImageAsync(string recordingId, CancellationToken cancellationToken)
  350. {
  351. throw new NotImplementedException();
  352. }
  353. public Task<ImageStream> GetProgramImageAsync(string programId, string channelId, CancellationToken cancellationToken)
  354. {
  355. throw new NotImplementedException();
  356. }
  357. public async Task<IEnumerable<RecordingInfo>> GetRecordingsAsync(CancellationToken cancellationToken)
  358. {
  359. var recordings = _recordingProvider.GetAll().ToList();
  360. var updated = false;
  361. foreach (var recording in recordings)
  362. {
  363. if (recording.Status == RecordingStatus.InProgress)
  364. {
  365. if (string.IsNullOrWhiteSpace(recording.TimerId) || !_activeRecordings.ContainsKey(recording.TimerId))
  366. {
  367. recording.Status = RecordingStatus.Cancelled;
  368. recording.DateLastUpdated = DateTime.UtcNow;
  369. _recordingProvider.Update(recording);
  370. updated = true;
  371. }
  372. }
  373. }
  374. if (updated)
  375. {
  376. recordings = _recordingProvider.GetAll().ToList();
  377. }
  378. return recordings;
  379. }
  380. public Task<IEnumerable<TimerInfo>> GetTimersAsync(CancellationToken cancellationToken)
  381. {
  382. return Task.FromResult((IEnumerable<TimerInfo>)_timerProvider.GetAll());
  383. }
  384. public Task<SeriesTimerInfo> GetNewTimerDefaultsAsync(CancellationToken cancellationToken, ProgramInfo program = null)
  385. {
  386. var config = GetConfiguration();
  387. var defaults = new SeriesTimerInfo()
  388. {
  389. PostPaddingSeconds = Math.Max(config.PostPaddingSeconds, 0),
  390. PrePaddingSeconds = Math.Max(config.PrePaddingSeconds, 0),
  391. RecordAnyChannel = false,
  392. RecordAnyTime = false,
  393. RecordNewOnly = false
  394. };
  395. if (program != null)
  396. {
  397. defaults.SeriesId = program.SeriesId;
  398. defaults.ProgramId = program.Id;
  399. }
  400. return Task.FromResult(defaults);
  401. }
  402. public Task<IEnumerable<SeriesTimerInfo>> GetSeriesTimersAsync(CancellationToken cancellationToken)
  403. {
  404. return Task.FromResult((IEnumerable<SeriesTimerInfo>)_seriesTimerProvider.GetAll());
  405. }
  406. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  407. {
  408. try
  409. {
  410. return await GetProgramsAsyncInternal(channelId, startDateUtc, endDateUtc, cancellationToken).ConfigureAwait(false);
  411. }
  412. catch (OperationCanceledException)
  413. {
  414. throw;
  415. }
  416. catch (Exception ex)
  417. {
  418. _logger.ErrorException("Error getting programs", ex);
  419. return GetEpgDataForChannel(channelId).Where(i => i.StartDate <= endDateUtc && i.EndDate >= startDateUtc);
  420. }
  421. }
  422. private bool IsListingProviderEnabledForTuner(ListingsProviderInfo info, string tunerHostId)
  423. {
  424. 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 activeRecordingInfo = new ActiveRecordingInfo
  548. {
  549. CancellationTokenSource = new CancellationTokenSource(),
  550. TimerId = timer.Id
  551. };
  552. if (_activeRecordings.TryAdd(timer.Id, activeRecordingInfo))
  553. {
  554. await RecordStream(timer, recordingEndDate, activeRecordingInfo, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false);
  555. }
  556. else
  557. {
  558. _logger.Info("Skipping RecordStream because it's already in progress.");
  559. }
  560. }
  561. catch (OperationCanceledException)
  562. {
  563. }
  564. catch (Exception ex)
  565. {
  566. _logger.ErrorException("Error recording stream", ex);
  567. }
  568. }
  569. private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate, ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken)
  570. {
  571. if (timer == null)
  572. {
  573. throw new ArgumentNullException("timer");
  574. }
  575. ProgramInfo info = null;
  576. if (string.IsNullOrWhiteSpace(timer.ProgramId))
  577. {
  578. _logger.Info("Timer {0} has null programId", timer.Id);
  579. }
  580. else
  581. {
  582. info = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  583. }
  584. if (info == null)
  585. {
  586. _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  587. info = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  588. }
  589. if (info == null)
  590. {
  591. throw new InvalidOperationException(string.Format("Program with Id {0} not found", timer.ProgramId));
  592. }
  593. var recordPath = RecordingPath;
  594. if (info.IsMovie)
  595. {
  596. recordPath = Path.Combine(recordPath, "Movies", _fileSystem.GetValidFilename(info.Name).Trim());
  597. }
  598. else if (info.IsSeries)
  599. {
  600. recordPath = Path.Combine(recordPath, "Series", _fileSystem.GetValidFilename(info.Name).Trim());
  601. }
  602. else if (info.IsKids)
  603. {
  604. recordPath = Path.Combine(recordPath, "Kids", _fileSystem.GetValidFilename(info.Name).Trim());
  605. }
  606. else if (info.IsSports)
  607. {
  608. recordPath = Path.Combine(recordPath, "Sports", _fileSystem.GetValidFilename(info.Name).Trim());
  609. }
  610. else
  611. {
  612. recordPath = Path.Combine(recordPath, "Other", _fileSystem.GetValidFilename(info.Name).Trim());
  613. }
  614. var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer, info)).Trim() + ".ts";
  615. recordPath = Path.Combine(recordPath, recordingFileName);
  616. var recordingId = info.Id.GetMD5().ToString("N");
  617. var recording = _recordingProvider.GetAll().FirstOrDefault(x => string.Equals(x.Id, recordingId, StringComparison.OrdinalIgnoreCase));
  618. if (recording == null)
  619. {
  620. recording = new RecordingInfo
  621. {
  622. ChannelId = info.ChannelId,
  623. Id = recordingId,
  624. StartDate = info.StartDate,
  625. EndDate = info.EndDate,
  626. Genres = info.Genres,
  627. IsKids = info.IsKids,
  628. IsLive = info.IsLive,
  629. IsMovie = info.IsMovie,
  630. IsHD = info.IsHD,
  631. IsNews = info.IsNews,
  632. IsPremiere = info.IsPremiere,
  633. IsSeries = info.IsSeries,
  634. IsSports = info.IsSports,
  635. IsRepeat = !info.IsPremiere,
  636. Name = info.Name,
  637. EpisodeTitle = info.EpisodeTitle,
  638. ProgramId = info.Id,
  639. ImagePath = info.ImagePath,
  640. ImageUrl = info.ImageUrl,
  641. OriginalAirDate = info.OriginalAirDate,
  642. Status = RecordingStatus.Scheduled,
  643. Overview = info.Overview,
  644. SeriesTimerId = timer.SeriesTimerId,
  645. TimerId = timer.Id,
  646. ShowId = info.ShowId
  647. };
  648. _recordingProvider.AddOrUpdate(recording);
  649. }
  650. try
  651. {
  652. var result = await GetChannelStreamInternal(timer.ChannelId, null, CancellationToken.None).ConfigureAwait(false);
  653. var mediaStreamInfo = result.Item1;
  654. var isResourceOpen = true;
  655. // Unfortunately due to the semaphore we have to have a nested try/finally
  656. try
  657. {
  658. // HDHR doesn't seem to release the tuner right away after first probing with ffmpeg
  659. //await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  660. var duration = recordingEndDate - DateTime.UtcNow;
  661. var recorder = await GetRecorder().ConfigureAwait(false);
  662. if (recorder is EncodedRecorder)
  663. {
  664. recordPath = Path.ChangeExtension(recordPath, ".mp4");
  665. }
  666. recordPath = EnsureFileUnique(recordPath, timer.Id);
  667. _fileSystem.CreateDirectory(Path.GetDirectoryName(recordPath));
  668. activeRecordingInfo.Path = recordPath;
  669. _libraryMonitor.ReportFileSystemChangeBeginning(recordPath);
  670. recording.Path = recordPath;
  671. recording.Status = RecordingStatus.InProgress;
  672. recording.DateLastUpdated = DateTime.UtcNow;
  673. _recordingProvider.AddOrUpdate(recording);
  674. _logger.Info("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
  675. _logger.Info("Writing file to path: " + recordPath);
  676. _logger.Info("Opening recording stream from tuner provider");
  677. Action onStarted = () =>
  678. {
  679. result.Item2.Release();
  680. isResourceOpen = false;
  681. };
  682. await recorder.Record(mediaStreamInfo, recordPath, duration, onStarted, cancellationToken).ConfigureAwait(false);
  683. recording.Status = RecordingStatus.Completed;
  684. _logger.Info("Recording completed: {0}", recordPath);
  685. }
  686. finally
  687. {
  688. if (isResourceOpen)
  689. {
  690. result.Item2.Release();
  691. }
  692. _libraryMonitor.ReportFileSystemChangeComplete(recordPath, false);
  693. }
  694. }
  695. catch (OperationCanceledException)
  696. {
  697. _logger.Info("Recording stopped: {0}", recordPath);
  698. recording.Status = RecordingStatus.Completed;
  699. }
  700. catch (Exception ex)
  701. {
  702. _logger.ErrorException("Error recording to {0}", ex, recordPath);
  703. recording.Status = RecordingStatus.Error;
  704. }
  705. finally
  706. {
  707. ActiveRecordingInfo removed;
  708. _activeRecordings.TryRemove(timer.Id, out removed);
  709. }
  710. recording.DateLastUpdated = DateTime.UtcNow;
  711. _recordingProvider.AddOrUpdate(recording);
  712. if (recording.Status == RecordingStatus.Completed)
  713. {
  714. OnSuccessfulRecording(recording);
  715. _timerProvider.Delete(timer);
  716. }
  717. else if (DateTime.UtcNow < timer.EndDate)
  718. {
  719. const int retryIntervalSeconds = 60;
  720. _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds);
  721. _timerProvider.StartTimer(timer, TimeSpan.FromSeconds(retryIntervalSeconds));
  722. }
  723. else
  724. {
  725. _timerProvider.Delete(timer);
  726. _recordingProvider.Delete(recording);
  727. }
  728. }
  729. private string EnsureFileUnique(string path, string timerId)
  730. {
  731. var originalPath = path;
  732. var index = 1;
  733. while (FileExists(path, timerId))
  734. {
  735. var parent = Path.GetDirectoryName(originalPath);
  736. var name = Path.GetFileNameWithoutExtension(originalPath);
  737. name += "-" + index.ToString(CultureInfo.InvariantCulture);
  738. path = Path.ChangeExtension(Path.Combine(parent, name), Path.GetExtension(originalPath));
  739. index++;
  740. }
  741. return path;
  742. }
  743. private bool FileExists(string path, string timerId)
  744. {
  745. if (_fileSystem.FileExists(path))
  746. {
  747. return true;
  748. }
  749. var hasRecordingAtPath = _activeRecordings.Values.ToList().Any(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.TimerId, timerId, StringComparison.OrdinalIgnoreCase));
  750. if (hasRecordingAtPath)
  751. {
  752. return true;
  753. }
  754. return false;
  755. }
  756. private async Task<IRecorder> GetRecorder()
  757. {
  758. if (GetConfiguration().EnableRecordingEncoding)
  759. {
  760. var regInfo = await _security.GetRegistrationStatus("embytvrecordingconversion").ConfigureAwait(false);
  761. if (regInfo.IsValid)
  762. {
  763. return new EncodedRecorder(_logger, _fileSystem, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer);
  764. }
  765. }
  766. return new DirectRecorder(_logger, _httpClient, _fileSystem);
  767. }
  768. private async void OnSuccessfulRecording(RecordingInfo recording)
  769. {
  770. if (GetConfiguration().EnableAutoOrganize)
  771. {
  772. if (recording.IsSeries)
  773. {
  774. try
  775. {
  776. // this is to account for the library monitor holding a lock for additional time after the change is complete.
  777. // ideally this shouldn't be hard-coded
  778. await Task.Delay(30000).ConfigureAwait(false);
  779. var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager);
  780. var result = await organize.OrganizeEpisodeFile(recording.Path, CancellationToken.None).ConfigureAwait(false);
  781. if (result.Status == FileSortingStatus.Success)
  782. {
  783. _recordingProvider.Delete(recording);
  784. }
  785. }
  786. catch (Exception ex)
  787. {
  788. _logger.ErrorException("Error processing new recording", ex);
  789. }
  790. }
  791. }
  792. }
  793. private ProgramInfo GetProgramInfoFromCache(string channelId, string programId)
  794. {
  795. var epgData = GetEpgDataForChannel(channelId);
  796. return epgData.FirstOrDefault(p => string.Equals(p.Id, programId, StringComparison.OrdinalIgnoreCase));
  797. }
  798. private ProgramInfo GetProgramInfoFromCache(string channelId, DateTime startDateUtc)
  799. {
  800. var epgData = GetEpgDataForChannel(channelId);
  801. var startDateTicks = startDateUtc.Ticks;
  802. // Find the first program that starts within 3 minutes
  803. return epgData.FirstOrDefault(p => Math.Abs(startDateTicks - p.StartDate.Ticks) <= TimeSpan.FromMinutes(3).Ticks);
  804. }
  805. private string RecordingPath
  806. {
  807. get
  808. {
  809. var path = GetConfiguration().RecordingPath;
  810. return string.IsNullOrWhiteSpace(path)
  811. ? Path.Combine(DataPath, "recordings")
  812. : path;
  813. }
  814. }
  815. private LiveTvOptions GetConfiguration()
  816. {
  817. return _config.GetConfiguration<LiveTvOptions>("livetv");
  818. }
  819. private async Task UpdateTimersForSeriesTimer(List<ProgramInfo> epgData, SeriesTimerInfo seriesTimer, bool deleteInvalidTimers)
  820. {
  821. var newTimers = GetTimersForSeries(seriesTimer, epgData, _recordingProvider.GetAll()).ToList();
  822. var registration = await GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
  823. if (registration.IsValid)
  824. {
  825. foreach (var timer in newTimers)
  826. {
  827. _timerProvider.AddOrUpdate(timer);
  828. }
  829. }
  830. if (deleteInvalidTimers)
  831. {
  832. var allTimers = GetTimersForSeries(seriesTimer, epgData, new List<RecordingInfo>())
  833. .Select(i => i.Id)
  834. .ToList();
  835. var deletes = _timerProvider.GetAll()
  836. .Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
  837. .Where(i => !allTimers.Contains(i.Id, StringComparer.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
  838. .ToList();
  839. foreach (var timer in deletes)
  840. {
  841. await CancelTimerAsync(timer.Id, CancellationToken.None).ConfigureAwait(false);
  842. }
  843. }
  844. }
  845. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms, IReadOnlyList<RecordingInfo> currentRecordings)
  846. {
  847. if (seriesTimer == null)
  848. {
  849. throw new ArgumentNullException("seriesTimer");
  850. }
  851. if (allPrograms == null)
  852. {
  853. throw new ArgumentNullException("allPrograms");
  854. }
  855. if (currentRecordings == null)
  856. {
  857. throw new ArgumentNullException("currentRecordings");
  858. }
  859. // Exclude programs that have already ended
  860. allPrograms = allPrograms.Where(i => i.EndDate > DateTime.UtcNow && i.StartDate > DateTime.UtcNow);
  861. allPrograms = GetProgramsForSeries(seriesTimer, allPrograms);
  862. var recordingShowIds = currentRecordings.Select(i => i.ProgramId).Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  863. allPrograms = allPrograms.Where(i => !recordingShowIds.Contains(i.Id, StringComparer.OrdinalIgnoreCase));
  864. return allPrograms.Select(i => RecordingHelper.CreateTimer(i, seriesTimer));
  865. }
  866. private IEnumerable<ProgramInfo> GetProgramsForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  867. {
  868. if (!seriesTimer.RecordAnyTime)
  869. {
  870. allPrograms = allPrograms.Where(epg => Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - epg.StartDate.TimeOfDay.Ticks) < TimeSpan.FromMinutes(5).Ticks);
  871. }
  872. if (seriesTimer.RecordNewOnly)
  873. {
  874. allPrograms = allPrograms.Where(epg => !epg.IsRepeat);
  875. }
  876. if (!seriesTimer.RecordAnyChannel)
  877. {
  878. allPrograms = allPrograms.Where(epg => string.Equals(epg.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase));
  879. }
  880. allPrograms = allPrograms.Where(i => seriesTimer.Days.Contains(i.StartDate.ToLocalTime().DayOfWeek));
  881. if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
  882. {
  883. _logger.Error("seriesTimer.SeriesId is null. Cannot find programs for series");
  884. return new List<ProgramInfo>();
  885. }
  886. return allPrograms.Where(i => string.Equals(i.SeriesId, seriesTimer.SeriesId, StringComparison.OrdinalIgnoreCase));
  887. }
  888. private string GetChannelEpgCachePath(string channelId)
  889. {
  890. return Path.Combine(_config.CommonApplicationPaths.CachePath, "embytvepg", channelId + ".json");
  891. }
  892. private readonly object _epgLock = new object();
  893. private void SaveEpgDataForChannel(string channelId, List<ProgramInfo> epgData)
  894. {
  895. var path = GetChannelEpgCachePath(channelId);
  896. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  897. lock (_epgLock)
  898. {
  899. _jsonSerializer.SerializeToFile(epgData, path);
  900. }
  901. }
  902. private List<ProgramInfo> GetEpgDataForChannel(string channelId)
  903. {
  904. try
  905. {
  906. lock (_epgLock)
  907. {
  908. return _jsonSerializer.DeserializeFromFile<List<ProgramInfo>>(GetChannelEpgCachePath(channelId));
  909. }
  910. }
  911. catch
  912. {
  913. return new List<ProgramInfo>();
  914. }
  915. }
  916. private List<ProgramInfo> GetEpgDataForChannels(List<string> channelIds)
  917. {
  918. return channelIds.SelectMany(GetEpgDataForChannel).ToList();
  919. }
  920. public void Dispose()
  921. {
  922. foreach (var pair in _activeRecordings.ToList())
  923. {
  924. pair.Value.CancellationTokenSource.Cancel();
  925. }
  926. }
  927. public Task<MBRegistrationRecord> GetRegistrationInfo(string feature)
  928. {
  929. if (string.Equals(feature, "seriesrecordings", StringComparison.OrdinalIgnoreCase))
  930. {
  931. return _security.GetRegistrationStatus("embytvseriesrecordings");
  932. }
  933. return Task.FromResult(new MBRegistrationRecord
  934. {
  935. IsValid = true,
  936. IsRegistered = true
  937. });
  938. }
  939. class ActiveRecordingInfo
  940. {
  941. public string Path { get; set; }
  942. public string TimerId { get; set; }
  943. public CancellationTokenSource CancellationTokenSource { get; set; }
  944. }
  945. }
  946. }