EmbyTV.cs 57 KB

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