EmbyTV.cs 33 KB

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