EmbyTV.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  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.IO;
  26. using System.Linq;
  27. using System.Threading;
  28. using System.Threading.Tasks;
  29. using CommonIO;
  30. using MediaBrowser.Common.Extensions;
  31. namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
  32. {
  33. public class EmbyTV : ILiveTvService, IHasRegistrationInfo, IDisposable
  34. {
  35. private readonly IApplicationHost _appHpst;
  36. private readonly ILogger _logger;
  37. private readonly IHttpClient _httpClient;
  38. private readonly IServerConfigurationManager _config;
  39. private readonly IJsonSerializer _jsonSerializer;
  40. private readonly ItemDataProvider<RecordingInfo> _recordingProvider;
  41. private readonly ItemDataProvider<SeriesTimerInfo> _seriesTimerProvider;
  42. private readonly TimerManager _timerProvider;
  43. private readonly LiveTvManager _liveTvManager;
  44. private readonly IFileSystem _fileSystem;
  45. private readonly ISecurityManager _security;
  46. private readonly ILibraryMonitor _libraryMonitor;
  47. private readonly ILibraryManager _libraryManager;
  48. private readonly IProviderManager _providerManager;
  49. private readonly IFileOrganizationService _organizationService;
  50. private readonly IMediaEncoder _mediaEncoder;
  51. public static EmbyTV Current;
  52. 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)
  53. {
  54. Current = this;
  55. _appHpst = appHost;
  56. _logger = logger;
  57. _httpClient = httpClient;
  58. _config = config;
  59. _fileSystem = fileSystem;
  60. _security = security;
  61. _libraryManager = libraryManager;
  62. _libraryMonitor = libraryMonitor;
  63. _providerManager = providerManager;
  64. _organizationService = organizationService;
  65. _mediaEncoder = mediaEncoder;
  66. _liveTvManager = (LiveTvManager)liveTvManager;
  67. _jsonSerializer = jsonSerializer;
  68. _recordingProvider = new ItemDataProvider<RecordingInfo>(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "recordings"), (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase));
  69. _seriesTimerProvider = new SeriesTimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers"));
  70. _timerProvider = new TimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "timers"));
  71. _timerProvider.TimerFired += _timerProvider_TimerFired;
  72. }
  73. public void Start()
  74. {
  75. _timerProvider.RestartTimers();
  76. }
  77. public event EventHandler DataSourceChanged;
  78. public event EventHandler<RecordingStatusChangedEventArgs> RecordingStatusChanged;
  79. private readonly ConcurrentDictionary<string, CancellationTokenSource> _activeRecordings =
  80. new ConcurrentDictionary<string, CancellationTokenSource>(StringComparer.OrdinalIgnoreCase);
  81. public string Name
  82. {
  83. get { return "Emby"; }
  84. }
  85. public string DataPath
  86. {
  87. get { return Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv"); }
  88. }
  89. public string HomePageUrl
  90. {
  91. get { return "http://emby.media"; }
  92. }
  93. public async Task<LiveTvServiceStatusInfo> GetStatusInfoAsync(CancellationToken cancellationToken)
  94. {
  95. var status = new LiveTvServiceStatusInfo();
  96. var list = new List<LiveTvTunerInfo>();
  97. foreach (var hostInstance in _liveTvManager.TunerHosts)
  98. {
  99. try
  100. {
  101. var tuners = await hostInstance.GetTunerInfos(cancellationToken).ConfigureAwait(false);
  102. list.AddRange(tuners);
  103. }
  104. catch (Exception ex)
  105. {
  106. _logger.ErrorException("Error getting tuners", ex);
  107. }
  108. }
  109. status.Tuners = list;
  110. status.Status = LiveTvServiceStatus.Ok;
  111. status.Version = _appHpst.ApplicationVersion.ToString();
  112. status.IsVisible = false;
  113. return status;
  114. }
  115. public async Task RefreshSeriesTimers(CancellationToken cancellationToken, IProgress<double> progress)
  116. {
  117. var timers = await GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  118. List<ChannelInfo> channels = null;
  119. foreach (var timer in timers)
  120. {
  121. List<ProgramInfo> epgData;
  122. if (timer.RecordAnyChannel)
  123. {
  124. if (channels == null)
  125. {
  126. channels = (await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false)).ToList();
  127. }
  128. var channelIds = channels.Select(i => i.Id).ToList();
  129. epgData = GetEpgDataForChannels(channelIds);
  130. }
  131. else
  132. {
  133. epgData = GetEpgDataForChannel(timer.ChannelId);
  134. }
  135. await UpdateTimersForSeriesTimer(epgData, timer).ConfigureAwait(false);
  136. }
  137. }
  138. private List<ChannelInfo> _channelCache = null;
  139. private async Task<IEnumerable<ChannelInfo>> GetChannelsAsync(bool enableCache, CancellationToken cancellationToken)
  140. {
  141. if (enableCache && _channelCache != null)
  142. {
  143. return _channelCache.ToList();
  144. }
  145. var list = new List<ChannelInfo>();
  146. foreach (var hostInstance in _liveTvManager.TunerHosts)
  147. {
  148. try
  149. {
  150. var channels = await hostInstance.GetChannels(cancellationToken).ConfigureAwait(false);
  151. list.AddRange(channels);
  152. }
  153. catch (Exception ex)
  154. {
  155. _logger.ErrorException("Error getting channels", ex);
  156. }
  157. }
  158. if (list.Count > 0)
  159. {
  160. foreach (var provider in GetListingProviders())
  161. {
  162. try
  163. {
  164. await provider.Item1.AddMetadata(provider.Item2, list, cancellationToken).ConfigureAwait(false);
  165. }
  166. catch (NotSupportedException)
  167. {
  168. }
  169. catch (Exception ex)
  170. {
  171. _logger.ErrorException("Error adding metadata", ex);
  172. }
  173. }
  174. }
  175. _channelCache = list;
  176. return list;
  177. }
  178. public Task<IEnumerable<ChannelInfo>> GetChannelsAsync(CancellationToken cancellationToken)
  179. {
  180. return GetChannelsAsync(false, cancellationToken);
  181. }
  182. public Task CancelSeriesTimerAsync(string timerId, CancellationToken cancellationToken)
  183. {
  184. var timers = _timerProvider.GetAll().Where(i => string.Equals(i.SeriesTimerId, timerId, StringComparison.OrdinalIgnoreCase));
  185. foreach (var timer in timers)
  186. {
  187. CancelTimerInternal(timer.Id);
  188. }
  189. var remove = _seriesTimerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
  190. if (remove != null)
  191. {
  192. _seriesTimerProvider.Delete(remove);
  193. }
  194. return Task.FromResult(true);
  195. }
  196. private void CancelTimerInternal(string timerId)
  197. {
  198. var remove = _timerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
  199. if (remove != null)
  200. {
  201. _timerProvider.Delete(remove);
  202. }
  203. CancellationTokenSource cancellationTokenSource;
  204. if (_activeRecordings.TryGetValue(timerId, out cancellationTokenSource))
  205. {
  206. cancellationTokenSource.Cancel();
  207. }
  208. }
  209. public Task CancelTimerAsync(string timerId, CancellationToken cancellationToken)
  210. {
  211. CancelTimerInternal(timerId);
  212. return Task.FromResult(true);
  213. }
  214. public async Task DeleteRecordingAsync(string recordingId, CancellationToken cancellationToken)
  215. {
  216. var remove = _recordingProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, recordingId, StringComparison.OrdinalIgnoreCase));
  217. if (remove != null)
  218. {
  219. if (!string.IsNullOrWhiteSpace(remove.TimerId))
  220. {
  221. var enableDelay = _activeRecordings.ContainsKey(remove.TimerId);
  222. CancelTimerInternal(remove.TimerId);
  223. if (enableDelay)
  224. {
  225. // A hack yes, but need to make sure the file is closed before attempting to delete it
  226. await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  227. }
  228. }
  229. try
  230. {
  231. _fileSystem.DeleteFile(remove.Path);
  232. }
  233. catch (DirectoryNotFoundException)
  234. {
  235. }
  236. catch (FileNotFoundException)
  237. {
  238. }
  239. _recordingProvider.Delete(remove);
  240. }
  241. else
  242. {
  243. throw new ResourceNotFoundException("Recording not found: " + recordingId);
  244. }
  245. }
  246. public Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
  247. {
  248. info.Id = Guid.NewGuid().ToString("N");
  249. _timerProvider.Add(info);
  250. return Task.FromResult(0);
  251. }
  252. public async Task CreateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  253. {
  254. info.Id = Guid.NewGuid().ToString("N");
  255. List<ProgramInfo> epgData;
  256. if (info.RecordAnyChannel)
  257. {
  258. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  259. var channelIds = channels.Select(i => i.Id).ToList();
  260. epgData = GetEpgDataForChannels(channelIds);
  261. }
  262. else
  263. {
  264. epgData = GetEpgDataForChannel(info.ChannelId);
  265. }
  266. // populate info.seriesID
  267. var program = epgData.FirstOrDefault(i => string.Equals(i.Id, info.ProgramId, StringComparison.OrdinalIgnoreCase));
  268. if (program != null)
  269. {
  270. info.SeriesId = program.SeriesId;
  271. }
  272. else
  273. {
  274. throw new InvalidOperationException("SeriesId for program not found");
  275. }
  276. _seriesTimerProvider.Add(info);
  277. await UpdateTimersForSeriesTimer(epgData, info).ConfigureAwait(false);
  278. }
  279. public async Task UpdateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  280. {
  281. _seriesTimerProvider.Update(info);
  282. List<ProgramInfo> epgData;
  283. if (info.RecordAnyChannel)
  284. {
  285. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  286. var channelIds = channels.Select(i => i.Id).ToList();
  287. epgData = GetEpgDataForChannels(channelIds);
  288. }
  289. else
  290. {
  291. epgData = GetEpgDataForChannel(info.ChannelId);
  292. }
  293. await UpdateTimersForSeriesTimer(epgData, info).ConfigureAwait(false);
  294. }
  295. public Task UpdateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
  296. {
  297. _timerProvider.Update(info);
  298. return Task.FromResult(true);
  299. }
  300. public Task<ImageStream> GetChannelImageAsync(string channelId, CancellationToken cancellationToken)
  301. {
  302. throw new NotImplementedException();
  303. }
  304. public Task<ImageStream> GetRecordingImageAsync(string recordingId, CancellationToken cancellationToken)
  305. {
  306. throw new NotImplementedException();
  307. }
  308. public Task<ImageStream> GetProgramImageAsync(string programId, string channelId, CancellationToken cancellationToken)
  309. {
  310. throw new NotImplementedException();
  311. }
  312. public async Task<IEnumerable<RecordingInfo>> GetRecordingsAsync(CancellationToken cancellationToken)
  313. {
  314. var recordings = _recordingProvider.GetAll().ToList();
  315. var updated = false;
  316. foreach (var recording in recordings)
  317. {
  318. if (recording.Status == RecordingStatus.InProgress)
  319. {
  320. if (string.IsNullOrWhiteSpace(recording.TimerId) || !_activeRecordings.ContainsKey(recording.TimerId))
  321. {
  322. recording.Status = RecordingStatus.Cancelled;
  323. recording.DateLastUpdated = DateTime.UtcNow;
  324. _recordingProvider.Update(recording);
  325. updated = true;
  326. }
  327. }
  328. }
  329. if (updated)
  330. {
  331. recordings = _recordingProvider.GetAll().ToList();
  332. }
  333. return recordings;
  334. }
  335. public Task<IEnumerable<TimerInfo>> GetTimersAsync(CancellationToken cancellationToken)
  336. {
  337. return Task.FromResult((IEnumerable<TimerInfo>)_timerProvider.GetAll());
  338. }
  339. public Task<SeriesTimerInfo> GetNewTimerDefaultsAsync(CancellationToken cancellationToken, ProgramInfo program = null)
  340. {
  341. var config = GetConfiguration();
  342. var defaults = new SeriesTimerInfo()
  343. {
  344. PostPaddingSeconds = Math.Max(config.PostPaddingSeconds, 0),
  345. PrePaddingSeconds = Math.Max(config.PrePaddingSeconds, 0),
  346. RecordAnyChannel = false,
  347. RecordAnyTime = false,
  348. RecordNewOnly = false
  349. };
  350. if (program != null)
  351. {
  352. defaults.SeriesId = program.SeriesId;
  353. defaults.ProgramId = program.Id;
  354. }
  355. return Task.FromResult(defaults);
  356. }
  357. public Task<IEnumerable<SeriesTimerInfo>> GetSeriesTimersAsync(CancellationToken cancellationToken)
  358. {
  359. return Task.FromResult((IEnumerable<SeriesTimerInfo>)_seriesTimerProvider.GetAll());
  360. }
  361. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  362. {
  363. try
  364. {
  365. return await GetProgramsAsyncInternal(channelId, startDateUtc, endDateUtc, cancellationToken).ConfigureAwait(false);
  366. }
  367. catch (OperationCanceledException)
  368. {
  369. throw;
  370. }
  371. catch (Exception ex)
  372. {
  373. _logger.ErrorException("Error getting programs", ex);
  374. return GetEpgDataForChannel(channelId).Where(i => i.StartDate <= endDateUtc && i.EndDate >= startDateUtc);
  375. }
  376. }
  377. private async Task<IEnumerable<ProgramInfo>> GetProgramsAsyncInternal(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  378. {
  379. var channels = await GetChannelsAsync(true, cancellationToken).ConfigureAwait(false);
  380. var channel = channels.First(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  381. foreach (var provider in GetListingProviders())
  382. {
  383. var programs = await provider.Item1.GetProgramsAsync(provider.Item2, channel.Number, channel.Name, startDateUtc, endDateUtc, cancellationToken)
  384. .ConfigureAwait(false);
  385. var list = programs.ToList();
  386. // Replace the value that came from the provider with a normalized value
  387. foreach (var program in list)
  388. {
  389. program.ChannelId = channelId;
  390. }
  391. if (list.Count > 0)
  392. {
  393. SaveEpgDataForChannel(channelId, list);
  394. return list;
  395. }
  396. }
  397. return new List<ProgramInfo>();
  398. }
  399. private List<Tuple<IListingsProvider, ListingsProviderInfo>> GetListingProviders()
  400. {
  401. return GetConfiguration().ListingProviders
  402. .Select(i =>
  403. {
  404. var provider = _liveTvManager.ListingProviders.FirstOrDefault(l => string.Equals(l.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  405. return provider == null ? null : new Tuple<IListingsProvider, ListingsProviderInfo>(provider, i);
  406. })
  407. .Where(i => i != null)
  408. .ToList();
  409. }
  410. public Task<MediaSourceInfo> GetRecordingStream(string recordingId, string streamId, CancellationToken cancellationToken)
  411. {
  412. throw new NotImplementedException();
  413. }
  414. public async Task<MediaSourceInfo> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
  415. {
  416. _logger.Info("Streaming Channel " + channelId);
  417. foreach (var hostInstance in _liveTvManager.TunerHosts)
  418. {
  419. try
  420. {
  421. var result = await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
  422. result.Item2.Release();
  423. return result.Item1;
  424. }
  425. catch (Exception e)
  426. {
  427. _logger.ErrorException("Error getting channel stream", e);
  428. }
  429. }
  430. throw new ApplicationException("Tuner not found.");
  431. }
  432. private async Task<Tuple<MediaSourceInfo, SemaphoreSlim>> GetChannelStreamInternal(string channelId, string streamId, CancellationToken cancellationToken)
  433. {
  434. _logger.Info("Streaming Channel " + channelId);
  435. foreach (var hostInstance in _liveTvManager.TunerHosts)
  436. {
  437. try
  438. {
  439. return await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
  440. }
  441. catch (Exception e)
  442. {
  443. _logger.ErrorException("Error getting channel stream", e);
  444. }
  445. }
  446. throw new ApplicationException("Tuner not found.");
  447. }
  448. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  449. {
  450. foreach (var hostInstance in _liveTvManager.TunerHosts)
  451. {
  452. try
  453. {
  454. var sources = await hostInstance.GetChannelStreamMediaSources(channelId, cancellationToken).ConfigureAwait(false);
  455. if (sources.Count > 0)
  456. {
  457. return sources;
  458. }
  459. }
  460. catch (NotImplementedException)
  461. {
  462. }
  463. }
  464. throw new NotImplementedException();
  465. }
  466. public Task<List<MediaSourceInfo>> GetRecordingStreamMediaSources(string recordingId, CancellationToken cancellationToken)
  467. {
  468. throw new NotImplementedException();
  469. }
  470. public Task CloseLiveStream(string id, CancellationToken cancellationToken)
  471. {
  472. return Task.FromResult(0);
  473. }
  474. public Task RecordLiveStream(string id, CancellationToken cancellationToken)
  475. {
  476. return Task.FromResult(0);
  477. }
  478. public Task ResetTuner(string id, CancellationToken cancellationToken)
  479. {
  480. return Task.FromResult(0);
  481. }
  482. async void _timerProvider_TimerFired(object sender, GenericEventArgs<TimerInfo> e)
  483. {
  484. var timer = e.Argument;
  485. _logger.Info("Recording timer fired.");
  486. try
  487. {
  488. var recordingEndDate = timer.EndDate.AddSeconds(timer.PostPaddingSeconds);
  489. if (recordingEndDate <= DateTime.UtcNow)
  490. {
  491. _logger.Warn("Recording timer fired for timer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
  492. return;
  493. }
  494. var cancellationTokenSource = new CancellationTokenSource();
  495. if (_activeRecordings.TryAdd(timer.Id, cancellationTokenSource))
  496. {
  497. await RecordStream(timer, recordingEndDate, cancellationTokenSource.Token).ConfigureAwait(false);
  498. }
  499. }
  500. catch (OperationCanceledException)
  501. {
  502. }
  503. catch (Exception ex)
  504. {
  505. _logger.ErrorException("Error recording stream", ex);
  506. }
  507. }
  508. private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate, CancellationToken cancellationToken)
  509. {
  510. if (timer == null)
  511. {
  512. throw new ArgumentNullException("timer");
  513. }
  514. if (string.IsNullOrWhiteSpace(timer.ProgramId))
  515. {
  516. throw new InvalidOperationException("timer.ProgramId is null. Cannot record.");
  517. }
  518. var info = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  519. if (info == null)
  520. {
  521. throw new InvalidOperationException(string.Format("Program with Id {0} not found", timer.ProgramId));
  522. }
  523. var recordPath = RecordingPath;
  524. if (info.IsMovie)
  525. {
  526. recordPath = Path.Combine(recordPath, "Movies", _fileSystem.GetValidFilename(info.Name).Trim());
  527. }
  528. else if (info.IsSeries)
  529. {
  530. recordPath = Path.Combine(recordPath, "Series", _fileSystem.GetValidFilename(info.Name).Trim());
  531. }
  532. else if (info.IsKids)
  533. {
  534. recordPath = Path.Combine(recordPath, "Kids", _fileSystem.GetValidFilename(info.Name).Trim());
  535. }
  536. else if (info.IsSports)
  537. {
  538. recordPath = Path.Combine(recordPath, "Sports", _fileSystem.GetValidFilename(info.Name).Trim());
  539. }
  540. else
  541. {
  542. recordPath = Path.Combine(recordPath, "Other", _fileSystem.GetValidFilename(info.Name).Trim());
  543. }
  544. var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer, info)).Trim() + ".ts";
  545. recordPath = Path.Combine(recordPath, recordingFileName);
  546. _fileSystem.CreateDirectory(Path.GetDirectoryName(recordPath));
  547. var recordingId = info.Id.GetMD5().ToString("N");
  548. var recording = _recordingProvider.GetAll().FirstOrDefault(x => string.Equals(x.Id, recordingId, StringComparison.OrdinalIgnoreCase));
  549. if (recording == null)
  550. {
  551. recording = new RecordingInfo
  552. {
  553. ChannelId = info.ChannelId,
  554. Id = recordingId,
  555. StartDate = info.StartDate,
  556. EndDate = info.EndDate,
  557. Genres = info.Genres,
  558. IsKids = info.IsKids,
  559. IsLive = info.IsLive,
  560. IsMovie = info.IsMovie,
  561. IsHD = info.IsHD,
  562. IsNews = info.IsNews,
  563. IsPremiere = info.IsPremiere,
  564. IsSeries = info.IsSeries,
  565. IsSports = info.IsSports,
  566. IsRepeat = !info.IsPremiere,
  567. Name = info.Name,
  568. EpisodeTitle = info.EpisodeTitle,
  569. ProgramId = info.Id,
  570. ImagePath = info.ImagePath,
  571. ImageUrl = info.ImageUrl,
  572. OriginalAirDate = info.OriginalAirDate,
  573. Status = RecordingStatus.Scheduled,
  574. Overview = info.Overview,
  575. SeriesTimerId = timer.SeriesTimerId,
  576. TimerId = timer.Id,
  577. ShowId = info.ShowId
  578. };
  579. _recordingProvider.Add(recording);
  580. }
  581. try
  582. {
  583. var result = await GetChannelStreamInternal(timer.ChannelId, null, CancellationToken.None);
  584. var mediaStreamInfo = result.Item1;
  585. var isResourceOpen = true;
  586. // Unfortunately due to the semaphore we have to have a nested try/finally
  587. try
  588. {
  589. // HDHR doesn't seem to release the tuner right away after first probing with ffmpeg
  590. await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  591. var duration = recordingEndDate - DateTime.UtcNow;
  592. HttpRequestOptions httpRequestOptions = new HttpRequestOptions()
  593. {
  594. Url = mediaStreamInfo.Path
  595. };
  596. recording.Path = recordPath;
  597. recording.Status = RecordingStatus.InProgress;
  598. recording.DateLastUpdated = DateTime.UtcNow;
  599. _recordingProvider.Update(recording);
  600. _logger.Info("Beginning recording.");
  601. httpRequestOptions.BufferContent = false;
  602. var durationToken = new CancellationTokenSource(duration);
  603. var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token;
  604. httpRequestOptions.CancellationToken = linkedToken;
  605. _logger.Info("Writing file to path: " + recordPath);
  606. using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET"))
  607. {
  608. using (var output = _fileSystem.GetFileStream(recordPath, FileMode.Create, FileAccess.Write, FileShare.Read))
  609. {
  610. result.Item2.Release();
  611. isResourceOpen = false;
  612. await response.Content.CopyToAsync(output, StreamDefaults.DefaultCopyToBufferSize, linkedToken);
  613. }
  614. }
  615. recording.Status = RecordingStatus.Completed;
  616. _logger.Info("Recording completed");
  617. }
  618. finally
  619. {
  620. if (isResourceOpen)
  621. {
  622. result.Item2.Release();
  623. }
  624. }
  625. }
  626. catch (OperationCanceledException)
  627. {
  628. _logger.Info("Recording stopped");
  629. recording.Status = RecordingStatus.Completed;
  630. }
  631. catch (Exception ex)
  632. {
  633. _logger.ErrorException("Error recording", ex);
  634. recording.Status = RecordingStatus.Error;
  635. }
  636. finally
  637. {
  638. CancellationTokenSource removed;
  639. _activeRecordings.TryRemove(timer.Id, out removed);
  640. }
  641. recording.DateLastUpdated = DateTime.UtcNow;
  642. _recordingProvider.Update(recording);
  643. if (recording.Status == RecordingStatus.Completed)
  644. {
  645. OnSuccessfulRecording(recording);
  646. _timerProvider.Delete(timer);
  647. }
  648. else if (DateTime.UtcNow < timer.EndDate)
  649. {
  650. const int retryIntervalSeconds = 60;
  651. _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds);
  652. _timerProvider.StartTimer(timer, TimeSpan.FromSeconds(retryIntervalSeconds));
  653. }
  654. else
  655. {
  656. _timerProvider.Delete(timer);
  657. _recordingProvider.Delete(recording);
  658. }
  659. }
  660. private async void OnSuccessfulRecording(RecordingInfo recording)
  661. {
  662. if (GetConfiguration().EnableAutoOrganize)
  663. {
  664. if (recording.IsSeries)
  665. {
  666. try
  667. {
  668. var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager);
  669. var result = await organize.OrganizeEpisodeFile(recording.Path, CancellationToken.None).ConfigureAwait(false);
  670. if (result.Status == FileSortingStatus.Success)
  671. {
  672. _recordingProvider.Delete(recording);
  673. }
  674. }
  675. catch (Exception ex)
  676. {
  677. _logger.ErrorException("Error processing new recording", ex);
  678. }
  679. }
  680. }
  681. }
  682. private ProgramInfo GetProgramInfoFromCache(string channelId, string programId)
  683. {
  684. var epgData = GetEpgDataForChannel(channelId);
  685. return epgData.FirstOrDefault(p => string.Equals(p.Id, programId, StringComparison.OrdinalIgnoreCase));
  686. }
  687. private string RecordingPath
  688. {
  689. get
  690. {
  691. var path = GetConfiguration().RecordingPath;
  692. return string.IsNullOrWhiteSpace(path)
  693. ? Path.Combine(DataPath, "recordings")
  694. : path;
  695. }
  696. }
  697. private LiveTvOptions GetConfiguration()
  698. {
  699. return _config.GetConfiguration<LiveTvOptions>("livetv");
  700. }
  701. private async Task UpdateTimersForSeriesTimer(List<ProgramInfo> epgData, SeriesTimerInfo seriesTimer)
  702. {
  703. var registration = await GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
  704. if (registration.IsValid)
  705. {
  706. var newTimers = GetTimersForSeries(seriesTimer, epgData, _recordingProvider.GetAll()).ToList();
  707. foreach (var timer in newTimers)
  708. {
  709. _timerProvider.AddOrUpdate(timer);
  710. }
  711. }
  712. }
  713. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms, IReadOnlyList<RecordingInfo> currentRecordings)
  714. {
  715. // Exclude programs that have already ended
  716. allPrograms = allPrograms.Where(i => i.EndDate > DateTime.UtcNow);
  717. allPrograms = GetProgramsForSeries(seriesTimer, allPrograms);
  718. var recordingShowIds = currentRecordings.Select(i => i.ProgramId).Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  719. allPrograms = allPrograms.Where(i => !recordingShowIds.Contains(i.Id, StringComparer.OrdinalIgnoreCase));
  720. return allPrograms.Select(i => RecordingHelper.CreateTimer(i, seriesTimer));
  721. }
  722. private IEnumerable<ProgramInfo> GetProgramsForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  723. {
  724. if (!seriesTimer.RecordAnyTime)
  725. {
  726. allPrograms = allPrograms.Where(epg => (seriesTimer.StartDate.TimeOfDay == epg.StartDate.TimeOfDay));
  727. }
  728. if (seriesTimer.RecordNewOnly)
  729. {
  730. allPrograms = allPrograms.Where(epg => !epg.IsRepeat);
  731. }
  732. if (!seriesTimer.RecordAnyChannel)
  733. {
  734. allPrograms = allPrograms.Where(epg => string.Equals(epg.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase));
  735. }
  736. allPrograms = allPrograms.Where(i => seriesTimer.Days.Contains(i.StartDate.ToLocalTime().DayOfWeek));
  737. if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
  738. {
  739. _logger.Error("seriesTimer.SeriesId is null. Cannot find programs for series");
  740. return new List<ProgramInfo>();
  741. }
  742. return allPrograms.Where(i => string.Equals(i.SeriesId, seriesTimer.SeriesId, StringComparison.OrdinalIgnoreCase));
  743. }
  744. private string GetChannelEpgCachePath(string channelId)
  745. {
  746. return Path.Combine(_config.CommonApplicationPaths.CachePath, "embytvepg", channelId + ".json");
  747. }
  748. private readonly object _epgLock = new object();
  749. private void SaveEpgDataForChannel(string channelId, List<ProgramInfo> epgData)
  750. {
  751. var path = GetChannelEpgCachePath(channelId);
  752. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  753. lock (_epgLock)
  754. {
  755. _jsonSerializer.SerializeToFile(epgData, path);
  756. }
  757. }
  758. private List<ProgramInfo> GetEpgDataForChannel(string channelId)
  759. {
  760. try
  761. {
  762. lock (_epgLock)
  763. {
  764. return _jsonSerializer.DeserializeFromFile<List<ProgramInfo>>(GetChannelEpgCachePath(channelId));
  765. }
  766. }
  767. catch
  768. {
  769. return new List<ProgramInfo>();
  770. }
  771. }
  772. private List<ProgramInfo> GetEpgDataForChannels(List<string> channelIds)
  773. {
  774. return channelIds.SelectMany(GetEpgDataForChannel).ToList();
  775. }
  776. public void Dispose()
  777. {
  778. foreach (var pair in _activeRecordings.ToList())
  779. {
  780. pair.Value.Cancel();
  781. }
  782. }
  783. public Task<MBRegistrationRecord> GetRegistrationInfo(string feature)
  784. {
  785. if (string.Equals(feature, "seriesrecordings", StringComparison.OrdinalIgnoreCase))
  786. {
  787. return _security.GetRegistrationStatus("embytvseriesrecordings");
  788. }
  789. return Task.FromResult(new MBRegistrationRecord
  790. {
  791. IsValid = true,
  792. IsRegistered = true
  793. });
  794. }
  795. }
  796. }