EmbyTV.cs 53 KB

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