EmbyTV.cs 57 KB

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