EmbyTV.cs 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844
  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 async Task<IEnumerable<ChannelInfo>> GetChannelsAsync(bool enableCache, CancellationToken cancellationToken)
  290. {
  291. var list = new List<ChannelInfo>();
  292. foreach (var hostInstance in _liveTvManager.TunerHosts)
  293. {
  294. try
  295. {
  296. var channels = await hostInstance.GetChannels(enableCache, cancellationToken).ConfigureAwait(false);
  297. list.AddRange(channels);
  298. }
  299. catch (Exception ex)
  300. {
  301. _logger.ErrorException("Error getting channels", ex);
  302. }
  303. }
  304. foreach (var provider in GetListingProviders())
  305. {
  306. var enabledChannels = list
  307. .Where(i => IsListingProviderEnabledForTuner(provider.Item2, i.TunerHostId))
  308. .ToList();
  309. if (enabledChannels.Count > 0)
  310. {
  311. try
  312. {
  313. await provider.Item1.AddMetadata(provider.Item2, enabledChannels, cancellationToken).ConfigureAwait(false);
  314. }
  315. catch (NotSupportedException)
  316. {
  317. }
  318. catch (Exception ex)
  319. {
  320. _logger.ErrorException("Error adding metadata", ex);
  321. }
  322. }
  323. }
  324. return list;
  325. }
  326. public async Task<List<ChannelInfo>> GetChannelsForListingsProvider(ListingsProviderInfo listingsProvider, CancellationToken cancellationToken)
  327. {
  328. var list = new List<ChannelInfo>();
  329. foreach (var hostInstance in _liveTvManager.TunerHosts)
  330. {
  331. try
  332. {
  333. var channels = await hostInstance.GetChannels(false, cancellationToken).ConfigureAwait(false);
  334. list.AddRange(channels);
  335. }
  336. catch (Exception ex)
  337. {
  338. _logger.ErrorException("Error getting channels", ex);
  339. }
  340. }
  341. return list
  342. .Where(i => IsListingProviderEnabledForTuner(listingsProvider, i.TunerHostId))
  343. .ToList();
  344. }
  345. public Task<IEnumerable<ChannelInfo>> GetChannelsAsync(CancellationToken cancellationToken)
  346. {
  347. return GetChannelsAsync(false, cancellationToken);
  348. }
  349. public Task CancelSeriesTimerAsync(string timerId, CancellationToken cancellationToken)
  350. {
  351. var timers = _timerProvider
  352. .GetAll()
  353. .Where(i => string.Equals(i.SeriesTimerId, timerId, StringComparison.OrdinalIgnoreCase))
  354. .ToList();
  355. foreach (var timer in timers)
  356. {
  357. CancelTimerInternal(timer.Id, true);
  358. }
  359. var remove = _seriesTimerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
  360. if (remove != null)
  361. {
  362. _seriesTimerProvider.Delete(remove);
  363. }
  364. return Task.FromResult(true);
  365. }
  366. private void CancelTimerInternal(string timerId, bool isSeriesCancelled)
  367. {
  368. var timer = _timerProvider.GetTimer(timerId);
  369. if (timer != null)
  370. {
  371. if (string.IsNullOrWhiteSpace(timer.SeriesTimerId) || isSeriesCancelled)
  372. {
  373. _timerProvider.Delete(timer);
  374. }
  375. else
  376. {
  377. timer.Status = RecordingStatus.Cancelled;
  378. _timerProvider.AddOrUpdate(timer, false);
  379. }
  380. }
  381. ActiveRecordingInfo activeRecordingInfo;
  382. if (_activeRecordings.TryGetValue(timerId, out activeRecordingInfo))
  383. {
  384. activeRecordingInfo.CancellationTokenSource.Cancel();
  385. }
  386. }
  387. public Task CancelTimerAsync(string timerId, CancellationToken cancellationToken)
  388. {
  389. CancelTimerInternal(timerId, false);
  390. return Task.FromResult(true);
  391. }
  392. public Task DeleteRecordingAsync(string recordingId, CancellationToken cancellationToken)
  393. {
  394. return Task.FromResult(true);
  395. }
  396. public Task CreateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  397. {
  398. throw new NotImplementedException();
  399. }
  400. public Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
  401. {
  402. throw new NotImplementedException();
  403. }
  404. public Task<string> CreateTimer(TimerInfo timer, CancellationToken cancellationToken)
  405. {
  406. var existingTimer = _timerProvider.GetAll()
  407. .FirstOrDefault(i => string.Equals(timer.ProgramId, i.ProgramId, StringComparison.OrdinalIgnoreCase));
  408. if (existingTimer != null)
  409. {
  410. if (existingTimer.Status == RecordingStatus.Cancelled)
  411. {
  412. existingTimer.Status = RecordingStatus.New;
  413. _timerProvider.Update(existingTimer);
  414. return Task.FromResult(existingTimer.Id);
  415. }
  416. else
  417. {
  418. throw new ArgumentException("A scheduled recording already exists for this program.");
  419. }
  420. }
  421. timer.Id = Guid.NewGuid().ToString("N");
  422. ProgramInfo programInfo = null;
  423. if (!string.IsNullOrWhiteSpace(timer.ProgramId))
  424. {
  425. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  426. }
  427. if (programInfo == null)
  428. {
  429. _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  430. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  431. }
  432. if (programInfo != null)
  433. {
  434. RecordingHelper.CopyProgramInfoToTimerInfo(programInfo, timer);
  435. }
  436. _timerProvider.Add(timer);
  437. return Task.FromResult(timer.Id);
  438. }
  439. public async Task<string> CreateSeriesTimer(SeriesTimerInfo info, CancellationToken cancellationToken)
  440. {
  441. info.Id = Guid.NewGuid().ToString("N");
  442. List<ProgramInfo> epgData;
  443. if (info.RecordAnyChannel)
  444. {
  445. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  446. var channelIds = channels.Select(i => i.Id).ToList();
  447. epgData = GetEpgDataForChannels(channelIds);
  448. }
  449. else
  450. {
  451. epgData = GetEpgDataForChannel(info.ChannelId);
  452. }
  453. // populate info.seriesID
  454. var program = epgData.FirstOrDefault(i => string.Equals(i.Id, info.ProgramId, StringComparison.OrdinalIgnoreCase));
  455. if (program != null)
  456. {
  457. info.SeriesId = program.SeriesId;
  458. }
  459. else
  460. {
  461. throw new InvalidOperationException("SeriesId for program not found");
  462. }
  463. _seriesTimerProvider.Add(info);
  464. await UpdateTimersForSeriesTimer(epgData, info, false).ConfigureAwait(false);
  465. return info.Id;
  466. }
  467. public async Task UpdateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  468. {
  469. var instance = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  470. if (instance != null)
  471. {
  472. instance.ChannelId = info.ChannelId;
  473. instance.Days = info.Days;
  474. instance.EndDate = info.EndDate;
  475. instance.IsPostPaddingRequired = info.IsPostPaddingRequired;
  476. instance.IsPrePaddingRequired = info.IsPrePaddingRequired;
  477. instance.PostPaddingSeconds = info.PostPaddingSeconds;
  478. instance.PrePaddingSeconds = info.PrePaddingSeconds;
  479. instance.Priority = info.Priority;
  480. instance.RecordAnyChannel = info.RecordAnyChannel;
  481. instance.RecordAnyTime = info.RecordAnyTime;
  482. instance.RecordNewOnly = info.RecordNewOnly;
  483. instance.SkipEpisodesInLibrary = info.SkipEpisodesInLibrary;
  484. instance.KeepUpTo = info.KeepUpTo;
  485. instance.KeepUntil = info.KeepUntil;
  486. instance.StartDate = info.StartDate;
  487. _seriesTimerProvider.Update(instance);
  488. List<ProgramInfo> epgData;
  489. if (instance.RecordAnyChannel)
  490. {
  491. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  492. var channelIds = channels.Select(i => i.Id).ToList();
  493. epgData = GetEpgDataForChannels(channelIds);
  494. }
  495. else
  496. {
  497. epgData = GetEpgDataForChannel(instance.ChannelId);
  498. }
  499. await UpdateTimersForSeriesTimer(epgData, instance, true).ConfigureAwait(false);
  500. }
  501. }
  502. public Task UpdateTimerAsync(TimerInfo updatedTimer, CancellationToken cancellationToken)
  503. {
  504. var existingTimer = _timerProvider.GetTimer(updatedTimer.Id);
  505. if (existingTimer == null)
  506. {
  507. throw new ResourceNotFoundException();
  508. }
  509. // Only update if not currently active
  510. ActiveRecordingInfo activeRecordingInfo;
  511. if (!_activeRecordings.TryGetValue(updatedTimer.Id, out activeRecordingInfo))
  512. {
  513. UpdateExistingTimerWithNewData(existingTimer, updatedTimer);
  514. _timerProvider.Update(existingTimer);
  515. }
  516. return Task.FromResult(true);
  517. }
  518. private void UpdateExistingTimerWithNewData(TimerInfo existingTimer, TimerInfo updatedTimer)
  519. {
  520. // Update the program info but retain the status
  521. existingTimer.ChannelId = updatedTimer.ChannelId;
  522. existingTimer.CommunityRating = updatedTimer.CommunityRating;
  523. existingTimer.EndDate = updatedTimer.EndDate;
  524. existingTimer.EpisodeNumber = updatedTimer.EpisodeNumber;
  525. existingTimer.EpisodeTitle = updatedTimer.EpisodeTitle;
  526. existingTimer.Genres = updatedTimer.Genres;
  527. existingTimer.HomePageUrl = updatedTimer.HomePageUrl;
  528. existingTimer.IsKids = updatedTimer.IsKids;
  529. existingTimer.IsNews = updatedTimer.IsNews;
  530. existingTimer.IsMovie = updatedTimer.IsMovie;
  531. existingTimer.IsProgramSeries = updatedTimer.IsProgramSeries;
  532. existingTimer.IsSports = updatedTimer.IsSports;
  533. existingTimer.Name = updatedTimer.Name;
  534. existingTimer.OfficialRating = updatedTimer.OfficialRating;
  535. existingTimer.OriginalAirDate = updatedTimer.OriginalAirDate;
  536. existingTimer.Overview = updatedTimer.Overview;
  537. existingTimer.ProductionYear = updatedTimer.ProductionYear;
  538. existingTimer.ProgramId = updatedTimer.ProgramId;
  539. existingTimer.SeasonNumber = updatedTimer.SeasonNumber;
  540. existingTimer.ShortOverview = updatedTimer.ShortOverview;
  541. existingTimer.StartDate = updatedTimer.StartDate;
  542. }
  543. public Task<ImageStream> GetChannelImageAsync(string channelId, CancellationToken cancellationToken)
  544. {
  545. throw new NotImplementedException();
  546. }
  547. public Task<ImageStream> GetRecordingImageAsync(string recordingId, CancellationToken cancellationToken)
  548. {
  549. throw new NotImplementedException();
  550. }
  551. public Task<ImageStream> GetProgramImageAsync(string programId, string channelId, CancellationToken cancellationToken)
  552. {
  553. throw new NotImplementedException();
  554. }
  555. public async Task<IEnumerable<RecordingInfo>> GetRecordingsAsync(CancellationToken cancellationToken)
  556. {
  557. return new List<RecordingInfo>();
  558. }
  559. public Task<IEnumerable<TimerInfo>> GetTimersAsync(CancellationToken cancellationToken)
  560. {
  561. var excludeStatues = new List<RecordingStatus>
  562. {
  563. RecordingStatus.Completed,
  564. RecordingStatus.Cancelled
  565. };
  566. var timers = _timerProvider.GetAll()
  567. .Where(i => !excludeStatues.Contains(i.Status));
  568. return Task.FromResult(timers);
  569. }
  570. public Task<SeriesTimerInfo> GetNewTimerDefaultsAsync(CancellationToken cancellationToken, ProgramInfo program = null)
  571. {
  572. var config = GetConfiguration();
  573. var defaults = new SeriesTimerInfo()
  574. {
  575. PostPaddingSeconds = Math.Max(config.PostPaddingSeconds, 0),
  576. PrePaddingSeconds = Math.Max(config.PrePaddingSeconds, 0),
  577. RecordAnyChannel = true,
  578. RecordAnyTime = true,
  579. RecordNewOnly = true,
  580. Days = new List<DayOfWeek>
  581. {
  582. DayOfWeek.Sunday,
  583. DayOfWeek.Monday,
  584. DayOfWeek.Tuesday,
  585. DayOfWeek.Wednesday,
  586. DayOfWeek.Thursday,
  587. DayOfWeek.Friday,
  588. DayOfWeek.Saturday
  589. }
  590. };
  591. if (program != null)
  592. {
  593. defaults.SeriesId = program.SeriesId;
  594. defaults.ProgramId = program.Id;
  595. }
  596. defaults.SkipEpisodesInLibrary = true;
  597. defaults.KeepUntil = KeepUntil.UntilDeleted;
  598. return Task.FromResult(defaults);
  599. }
  600. public Task<IEnumerable<SeriesTimerInfo>> GetSeriesTimersAsync(CancellationToken cancellationToken)
  601. {
  602. return Task.FromResult((IEnumerable<SeriesTimerInfo>)_seriesTimerProvider.GetAll());
  603. }
  604. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  605. {
  606. try
  607. {
  608. return await GetProgramsAsyncInternal(channelId, startDateUtc, endDateUtc, cancellationToken).ConfigureAwait(false);
  609. }
  610. catch (OperationCanceledException)
  611. {
  612. throw;
  613. }
  614. catch (Exception ex)
  615. {
  616. _logger.ErrorException("Error getting programs", ex);
  617. return GetEpgDataForChannel(channelId).Where(i => i.StartDate <= endDateUtc && i.EndDate >= startDateUtc);
  618. }
  619. }
  620. private bool IsListingProviderEnabledForTuner(ListingsProviderInfo info, string tunerHostId)
  621. {
  622. if (info.EnableAllTuners)
  623. {
  624. return true;
  625. }
  626. if (string.IsNullOrWhiteSpace(tunerHostId))
  627. {
  628. throw new ArgumentNullException("tunerHostId");
  629. }
  630. return info.EnabledTuners.Contains(tunerHostId, StringComparer.OrdinalIgnoreCase);
  631. }
  632. private async Task<IEnumerable<ProgramInfo>> GetProgramsAsyncInternal(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  633. {
  634. var channels = await GetChannelsAsync(true, cancellationToken).ConfigureAwait(false);
  635. var channel = channels.First(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  636. foreach (var provider in GetListingProviders())
  637. {
  638. if (!IsListingProviderEnabledForTuner(provider.Item2, channel.TunerHostId))
  639. {
  640. _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);
  641. continue;
  642. }
  643. _logger.Debug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
  644. var channelMappings = GetChannelMappings(provider.Item2);
  645. var channelNumber = channel.Number;
  646. string mappedChannelNumber;
  647. if (channelMappings.TryGetValue(channelNumber, out mappedChannelNumber))
  648. {
  649. _logger.Debug("Found mapped channel on provider {0}. Tuner channel number: {1}, Mapped channel number: {2}", provider.Item1.Name, channelNumber, mappedChannelNumber);
  650. channelNumber = mappedChannelNumber;
  651. }
  652. var programs = await provider.Item1.GetProgramsAsync(provider.Item2, channelNumber, channel.Name, startDateUtc, endDateUtc, cancellationToken)
  653. .ConfigureAwait(false);
  654. var list = programs.ToList();
  655. // Replace the value that came from the provider with a normalized value
  656. foreach (var program in list)
  657. {
  658. program.ChannelId = channelId;
  659. }
  660. if (list.Count > 0)
  661. {
  662. SaveEpgDataForChannel(channelId, list);
  663. return list;
  664. }
  665. }
  666. return new List<ProgramInfo>();
  667. }
  668. private Dictionary<string, string> GetChannelMappings(ListingsProviderInfo info)
  669. {
  670. var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  671. foreach (var mapping in info.ChannelMappings)
  672. {
  673. dict[mapping.Name] = mapping.Value;
  674. }
  675. return dict;
  676. }
  677. private List<Tuple<IListingsProvider, ListingsProviderInfo>> GetListingProviders()
  678. {
  679. return GetConfiguration().ListingProviders
  680. .Select(i =>
  681. {
  682. var provider = _liveTvManager.ListingProviders.FirstOrDefault(l => string.Equals(l.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  683. return provider == null ? null : new Tuple<IListingsProvider, ListingsProviderInfo>(provider, i);
  684. })
  685. .Where(i => i != null)
  686. .ToList();
  687. }
  688. public Task<MediaSourceInfo> GetRecordingStream(string recordingId, string streamId, CancellationToken cancellationToken)
  689. {
  690. throw new NotImplementedException();
  691. }
  692. private readonly SemaphoreSlim _liveStreamsSemaphore = new SemaphoreSlim(1, 1);
  693. private readonly Dictionary<string, LiveStream> _liveStreams = new Dictionary<string, LiveStream>();
  694. public async Task<MediaSourceInfo> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
  695. {
  696. var result = await GetChannelStreamInternal(channelId, streamId, cancellationToken).ConfigureAwait(false);
  697. return result.Item2;
  698. }
  699. private MediaSourceInfo CloneMediaSource(MediaSourceInfo mediaSource, int consumerId)
  700. {
  701. var json = _jsonSerializer.SerializeToString(mediaSource);
  702. mediaSource = _jsonSerializer.DeserializeFromString<MediaSourceInfo>(json);
  703. mediaSource.Id = consumerId.ToString(CultureInfo.InvariantCulture) + "_" + mediaSource.Id;
  704. return mediaSource;
  705. }
  706. private async Task<Tuple<LiveStream, MediaSourceInfo, ITunerHost>> GetChannelStreamInternal(string channelId, string streamId, CancellationToken cancellationToken)
  707. {
  708. _logger.Info("Streaming Channel " + channelId);
  709. await _liveStreamsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  710. var result = _liveStreams.Values.FirstOrDefault(i => string.Equals(i.OriginalStreamId, streamId, StringComparison.OrdinalIgnoreCase));
  711. if (result != null)
  712. {
  713. //result.ConsumerCount++;
  714. //_logger.Info("Live stream {0} consumer count is now {1}", streamId, result.ConsumerCount);
  715. //_liveStreamsSemaphore.Release();
  716. //return new Tuple<LiveStream, MediaSourceInfo, ITunerHost>(result, CloneMediaSource(result.OpenedMediaSource, result.ConsumerCount - 1), result.TunerHost);
  717. }
  718. try
  719. {
  720. foreach (var hostInstance in _liveTvManager.TunerHosts)
  721. {
  722. try
  723. {
  724. result = await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
  725. _liveStreams[result.OpenedMediaSource.Id] = result;
  726. result.ConsumerCount++;
  727. result.TunerHost = hostInstance;
  728. result.OriginalStreamId = streamId;
  729. _logger.Info("Returning mediasource streamId {0}, mediaSource.Id {1}, mediaSource.LiveStreamId {2}",
  730. streamId, result.OpenedMediaSource.Id, result.OpenedMediaSource.LiveStreamId);
  731. return new Tuple<LiveStream, MediaSourceInfo, ITunerHost>(result, CloneMediaSource(result.OpenedMediaSource, 0), hostInstance);
  732. }
  733. catch (FileNotFoundException)
  734. {
  735. }
  736. catch (OperationCanceledException)
  737. {
  738. }
  739. }
  740. }
  741. finally
  742. {
  743. _liveStreamsSemaphore.Release();
  744. }
  745. throw new ApplicationException("Tuner not found.");
  746. }
  747. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  748. {
  749. foreach (var hostInstance in _liveTvManager.TunerHosts)
  750. {
  751. try
  752. {
  753. var sources = await hostInstance.GetChannelStreamMediaSources(channelId, cancellationToken).ConfigureAwait(false);
  754. if (sources.Count > 0)
  755. {
  756. return sources;
  757. }
  758. }
  759. catch (NotImplementedException)
  760. {
  761. }
  762. }
  763. throw new NotImplementedException();
  764. }
  765. public Task<List<MediaSourceInfo>> GetRecordingStreamMediaSources(string recordingId, CancellationToken cancellationToken)
  766. {
  767. throw new NotImplementedException();
  768. }
  769. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  770. {
  771. // Ignore the consumer id
  772. id = id.Substring(id.IndexOf('_') + 1);
  773. await _liveStreamsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  774. try
  775. {
  776. LiveStream stream;
  777. if (_liveStreams.TryGetValue(id, out stream))
  778. {
  779. stream.ConsumerCount--;
  780. _logger.Info("Live stream {0} consumer count is now {1}", id, stream.ConsumerCount);
  781. if (stream.ConsumerCount <= 0)
  782. {
  783. _liveStreams.Remove(id);
  784. _logger.Info("Closing live stream {0}", id);
  785. await stream.Close().ConfigureAwait(false);
  786. _logger.Info("Live stream {0} closed successfully", id);
  787. }
  788. }
  789. else
  790. {
  791. _logger.Warn("Live stream not found: {0}, unable to close", id);
  792. }
  793. }
  794. catch (OperationCanceledException)
  795. {
  796. }
  797. catch (Exception ex)
  798. {
  799. _logger.ErrorException("Error closing live stream", ex);
  800. }
  801. finally
  802. {
  803. _liveStreamsSemaphore.Release();
  804. }
  805. }
  806. public Task RecordLiveStream(string id, CancellationToken cancellationToken)
  807. {
  808. return Task.FromResult(0);
  809. }
  810. public Task ResetTuner(string id, CancellationToken cancellationToken)
  811. {
  812. return Task.FromResult(0);
  813. }
  814. async void _timerProvider_TimerFired(object sender, GenericEventArgs<TimerInfo> e)
  815. {
  816. var timer = e.Argument;
  817. _logger.Info("Recording timer fired.");
  818. try
  819. {
  820. var recordingEndDate = timer.EndDate.AddSeconds(timer.PostPaddingSeconds);
  821. if (recordingEndDate <= DateTime.UtcNow)
  822. {
  823. _logger.Warn("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
  824. OnTimerOutOfDate(timer);
  825. return;
  826. }
  827. var activeRecordingInfo = new ActiveRecordingInfo
  828. {
  829. CancellationTokenSource = new CancellationTokenSource(),
  830. TimerId = timer.Id
  831. };
  832. if (_activeRecordings.TryAdd(timer.Id, activeRecordingInfo))
  833. {
  834. await RecordStream(timer, recordingEndDate, activeRecordingInfo, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false);
  835. }
  836. else
  837. {
  838. _logger.Info("Skipping RecordStream because it's already in progress.");
  839. }
  840. }
  841. catch (OperationCanceledException)
  842. {
  843. }
  844. catch (Exception ex)
  845. {
  846. _logger.ErrorException("Error recording stream", ex);
  847. }
  848. }
  849. private string GetRecordingPath(TimerInfo timer, out string seriesPath)
  850. {
  851. var recordPath = RecordingPath;
  852. var config = GetConfiguration();
  853. seriesPath = null;
  854. if (timer.IsProgramSeries)
  855. {
  856. var customRecordingPath = config.SeriesRecordingPath;
  857. var allowSubfolder = true;
  858. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  859. {
  860. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  861. recordPath = customRecordingPath;
  862. }
  863. if (allowSubfolder && config.EnableRecordingSubfolders)
  864. {
  865. recordPath = Path.Combine(recordPath, "Series");
  866. }
  867. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  868. // Can't use the year here in the folder name because it is the year of the episode, not the series.
  869. recordPath = Path.Combine(recordPath, folderName);
  870. seriesPath = recordPath;
  871. if (timer.SeasonNumber.HasValue)
  872. {
  873. folderName = string.Format("Season {0}", timer.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture));
  874. recordPath = Path.Combine(recordPath, folderName);
  875. }
  876. }
  877. else if (timer.IsMovie)
  878. {
  879. var customRecordingPath = config.MovieRecordingPath;
  880. var allowSubfolder = true;
  881. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  882. {
  883. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  884. recordPath = customRecordingPath;
  885. }
  886. if (allowSubfolder && config.EnableRecordingSubfolders)
  887. {
  888. recordPath = Path.Combine(recordPath, "Movies");
  889. }
  890. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  891. if (timer.ProductionYear.HasValue)
  892. {
  893. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  894. }
  895. recordPath = Path.Combine(recordPath, folderName);
  896. }
  897. else if (timer.IsKids)
  898. {
  899. if (config.EnableRecordingSubfolders)
  900. {
  901. recordPath = Path.Combine(recordPath, "Kids");
  902. }
  903. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  904. if (timer.ProductionYear.HasValue)
  905. {
  906. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  907. }
  908. recordPath = Path.Combine(recordPath, folderName);
  909. }
  910. else if (timer.IsSports)
  911. {
  912. if (config.EnableRecordingSubfolders)
  913. {
  914. recordPath = Path.Combine(recordPath, "Sports");
  915. }
  916. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  917. }
  918. else
  919. {
  920. if (config.EnableRecordingSubfolders)
  921. {
  922. recordPath = Path.Combine(recordPath, "Other");
  923. }
  924. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  925. }
  926. var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer)).Trim() + ".ts";
  927. return Path.Combine(recordPath, recordingFileName);
  928. }
  929. private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate,
  930. ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken)
  931. {
  932. if (timer == null)
  933. {
  934. throw new ArgumentNullException("timer");
  935. }
  936. ProgramInfo programInfo = null;
  937. if (!string.IsNullOrWhiteSpace(timer.ProgramId))
  938. {
  939. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  940. }
  941. if (programInfo == null)
  942. {
  943. _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  944. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  945. }
  946. if (programInfo != null)
  947. {
  948. RecordingHelper.CopyProgramInfoToTimerInfo(programInfo, timer);
  949. }
  950. string seriesPath = null;
  951. var recordPath = GetRecordingPath(timer, out seriesPath);
  952. var recordingStatus = RecordingStatus.New;
  953. string liveStreamId = null;
  954. try
  955. {
  956. var allMediaSources =
  957. await GetChannelStreamMediaSources(timer.ChannelId, CancellationToken.None).ConfigureAwait(false);
  958. var liveStreamInfo = await GetChannelStreamInternal(timer.ChannelId, allMediaSources[0].Id, CancellationToken.None)
  959. .ConfigureAwait(false);
  960. var mediaStreamInfo = liveStreamInfo.Item2;
  961. liveStreamId = mediaStreamInfo.Id;
  962. // HDHR doesn't seem to release the tuner right away after first probing with ffmpeg
  963. //await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  964. var recorder = await GetRecorder().ConfigureAwait(false);
  965. recordPath = recorder.GetOutputPath(mediaStreamInfo, recordPath);
  966. recordPath = EnsureFileUnique(recordPath, timer.Id);
  967. _libraryManager.RegisterIgnoredPath(recordPath);
  968. _libraryMonitor.ReportFileSystemChangeBeginning(recordPath);
  969. _fileSystem.CreateDirectory(Path.GetDirectoryName(recordPath));
  970. activeRecordingInfo.Path = recordPath;
  971. var duration = recordingEndDate - DateTime.UtcNow;
  972. _logger.Info("Beginning recording. Will record for {0} minutes.",
  973. duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
  974. _logger.Info("Writing file to path: " + recordPath);
  975. _logger.Info("Opening recording stream from tuner provider");
  976. Action onStarted = () =>
  977. {
  978. timer.Status = RecordingStatus.InProgress;
  979. _timerProvider.AddOrUpdate(timer, false);
  980. SaveNfo(timer, recordPath, seriesPath);
  981. EnforceKeepUpTo(timer);
  982. };
  983. await recorder.Record(mediaStreamInfo, recordPath, duration, onStarted, cancellationToken)
  984. .ConfigureAwait(false);
  985. recordingStatus = RecordingStatus.Completed;
  986. _logger.Info("Recording completed: {0}", recordPath);
  987. }
  988. catch (OperationCanceledException)
  989. {
  990. _logger.Info("Recording stopped: {0}", recordPath);
  991. recordingStatus = RecordingStatus.Completed;
  992. }
  993. catch (Exception ex)
  994. {
  995. _logger.ErrorException("Error recording to {0}", ex, recordPath);
  996. recordingStatus = RecordingStatus.Error;
  997. }
  998. if (!string.IsNullOrWhiteSpace(liveStreamId))
  999. {
  1000. try
  1001. {
  1002. await CloseLiveStream(liveStreamId, CancellationToken.None).ConfigureAwait(false);
  1003. }
  1004. catch (Exception ex)
  1005. {
  1006. _logger.ErrorException("Error closing live stream", ex);
  1007. }
  1008. }
  1009. _libraryManager.UnRegisterIgnoredPath(recordPath);
  1010. _libraryMonitor.ReportFileSystemChangeComplete(recordPath, true);
  1011. ActiveRecordingInfo removed;
  1012. _activeRecordings.TryRemove(timer.Id, out removed);
  1013. if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate)
  1014. {
  1015. const int retryIntervalSeconds = 60;
  1016. _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds);
  1017. timer.Status = RecordingStatus.New;
  1018. timer.StartDate = DateTime.UtcNow.AddSeconds(retryIntervalSeconds);
  1019. _timerProvider.AddOrUpdate(timer);
  1020. }
  1021. else if (File.Exists(recordPath))
  1022. {
  1023. timer.RecordingPath = recordPath;
  1024. timer.Status = RecordingStatus.Completed;
  1025. _timerProvider.AddOrUpdate(timer, false);
  1026. OnSuccessfulRecording(timer, recordPath);
  1027. }
  1028. else
  1029. {
  1030. _timerProvider.Delete(timer);
  1031. }
  1032. }
  1033. private async void EnforceKeepUpTo(TimerInfo timer)
  1034. {
  1035. if (string.IsNullOrWhiteSpace(timer.SeriesTimerId))
  1036. {
  1037. return;
  1038. }
  1039. var seriesTimerId = timer.SeriesTimerId;
  1040. var seriesTimer = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, seriesTimerId, StringComparison.OrdinalIgnoreCase));
  1041. if (seriesTimer == null || seriesTimer.KeepUpTo <= 1)
  1042. {
  1043. return;
  1044. }
  1045. if (_disposed)
  1046. {
  1047. return;
  1048. }
  1049. await _recordingDeleteSemaphore.WaitAsync().ConfigureAwait(false);
  1050. try
  1051. {
  1052. if (_disposed)
  1053. {
  1054. return;
  1055. }
  1056. var timersToDelete = _timerProvider.GetAll()
  1057. .Where(i => i.Status == RecordingStatus.Completed && !string.IsNullOrWhiteSpace(i.RecordingPath))
  1058. .Where(i => string.Equals(i.SeriesTimerId, seriesTimerId, StringComparison.OrdinalIgnoreCase))
  1059. .OrderByDescending(i => i.EndDate)
  1060. .Where(i => File.Exists(i.RecordingPath))
  1061. .Skip(seriesTimer.KeepUpTo - 1)
  1062. .ToList();
  1063. await DeleteLibraryItemsForTimers(timersToDelete).ConfigureAwait(false);
  1064. }
  1065. finally
  1066. {
  1067. _recordingDeleteSemaphore.Release();
  1068. }
  1069. }
  1070. private readonly SemaphoreSlim _recordingDeleteSemaphore = new SemaphoreSlim(1, 1);
  1071. private async Task DeleteLibraryItemsForTimers(List<TimerInfo> timers)
  1072. {
  1073. foreach (var timer in timers)
  1074. {
  1075. if (_disposed)
  1076. {
  1077. return;
  1078. }
  1079. try
  1080. {
  1081. await DeleteLibraryItemForTimer(timer).ConfigureAwait(false);
  1082. }
  1083. catch (Exception ex)
  1084. {
  1085. _logger.ErrorException("Error deleting recording", ex);
  1086. }
  1087. }
  1088. }
  1089. private async Task DeleteLibraryItemForTimer(TimerInfo timer)
  1090. {
  1091. var libraryItem = _libraryManager.FindByPath(timer.RecordingPath, false);
  1092. if (libraryItem != null)
  1093. {
  1094. await _libraryManager.DeleteItem(libraryItem, new DeleteOptions
  1095. {
  1096. DeleteFileLocation = true
  1097. });
  1098. }
  1099. else
  1100. {
  1101. try
  1102. {
  1103. File.Delete(timer.RecordingPath);
  1104. }
  1105. catch (DirectoryNotFoundException)
  1106. {
  1107. }
  1108. catch (FileNotFoundException)
  1109. {
  1110. }
  1111. }
  1112. _timerProvider.Delete(timer);
  1113. }
  1114. private string EnsureFileUnique(string path, string timerId)
  1115. {
  1116. var originalPath = path;
  1117. var index = 1;
  1118. while (FileExists(path, timerId))
  1119. {
  1120. var parent = Path.GetDirectoryName(originalPath);
  1121. var name = Path.GetFileNameWithoutExtension(originalPath);
  1122. name += "-" + index.ToString(CultureInfo.InvariantCulture);
  1123. path = Path.ChangeExtension(Path.Combine(parent, name), Path.GetExtension(originalPath));
  1124. index++;
  1125. }
  1126. return path;
  1127. }
  1128. private bool FileExists(string path, string timerId)
  1129. {
  1130. if (_fileSystem.FileExists(path))
  1131. {
  1132. return true;
  1133. }
  1134. var hasRecordingAtPath = _activeRecordings.Values.ToList().Any(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.TimerId, timerId, StringComparison.OrdinalIgnoreCase));
  1135. if (hasRecordingAtPath)
  1136. {
  1137. return true;
  1138. }
  1139. return false;
  1140. }
  1141. private async Task<IRecorder> GetRecorder()
  1142. {
  1143. var config = GetConfiguration();
  1144. if (config.EnableRecordingEncoding)
  1145. {
  1146. var regInfo = await _liveTvManager.GetRegistrationInfo("embytvrecordingconversion").ConfigureAwait(false);
  1147. if (regInfo.IsValid)
  1148. {
  1149. return new EncodedRecorder(_logger, _fileSystem, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, config, _httpClient);
  1150. }
  1151. }
  1152. return new DirectRecorder(_logger, _httpClient, _fileSystem);
  1153. }
  1154. private async void OnSuccessfulRecording(TimerInfo timer, string path)
  1155. {
  1156. if (timer.IsProgramSeries && GetConfiguration().EnableAutoOrganize)
  1157. {
  1158. try
  1159. {
  1160. // this is to account for the library monitor holding a lock for additional time after the change is complete.
  1161. // ideally this shouldn't be hard-coded
  1162. await Task.Delay(30000).ConfigureAwait(false);
  1163. var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager);
  1164. var result = await organize.OrganizeEpisodeFile(path, _config.GetAutoOrganizeOptions(), false, CancellationToken.None).ConfigureAwait(false);
  1165. if (result.Status == FileSortingStatus.Success)
  1166. {
  1167. return;
  1168. }
  1169. }
  1170. catch (Exception ex)
  1171. {
  1172. _logger.ErrorException("Error processing new recording", ex);
  1173. }
  1174. }
  1175. }
  1176. private void SaveNfo(TimerInfo timer, string recordingPath, string seriesPath)
  1177. {
  1178. try
  1179. {
  1180. if (timer.IsProgramSeries)
  1181. {
  1182. SaveSeriesNfo(timer, recordingPath, seriesPath);
  1183. }
  1184. else if (!timer.IsMovie || timer.IsSports)
  1185. {
  1186. SaveVideoNfo(timer, recordingPath);
  1187. }
  1188. }
  1189. catch (Exception ex)
  1190. {
  1191. _logger.ErrorException("Error saving nfo", ex);
  1192. }
  1193. }
  1194. private void SaveSeriesNfo(TimerInfo timer, string recordingPath, string seriesPath)
  1195. {
  1196. var nfoPath = Path.Combine(seriesPath, "tvshow.nfo");
  1197. if (File.Exists(nfoPath))
  1198. {
  1199. return;
  1200. }
  1201. using (var stream = _fileSystem.GetFileStream(nfoPath, FileMode.Create, FileAccess.Write, FileShare.Read))
  1202. {
  1203. var settings = new XmlWriterSettings
  1204. {
  1205. Indent = true,
  1206. Encoding = Encoding.UTF8,
  1207. CloseOutput = false
  1208. };
  1209. using (XmlWriter writer = XmlWriter.Create(stream, settings))
  1210. {
  1211. writer.WriteStartDocument(true);
  1212. writer.WriteStartElement("tvshow");
  1213. if (!string.IsNullOrWhiteSpace(timer.Name))
  1214. {
  1215. writer.WriteElementString("title", timer.Name);
  1216. }
  1217. writer.WriteEndElement();
  1218. writer.WriteEndDocument();
  1219. }
  1220. }
  1221. }
  1222. public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
  1223. private void SaveVideoNfo(TimerInfo timer, string recordingPath)
  1224. {
  1225. var nfoPath = Path.ChangeExtension(recordingPath, ".nfo");
  1226. if (File.Exists(nfoPath))
  1227. {
  1228. return;
  1229. }
  1230. using (var stream = _fileSystem.GetFileStream(nfoPath, FileMode.Create, FileAccess.Write, FileShare.Read))
  1231. {
  1232. var settings = new XmlWriterSettings
  1233. {
  1234. Indent = true,
  1235. Encoding = Encoding.UTF8,
  1236. CloseOutput = false
  1237. };
  1238. using (XmlWriter writer = XmlWriter.Create(stream, settings))
  1239. {
  1240. writer.WriteStartDocument(true);
  1241. writer.WriteStartElement("movie");
  1242. if (!string.IsNullOrWhiteSpace(timer.Name))
  1243. {
  1244. writer.WriteElementString("title", timer.Name);
  1245. }
  1246. writer.WriteElementString("dateadded", DateTime.UtcNow.ToLocalTime().ToString(DateAddedFormat));
  1247. if (timer.ProductionYear.HasValue)
  1248. {
  1249. writer.WriteElementString("year", timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture));
  1250. }
  1251. if (!string.IsNullOrEmpty(timer.OfficialRating))
  1252. {
  1253. writer.WriteElementString("mpaa", timer.OfficialRating);
  1254. }
  1255. var overview = (timer.Overview ?? string.Empty)
  1256. .StripHtml()
  1257. .Replace("&quot;", "'");
  1258. writer.WriteElementString("plot", overview);
  1259. writer.WriteElementString("lockdata", true.ToString().ToLower());
  1260. if (timer.CommunityRating.HasValue)
  1261. {
  1262. writer.WriteElementString("rating", timer.CommunityRating.Value.ToString(CultureInfo.InvariantCulture));
  1263. }
  1264. if (timer.IsSports)
  1265. {
  1266. AddGenre(timer.Genres, "Sports");
  1267. }
  1268. if (timer.IsKids)
  1269. {
  1270. AddGenre(timer.Genres, "Kids");
  1271. }
  1272. if (timer.IsNews)
  1273. {
  1274. AddGenre(timer.Genres, "News");
  1275. }
  1276. foreach (var genre in timer.Genres)
  1277. {
  1278. writer.WriteElementString("genre", genre);
  1279. }
  1280. if (!string.IsNullOrWhiteSpace(timer.ShortOverview))
  1281. {
  1282. writer.WriteElementString("outline", timer.ShortOverview);
  1283. }
  1284. if (!string.IsNullOrWhiteSpace(timer.HomePageUrl))
  1285. {
  1286. writer.WriteElementString("website", timer.HomePageUrl);
  1287. }
  1288. writer.WriteEndElement();
  1289. writer.WriteEndDocument();
  1290. }
  1291. }
  1292. }
  1293. private void AddGenre(List<string> genres, string genre)
  1294. {
  1295. if (!genres.Contains(genre, StringComparer.OrdinalIgnoreCase))
  1296. {
  1297. genres.Add(genre);
  1298. }
  1299. }
  1300. private ProgramInfo GetProgramInfoFromCache(string channelId, string programId)
  1301. {
  1302. var epgData = GetEpgDataForChannel(channelId);
  1303. return epgData.FirstOrDefault(p => string.Equals(p.Id, programId, StringComparison.OrdinalIgnoreCase));
  1304. }
  1305. private ProgramInfo GetProgramInfoFromCache(string channelId, DateTime startDateUtc)
  1306. {
  1307. var epgData = GetEpgDataForChannel(channelId);
  1308. var startDateTicks = startDateUtc.Ticks;
  1309. // Find the first program that starts within 3 minutes
  1310. return epgData.FirstOrDefault(p => Math.Abs(startDateTicks - p.StartDate.Ticks) <= TimeSpan.FromMinutes(3).Ticks);
  1311. }
  1312. private LiveTvOptions GetConfiguration()
  1313. {
  1314. return _config.GetConfiguration<LiveTvOptions>("livetv");
  1315. }
  1316. private bool ShouldCancelTimerForSeriesTimer(SeriesTimerInfo seriesTimer, TimerInfo timer)
  1317. {
  1318. return seriesTimer.SkipEpisodesInLibrary && IsProgramAlreadyInLibrary(timer);
  1319. }
  1320. private async Task UpdateTimersForSeriesTimer(List<ProgramInfo> epgData, SeriesTimerInfo seriesTimer, bool deleteInvalidTimers)
  1321. {
  1322. var allTimers = GetTimersForSeries(seriesTimer, epgData)
  1323. .ToList();
  1324. var registration = await _liveTvManager.GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
  1325. if (registration.IsValid)
  1326. {
  1327. foreach (var timer in allTimers)
  1328. {
  1329. var existingTimer = _timerProvider.GetTimer(timer.Id);
  1330. if (existingTimer == null)
  1331. {
  1332. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1333. {
  1334. timer.Status = RecordingStatus.Cancelled;
  1335. }
  1336. _timerProvider.Add(timer);
  1337. }
  1338. else
  1339. {
  1340. // Only update if not currently active
  1341. ActiveRecordingInfo activeRecordingInfo;
  1342. if (!_activeRecordings.TryGetValue(timer.Id, out activeRecordingInfo))
  1343. {
  1344. UpdateExistingTimerWithNewData(existingTimer, timer);
  1345. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1346. {
  1347. existingTimer.Status = RecordingStatus.Cancelled;
  1348. }
  1349. existingTimer.SeriesTimerId = seriesTimer.Id;
  1350. _timerProvider.Update(existingTimer);
  1351. }
  1352. }
  1353. }
  1354. }
  1355. if (deleteInvalidTimers)
  1356. {
  1357. var allTimerIds = allTimers
  1358. .Select(i => i.Id)
  1359. .ToList();
  1360. var deleteStatuses = new List<RecordingStatus>
  1361. {
  1362. RecordingStatus.New
  1363. };
  1364. var deletes = _timerProvider.GetAll()
  1365. .Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
  1366. .Where(i => !allTimerIds.Contains(i.Id, StringComparer.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
  1367. .Where(i => deleteStatuses.Contains(i.Status))
  1368. .ToList();
  1369. foreach (var timer in deletes)
  1370. {
  1371. CancelTimerInternal(timer.Id, false);
  1372. }
  1373. }
  1374. }
  1375. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer,
  1376. IEnumerable<ProgramInfo> allPrograms)
  1377. {
  1378. if (seriesTimer == null)
  1379. {
  1380. throw new ArgumentNullException("seriesTimer");
  1381. }
  1382. if (allPrograms == null)
  1383. {
  1384. throw new ArgumentNullException("allPrograms");
  1385. }
  1386. // Exclude programs that have already ended
  1387. allPrograms = allPrograms.Where(i => i.EndDate > DateTime.UtcNow);
  1388. allPrograms = GetProgramsForSeries(seriesTimer, allPrograms);
  1389. return allPrograms.Select(i => RecordingHelper.CreateTimer(i, seriesTimer));
  1390. }
  1391. private bool IsProgramAlreadyInLibrary(TimerInfo program)
  1392. {
  1393. if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle))
  1394. {
  1395. var seriesIds = _libraryManager.GetItemIds(new InternalItemsQuery
  1396. {
  1397. IncludeItemTypes = new[] { typeof(Series).Name },
  1398. Name = program.Name
  1399. }).Select(i => i.ToString("N")).ToArray();
  1400. if (seriesIds.Length == 0)
  1401. {
  1402. return false;
  1403. }
  1404. if (program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue)
  1405. {
  1406. var result = _libraryManager.GetItemsResult(new InternalItemsQuery
  1407. {
  1408. IncludeItemTypes = new[] { typeof(Episode).Name },
  1409. ParentIndexNumber = program.SeasonNumber.Value,
  1410. IndexNumber = program.EpisodeNumber.Value,
  1411. AncestorIds = seriesIds,
  1412. ExcludeLocationTypes = new[] { LocationType.Virtual }
  1413. });
  1414. if (result.TotalRecordCount > 0)
  1415. {
  1416. return true;
  1417. }
  1418. }
  1419. if (!string.IsNullOrWhiteSpace(program.EpisodeTitle))
  1420. {
  1421. var result = _libraryManager.GetItemsResult(new InternalItemsQuery
  1422. {
  1423. IncludeItemTypes = new[] { typeof(Episode).Name },
  1424. Name = program.EpisodeTitle,
  1425. AncestorIds = seriesIds,
  1426. ExcludeLocationTypes = new[] { LocationType.Virtual }
  1427. });
  1428. if (result.TotalRecordCount > 0)
  1429. {
  1430. return true;
  1431. }
  1432. }
  1433. }
  1434. return false;
  1435. }
  1436. private IEnumerable<ProgramInfo> GetProgramsForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  1437. {
  1438. if (!seriesTimer.RecordAnyTime)
  1439. {
  1440. allPrograms = allPrograms.Where(epg => Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - epg.StartDate.TimeOfDay.Ticks) < TimeSpan.FromMinutes(5).Ticks);
  1441. allPrograms = allPrograms.Where(i => seriesTimer.Days.Contains(i.StartDate.ToLocalTime().DayOfWeek));
  1442. }
  1443. if (seriesTimer.RecordNewOnly)
  1444. {
  1445. allPrograms = allPrograms.Where(epg => !epg.IsRepeat);
  1446. }
  1447. if (!seriesTimer.RecordAnyChannel)
  1448. {
  1449. allPrograms = allPrograms.Where(epg => string.Equals(epg.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase));
  1450. }
  1451. if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
  1452. {
  1453. _logger.Error("seriesTimer.SeriesId is null. Cannot find programs for series");
  1454. return new List<ProgramInfo>();
  1455. }
  1456. return allPrograms.Where(i => string.Equals(i.SeriesId, seriesTimer.SeriesId, StringComparison.OrdinalIgnoreCase));
  1457. }
  1458. private string GetChannelEpgCachePath(string channelId)
  1459. {
  1460. return Path.Combine(_config.CommonApplicationPaths.CachePath, "embytvepg", channelId + ".json");
  1461. }
  1462. private readonly object _epgLock = new object();
  1463. private void SaveEpgDataForChannel(string channelId, List<ProgramInfo> epgData)
  1464. {
  1465. var path = GetChannelEpgCachePath(channelId);
  1466. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  1467. lock (_epgLock)
  1468. {
  1469. _jsonSerializer.SerializeToFile(epgData, path);
  1470. }
  1471. }
  1472. private List<ProgramInfo> GetEpgDataForChannel(string channelId)
  1473. {
  1474. try
  1475. {
  1476. lock (_epgLock)
  1477. {
  1478. return _jsonSerializer.DeserializeFromFile<List<ProgramInfo>>(GetChannelEpgCachePath(channelId));
  1479. }
  1480. }
  1481. catch
  1482. {
  1483. return new List<ProgramInfo>();
  1484. }
  1485. }
  1486. private List<ProgramInfo> GetEpgDataForChannels(List<string> channelIds)
  1487. {
  1488. return channelIds.SelectMany(GetEpgDataForChannel).ToList();
  1489. }
  1490. private bool _disposed;
  1491. public void Dispose()
  1492. {
  1493. _disposed = true;
  1494. foreach (var pair in _activeRecordings.ToList())
  1495. {
  1496. pair.Value.CancellationTokenSource.Cancel();
  1497. }
  1498. }
  1499. public List<VirtualFolderInfo> GetRecordingFolders()
  1500. {
  1501. var list = new List<VirtualFolderInfo>();
  1502. var defaultFolder = RecordingPath;
  1503. var defaultName = "Recordings";
  1504. if (Directory.Exists(defaultFolder))
  1505. {
  1506. list.Add(new VirtualFolderInfo
  1507. {
  1508. Locations = new List<string> { defaultFolder },
  1509. Name = defaultName
  1510. });
  1511. }
  1512. var customPath = GetConfiguration().MovieRecordingPath;
  1513. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath))
  1514. {
  1515. list.Add(new VirtualFolderInfo
  1516. {
  1517. Locations = new List<string> { customPath },
  1518. Name = "Recorded Movies",
  1519. CollectionType = CollectionType.Movies
  1520. });
  1521. }
  1522. customPath = GetConfiguration().SeriesRecordingPath;
  1523. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath))
  1524. {
  1525. list.Add(new VirtualFolderInfo
  1526. {
  1527. Locations = new List<string> { customPath },
  1528. Name = "Recorded Series",
  1529. CollectionType = CollectionType.TvShows
  1530. });
  1531. }
  1532. return list;
  1533. }
  1534. class ActiveRecordingInfo
  1535. {
  1536. public string Path { get; set; }
  1537. public string TimerId { get; set; }
  1538. public CancellationTokenSource CancellationTokenSource { get; set; }
  1539. }
  1540. }
  1541. }