EmbyTV.cs 73 KB

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