EmbyTV.cs 69 KB

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