EmbyTV.cs 75 KB

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