EmbyTV.cs 38 KB

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