EmbyTV.cs 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Common.Security;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Drawing;
  7. using MediaBrowser.Controller.FileOrganization;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.LiveTv;
  10. using MediaBrowser.Controller.MediaEncoding;
  11. using MediaBrowser.Controller.Providers;
  12. using MediaBrowser.Model.Dto;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.Events;
  15. using MediaBrowser.Model.LiveTv;
  16. using MediaBrowser.Model.Logging;
  17. using MediaBrowser.Model.Serialization;
  18. using MediaBrowser.Server.Implementations.FileOrganization;
  19. using System;
  20. using System.Collections.Concurrent;
  21. using System.Collections.Generic;
  22. using System.Globalization;
  23. using System.IO;
  24. using System.Linq;
  25. using System.Text;
  26. using System.Threading;
  27. using System.Threading.Tasks;
  28. using System.Xml;
  29. using CommonIO;
  30. using MediaBrowser.Common.Extensions;
  31. using MediaBrowser.Controller.Entities;
  32. using MediaBrowser.Controller.Entities.TV;
  33. using MediaBrowser.Model.Configuration;
  34. using MediaBrowser.Model.FileOrganization;
  35. using Microsoft.Win32;
  36. namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV
  37. {
  38. public class EmbyTV : ILiveTvService, ISupportsNewTimerIds, IDisposable
  39. {
  40. private readonly IApplicationHost _appHpst;
  41. private readonly ILogger _logger;
  42. private readonly IHttpClient _httpClient;
  43. private readonly IServerConfigurationManager _config;
  44. private readonly IJsonSerializer _jsonSerializer;
  45. private readonly ItemDataProvider<SeriesTimerInfo> _seriesTimerProvider;
  46. private readonly TimerManager _timerProvider;
  47. private readonly LiveTvManager _liveTvManager;
  48. private readonly IFileSystem _fileSystem;
  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 event EventHandler DataSourceChanged { add { } remove { } }
  56. public event EventHandler<RecordingStatusChangedEventArgs> RecordingStatusChanged { add { } remove { } }
  57. private readonly ConcurrentDictionary<string, ActiveRecordingInfo> _activeRecordings =
  58. new ConcurrentDictionary<string, ActiveRecordingInfo>(StringComparer.OrdinalIgnoreCase);
  59. public EmbyTV(IApplicationHost appHost, ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IServerConfigurationManager config, ILiveTvManager liveTvManager, IFileSystem fileSystem, ILibraryManager libraryManager, ILibraryMonitor libraryMonitor, IProviderManager providerManager, IFileOrganizationService organizationService, IMediaEncoder mediaEncoder)
  60. {
  61. Current = this;
  62. _appHpst = appHost;
  63. _logger = logger;
  64. _httpClient = httpClient;
  65. _config = config;
  66. _fileSystem = fileSystem;
  67. _libraryManager = libraryManager;
  68. _libraryMonitor = libraryMonitor;
  69. _providerManager = providerManager;
  70. _organizationService = organizationService;
  71. _mediaEncoder = mediaEncoder;
  72. _liveTvManager = (LiveTvManager)liveTvManager;
  73. _jsonSerializer = jsonSerializer;
  74. _seriesTimerProvider = new SeriesTimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers"));
  75. _timerProvider = new TimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "timers"), _logger);
  76. _timerProvider.TimerFired += _timerProvider_TimerFired;
  77. _config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
  78. }
  79. private void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
  80. {
  81. if (string.Equals(e.Key, "livetv", StringComparison.OrdinalIgnoreCase))
  82. {
  83. OnRecordingFoldersChanged();
  84. }
  85. }
  86. public void Start()
  87. {
  88. _timerProvider.RestartTimers();
  89. SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;
  90. CreateRecordingFolders();
  91. }
  92. private void OnRecordingFoldersChanged()
  93. {
  94. CreateRecordingFolders();
  95. }
  96. internal void CreateRecordingFolders()
  97. {
  98. try
  99. {
  100. CreateRecordingFoldersInternal();
  101. }
  102. catch (Exception ex)
  103. {
  104. _logger.ErrorException("Error creating recording folders", ex);
  105. }
  106. }
  107. internal void CreateRecordingFoldersInternal()
  108. {
  109. var recordingFolders = GetRecordingFolders();
  110. var virtualFolders = _libraryManager.GetVirtualFolders()
  111. .ToList();
  112. var allExistingPaths = virtualFolders.SelectMany(i => i.Locations).ToList();
  113. var pathsAdded = new List<string>();
  114. foreach (var recordingFolder in recordingFolders)
  115. {
  116. var pathsToCreate = recordingFolder.Locations
  117. .Where(i => !allExistingPaths.Contains(i, StringComparer.OrdinalIgnoreCase))
  118. .ToList();
  119. if (pathsToCreate.Count == 0)
  120. {
  121. continue;
  122. }
  123. var mediaPathInfos = pathsToCreate.Select(i => new MediaPathInfo { Path = i }).ToArray();
  124. var libraryOptions = new LibraryOptions
  125. {
  126. PathInfos = mediaPathInfos
  127. };
  128. try
  129. {
  130. _libraryManager.AddVirtualFolder(recordingFolder.Name, recordingFolder.CollectionType, libraryOptions, true);
  131. }
  132. catch (Exception ex)
  133. {
  134. _logger.ErrorException("Error creating virtual folder", ex);
  135. }
  136. pathsAdded.AddRange(pathsToCreate);
  137. }
  138. var config = GetConfiguration();
  139. var pathsToRemove = config.MediaLocationsCreated
  140. .Except(recordingFolders.SelectMany(i => i.Locations))
  141. .ToList();
  142. if (pathsAdded.Count > 0 || pathsToRemove.Count > 0)
  143. {
  144. pathsAdded.InsertRange(0, config.MediaLocationsCreated);
  145. config.MediaLocationsCreated = pathsAdded.Except(pathsToRemove).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
  146. _config.SaveConfiguration("livetv", config);
  147. }
  148. foreach (var path in pathsToRemove)
  149. {
  150. RemovePathFromLibrary(path);
  151. }
  152. }
  153. private void RemovePathFromLibrary(string path)
  154. {
  155. _logger.Debug("Removing path from library: {0}", path);
  156. var requiresRefresh = false;
  157. var virtualFolders = _libraryManager.GetVirtualFolders()
  158. .ToList();
  159. foreach (var virtualFolder in virtualFolders)
  160. {
  161. if (!virtualFolder.Locations.Contains(path, StringComparer.OrdinalIgnoreCase))
  162. {
  163. continue;
  164. }
  165. if (virtualFolder.Locations.Count == 1)
  166. {
  167. // remove entire virtual folder
  168. try
  169. {
  170. _libraryManager.RemoveVirtualFolder(virtualFolder.Name, true);
  171. }
  172. catch (Exception ex)
  173. {
  174. _logger.ErrorException("Error removing virtual folder", ex);
  175. }
  176. }
  177. else
  178. {
  179. try
  180. {
  181. _libraryManager.RemoveMediaPath(virtualFolder.Name, path);
  182. requiresRefresh = true;
  183. }
  184. catch (Exception ex)
  185. {
  186. _logger.ErrorException("Error removing media path", ex);
  187. }
  188. }
  189. }
  190. if (requiresRefresh)
  191. {
  192. _libraryManager.ValidateMediaLibrary(new Progress<Double>(), CancellationToken.None);
  193. }
  194. }
  195. void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
  196. {
  197. _logger.Info("Power mode changed to {0}", e.Mode);
  198. if (e.Mode == PowerModes.Resume)
  199. {
  200. _timerProvider.RestartTimers();
  201. }
  202. }
  203. public string Name
  204. {
  205. get { return "Emby"; }
  206. }
  207. public string DataPath
  208. {
  209. get { return Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv"); }
  210. }
  211. private string DefaultRecordingPath
  212. {
  213. get
  214. {
  215. return Path.Combine(DataPath, "recordings");
  216. }
  217. }
  218. private string RecordingPath
  219. {
  220. get
  221. {
  222. var path = GetConfiguration().RecordingPath;
  223. return string.IsNullOrWhiteSpace(path)
  224. ? DefaultRecordingPath
  225. : path;
  226. }
  227. }
  228. public string HomePageUrl
  229. {
  230. get { return "http://emby.media"; }
  231. }
  232. public async Task<LiveTvServiceStatusInfo> GetStatusInfoAsync(CancellationToken cancellationToken)
  233. {
  234. var status = new LiveTvServiceStatusInfo();
  235. var list = new List<LiveTvTunerInfo>();
  236. foreach (var hostInstance in _liveTvManager.TunerHosts)
  237. {
  238. try
  239. {
  240. var tuners = await hostInstance.GetTunerInfos(cancellationToken).ConfigureAwait(false);
  241. list.AddRange(tuners);
  242. }
  243. catch (Exception ex)
  244. {
  245. _logger.ErrorException("Error getting tuners", ex);
  246. }
  247. }
  248. status.Tuners = list;
  249. status.Status = LiveTvServiceStatus.Ok;
  250. status.Version = _appHpst.ApplicationVersion.ToString();
  251. status.IsVisible = false;
  252. return status;
  253. }
  254. public async Task RefreshSeriesTimers(CancellationToken cancellationToken, IProgress<double> progress)
  255. {
  256. var seriesTimers = await GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  257. List<ChannelInfo> channels = null;
  258. foreach (var timer in seriesTimers)
  259. {
  260. List<ProgramInfo> epgData;
  261. if (timer.RecordAnyChannel)
  262. {
  263. if (channels == null)
  264. {
  265. channels = (await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false)).ToList();
  266. }
  267. var channelIds = channels.Select(i => i.Id).ToList();
  268. epgData = GetEpgDataForChannels(channelIds);
  269. }
  270. else
  271. {
  272. epgData = GetEpgDataForChannel(timer.ChannelId);
  273. }
  274. await UpdateTimersForSeriesTimer(epgData, timer, true).ConfigureAwait(false);
  275. }
  276. var timers = await GetTimersAsync(cancellationToken).ConfigureAwait(false);
  277. foreach (var timer in timers.ToList())
  278. {
  279. if (DateTime.UtcNow > timer.EndDate && !_activeRecordings.ContainsKey(timer.Id))
  280. {
  281. OnTimerOutOfDate(timer);
  282. }
  283. }
  284. }
  285. private void OnTimerOutOfDate(TimerInfo timer)
  286. {
  287. _timerProvider.Delete(timer);
  288. }
  289. private List<ChannelInfo> _channelCache = null;
  290. private async Task<IEnumerable<ChannelInfo>> GetChannelsAsync(bool enableCache, CancellationToken cancellationToken)
  291. {
  292. if (enableCache && _channelCache != null)
  293. {
  294. return _channelCache.ToList();
  295. }
  296. var list = new List<ChannelInfo>();
  297. foreach (var hostInstance in _liveTvManager.TunerHosts)
  298. {
  299. try
  300. {
  301. var channels = await hostInstance.GetChannels(cancellationToken).ConfigureAwait(false);
  302. list.AddRange(channels);
  303. }
  304. catch (Exception ex)
  305. {
  306. _logger.ErrorException("Error getting channels", ex);
  307. }
  308. }
  309. foreach (var provider in GetListingProviders())
  310. {
  311. var enabledChannels = list
  312. .Where(i => IsListingProviderEnabledForTuner(provider.Item2, i.TunerHostId))
  313. .ToList();
  314. if (enabledChannels.Count > 0)
  315. {
  316. try
  317. {
  318. await provider.Item1.AddMetadata(provider.Item2, enabledChannels, cancellationToken).ConfigureAwait(false);
  319. }
  320. catch (NotSupportedException)
  321. {
  322. }
  323. catch (Exception ex)
  324. {
  325. _logger.ErrorException("Error adding metadata", ex);
  326. }
  327. }
  328. }
  329. _channelCache = list.ToList();
  330. return list;
  331. }
  332. public async Task<List<ChannelInfo>> GetChannelsForListingsProvider(ListingsProviderInfo listingsProvider, CancellationToken cancellationToken)
  333. {
  334. var list = new List<ChannelInfo>();
  335. foreach (var hostInstance in _liveTvManager.TunerHosts)
  336. {
  337. try
  338. {
  339. var channels = await hostInstance.GetChannels(cancellationToken).ConfigureAwait(false);
  340. list.AddRange(channels);
  341. }
  342. catch (Exception ex)
  343. {
  344. _logger.ErrorException("Error getting channels", ex);
  345. }
  346. }
  347. return list
  348. .Where(i => IsListingProviderEnabledForTuner(listingsProvider, i.TunerHostId))
  349. .ToList();
  350. }
  351. public Task<IEnumerable<ChannelInfo>> GetChannelsAsync(CancellationToken cancellationToken)
  352. {
  353. return GetChannelsAsync(false, cancellationToken);
  354. }
  355. public Task CancelSeriesTimerAsync(string timerId, CancellationToken cancellationToken)
  356. {
  357. var timers = _timerProvider
  358. .GetAll()
  359. .Where(i => string.Equals(i.SeriesTimerId, timerId, StringComparison.OrdinalIgnoreCase))
  360. .ToList();
  361. foreach (var timer in timers)
  362. {
  363. CancelTimerInternal(timer.Id, true);
  364. }
  365. var remove = _seriesTimerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
  366. if (remove != null)
  367. {
  368. _seriesTimerProvider.Delete(remove);
  369. }
  370. return Task.FromResult(true);
  371. }
  372. private void CancelTimerInternal(string timerId, bool isSeriesCancelled)
  373. {
  374. var timer = _timerProvider.GetTimer(timerId);
  375. if (timer != null)
  376. {
  377. if (string.IsNullOrWhiteSpace(timer.SeriesTimerId) || isSeriesCancelled)
  378. {
  379. _timerProvider.Delete(timer);
  380. }
  381. else
  382. {
  383. timer.Status = RecordingStatus.Cancelled;
  384. _timerProvider.AddOrUpdate(timer, false);
  385. }
  386. }
  387. ActiveRecordingInfo activeRecordingInfo;
  388. if (_activeRecordings.TryGetValue(timerId, out activeRecordingInfo))
  389. {
  390. activeRecordingInfo.CancellationTokenSource.Cancel();
  391. }
  392. }
  393. public Task CancelTimerAsync(string timerId, CancellationToken cancellationToken)
  394. {
  395. CancelTimerInternal(timerId, false);
  396. return Task.FromResult(true);
  397. }
  398. public Task DeleteRecordingAsync(string recordingId, CancellationToken cancellationToken)
  399. {
  400. return Task.FromResult(true);
  401. }
  402. public Task CreateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  403. {
  404. throw new NotImplementedException();
  405. }
  406. public Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
  407. {
  408. throw new NotImplementedException();
  409. }
  410. public Task<string> CreateTimer(TimerInfo timer, CancellationToken cancellationToken)
  411. {
  412. var existingTimer = _timerProvider.GetAll()
  413. .FirstOrDefault(i => string.Equals(timer.ProgramId, i.ProgramId, StringComparison.OrdinalIgnoreCase));
  414. if (existingTimer != null)
  415. {
  416. if (existingTimer.Status == RecordingStatus.Cancelled)
  417. {
  418. existingTimer.Status = RecordingStatus.New;
  419. _timerProvider.Update(existingTimer);
  420. return Task.FromResult(existingTimer.Id);
  421. }
  422. else
  423. {
  424. throw new ArgumentException("A scheduled recording already exists for this program.");
  425. }
  426. }
  427. timer.Id = Guid.NewGuid().ToString("N");
  428. ProgramInfo programInfo = null;
  429. if (!string.IsNullOrWhiteSpace(timer.ProgramId))
  430. {
  431. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  432. }
  433. if (programInfo == null)
  434. {
  435. _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  436. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  437. }
  438. if (programInfo != null)
  439. {
  440. RecordingHelper.CopyProgramInfoToTimerInfo(programInfo, timer);
  441. }
  442. _timerProvider.Add(timer);
  443. return Task.FromResult(timer.Id);
  444. }
  445. public async Task<string> CreateSeriesTimer(SeriesTimerInfo info, CancellationToken cancellationToken)
  446. {
  447. info.Id = Guid.NewGuid().ToString("N");
  448. List<ProgramInfo> epgData;
  449. if (info.RecordAnyChannel)
  450. {
  451. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  452. var channelIds = channels.Select(i => i.Id).ToList();
  453. epgData = GetEpgDataForChannels(channelIds);
  454. }
  455. else
  456. {
  457. epgData = GetEpgDataForChannel(info.ChannelId);
  458. }
  459. // populate info.seriesID
  460. var program = epgData.FirstOrDefault(i => string.Equals(i.Id, info.ProgramId, StringComparison.OrdinalIgnoreCase));
  461. if (program != null)
  462. {
  463. info.SeriesId = program.SeriesId;
  464. }
  465. else
  466. {
  467. throw new InvalidOperationException("SeriesId for program not found");
  468. }
  469. _seriesTimerProvider.Add(info);
  470. await UpdateTimersForSeriesTimer(epgData, info, false).ConfigureAwait(false);
  471. return info.Id;
  472. }
  473. public async Task UpdateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  474. {
  475. var instance = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  476. if (instance != null)
  477. {
  478. instance.ChannelId = info.ChannelId;
  479. instance.Days = info.Days;
  480. instance.EndDate = info.EndDate;
  481. instance.IsPostPaddingRequired = info.IsPostPaddingRequired;
  482. instance.IsPrePaddingRequired = info.IsPrePaddingRequired;
  483. instance.PostPaddingSeconds = info.PostPaddingSeconds;
  484. instance.PrePaddingSeconds = info.PrePaddingSeconds;
  485. instance.Priority = info.Priority;
  486. instance.RecordAnyChannel = info.RecordAnyChannel;
  487. instance.RecordAnyTime = info.RecordAnyTime;
  488. instance.RecordNewOnly = info.RecordNewOnly;
  489. instance.SkipEpisodesInLibrary = info.SkipEpisodesInLibrary;
  490. instance.KeepUpTo = info.KeepUpTo;
  491. instance.KeepUntil = info.KeepUntil;
  492. instance.StartDate = info.StartDate;
  493. _seriesTimerProvider.Update(instance);
  494. List<ProgramInfo> epgData;
  495. if (instance.RecordAnyChannel)
  496. {
  497. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  498. var channelIds = channels.Select(i => i.Id).ToList();
  499. epgData = GetEpgDataForChannels(channelIds);
  500. }
  501. else
  502. {
  503. epgData = GetEpgDataForChannel(instance.ChannelId);
  504. }
  505. await UpdateTimersForSeriesTimer(epgData, instance, true).ConfigureAwait(false);
  506. }
  507. }
  508. public Task UpdateTimerAsync(TimerInfo updatedTimer, CancellationToken cancellationToken)
  509. {
  510. var existingTimer = _timerProvider.GetTimer(updatedTimer.Id);
  511. if (existingTimer == null)
  512. {
  513. throw new ResourceNotFoundException();
  514. }
  515. // Only update if not currently active
  516. ActiveRecordingInfo activeRecordingInfo;
  517. if (!_activeRecordings.TryGetValue(updatedTimer.Id, out activeRecordingInfo))
  518. {
  519. UpdateExistingTimerWithNewData(existingTimer, updatedTimer);
  520. _timerProvider.Update(existingTimer);
  521. }
  522. return Task.FromResult(true);
  523. }
  524. private void UpdateExistingTimerWithNewData(TimerInfo existingTimer, TimerInfo updatedTimer)
  525. {
  526. // Update the program info but retain the status
  527. existingTimer.ChannelId = updatedTimer.ChannelId;
  528. existingTimer.CommunityRating = updatedTimer.CommunityRating;
  529. existingTimer.EndDate = updatedTimer.EndDate;
  530. existingTimer.EpisodeNumber = updatedTimer.EpisodeNumber;
  531. existingTimer.EpisodeTitle = updatedTimer.EpisodeTitle;
  532. existingTimer.Genres = updatedTimer.Genres;
  533. existingTimer.HomePageUrl = updatedTimer.HomePageUrl;
  534. existingTimer.IsKids = updatedTimer.IsKids;
  535. existingTimer.IsMovie = updatedTimer.IsMovie;
  536. existingTimer.IsProgramSeries = updatedTimer.IsProgramSeries;
  537. existingTimer.IsSports = updatedTimer.IsSports;
  538. existingTimer.Name = updatedTimer.Name;
  539. existingTimer.OfficialRating = updatedTimer.OfficialRating;
  540. existingTimer.OriginalAirDate = updatedTimer.OriginalAirDate;
  541. existingTimer.Overview = updatedTimer.Overview;
  542. existingTimer.ProductionYear = updatedTimer.ProductionYear;
  543. existingTimer.ProgramId = updatedTimer.ProgramId;
  544. existingTimer.SeasonNumber = updatedTimer.SeasonNumber;
  545. existingTimer.ShortOverview = updatedTimer.ShortOverview;
  546. existingTimer.StartDate = updatedTimer.StartDate;
  547. }
  548. public Task<ImageStream> GetChannelImageAsync(string channelId, CancellationToken cancellationToken)
  549. {
  550. throw new NotImplementedException();
  551. }
  552. public Task<ImageStream> GetRecordingImageAsync(string recordingId, CancellationToken cancellationToken)
  553. {
  554. throw new NotImplementedException();
  555. }
  556. public Task<ImageStream> GetProgramImageAsync(string programId, string channelId, CancellationToken cancellationToken)
  557. {
  558. throw new NotImplementedException();
  559. }
  560. public async Task<IEnumerable<RecordingInfo>> GetRecordingsAsync(CancellationToken cancellationToken)
  561. {
  562. return new List<RecordingInfo>();
  563. }
  564. public Task<IEnumerable<TimerInfo>> GetTimersAsync(CancellationToken cancellationToken)
  565. {
  566. var excludeStatues = new List<RecordingStatus>
  567. {
  568. RecordingStatus.Completed,
  569. RecordingStatus.Cancelled
  570. };
  571. var timers = _timerProvider.GetAll()
  572. .Where(i => !excludeStatues.Contains(i.Status));
  573. return Task.FromResult(timers);
  574. }
  575. public Task<SeriesTimerInfo> GetNewTimerDefaultsAsync(CancellationToken cancellationToken, ProgramInfo program = null)
  576. {
  577. var config = GetConfiguration();
  578. var defaults = new SeriesTimerInfo()
  579. {
  580. PostPaddingSeconds = Math.Max(config.PostPaddingSeconds, 0),
  581. PrePaddingSeconds = Math.Max(config.PrePaddingSeconds, 0),
  582. RecordAnyChannel = true,
  583. RecordAnyTime = true,
  584. RecordNewOnly = true,
  585. Days = new List<DayOfWeek>
  586. {
  587. DayOfWeek.Sunday,
  588. DayOfWeek.Monday,
  589. DayOfWeek.Tuesday,
  590. DayOfWeek.Wednesday,
  591. DayOfWeek.Thursday,
  592. DayOfWeek.Friday,
  593. DayOfWeek.Saturday
  594. }
  595. };
  596. if (program != null)
  597. {
  598. defaults.SeriesId = program.SeriesId;
  599. defaults.ProgramId = program.Id;
  600. }
  601. defaults.SkipEpisodesInLibrary = true;
  602. defaults.KeepUntil = KeepUntil.UntilDeleted;
  603. return Task.FromResult(defaults);
  604. }
  605. public Task<IEnumerable<SeriesTimerInfo>> GetSeriesTimersAsync(CancellationToken cancellationToken)
  606. {
  607. return Task.FromResult((IEnumerable<SeriesTimerInfo>)_seriesTimerProvider.GetAll());
  608. }
  609. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  610. {
  611. try
  612. {
  613. return await GetProgramsAsyncInternal(channelId, startDateUtc, endDateUtc, cancellationToken).ConfigureAwait(false);
  614. }
  615. catch (OperationCanceledException)
  616. {
  617. throw;
  618. }
  619. catch (Exception ex)
  620. {
  621. _logger.ErrorException("Error getting programs", ex);
  622. return GetEpgDataForChannel(channelId).Where(i => i.StartDate <= endDateUtc && i.EndDate >= startDateUtc);
  623. }
  624. }
  625. private bool IsListingProviderEnabledForTuner(ListingsProviderInfo info, string tunerHostId)
  626. {
  627. if (info.EnableAllTuners)
  628. {
  629. return true;
  630. }
  631. if (string.IsNullOrWhiteSpace(tunerHostId))
  632. {
  633. throw new ArgumentNullException("tunerHostId");
  634. }
  635. return info.EnabledTuners.Contains(tunerHostId, StringComparer.OrdinalIgnoreCase);
  636. }
  637. private async Task<IEnumerable<ProgramInfo>> GetProgramsAsyncInternal(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  638. {
  639. var channels = await GetChannelsAsync(true, cancellationToken).ConfigureAwait(false);
  640. var channel = channels.First(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  641. foreach (var provider in GetListingProviders())
  642. {
  643. if (!IsListingProviderEnabledForTuner(provider.Item2, channel.TunerHostId))
  644. {
  645. _logger.Debug("Skipping getting programs for channel {0}-{1} from {2}-{3}, because it's not enabled for this tuner.", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
  646. continue;
  647. }
  648. _logger.Debug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
  649. var channelMappings = GetChannelMappings(provider.Item2);
  650. var channelNumber = channel.Number;
  651. string mappedChannelNumber;
  652. if (channelMappings.TryGetValue(channelNumber, out mappedChannelNumber))
  653. {
  654. _logger.Debug("Found mapped channel on provider {0}. Tuner channel number: {1}, Mapped channel number: {2}", provider.Item1.Name, channelNumber, mappedChannelNumber);
  655. channelNumber = mappedChannelNumber;
  656. }
  657. var programs = await provider.Item1.GetProgramsAsync(provider.Item2, channelNumber, channel.Name, startDateUtc, endDateUtc, cancellationToken)
  658. .ConfigureAwait(false);
  659. var list = programs.ToList();
  660. // Replace the value that came from the provider with a normalized value
  661. foreach (var program in list)
  662. {
  663. program.ChannelId = channelId;
  664. }
  665. if (list.Count > 0)
  666. {
  667. SaveEpgDataForChannel(channelId, list);
  668. return list;
  669. }
  670. }
  671. return new List<ProgramInfo>();
  672. }
  673. private Dictionary<string, string> GetChannelMappings(ListingsProviderInfo info)
  674. {
  675. var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  676. foreach (var mapping in info.ChannelMappings)
  677. {
  678. dict[mapping.Name] = mapping.Value;
  679. }
  680. return dict;
  681. }
  682. private List<Tuple<IListingsProvider, ListingsProviderInfo>> GetListingProviders()
  683. {
  684. return GetConfiguration().ListingProviders
  685. .Select(i =>
  686. {
  687. var provider = _liveTvManager.ListingProviders.FirstOrDefault(l => string.Equals(l.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  688. return provider == null ? null : new Tuple<IListingsProvider, ListingsProviderInfo>(provider, i);
  689. })
  690. .Where(i => i != null)
  691. .ToList();
  692. }
  693. public Task<MediaSourceInfo> GetRecordingStream(string recordingId, string streamId, CancellationToken cancellationToken)
  694. {
  695. throw new NotImplementedException();
  696. }
  697. private readonly SemaphoreSlim _liveStreamsSemaphore = new SemaphoreSlim(1, 1);
  698. private readonly Dictionary<string, LiveStream> _liveStreams = new Dictionary<string, LiveStream>();
  699. public async Task<MediaSourceInfo> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
  700. {
  701. var result = await GetChannelStreamInternal(channelId, streamId, cancellationToken).ConfigureAwait(false);
  702. return result.Item1.PublicMediaSource;
  703. }
  704. private async Task<Tuple<LiveStream, ITunerHost>> GetChannelStreamInternal(string channelId, string streamId, CancellationToken cancellationToken)
  705. {
  706. _logger.Info("Streaming Channel " + channelId);
  707. foreach (var hostInstance in _liveTvManager.TunerHosts)
  708. {
  709. try
  710. {
  711. var result = await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
  712. await _liveStreamsSemaphore.WaitAsync().ConfigureAwait(false);
  713. _liveStreams[result.Id] = result;
  714. _liveStreamsSemaphore.Release();
  715. return new Tuple<LiveStream, ITunerHost>(result, hostInstance);
  716. }
  717. catch (FileNotFoundException)
  718. {
  719. }
  720. catch (Exception e)
  721. {
  722. _logger.ErrorException("Error getting channel stream", e);
  723. }
  724. }
  725. throw new ApplicationException("Tuner not found.");
  726. }
  727. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  728. {
  729. foreach (var hostInstance in _liveTvManager.TunerHosts)
  730. {
  731. try
  732. {
  733. var sources = await hostInstance.GetChannelStreamMediaSources(channelId, cancellationToken).ConfigureAwait(false);
  734. if (sources.Count > 0)
  735. {
  736. return sources;
  737. }
  738. }
  739. catch (NotImplementedException)
  740. {
  741. }
  742. }
  743. throw new NotImplementedException();
  744. }
  745. public Task<List<MediaSourceInfo>> GetRecordingStreamMediaSources(string recordingId, CancellationToken cancellationToken)
  746. {
  747. throw new NotImplementedException();
  748. }
  749. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  750. {
  751. await _liveStreamsSemaphore.WaitAsync().ConfigureAwait(false);
  752. try
  753. {
  754. LiveStream stream;
  755. if (_liveStreams.TryGetValue(id, out stream))
  756. {
  757. _liveStreams.Remove(id);
  758. try
  759. {
  760. await stream.Close().ConfigureAwait(false);
  761. }
  762. catch (Exception ex)
  763. {
  764. _logger.ErrorException("Error closing live stream", ex);
  765. }
  766. }
  767. }
  768. finally
  769. {
  770. _liveStreamsSemaphore.Release();
  771. }
  772. }
  773. public Task RecordLiveStream(string id, CancellationToken cancellationToken)
  774. {
  775. return Task.FromResult(0);
  776. }
  777. public Task ResetTuner(string id, CancellationToken cancellationToken)
  778. {
  779. return Task.FromResult(0);
  780. }
  781. async void _timerProvider_TimerFired(object sender, GenericEventArgs<TimerInfo> e)
  782. {
  783. var timer = e.Argument;
  784. _logger.Info("Recording timer fired.");
  785. try
  786. {
  787. var recordingEndDate = timer.EndDate.AddSeconds(timer.PostPaddingSeconds);
  788. if (recordingEndDate <= DateTime.UtcNow)
  789. {
  790. _logger.Warn("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
  791. OnTimerOutOfDate(timer);
  792. return;
  793. }
  794. var activeRecordingInfo = new ActiveRecordingInfo
  795. {
  796. CancellationTokenSource = new CancellationTokenSource(),
  797. TimerId = timer.Id
  798. };
  799. if (_activeRecordings.TryAdd(timer.Id, activeRecordingInfo))
  800. {
  801. await RecordStream(timer, recordingEndDate, activeRecordingInfo, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false);
  802. }
  803. else
  804. {
  805. _logger.Info("Skipping RecordStream because it's already in progress.");
  806. }
  807. }
  808. catch (OperationCanceledException)
  809. {
  810. }
  811. catch (Exception ex)
  812. {
  813. _logger.ErrorException("Error recording stream", ex);
  814. }
  815. }
  816. private string GetRecordingPath(TimerInfo timer, out string seriesPath)
  817. {
  818. var recordPath = RecordingPath;
  819. var config = GetConfiguration();
  820. seriesPath = null;
  821. if (timer.IsProgramSeries)
  822. {
  823. var customRecordingPath = config.SeriesRecordingPath;
  824. var allowSubfolder = true;
  825. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  826. {
  827. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  828. recordPath = customRecordingPath;
  829. }
  830. if (allowSubfolder && config.EnableRecordingSubfolders)
  831. {
  832. recordPath = Path.Combine(recordPath, "Series");
  833. }
  834. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  835. // Can't use the year here in the folder name because it is the year of the episode, not the series.
  836. recordPath = Path.Combine(recordPath, folderName);
  837. seriesPath = recordPath;
  838. if (timer.SeasonNumber.HasValue)
  839. {
  840. folderName = string.Format("Season {0}", timer.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture));
  841. recordPath = Path.Combine(recordPath, folderName);
  842. }
  843. }
  844. else if (timer.IsMovie)
  845. {
  846. var customRecordingPath = config.MovieRecordingPath;
  847. var allowSubfolder = true;
  848. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  849. {
  850. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  851. recordPath = customRecordingPath;
  852. }
  853. if (allowSubfolder && config.EnableRecordingSubfolders)
  854. {
  855. recordPath = Path.Combine(recordPath, "Movies");
  856. }
  857. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  858. if (timer.ProductionYear.HasValue)
  859. {
  860. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  861. }
  862. recordPath = Path.Combine(recordPath, folderName);
  863. }
  864. else if (timer.IsKids)
  865. {
  866. if (config.EnableRecordingSubfolders)
  867. {
  868. recordPath = Path.Combine(recordPath, "Kids");
  869. }
  870. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  871. if (timer.ProductionYear.HasValue)
  872. {
  873. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  874. }
  875. recordPath = Path.Combine(recordPath, folderName);
  876. }
  877. else if (timer.IsSports)
  878. {
  879. if (config.EnableRecordingSubfolders)
  880. {
  881. recordPath = Path.Combine(recordPath, "Sports");
  882. }
  883. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  884. }
  885. else
  886. {
  887. if (config.EnableRecordingSubfolders)
  888. {
  889. recordPath = Path.Combine(recordPath, "Other");
  890. }
  891. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  892. }
  893. var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer)).Trim() + ".ts";
  894. return Path.Combine(recordPath, recordingFileName);
  895. }
  896. private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate,
  897. ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken)
  898. {
  899. if (timer == null)
  900. {
  901. throw new ArgumentNullException("timer");
  902. }
  903. ProgramInfo programInfo = null;
  904. if (!string.IsNullOrWhiteSpace(timer.ProgramId))
  905. {
  906. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  907. }
  908. if (programInfo == null)
  909. {
  910. _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  911. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  912. }
  913. if (programInfo != null)
  914. {
  915. RecordingHelper.CopyProgramInfoToTimerInfo(programInfo, timer);
  916. }
  917. string seriesPath = null;
  918. var recordPath = GetRecordingPath(timer, out seriesPath);
  919. var recordingStatus = RecordingStatus.New;
  920. LiveStream liveStream = null;
  921. try
  922. {
  923. var allMediaSources =
  924. await GetChannelStreamMediaSources(timer.ChannelId, CancellationToken.None).ConfigureAwait(false);
  925. var liveStreamInfo =
  926. await
  927. GetChannelStreamInternal(timer.ChannelId, allMediaSources[0].Id, CancellationToken.None)
  928. .ConfigureAwait(false);
  929. liveStream = liveStreamInfo.Item1;
  930. var mediaStreamInfo = liveStreamInfo.Item1.PublicMediaSource;
  931. var tunerHost = liveStreamInfo.Item2;
  932. // HDHR doesn't seem to release the tuner right away after first probing with ffmpeg
  933. //await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  934. var recorder = await GetRecorder().ConfigureAwait(false);
  935. recordPath = recorder.GetOutputPath(mediaStreamInfo, recordPath);
  936. recordPath = EnsureFileUnique(recordPath, timer.Id);
  937. _libraryManager.RegisterIgnoredPath(recordPath);
  938. _libraryMonitor.ReportFileSystemChangeBeginning(recordPath);
  939. _fileSystem.CreateDirectory(Path.GetDirectoryName(recordPath));
  940. activeRecordingInfo.Path = recordPath;
  941. var duration = recordingEndDate - DateTime.UtcNow;
  942. _logger.Info("Beginning recording. Will record for {0} minutes.",
  943. duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
  944. _logger.Info("Writing file to path: " + recordPath);
  945. _logger.Info("Opening recording stream from tuner provider");
  946. Action onStarted = () =>
  947. {
  948. timer.Status = RecordingStatus.InProgress;
  949. _timerProvider.AddOrUpdate(timer, false);
  950. SaveNfo(timer, recordPath, seriesPath);
  951. EnforceKeepUpTo(timer);
  952. };
  953. var pathWithDuration = tunerHost.ApplyDuration(mediaStreamInfo.Path, duration);
  954. // If it supports supplying duration via url
  955. if (!string.Equals(pathWithDuration, mediaStreamInfo.Path, StringComparison.OrdinalIgnoreCase))
  956. {
  957. mediaStreamInfo.Path = pathWithDuration;
  958. mediaStreamInfo.RunTimeTicks = duration.Ticks;
  959. }
  960. await recorder.Record(mediaStreamInfo, recordPath, duration, onStarted, cancellationToken)
  961. .ConfigureAwait(false);
  962. recordingStatus = RecordingStatus.Completed;
  963. _logger.Info("Recording completed: {0}", recordPath);
  964. }
  965. catch (OperationCanceledException)
  966. {
  967. _logger.Info("Recording stopped: {0}", recordPath);
  968. recordingStatus = RecordingStatus.Completed;
  969. }
  970. catch (Exception ex)
  971. {
  972. _logger.ErrorException("Error recording to {0}", ex, recordPath);
  973. recordingStatus = RecordingStatus.Error;
  974. }
  975. if (liveStream != null)
  976. {
  977. try
  978. {
  979. await CloseLiveStream(liveStream.Id, CancellationToken.None).ConfigureAwait(false);
  980. }
  981. catch (Exception ex)
  982. {
  983. _logger.ErrorException("Error closing live stream", ex);
  984. }
  985. }
  986. _libraryManager.UnRegisterIgnoredPath(recordPath);
  987. _libraryMonitor.ReportFileSystemChangeComplete(recordPath, true);
  988. ActiveRecordingInfo removed;
  989. _activeRecordings.TryRemove(timer.Id, out removed);
  990. if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate)
  991. {
  992. const int retryIntervalSeconds = 60;
  993. _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds);
  994. timer.Status = RecordingStatus.New;
  995. timer.StartDate = DateTime.UtcNow.AddSeconds(retryIntervalSeconds);
  996. _timerProvider.AddOrUpdate(timer);
  997. }
  998. else if (File.Exists(recordPath))
  999. {
  1000. timer.RecordingPath = recordPath;
  1001. timer.Status = RecordingStatus.Completed;
  1002. _timerProvider.AddOrUpdate(timer, false);
  1003. OnSuccessfulRecording(timer, recordPath);
  1004. }
  1005. else
  1006. {
  1007. _timerProvider.Delete(timer);
  1008. }
  1009. }
  1010. private async void EnforceKeepUpTo(TimerInfo timer)
  1011. {
  1012. if (string.IsNullOrWhiteSpace(timer.SeriesTimerId))
  1013. {
  1014. return;
  1015. }
  1016. var seriesTimerId = timer.SeriesTimerId;
  1017. var seriesTimer = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, seriesTimerId, StringComparison.OrdinalIgnoreCase));
  1018. if (seriesTimer == null || seriesTimer.KeepUpTo <= 1)
  1019. {
  1020. return;
  1021. }
  1022. if (_disposed)
  1023. {
  1024. return;
  1025. }
  1026. await _recordingDeleteSemaphore.WaitAsync().ConfigureAwait(false);
  1027. try
  1028. {
  1029. if (_disposed)
  1030. {
  1031. return;
  1032. }
  1033. var timersToDelete = _timerProvider.GetAll()
  1034. .Where(i => i.Status == RecordingStatus.Completed && !string.IsNullOrWhiteSpace(i.RecordingPath))
  1035. .Where(i => string.Equals(i.SeriesTimerId, seriesTimerId, StringComparison.OrdinalIgnoreCase))
  1036. .OrderByDescending(i => i.EndDate)
  1037. .Where(i => File.Exists(i.RecordingPath))
  1038. .Skip(seriesTimer.KeepUpTo - 1)
  1039. .ToList();
  1040. await DeleteLibraryItemsForTimers(timersToDelete).ConfigureAwait(false);
  1041. }
  1042. finally
  1043. {
  1044. _recordingDeleteSemaphore.Release();
  1045. }
  1046. }
  1047. private readonly SemaphoreSlim _recordingDeleteSemaphore = new SemaphoreSlim(1,1);
  1048. private async Task DeleteLibraryItemsForTimers(List<TimerInfo> timers)
  1049. {
  1050. foreach (var timer in timers)
  1051. {
  1052. if (_disposed)
  1053. {
  1054. return;
  1055. }
  1056. try
  1057. {
  1058. await DeleteLibraryItemForTimer(timer).ConfigureAwait(false);
  1059. }
  1060. catch (Exception ex)
  1061. {
  1062. _logger.ErrorException("Error deleting recording", ex);
  1063. }
  1064. }
  1065. }
  1066. private async Task DeleteLibraryItemForTimer(TimerInfo timer)
  1067. {
  1068. var libraryItem = _libraryManager.FindByPath(timer.RecordingPath, false);
  1069. if (libraryItem != null)
  1070. {
  1071. await _libraryManager.DeleteItem(libraryItem, new DeleteOptions
  1072. {
  1073. DeleteFileLocation = true
  1074. });
  1075. }
  1076. else
  1077. {
  1078. try
  1079. {
  1080. File.Delete(timer.RecordingPath);
  1081. }
  1082. catch (DirectoryNotFoundException)
  1083. {
  1084. }
  1085. catch (FileNotFoundException)
  1086. {
  1087. }
  1088. }
  1089. _timerProvider.Delete(timer);
  1090. }
  1091. private string EnsureFileUnique(string path, string timerId)
  1092. {
  1093. var originalPath = path;
  1094. var index = 1;
  1095. while (FileExists(path, timerId))
  1096. {
  1097. var parent = Path.GetDirectoryName(originalPath);
  1098. var name = Path.GetFileNameWithoutExtension(originalPath);
  1099. name += "-" + index.ToString(CultureInfo.InvariantCulture);
  1100. path = Path.ChangeExtension(Path.Combine(parent, name), Path.GetExtension(originalPath));
  1101. index++;
  1102. }
  1103. return path;
  1104. }
  1105. private bool FileExists(string path, string timerId)
  1106. {
  1107. if (_fileSystem.FileExists(path))
  1108. {
  1109. return true;
  1110. }
  1111. var hasRecordingAtPath = _activeRecordings.Values.ToList().Any(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.TimerId, timerId, StringComparison.OrdinalIgnoreCase));
  1112. if (hasRecordingAtPath)
  1113. {
  1114. return true;
  1115. }
  1116. return false;
  1117. }
  1118. private async Task<IRecorder> GetRecorder()
  1119. {
  1120. var config = GetConfiguration();
  1121. if (config.EnableRecordingEncoding)
  1122. {
  1123. var regInfo = await _liveTvManager.GetRegistrationInfo("embytvrecordingconversion").ConfigureAwait(false);
  1124. if (regInfo.IsValid)
  1125. {
  1126. return new EncodedRecorder(_logger, _fileSystem, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, config, _httpClient);
  1127. }
  1128. }
  1129. return new DirectRecorder(_logger, _httpClient, _fileSystem);
  1130. }
  1131. private async void OnSuccessfulRecording(TimerInfo timer, string path)
  1132. {
  1133. if (timer.IsProgramSeries && GetConfiguration().EnableAutoOrganize)
  1134. {
  1135. try
  1136. {
  1137. // this is to account for the library monitor holding a lock for additional time after the change is complete.
  1138. // ideally this shouldn't be hard-coded
  1139. await Task.Delay(30000).ConfigureAwait(false);
  1140. var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager);
  1141. var result = await organize.OrganizeEpisodeFile(path, _config.GetAutoOrganizeOptions(), false, CancellationToken.None).ConfigureAwait(false);
  1142. if (result.Status == FileSortingStatus.Success)
  1143. {
  1144. return;
  1145. }
  1146. }
  1147. catch (Exception ex)
  1148. {
  1149. _logger.ErrorException("Error processing new recording", ex);
  1150. }
  1151. }
  1152. }
  1153. private void SaveNfo(TimerInfo timer, string recordingPath, string seriesPath)
  1154. {
  1155. try
  1156. {
  1157. if (timer.IsProgramSeries)
  1158. {
  1159. SaveSeriesNfo(timer, recordingPath, seriesPath);
  1160. }
  1161. else if (!timer.IsMovie || timer.IsSports)
  1162. {
  1163. SaveVideoNfo(timer, recordingPath);
  1164. }
  1165. }
  1166. catch (Exception ex)
  1167. {
  1168. _logger.ErrorException("Error saving nfo", ex);
  1169. }
  1170. }
  1171. private void SaveSeriesNfo(TimerInfo timer, string recordingPath, string seriesPath)
  1172. {
  1173. var nfoPath = Path.Combine(seriesPath, "tvshow.nfo");
  1174. if (File.Exists(nfoPath))
  1175. {
  1176. return;
  1177. }
  1178. using (var stream = _fileSystem.GetFileStream(nfoPath, FileMode.Create, FileAccess.Write, FileShare.Read))
  1179. {
  1180. var settings = new XmlWriterSettings
  1181. {
  1182. Indent = true,
  1183. Encoding = Encoding.UTF8,
  1184. CloseOutput = false
  1185. };
  1186. using (XmlWriter writer = XmlWriter.Create(stream, settings))
  1187. {
  1188. writer.WriteStartDocument(true);
  1189. writer.WriteStartElement("tvshow");
  1190. if (!string.IsNullOrWhiteSpace(timer.Name))
  1191. {
  1192. writer.WriteElementString("title", timer.Name);
  1193. }
  1194. writer.WriteEndElement();
  1195. writer.WriteEndDocument();
  1196. }
  1197. }
  1198. }
  1199. public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
  1200. private void SaveVideoNfo(TimerInfo timer, string recordingPath)
  1201. {
  1202. var nfoPath = Path.ChangeExtension(recordingPath, ".nfo");
  1203. if (File.Exists(nfoPath))
  1204. {
  1205. return;
  1206. }
  1207. using (var stream = _fileSystem.GetFileStream(nfoPath, FileMode.Create, FileAccess.Write, FileShare.Read))
  1208. {
  1209. var settings = new XmlWriterSettings
  1210. {
  1211. Indent = true,
  1212. Encoding = Encoding.UTF8,
  1213. CloseOutput = false
  1214. };
  1215. using (XmlWriter writer = XmlWriter.Create(stream, settings))
  1216. {
  1217. writer.WriteStartDocument(true);
  1218. writer.WriteStartElement("movie");
  1219. if (!string.IsNullOrWhiteSpace(timer.Name))
  1220. {
  1221. writer.WriteElementString("title", timer.Name);
  1222. }
  1223. writer.WriteElementString("dateadded", DateTime.UtcNow.ToLocalTime().ToString(DateAddedFormat));
  1224. if (timer.ProductionYear.HasValue)
  1225. {
  1226. writer.WriteElementString("year", timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture));
  1227. }
  1228. if (!string.IsNullOrEmpty(timer.OfficialRating))
  1229. {
  1230. writer.WriteElementString("mpaa", timer.OfficialRating);
  1231. }
  1232. var overview = (timer.Overview ?? string.Empty)
  1233. .StripHtml()
  1234. .Replace("&quot;", "'");
  1235. writer.WriteElementString("plot", overview);
  1236. writer.WriteElementString("lockdata", true.ToString().ToLower());
  1237. if (timer.CommunityRating.HasValue)
  1238. {
  1239. writer.WriteElementString("rating", timer.CommunityRating.Value.ToString(CultureInfo.InvariantCulture));
  1240. }
  1241. if (timer.IsSports)
  1242. {
  1243. AddGenre(timer.Genres, "Sports");
  1244. }
  1245. if (timer.IsKids)
  1246. {
  1247. AddGenre(timer.Genres, "Kids");
  1248. }
  1249. foreach (var genre in timer.Genres)
  1250. {
  1251. writer.WriteElementString("genre", genre);
  1252. }
  1253. if (!string.IsNullOrWhiteSpace(timer.ShortOverview))
  1254. {
  1255. writer.WriteElementString("outline", timer.ShortOverview);
  1256. }
  1257. if (!string.IsNullOrWhiteSpace(timer.HomePageUrl))
  1258. {
  1259. writer.WriteElementString("website", timer.HomePageUrl);
  1260. }
  1261. writer.WriteEndElement();
  1262. writer.WriteEndDocument();
  1263. }
  1264. }
  1265. }
  1266. private void AddGenre(List<string> genres, string genre)
  1267. {
  1268. if (!genres.Contains(genre, StringComparer.OrdinalIgnoreCase))
  1269. {
  1270. genres.Add(genre);
  1271. }
  1272. }
  1273. private ProgramInfo GetProgramInfoFromCache(string channelId, string programId)
  1274. {
  1275. var epgData = GetEpgDataForChannel(channelId);
  1276. return epgData.FirstOrDefault(p => string.Equals(p.Id, programId, StringComparison.OrdinalIgnoreCase));
  1277. }
  1278. private ProgramInfo GetProgramInfoFromCache(string channelId, DateTime startDateUtc)
  1279. {
  1280. var epgData = GetEpgDataForChannel(channelId);
  1281. var startDateTicks = startDateUtc.Ticks;
  1282. // Find the first program that starts within 3 minutes
  1283. return epgData.FirstOrDefault(p => Math.Abs(startDateTicks - p.StartDate.Ticks) <= TimeSpan.FromMinutes(3).Ticks);
  1284. }
  1285. private LiveTvOptions GetConfiguration()
  1286. {
  1287. return _config.GetConfiguration<LiveTvOptions>("livetv");
  1288. }
  1289. private bool ShouldCancelTimerForSeriesTimer(SeriesTimerInfo seriesTimer, TimerInfo timer)
  1290. {
  1291. return seriesTimer.SkipEpisodesInLibrary && IsProgramAlreadyInLibrary(timer);
  1292. }
  1293. private async Task UpdateTimersForSeriesTimer(List<ProgramInfo> epgData, SeriesTimerInfo seriesTimer, bool deleteInvalidTimers)
  1294. {
  1295. var allTimers = GetTimersForSeries(seriesTimer, epgData)
  1296. .ToList();
  1297. var registration = await _liveTvManager.GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
  1298. if (registration.IsValid)
  1299. {
  1300. foreach (var timer in allTimers)
  1301. {
  1302. var existingTimer = _timerProvider.GetTimer(timer.Id);
  1303. if (existingTimer == null)
  1304. {
  1305. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1306. {
  1307. timer.Status = RecordingStatus.Cancelled;
  1308. }
  1309. _timerProvider.Add(timer);
  1310. }
  1311. else
  1312. {
  1313. // Only update if not currently active
  1314. ActiveRecordingInfo activeRecordingInfo;
  1315. if (!_activeRecordings.TryGetValue(timer.Id, out activeRecordingInfo))
  1316. {
  1317. UpdateExistingTimerWithNewData(existingTimer, timer);
  1318. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1319. {
  1320. existingTimer.Status = RecordingStatus.Cancelled;
  1321. }
  1322. existingTimer.SeriesTimerId = seriesTimer.Id;
  1323. _timerProvider.Update(existingTimer);
  1324. }
  1325. }
  1326. }
  1327. }
  1328. if (deleteInvalidTimers)
  1329. {
  1330. var allTimerIds = allTimers
  1331. .Select(i => i.Id)
  1332. .ToList();
  1333. var deleteStatuses = new List<RecordingStatus>
  1334. {
  1335. RecordingStatus.New
  1336. };
  1337. var deletes = _timerProvider.GetAll()
  1338. .Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
  1339. .Where(i => !allTimerIds.Contains(i.Id, StringComparer.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
  1340. .Where(i => deleteStatuses.Contains(i.Status))
  1341. .ToList();
  1342. foreach (var timer in deletes)
  1343. {
  1344. CancelTimerInternal(timer.Id, false);
  1345. }
  1346. }
  1347. }
  1348. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer,
  1349. IEnumerable<ProgramInfo> allPrograms)
  1350. {
  1351. if (seriesTimer == null)
  1352. {
  1353. throw new ArgumentNullException("seriesTimer");
  1354. }
  1355. if (allPrograms == null)
  1356. {
  1357. throw new ArgumentNullException("allPrograms");
  1358. }
  1359. // Exclude programs that have already ended
  1360. allPrograms = allPrograms.Where(i => i.EndDate > DateTime.UtcNow);
  1361. allPrograms = GetProgramsForSeries(seriesTimer, allPrograms);
  1362. return allPrograms.Select(i => RecordingHelper.CreateTimer(i, seriesTimer));
  1363. }
  1364. private bool IsProgramAlreadyInLibrary(TimerInfo program)
  1365. {
  1366. if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle))
  1367. {
  1368. var seriesIds = _libraryManager.GetItemIds(new InternalItemsQuery
  1369. {
  1370. IncludeItemTypes = new[] { typeof(Series).Name },
  1371. Name = program.Name
  1372. }).Select(i => i.ToString("N")).ToArray();
  1373. if (seriesIds.Length == 0)
  1374. {
  1375. return false;
  1376. }
  1377. if (program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue)
  1378. {
  1379. var result = _libraryManager.GetItemsResult(new InternalItemsQuery
  1380. {
  1381. IncludeItemTypes = new[] { typeof(Episode).Name },
  1382. ParentIndexNumber = program.SeasonNumber.Value,
  1383. IndexNumber = program.EpisodeNumber.Value,
  1384. AncestorIds = seriesIds,
  1385. ExcludeLocationTypes = new[] { LocationType.Virtual }
  1386. });
  1387. if (result.TotalRecordCount > 0)
  1388. {
  1389. return true;
  1390. }
  1391. }
  1392. if (!string.IsNullOrWhiteSpace(program.EpisodeTitle))
  1393. {
  1394. var result = _libraryManager.GetItemsResult(new InternalItemsQuery
  1395. {
  1396. IncludeItemTypes = new[] { typeof(Episode).Name },
  1397. Name = program.EpisodeTitle,
  1398. AncestorIds = seriesIds,
  1399. ExcludeLocationTypes = new[] { LocationType.Virtual }
  1400. });
  1401. if (result.TotalRecordCount > 0)
  1402. {
  1403. return true;
  1404. }
  1405. }
  1406. }
  1407. return false;
  1408. }
  1409. private IEnumerable<ProgramInfo> GetProgramsForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  1410. {
  1411. if (!seriesTimer.RecordAnyTime)
  1412. {
  1413. allPrograms = allPrograms.Where(epg => Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - epg.StartDate.TimeOfDay.Ticks) < TimeSpan.FromMinutes(5).Ticks);
  1414. allPrograms = allPrograms.Where(i => seriesTimer.Days.Contains(i.StartDate.ToLocalTime().DayOfWeek));
  1415. }
  1416. if (seriesTimer.RecordNewOnly)
  1417. {
  1418. allPrograms = allPrograms.Where(epg => !epg.IsRepeat);
  1419. }
  1420. if (!seriesTimer.RecordAnyChannel)
  1421. {
  1422. allPrograms = allPrograms.Where(epg => string.Equals(epg.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase));
  1423. }
  1424. if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
  1425. {
  1426. _logger.Error("seriesTimer.SeriesId is null. Cannot find programs for series");
  1427. return new List<ProgramInfo>();
  1428. }
  1429. return allPrograms.Where(i => string.Equals(i.SeriesId, seriesTimer.SeriesId, StringComparison.OrdinalIgnoreCase));
  1430. }
  1431. private string GetChannelEpgCachePath(string channelId)
  1432. {
  1433. return Path.Combine(_config.CommonApplicationPaths.CachePath, "embytvepg", channelId + ".json");
  1434. }
  1435. private readonly object _epgLock = new object();
  1436. private void SaveEpgDataForChannel(string channelId, List<ProgramInfo> epgData)
  1437. {
  1438. var path = GetChannelEpgCachePath(channelId);
  1439. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  1440. lock (_epgLock)
  1441. {
  1442. _jsonSerializer.SerializeToFile(epgData, path);
  1443. }
  1444. }
  1445. private List<ProgramInfo> GetEpgDataForChannel(string channelId)
  1446. {
  1447. try
  1448. {
  1449. lock (_epgLock)
  1450. {
  1451. return _jsonSerializer.DeserializeFromFile<List<ProgramInfo>>(GetChannelEpgCachePath(channelId));
  1452. }
  1453. }
  1454. catch
  1455. {
  1456. return new List<ProgramInfo>();
  1457. }
  1458. }
  1459. private List<ProgramInfo> GetEpgDataForChannels(List<string> channelIds)
  1460. {
  1461. return channelIds.SelectMany(GetEpgDataForChannel).ToList();
  1462. }
  1463. private bool _disposed;
  1464. public void Dispose()
  1465. {
  1466. _disposed = true;
  1467. foreach (var pair in _activeRecordings.ToList())
  1468. {
  1469. pair.Value.CancellationTokenSource.Cancel();
  1470. }
  1471. }
  1472. public List<VirtualFolderInfo> GetRecordingFolders()
  1473. {
  1474. var list = new List<VirtualFolderInfo>();
  1475. var defaultFolder = RecordingPath;
  1476. var defaultName = "Recordings";
  1477. if (Directory.Exists(defaultFolder))
  1478. {
  1479. list.Add(new VirtualFolderInfo
  1480. {
  1481. Locations = new List<string> { defaultFolder },
  1482. Name = defaultName
  1483. });
  1484. }
  1485. var customPath = GetConfiguration().MovieRecordingPath;
  1486. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath))
  1487. {
  1488. list.Add(new VirtualFolderInfo
  1489. {
  1490. Locations = new List<string> { customPath },
  1491. Name = "Recorded Movies",
  1492. CollectionType = CollectionType.Movies
  1493. });
  1494. }
  1495. customPath = GetConfiguration().SeriesRecordingPath;
  1496. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath))
  1497. {
  1498. list.Add(new VirtualFolderInfo
  1499. {
  1500. Locations = new List<string> { customPath },
  1501. Name = "Recorded Series",
  1502. CollectionType = CollectionType.TvShows
  1503. });
  1504. }
  1505. return list;
  1506. }
  1507. class ActiveRecordingInfo
  1508. {
  1509. public string Path { get; set; }
  1510. public string TimerId { get; set; }
  1511. public CancellationTokenSource CancellationTokenSource { get; set; }
  1512. }
  1513. }
  1514. }