EmbyTV.cs 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542
  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. using MediaBrowser.Model.Extensions;
  42. namespace Emby.Server.Implementations.LiveTv.EmbyTV
  43. {
  44. public class EmbyTV : ILiveTvService, ISupportsDirectStreamProvider, ISupportsNewTimerIds, IDisposable
  45. {
  46. private readonly IServerApplicationHost _appHost;
  47. private readonly ILogger _logger;
  48. private readonly IHttpClient _httpClient;
  49. private readonly IServerConfigurationManager _config;
  50. private readonly IJsonSerializer _jsonSerializer;
  51. private readonly ItemDataProvider<SeriesTimerInfo> _seriesTimerProvider;
  52. private readonly TimerManager _timerProvider;
  53. private readonly LiveTvManager _liveTvManager;
  54. private readonly IFileSystem _fileSystem;
  55. private readonly ILibraryMonitor _libraryMonitor;
  56. private readonly ILibraryManager _libraryManager;
  57. private readonly IProviderManager _providerManager;
  58. private readonly IFileOrganizationService _organizationService;
  59. private readonly IMediaEncoder _mediaEncoder;
  60. private readonly IProcessFactory _processFactory;
  61. private readonly ISystemEvents _systemEvents;
  62. public static EmbyTV Current;
  63. public event EventHandler DataSourceChanged;
  64. public event EventHandler<RecordingStatusChangedEventArgs> RecordingStatusChanged;
  65. private readonly ConcurrentDictionary<string, ActiveRecordingInfo> _activeRecordings =
  66. new ConcurrentDictionary<string, ActiveRecordingInfo>(StringComparer.OrdinalIgnoreCase);
  67. 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)
  68. {
  69. Current = this;
  70. _appHost = appHost;
  71. _logger = logger;
  72. _httpClient = httpClient;
  73. _config = config;
  74. _fileSystem = fileSystem;
  75. _libraryManager = libraryManager;
  76. _libraryMonitor = libraryMonitor;
  77. _providerManager = providerManager;
  78. _organizationService = organizationService;
  79. _mediaEncoder = mediaEncoder;
  80. _processFactory = processFactory;
  81. _systemEvents = systemEvents;
  82. _liveTvManager = (LiveTvManager)liveTvManager;
  83. _jsonSerializer = jsonSerializer;
  84. _seriesTimerProvider = new SeriesTimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers"));
  85. _timerProvider = new TimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "timers"), _logger, timerFactory);
  86. _timerProvider.TimerFired += _timerProvider_TimerFired;
  87. _config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated;
  88. }
  89. private void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e)
  90. {
  91. if (string.Equals(e.Key, "livetv", StringComparison.OrdinalIgnoreCase))
  92. {
  93. OnRecordingFoldersChanged();
  94. }
  95. }
  96. public void Start()
  97. {
  98. _timerProvider.RestartTimers();
  99. _systemEvents.Resume += _systemEvents_Resume;
  100. CreateRecordingFolders();
  101. }
  102. private void _systemEvents_Resume(object sender, EventArgs e)
  103. {
  104. _timerProvider.RestartTimers();
  105. }
  106. private void OnRecordingFoldersChanged()
  107. {
  108. CreateRecordingFolders();
  109. }
  110. internal void CreateRecordingFolders()
  111. {
  112. try
  113. {
  114. CreateRecordingFoldersInternal();
  115. }
  116. catch (Exception ex)
  117. {
  118. _logger.ErrorException("Error creating recording folders", ex);
  119. }
  120. }
  121. internal void CreateRecordingFoldersInternal()
  122. {
  123. var recordingFolders = GetRecordingFolders();
  124. var virtualFolders = _libraryManager.GetVirtualFolders()
  125. .ToList();
  126. var allExistingPaths = virtualFolders.SelectMany(i => i.Locations).ToList();
  127. var pathsAdded = new List<string>();
  128. foreach (var recordingFolder in recordingFolders)
  129. {
  130. var pathsToCreate = recordingFolder.Locations
  131. .Where(i => !allExistingPaths.Any(p => _fileSystem.AreEqual(p, i)))
  132. .ToList();
  133. if (pathsToCreate.Count == 0)
  134. {
  135. continue;
  136. }
  137. var mediaPathInfos = pathsToCreate.Select(i => new MediaPathInfo { Path = i }).ToArray();
  138. var libraryOptions = new LibraryOptions
  139. {
  140. PathInfos = mediaPathInfos
  141. };
  142. try
  143. {
  144. _libraryManager.AddVirtualFolder(recordingFolder.Name, recordingFolder.CollectionType, libraryOptions, true);
  145. }
  146. catch (Exception ex)
  147. {
  148. _logger.ErrorException("Error creating virtual folder", ex);
  149. }
  150. pathsAdded.AddRange(pathsToCreate);
  151. }
  152. var config = GetConfiguration();
  153. var pathsToRemove = config.MediaLocationsCreated
  154. .Except(recordingFolders.SelectMany(i => i.Locations))
  155. .ToList();
  156. if (pathsAdded.Count > 0 || pathsToRemove.Count > 0)
  157. {
  158. pathsAdded.InsertRange(0, config.MediaLocationsCreated);
  159. config.MediaLocationsCreated = pathsAdded.Except(pathsToRemove).Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
  160. _config.SaveConfiguration("livetv", config);
  161. }
  162. foreach (var path in pathsToRemove)
  163. {
  164. RemovePathFromLibrary(path);
  165. }
  166. }
  167. private void RemovePathFromLibrary(string path)
  168. {
  169. _logger.Debug("Removing path from library: {0}", path);
  170. var requiresRefresh = false;
  171. var virtualFolders = _libraryManager.GetVirtualFolders()
  172. .ToList();
  173. foreach (var virtualFolder in virtualFolders)
  174. {
  175. if (!virtualFolder.Locations.Contains(path, StringComparer.OrdinalIgnoreCase))
  176. {
  177. continue;
  178. }
  179. if (virtualFolder.Locations.Count == 1)
  180. {
  181. // remove entire virtual folder
  182. try
  183. {
  184. _libraryManager.RemoveVirtualFolder(virtualFolder.Name, true);
  185. }
  186. catch (Exception ex)
  187. {
  188. _logger.ErrorException("Error removing virtual folder", ex);
  189. }
  190. }
  191. else
  192. {
  193. try
  194. {
  195. _libraryManager.RemoveMediaPath(virtualFolder.Name, path);
  196. requiresRefresh = true;
  197. }
  198. catch (Exception ex)
  199. {
  200. _logger.ErrorException("Error removing media path", ex);
  201. }
  202. }
  203. }
  204. if (requiresRefresh)
  205. {
  206. _libraryManager.ValidateMediaLibrary(new Progress<Double>(), CancellationToken.None);
  207. }
  208. }
  209. public string Name
  210. {
  211. get { return "Emby"; }
  212. }
  213. public string DataPath
  214. {
  215. get { return Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv"); }
  216. }
  217. private string DefaultRecordingPath
  218. {
  219. get
  220. {
  221. return Path.Combine(DataPath, "recordings");
  222. }
  223. }
  224. private string RecordingPath
  225. {
  226. get
  227. {
  228. var path = GetConfiguration().RecordingPath;
  229. return string.IsNullOrWhiteSpace(path)
  230. ? DefaultRecordingPath
  231. : path;
  232. }
  233. }
  234. public string HomePageUrl
  235. {
  236. get { return "http://emby.media"; }
  237. }
  238. public async Task<LiveTvServiceStatusInfo> GetStatusInfoAsync(CancellationToken cancellationToken)
  239. {
  240. var status = new LiveTvServiceStatusInfo();
  241. var list = new List<LiveTvTunerInfo>();
  242. foreach (var hostInstance in _liveTvManager.TunerHosts)
  243. {
  244. try
  245. {
  246. var tuners = await hostInstance.GetTunerInfos(cancellationToken).ConfigureAwait(false);
  247. list.AddRange(tuners);
  248. }
  249. catch (Exception ex)
  250. {
  251. _logger.ErrorException("Error getting tuners", ex);
  252. }
  253. }
  254. status.Tuners = list;
  255. status.Status = LiveTvServiceStatus.Ok;
  256. status.Version = _appHost.ApplicationVersion.ToString();
  257. status.IsVisible = false;
  258. return status;
  259. }
  260. public async Task RefreshSeriesTimers(CancellationToken cancellationToken, IProgress<double> progress)
  261. {
  262. var seriesTimers = await GetSeriesTimersAsync(cancellationToken).ConfigureAwait(false);
  263. List<ChannelInfo> channels = null;
  264. foreach (var timer in seriesTimers)
  265. {
  266. List<ProgramInfo> epgData;
  267. if (timer.RecordAnyChannel)
  268. {
  269. if (channels == null)
  270. {
  271. channels = (await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false)).ToList();
  272. }
  273. var channelIds = channels.Select(i => i.Id).ToList();
  274. epgData = GetEpgDataForChannels(channelIds);
  275. }
  276. else
  277. {
  278. epgData = GetEpgDataForChannel(timer.ChannelId);
  279. }
  280. await UpdateTimersForSeriesTimer(epgData, timer, false, true).ConfigureAwait(false);
  281. }
  282. }
  283. public async Task RefreshTimers(CancellationToken cancellationToken, IProgress<double> progress)
  284. {
  285. var timers = await GetTimersAsync(cancellationToken).ConfigureAwait(false);
  286. foreach (var timer in timers)
  287. {
  288. if (DateTime.UtcNow > timer.EndDate && !_activeRecordings.ContainsKey(timer.Id))
  289. {
  290. OnTimerOutOfDate(timer);
  291. continue;
  292. }
  293. if (string.IsNullOrWhiteSpace(timer.ProgramId) || string.IsNullOrWhiteSpace(timer.ChannelId))
  294. {
  295. continue;
  296. }
  297. var epg = GetEpgDataForChannel(timer.ChannelId);
  298. var program = epg.FirstOrDefault(i => string.Equals(i.Id, timer.ProgramId, StringComparison.OrdinalIgnoreCase));
  299. if (program == null)
  300. {
  301. OnTimerOutOfDate(timer);
  302. continue;
  303. }
  304. RecordingHelper.CopyProgramInfoToTimerInfo(program, timer);
  305. _timerProvider.Update(timer);
  306. }
  307. }
  308. private void OnTimerOutOfDate(TimerInfo timer)
  309. {
  310. _timerProvider.Delete(timer);
  311. }
  312. private async Task<IEnumerable<ChannelInfo>> GetChannelsAsync(bool enableCache, CancellationToken cancellationToken)
  313. {
  314. var list = new List<ChannelInfo>();
  315. foreach (var hostInstance in _liveTvManager.TunerHosts)
  316. {
  317. try
  318. {
  319. var channels = await hostInstance.GetChannels(enableCache, cancellationToken).ConfigureAwait(false);
  320. list.AddRange(channels);
  321. }
  322. catch (Exception ex)
  323. {
  324. _logger.ErrorException("Error getting channels", ex);
  325. }
  326. }
  327. foreach (var provider in GetListingProviders())
  328. {
  329. var enabledChannels = list
  330. .Where(i => IsListingProviderEnabledForTuner(provider.Item2, i.TunerHostId))
  331. .ToList();
  332. if (enabledChannels.Count > 0)
  333. {
  334. try
  335. {
  336. await AddMetadata(provider.Item1, provider.Item2, enabledChannels, enableCache, cancellationToken).ConfigureAwait(false);
  337. }
  338. catch (NotSupportedException)
  339. {
  340. }
  341. catch (Exception ex)
  342. {
  343. _logger.ErrorException("Error adding metadata", ex);
  344. }
  345. }
  346. }
  347. return list;
  348. }
  349. private async Task AddMetadata(IListingsProvider provider, ListingsProviderInfo info, List<ChannelInfo> tunerChannels, bool enableCache, CancellationToken cancellationToken)
  350. {
  351. var epgChannels = await GetEpgChannels(provider, info, enableCache, cancellationToken).ConfigureAwait(false);
  352. foreach (var tunerChannel in tunerChannels)
  353. {
  354. var epgChannel = GetEpgChannelFromTunerChannel(info, tunerChannel, epgChannels);
  355. if (epgChannel != null)
  356. {
  357. if (!string.IsNullOrWhiteSpace(epgChannel.Name))
  358. {
  359. tunerChannel.Name = epgChannel.Name;
  360. }
  361. if (!string.IsNullOrWhiteSpace(epgChannel.ImageUrl))
  362. {
  363. tunerChannel.ImageUrl = epgChannel.ImageUrl;
  364. tunerChannel.HasImage = true;
  365. }
  366. }
  367. }
  368. }
  369. private readonly ConcurrentDictionary<string, List<ChannelInfo>> _epgChannels =
  370. new ConcurrentDictionary<string, List<ChannelInfo>>(StringComparer.OrdinalIgnoreCase);
  371. private async Task<List<ChannelInfo>> GetEpgChannels(IListingsProvider provider, ListingsProviderInfo info, bool enableCache, CancellationToken cancellationToken)
  372. {
  373. List<ChannelInfo> result;
  374. if (!enableCache || !_epgChannels.TryGetValue(info.Id, out result))
  375. {
  376. result = await provider.GetChannels(info, cancellationToken).ConfigureAwait(false);
  377. _epgChannels.AddOrUpdate(info.Id, result, (k, v) => result);
  378. }
  379. return result;
  380. }
  381. private async Task<ChannelInfo> GetEpgChannelFromTunerChannel(IListingsProvider provider, ListingsProviderInfo info, ChannelInfo tunerChannel, CancellationToken cancellationToken)
  382. {
  383. var epgChannels = await GetEpgChannels(provider, info, true, cancellationToken).ConfigureAwait(false);
  384. return GetEpgChannelFromTunerChannel(info, tunerChannel, epgChannels);
  385. }
  386. private string GetMappedChannel(string channelId, List<NameValuePair> mappings)
  387. {
  388. foreach (NameValuePair mapping in mappings)
  389. {
  390. if (StringHelper.EqualsIgnoreCase(mapping.Name, channelId))
  391. {
  392. return mapping.Value;
  393. }
  394. }
  395. return channelId;
  396. }
  397. private ChannelInfo GetEpgChannelFromTunerChannel(ListingsProviderInfo info, ChannelInfo tunerChannel, List<ChannelInfo> epgChannels)
  398. {
  399. return GetEpgChannelFromTunerChannel(info.ChannelMappings.ToList(), tunerChannel, epgChannels);
  400. }
  401. public ChannelInfo GetEpgChannelFromTunerChannel(List<NameValuePair> mappings, ChannelInfo tunerChannel, List<ChannelInfo> epgChannels)
  402. {
  403. if (!string.IsNullOrWhiteSpace(tunerChannel.Id))
  404. {
  405. var mappedTunerChannelId = GetMappedChannel(tunerChannel.Id, mappings);
  406. if (string.IsNullOrWhiteSpace(mappedTunerChannelId))
  407. {
  408. mappedTunerChannelId = tunerChannel.Id;
  409. }
  410. var channel = epgChannels.FirstOrDefault(i => string.Equals(mappedTunerChannelId, i.Id, StringComparison.OrdinalIgnoreCase));
  411. if (channel != null)
  412. {
  413. return channel;
  414. }
  415. }
  416. if (!string.IsNullOrWhiteSpace(tunerChannel.TunerChannelId))
  417. {
  418. var mappedTunerChannelId = GetMappedChannel(tunerChannel.TunerChannelId, mappings);
  419. if (string.IsNullOrWhiteSpace(mappedTunerChannelId))
  420. {
  421. mappedTunerChannelId = tunerChannel.TunerChannelId;
  422. }
  423. var channel = epgChannels.FirstOrDefault(i => string.Equals(mappedTunerChannelId, i.Id, StringComparison.OrdinalIgnoreCase));
  424. if (channel != null)
  425. {
  426. return channel;
  427. }
  428. }
  429. if (!string.IsNullOrWhiteSpace(tunerChannel.Number))
  430. {
  431. var tunerChannelNumber = GetMappedChannel(tunerChannel.Number, mappings);
  432. if (string.IsNullOrWhiteSpace(tunerChannelNumber))
  433. {
  434. tunerChannelNumber = tunerChannel.Number;
  435. }
  436. var channel = epgChannels.FirstOrDefault(i => string.Equals(tunerChannelNumber, i.Number, StringComparison.OrdinalIgnoreCase));
  437. if (channel != null)
  438. {
  439. return channel;
  440. }
  441. }
  442. if (!string.IsNullOrWhiteSpace(tunerChannel.Name))
  443. {
  444. var normalizedName = NormalizeName(tunerChannel.Name);
  445. var channel = epgChannels.FirstOrDefault(i => string.Equals(normalizedName, NormalizeName(i.Name ?? string.Empty), StringComparison.OrdinalIgnoreCase));
  446. if (channel != null)
  447. {
  448. return channel;
  449. }
  450. }
  451. return null;
  452. }
  453. private string NormalizeName(string value)
  454. {
  455. return value.Replace(" ", string.Empty).Replace("-", string.Empty);
  456. }
  457. public async Task<List<ChannelInfo>> GetChannelsForListingsProvider(ListingsProviderInfo listingsProvider, CancellationToken cancellationToken)
  458. {
  459. var list = new List<ChannelInfo>();
  460. foreach (var hostInstance in _liveTvManager.TunerHosts)
  461. {
  462. try
  463. {
  464. var channels = await hostInstance.GetChannels(false, cancellationToken).ConfigureAwait(false);
  465. list.AddRange(channels);
  466. }
  467. catch (Exception ex)
  468. {
  469. _logger.ErrorException("Error getting channels", ex);
  470. }
  471. }
  472. return list
  473. .Where(i => IsListingProviderEnabledForTuner(listingsProvider, i.TunerHostId))
  474. .ToList();
  475. }
  476. public Task<IEnumerable<ChannelInfo>> GetChannelsAsync(CancellationToken cancellationToken)
  477. {
  478. return GetChannelsAsync(false, cancellationToken);
  479. }
  480. public Task CancelSeriesTimerAsync(string timerId, CancellationToken cancellationToken)
  481. {
  482. var timers = _timerProvider
  483. .GetAll()
  484. .Where(i => string.Equals(i.SeriesTimerId, timerId, StringComparison.OrdinalIgnoreCase))
  485. .ToList();
  486. foreach (var timer in timers)
  487. {
  488. CancelTimerInternal(timer.Id, true);
  489. }
  490. var remove = _seriesTimerProvider.GetAll().FirstOrDefault(r => string.Equals(r.Id, timerId, StringComparison.OrdinalIgnoreCase));
  491. if (remove != null)
  492. {
  493. _seriesTimerProvider.Delete(remove);
  494. }
  495. return Task.FromResult(true);
  496. }
  497. private void CancelTimerInternal(string timerId, bool isSeriesCancelled)
  498. {
  499. var timer = _timerProvider.GetTimer(timerId);
  500. if (timer != null)
  501. {
  502. if (string.IsNullOrWhiteSpace(timer.SeriesTimerId) || isSeriesCancelled)
  503. {
  504. _timerProvider.Delete(timer);
  505. }
  506. else
  507. {
  508. timer.Status = RecordingStatus.Cancelled;
  509. _timerProvider.AddOrUpdate(timer, false);
  510. }
  511. }
  512. ActiveRecordingInfo activeRecordingInfo;
  513. if (_activeRecordings.TryGetValue(timerId, out activeRecordingInfo))
  514. {
  515. activeRecordingInfo.CancellationTokenSource.Cancel();
  516. }
  517. }
  518. public Task CancelTimerAsync(string timerId, CancellationToken cancellationToken)
  519. {
  520. CancelTimerInternal(timerId, false);
  521. return Task.FromResult(true);
  522. }
  523. public Task DeleteRecordingAsync(string recordingId, CancellationToken cancellationToken)
  524. {
  525. return Task.FromResult(true);
  526. }
  527. public Task CreateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  528. {
  529. throw new NotImplementedException();
  530. }
  531. public Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken)
  532. {
  533. throw new NotImplementedException();
  534. }
  535. public Task<string> CreateTimer(TimerInfo timer, CancellationToken cancellationToken)
  536. {
  537. var existingTimer = _timerProvider.GetAll()
  538. .FirstOrDefault(i => string.Equals(timer.ProgramId, i.ProgramId, StringComparison.OrdinalIgnoreCase));
  539. if (existingTimer != null)
  540. {
  541. if (existingTimer.Status == RecordingStatus.Cancelled ||
  542. existingTimer.Status == RecordingStatus.Completed)
  543. {
  544. existingTimer.Status = RecordingStatus.New;
  545. existingTimer.IsManual = true;
  546. _timerProvider.Update(existingTimer);
  547. return Task.FromResult(existingTimer.Id);
  548. }
  549. else
  550. {
  551. throw new ArgumentException("A scheduled recording already exists for this program.");
  552. }
  553. }
  554. timer.Id = Guid.NewGuid().ToString("N");
  555. ProgramInfo programInfo = null;
  556. if (!string.IsNullOrWhiteSpace(timer.ProgramId))
  557. {
  558. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  559. }
  560. if (programInfo == null)
  561. {
  562. _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  563. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  564. }
  565. if (programInfo != null)
  566. {
  567. RecordingHelper.CopyProgramInfoToTimerInfo(programInfo, timer);
  568. }
  569. timer.IsManual = true;
  570. _timerProvider.Add(timer);
  571. return Task.FromResult(timer.Id);
  572. }
  573. public async Task<string> CreateSeriesTimer(SeriesTimerInfo info, CancellationToken cancellationToken)
  574. {
  575. info.Id = Guid.NewGuid().ToString("N");
  576. List<ProgramInfo> epgData;
  577. if (info.RecordAnyChannel)
  578. {
  579. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  580. var channelIds = channels.Select(i => i.Id).ToList();
  581. epgData = GetEpgDataForChannels(channelIds);
  582. }
  583. else
  584. {
  585. epgData = GetEpgDataForChannel(info.ChannelId);
  586. }
  587. // populate info.seriesID
  588. var program = epgData.FirstOrDefault(i => string.Equals(i.Id, info.ProgramId, StringComparison.OrdinalIgnoreCase));
  589. if (program != null)
  590. {
  591. info.SeriesId = program.SeriesId;
  592. }
  593. else
  594. {
  595. throw new InvalidOperationException("SeriesId for program not found");
  596. }
  597. _seriesTimerProvider.Add(info);
  598. await UpdateTimersForSeriesTimer(epgData, info, true, false).ConfigureAwait(false);
  599. return info.Id;
  600. }
  601. public async Task UpdateSeriesTimerAsync(SeriesTimerInfo info, CancellationToken cancellationToken)
  602. {
  603. var instance = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, info.Id, StringComparison.OrdinalIgnoreCase));
  604. if (instance != null)
  605. {
  606. instance.ChannelId = info.ChannelId;
  607. instance.Days = info.Days;
  608. instance.EndDate = info.EndDate;
  609. instance.IsPostPaddingRequired = info.IsPostPaddingRequired;
  610. instance.IsPrePaddingRequired = info.IsPrePaddingRequired;
  611. instance.PostPaddingSeconds = info.PostPaddingSeconds;
  612. instance.PrePaddingSeconds = info.PrePaddingSeconds;
  613. instance.Priority = info.Priority;
  614. instance.RecordAnyChannel = info.RecordAnyChannel;
  615. instance.RecordAnyTime = info.RecordAnyTime;
  616. instance.RecordNewOnly = info.RecordNewOnly;
  617. instance.SkipEpisodesInLibrary = info.SkipEpisodesInLibrary;
  618. instance.KeepUpTo = info.KeepUpTo;
  619. instance.KeepUntil = info.KeepUntil;
  620. instance.StartDate = info.StartDate;
  621. _seriesTimerProvider.Update(instance);
  622. List<ProgramInfo> epgData;
  623. if (instance.RecordAnyChannel)
  624. {
  625. var channels = await GetChannelsAsync(true, CancellationToken.None).ConfigureAwait(false);
  626. var channelIds = channels.Select(i => i.Id).ToList();
  627. epgData = GetEpgDataForChannels(channelIds);
  628. }
  629. else
  630. {
  631. epgData = GetEpgDataForChannel(instance.ChannelId);
  632. }
  633. await UpdateTimersForSeriesTimer(epgData, instance, true, true).ConfigureAwait(false);
  634. }
  635. }
  636. public Task UpdateTimerAsync(TimerInfo updatedTimer, CancellationToken cancellationToken)
  637. {
  638. var existingTimer = _timerProvider.GetTimer(updatedTimer.Id);
  639. if (existingTimer == null)
  640. {
  641. throw new ResourceNotFoundException();
  642. }
  643. // Only update if not currently active
  644. ActiveRecordingInfo activeRecordingInfo;
  645. if (!_activeRecordings.TryGetValue(updatedTimer.Id, out activeRecordingInfo))
  646. {
  647. existingTimer.PrePaddingSeconds = updatedTimer.PrePaddingSeconds;
  648. existingTimer.PostPaddingSeconds = updatedTimer.PostPaddingSeconds;
  649. existingTimer.IsPostPaddingRequired = updatedTimer.IsPostPaddingRequired;
  650. existingTimer.IsPrePaddingRequired = updatedTimer.IsPrePaddingRequired;
  651. _timerProvider.Update(existingTimer);
  652. }
  653. return Task.FromResult(true);
  654. }
  655. private void UpdateExistingTimerWithNewMetadata(TimerInfo existingTimer, TimerInfo updatedTimer)
  656. {
  657. // Update the program info but retain the status
  658. existingTimer.ChannelId = updatedTimer.ChannelId;
  659. existingTimer.CommunityRating = updatedTimer.CommunityRating;
  660. existingTimer.EndDate = updatedTimer.EndDate;
  661. existingTimer.EpisodeNumber = updatedTimer.EpisodeNumber;
  662. existingTimer.EpisodeTitle = updatedTimer.EpisodeTitle;
  663. existingTimer.Genres = updatedTimer.Genres;
  664. existingTimer.HomePageUrl = updatedTimer.HomePageUrl;
  665. existingTimer.IsKids = updatedTimer.IsKids;
  666. existingTimer.IsNews = updatedTimer.IsNews;
  667. existingTimer.IsMovie = updatedTimer.IsMovie;
  668. existingTimer.IsProgramSeries = updatedTimer.IsProgramSeries;
  669. existingTimer.IsRepeat = updatedTimer.IsRepeat;
  670. existingTimer.IsSports = updatedTimer.IsSports;
  671. existingTimer.Name = updatedTimer.Name;
  672. existingTimer.OfficialRating = updatedTimer.OfficialRating;
  673. existingTimer.OriginalAirDate = updatedTimer.OriginalAirDate;
  674. existingTimer.Overview = updatedTimer.Overview;
  675. existingTimer.ProductionYear = updatedTimer.ProductionYear;
  676. existingTimer.ProgramId = updatedTimer.ProgramId;
  677. existingTimer.SeasonNumber = updatedTimer.SeasonNumber;
  678. existingTimer.StartDate = updatedTimer.StartDate;
  679. existingTimer.ShowId = updatedTimer.ShowId;
  680. }
  681. public Task<ImageStream> GetChannelImageAsync(string channelId, CancellationToken cancellationToken)
  682. {
  683. throw new NotImplementedException();
  684. }
  685. public Task<ImageStream> GetRecordingImageAsync(string recordingId, CancellationToken cancellationToken)
  686. {
  687. throw new NotImplementedException();
  688. }
  689. public Task<ImageStream> GetProgramImageAsync(string programId, string channelId, CancellationToken cancellationToken)
  690. {
  691. throw new NotImplementedException();
  692. }
  693. public async Task<IEnumerable<RecordingInfo>> GetRecordingsAsync(CancellationToken cancellationToken)
  694. {
  695. return _activeRecordings.Values.ToList().Select(GetRecordingInfo).ToList();
  696. }
  697. public string GetActiveRecordingPath(string id)
  698. {
  699. ActiveRecordingInfo info;
  700. if (_activeRecordings.TryGetValue(id, out info))
  701. {
  702. return info.Path;
  703. }
  704. return null;
  705. }
  706. private RecordingInfo GetRecordingInfo(ActiveRecordingInfo info)
  707. {
  708. var timer = info.Timer;
  709. var program = info.Program;
  710. var result = new RecordingInfo
  711. {
  712. ChannelId = timer.ChannelId,
  713. CommunityRating = timer.CommunityRating,
  714. DateLastUpdated = DateTime.UtcNow,
  715. EndDate = timer.EndDate,
  716. EpisodeTitle = timer.EpisodeTitle,
  717. Genres = timer.Genres,
  718. Id = "recording" + timer.Id,
  719. IsKids = timer.IsKids,
  720. IsMovie = timer.IsMovie,
  721. IsNews = timer.IsNews,
  722. IsRepeat = timer.IsRepeat,
  723. IsSeries = timer.IsProgramSeries,
  724. IsSports = timer.IsSports,
  725. Name = timer.Name,
  726. OfficialRating = timer.OfficialRating,
  727. OriginalAirDate = timer.OriginalAirDate,
  728. Overview = timer.Overview,
  729. ProgramId = timer.ProgramId,
  730. SeriesTimerId = timer.SeriesTimerId,
  731. StartDate = timer.StartDate,
  732. Status = RecordingStatus.InProgress,
  733. TimerId = timer.Id
  734. };
  735. if (program != null)
  736. {
  737. result.Audio = program.Audio;
  738. result.ImagePath = program.ImagePath;
  739. result.ImageUrl = program.ImageUrl;
  740. result.IsHD = program.IsHD;
  741. result.IsLive = program.IsLive;
  742. result.IsPremiere = program.IsPremiere;
  743. result.ShowId = program.ShowId;
  744. }
  745. return result;
  746. }
  747. public Task<IEnumerable<TimerInfo>> GetTimersAsync(CancellationToken cancellationToken)
  748. {
  749. var excludeStatues = new List<RecordingStatus>
  750. {
  751. RecordingStatus.Completed
  752. };
  753. var timers = _timerProvider.GetAll()
  754. .Where(i => !excludeStatues.Contains(i.Status));
  755. return Task.FromResult(timers);
  756. }
  757. public Task<SeriesTimerInfo> GetNewTimerDefaultsAsync(CancellationToken cancellationToken, ProgramInfo program = null)
  758. {
  759. var config = GetConfiguration();
  760. var defaults = new SeriesTimerInfo()
  761. {
  762. PostPaddingSeconds = Math.Max(config.PostPaddingSeconds, 0),
  763. PrePaddingSeconds = Math.Max(config.PrePaddingSeconds, 0),
  764. RecordAnyChannel = false,
  765. RecordAnyTime = true,
  766. RecordNewOnly = true,
  767. Days = new List<DayOfWeek>
  768. {
  769. DayOfWeek.Sunday,
  770. DayOfWeek.Monday,
  771. DayOfWeek.Tuesday,
  772. DayOfWeek.Wednesday,
  773. DayOfWeek.Thursday,
  774. DayOfWeek.Friday,
  775. DayOfWeek.Saturday
  776. }
  777. };
  778. if (program != null)
  779. {
  780. defaults.SeriesId = program.SeriesId;
  781. defaults.ProgramId = program.Id;
  782. defaults.RecordNewOnly = !program.IsRepeat;
  783. }
  784. defaults.SkipEpisodesInLibrary = defaults.RecordNewOnly;
  785. defaults.KeepUntil = KeepUntil.UntilDeleted;
  786. return Task.FromResult(defaults);
  787. }
  788. public Task<IEnumerable<SeriesTimerInfo>> GetSeriesTimersAsync(CancellationToken cancellationToken)
  789. {
  790. return Task.FromResult((IEnumerable<SeriesTimerInfo>)_seriesTimerProvider.GetAll());
  791. }
  792. public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  793. {
  794. try
  795. {
  796. return await GetProgramsAsyncInternal(channelId, startDateUtc, endDateUtc, cancellationToken).ConfigureAwait(false);
  797. }
  798. catch (OperationCanceledException)
  799. {
  800. throw;
  801. }
  802. catch (Exception ex)
  803. {
  804. _logger.ErrorException("Error getting programs", ex);
  805. return GetEpgDataForChannel(channelId).Where(i => i.StartDate <= endDateUtc && i.EndDate >= startDateUtc);
  806. }
  807. }
  808. private bool IsListingProviderEnabledForTuner(ListingsProviderInfo info, string tunerHostId)
  809. {
  810. if (info.EnableAllTuners)
  811. {
  812. return true;
  813. }
  814. if (string.IsNullOrWhiteSpace(tunerHostId))
  815. {
  816. throw new ArgumentNullException("tunerHostId");
  817. }
  818. return info.EnabledTuners.Contains(tunerHostId, StringComparer.OrdinalIgnoreCase);
  819. }
  820. private async Task<IEnumerable<ProgramInfo>> GetProgramsAsyncInternal(string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken)
  821. {
  822. var channels = await GetChannelsAsync(true, cancellationToken).ConfigureAwait(false);
  823. var channel = channels.First(i => string.Equals(i.Id, channelId, StringComparison.OrdinalIgnoreCase));
  824. foreach (var provider in GetListingProviders())
  825. {
  826. if (!IsListingProviderEnabledForTuner(provider.Item2, channel.TunerHostId))
  827. {
  828. _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);
  829. continue;
  830. }
  831. _logger.Debug("Getting programs for channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Item1.Name, provider.Item2.ListingsId ?? string.Empty);
  832. var epgChannel = await GetEpgChannelFromTunerChannel(provider.Item1, provider.Item2, channel, cancellationToken).ConfigureAwait(false);
  833. List<ProgramInfo> programs;
  834. if (epgChannel == null)
  835. {
  836. programs = new List<ProgramInfo>();
  837. }
  838. else
  839. {
  840. programs = (await provider.Item1.GetProgramsAsync(provider.Item2, epgChannel.Id, startDateUtc, endDateUtc, cancellationToken)
  841. .ConfigureAwait(false)).ToList();
  842. }
  843. // Replace the value that came from the provider with a normalized value
  844. foreach (var program in programs)
  845. {
  846. program.ChannelId = channelId;
  847. if (provider.Item2.EnableNewProgramIds)
  848. {
  849. program.Id += "_" + channelId;
  850. }
  851. }
  852. if (programs.Count > 0)
  853. {
  854. SaveEpgDataForChannel(channelId, programs);
  855. return programs;
  856. }
  857. }
  858. return new List<ProgramInfo>();
  859. }
  860. private List<Tuple<IListingsProvider, ListingsProviderInfo>> GetListingProviders()
  861. {
  862. return GetConfiguration().ListingProviders
  863. .Select(i =>
  864. {
  865. var provider = _liveTvManager.ListingProviders.FirstOrDefault(l => string.Equals(l.Type, i.Type, StringComparison.OrdinalIgnoreCase));
  866. return provider == null ? null : new Tuple<IListingsProvider, ListingsProviderInfo>(provider, i);
  867. })
  868. .Where(i => i != null)
  869. .ToList();
  870. }
  871. public Task<MediaSourceInfo> GetRecordingStream(string recordingId, string streamId, CancellationToken cancellationToken)
  872. {
  873. throw new NotImplementedException();
  874. }
  875. private readonly SemaphoreSlim _liveStreamsSemaphore = new SemaphoreSlim(1, 1);
  876. private readonly List<LiveStream> _liveStreams = new List<LiveStream>();
  877. public async Task<MediaSourceInfo> GetChannelStream(string channelId, string streamId, CancellationToken cancellationToken)
  878. {
  879. var result = await GetChannelStreamWithDirectStreamProvider(channelId, streamId, cancellationToken).ConfigureAwait(false);
  880. return result.Item1;
  881. }
  882. public async Task<Tuple<MediaSourceInfo, IDirectStreamProvider>> GetChannelStreamWithDirectStreamProvider(string channelId, string streamId, CancellationToken cancellationToken)
  883. {
  884. var result = await GetChannelStreamInternal(channelId, streamId, cancellationToken).ConfigureAwait(false);
  885. return new Tuple<MediaSourceInfo, IDirectStreamProvider>(result.Item2, result.Item1 as IDirectStreamProvider);
  886. }
  887. private MediaSourceInfo CloneMediaSource(MediaSourceInfo mediaSource, bool enableStreamSharing)
  888. {
  889. var json = _jsonSerializer.SerializeToString(mediaSource);
  890. mediaSource = _jsonSerializer.DeserializeFromString<MediaSourceInfo>(json);
  891. mediaSource.Id = Guid.NewGuid().ToString("N") + "_" + mediaSource.Id;
  892. //if (mediaSource.DateLiveStreamOpened.HasValue && enableStreamSharing)
  893. //{
  894. // var ticks = (DateTime.UtcNow - mediaSource.DateLiveStreamOpened.Value).Ticks - TimeSpan.FromSeconds(10).Ticks;
  895. // ticks = Math.Max(0, ticks);
  896. // mediaSource.Path += "?t=" + ticks.ToString(CultureInfo.InvariantCulture) + "&s=" + mediaSource.DateLiveStreamOpened.Value.Ticks.ToString(CultureInfo.InvariantCulture);
  897. //}
  898. return mediaSource;
  899. }
  900. public async Task<LiveStream> GetLiveStream(string uniqueId)
  901. {
  902. await _liveStreamsSemaphore.WaitAsync().ConfigureAwait(false);
  903. try
  904. {
  905. return _liveStreams
  906. .FirstOrDefault(i => string.Equals(i.UniqueId, uniqueId, StringComparison.OrdinalIgnoreCase));
  907. }
  908. finally
  909. {
  910. _liveStreamsSemaphore.Release();
  911. }
  912. }
  913. private async Task<Tuple<LiveStream, MediaSourceInfo, ITunerHost>> GetChannelStreamInternal(string channelId, string streamId, CancellationToken cancellationToken)
  914. {
  915. _logger.Info("Streaming Channel " + channelId);
  916. await _liveStreamsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  917. try
  918. {
  919. var result = _liveStreams.FirstOrDefault(i => string.Equals(i.OriginalStreamId, streamId, StringComparison.OrdinalIgnoreCase));
  920. if (result != null && result.EnableStreamSharing)
  921. {
  922. var openedMediaSource = CloneMediaSource(result.OpenedMediaSource, result.EnableStreamSharing);
  923. result.SharedStreamIds.Add(openedMediaSource.Id);
  924. _logger.Info("Live stream {0} consumer count is now {1}", streamId, result.ConsumerCount);
  925. return new Tuple<LiveStream, MediaSourceInfo, ITunerHost>(result, openedMediaSource, result.TunerHost);
  926. }
  927. foreach (var hostInstance in _liveTvManager.TunerHosts)
  928. {
  929. try
  930. {
  931. result = await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false);
  932. var openedMediaSource = CloneMediaSource(result.OpenedMediaSource, result.EnableStreamSharing);
  933. result.SharedStreamIds.Add(openedMediaSource.Id);
  934. _liveStreams.Add(result);
  935. result.TunerHost = hostInstance;
  936. result.OriginalStreamId = streamId;
  937. _logger.Info("Returning mediasource streamId {0}, mediaSource.Id {1}, mediaSource.LiveStreamId {2}",
  938. streamId, openedMediaSource.Id, openedMediaSource.LiveStreamId);
  939. return new Tuple<LiveStream, MediaSourceInfo, ITunerHost>(result, openedMediaSource, hostInstance);
  940. }
  941. catch (FileNotFoundException)
  942. {
  943. }
  944. catch (OperationCanceledException)
  945. {
  946. }
  947. }
  948. }
  949. finally
  950. {
  951. _liveStreamsSemaphore.Release();
  952. }
  953. throw new Exception("Tuner not found.");
  954. }
  955. public async Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken)
  956. {
  957. if (string.IsNullOrWhiteSpace(channelId))
  958. {
  959. throw new ArgumentNullException("channelId");
  960. }
  961. foreach (var hostInstance in _liveTvManager.TunerHosts)
  962. {
  963. try
  964. {
  965. var sources = await hostInstance.GetChannelStreamMediaSources(channelId, cancellationToken).ConfigureAwait(false);
  966. if (sources.Count > 0)
  967. {
  968. return sources;
  969. }
  970. }
  971. catch (NotImplementedException)
  972. {
  973. }
  974. }
  975. throw new NotImplementedException();
  976. }
  977. public async Task<List<MediaSourceInfo>> GetRecordingStreamMediaSources(string recordingId, CancellationToken cancellationToken)
  978. {
  979. ActiveRecordingInfo info;
  980. recordingId = recordingId.Replace("recording", string.Empty);
  981. if (_activeRecordings.TryGetValue(recordingId, out info))
  982. {
  983. var stream = new MediaSourceInfo
  984. {
  985. Path = _appHost.GetLocalApiUrl("127.0.0.1") + "/LiveTv/LiveRecordings/" + recordingId + "/stream",
  986. Id = recordingId,
  987. SupportsDirectPlay = false,
  988. SupportsDirectStream = true,
  989. SupportsTranscoding = true,
  990. IsInfiniteStream = true,
  991. RequiresOpening = false,
  992. RequiresClosing = false,
  993. Protocol = MediaBrowser.Model.MediaInfo.MediaProtocol.Http,
  994. BufferMs = 0
  995. };
  996. var isAudio = false;
  997. await new LiveStreamHelper(_mediaEncoder, _logger).AddMediaInfoWithProbe(stream, isAudio, cancellationToken).ConfigureAwait(false);
  998. return new List<MediaSourceInfo>
  999. {
  1000. stream
  1001. };
  1002. }
  1003. throw new FileNotFoundException();
  1004. }
  1005. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  1006. {
  1007. // Ignore the consumer id
  1008. //id = id.Substring(id.IndexOf('_') + 1);
  1009. await _liveStreamsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  1010. try
  1011. {
  1012. var stream = _liveStreams.FirstOrDefault(i => i.SharedStreamIds.Contains(id));
  1013. if (stream != null)
  1014. {
  1015. stream.SharedStreamIds.Remove(id);
  1016. _logger.Info("Live stream {0} consumer count is now {1}", id, stream.ConsumerCount);
  1017. if (stream.ConsumerCount <= 0)
  1018. {
  1019. _liveStreams.Remove(stream);
  1020. _logger.Info("Closing live stream {0}", id);
  1021. await stream.Close().ConfigureAwait(false);
  1022. _logger.Info("Live stream {0} closed successfully", id);
  1023. }
  1024. }
  1025. else
  1026. {
  1027. _logger.Warn("Live stream not found: {0}, unable to close", id);
  1028. }
  1029. }
  1030. catch (OperationCanceledException)
  1031. {
  1032. }
  1033. catch (Exception ex)
  1034. {
  1035. _logger.ErrorException("Error closing live stream", ex);
  1036. }
  1037. finally
  1038. {
  1039. _liveStreamsSemaphore.Release();
  1040. }
  1041. }
  1042. public Task RecordLiveStream(string id, CancellationToken cancellationToken)
  1043. {
  1044. return Task.FromResult(0);
  1045. }
  1046. public Task ResetTuner(string id, CancellationToken cancellationToken)
  1047. {
  1048. return Task.FromResult(0);
  1049. }
  1050. async void _timerProvider_TimerFired(object sender, GenericEventArgs<TimerInfo> e)
  1051. {
  1052. var timer = e.Argument;
  1053. _logger.Info("Recording timer fired.");
  1054. try
  1055. {
  1056. var recordingEndDate = timer.EndDate.AddSeconds(timer.PostPaddingSeconds);
  1057. if (recordingEndDate <= DateTime.UtcNow)
  1058. {
  1059. _logger.Warn("Recording timer fired for updatedTimer {0}, Id: {1}, but the program has already ended.", timer.Name, timer.Id);
  1060. OnTimerOutOfDate(timer);
  1061. return;
  1062. }
  1063. var activeRecordingInfo = new ActiveRecordingInfo
  1064. {
  1065. CancellationTokenSource = new CancellationTokenSource(),
  1066. Timer = timer
  1067. };
  1068. if (_activeRecordings.TryAdd(timer.Id, activeRecordingInfo))
  1069. {
  1070. await RecordStream(timer, recordingEndDate, activeRecordingInfo, activeRecordingInfo.CancellationTokenSource.Token).ConfigureAwait(false);
  1071. }
  1072. else
  1073. {
  1074. _logger.Info("Skipping RecordStream because it's already in progress.");
  1075. }
  1076. }
  1077. catch (OperationCanceledException)
  1078. {
  1079. }
  1080. catch (Exception ex)
  1081. {
  1082. _logger.ErrorException("Error recording stream", ex);
  1083. }
  1084. }
  1085. private string GetRecordingPath(TimerInfo timer, out string seriesPath)
  1086. {
  1087. var recordPath = RecordingPath;
  1088. var config = GetConfiguration();
  1089. seriesPath = null;
  1090. if (timer.IsProgramSeries)
  1091. {
  1092. var customRecordingPath = config.SeriesRecordingPath;
  1093. var allowSubfolder = true;
  1094. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  1095. {
  1096. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  1097. recordPath = customRecordingPath;
  1098. }
  1099. if (allowSubfolder && config.EnableRecordingSubfolders)
  1100. {
  1101. recordPath = Path.Combine(recordPath, "Series");
  1102. }
  1103. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  1104. // Can't use the year here in the folder name because it is the year of the episode, not the series.
  1105. recordPath = Path.Combine(recordPath, folderName);
  1106. seriesPath = recordPath;
  1107. if (timer.SeasonNumber.HasValue)
  1108. {
  1109. folderName = string.Format("Season {0}", timer.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture));
  1110. recordPath = Path.Combine(recordPath, folderName);
  1111. }
  1112. }
  1113. else if (timer.IsMovie)
  1114. {
  1115. var customRecordingPath = config.MovieRecordingPath;
  1116. var allowSubfolder = true;
  1117. if (!string.IsNullOrWhiteSpace(customRecordingPath))
  1118. {
  1119. allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase);
  1120. recordPath = customRecordingPath;
  1121. }
  1122. if (allowSubfolder && config.EnableRecordingSubfolders)
  1123. {
  1124. recordPath = Path.Combine(recordPath, "Movies");
  1125. }
  1126. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  1127. if (timer.ProductionYear.HasValue)
  1128. {
  1129. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  1130. }
  1131. recordPath = Path.Combine(recordPath, folderName);
  1132. }
  1133. else if (timer.IsKids)
  1134. {
  1135. if (config.EnableRecordingSubfolders)
  1136. {
  1137. recordPath = Path.Combine(recordPath, "Kids");
  1138. }
  1139. var folderName = _fileSystem.GetValidFilename(timer.Name).Trim();
  1140. if (timer.ProductionYear.HasValue)
  1141. {
  1142. folderName += " (" + timer.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")";
  1143. }
  1144. recordPath = Path.Combine(recordPath, folderName);
  1145. }
  1146. else if (timer.IsSports)
  1147. {
  1148. if (config.EnableRecordingSubfolders)
  1149. {
  1150. recordPath = Path.Combine(recordPath, "Sports");
  1151. }
  1152. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  1153. }
  1154. else
  1155. {
  1156. if (config.EnableRecordingSubfolders)
  1157. {
  1158. recordPath = Path.Combine(recordPath, "Other");
  1159. }
  1160. recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(timer.Name).Trim());
  1161. }
  1162. var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer)).Trim() + ".ts";
  1163. return Path.Combine(recordPath, recordingFileName);
  1164. }
  1165. private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate,
  1166. ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken)
  1167. {
  1168. if (timer == null)
  1169. {
  1170. throw new ArgumentNullException("timer");
  1171. }
  1172. ProgramInfo programInfo = null;
  1173. if (!string.IsNullOrWhiteSpace(timer.ProgramId))
  1174. {
  1175. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId);
  1176. }
  1177. if (programInfo == null)
  1178. {
  1179. _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId);
  1180. programInfo = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate);
  1181. }
  1182. if (programInfo != null)
  1183. {
  1184. RecordingHelper.CopyProgramInfoToTimerInfo(programInfo, timer);
  1185. activeRecordingInfo.Program = programInfo;
  1186. }
  1187. string seriesPath = null;
  1188. var recordPath = GetRecordingPath(timer, out seriesPath);
  1189. var recordingStatus = RecordingStatus.New;
  1190. string liveStreamId = null;
  1191. OnRecordingStatusChanged();
  1192. try
  1193. {
  1194. var recorder = await GetRecorder().ConfigureAwait(false);
  1195. var allMediaSources = await GetChannelStreamMediaSources(timer.ChannelId, CancellationToken.None).ConfigureAwait(false);
  1196. var liveStreamInfo = await GetChannelStreamInternal(timer.ChannelId, allMediaSources[0].Id, CancellationToken.None)
  1197. .ConfigureAwait(false);
  1198. var mediaStreamInfo = liveStreamInfo.Item2;
  1199. liveStreamId = mediaStreamInfo.Id;
  1200. // HDHR doesn't seem to release the tuner right away after first probing with ffmpeg
  1201. //await Task.Delay(3000, cancellationToken).ConfigureAwait(false);
  1202. recordPath = recorder.GetOutputPath(mediaStreamInfo, recordPath);
  1203. recordPath = EnsureFileUnique(recordPath, timer.Id);
  1204. _libraryManager.RegisterIgnoredPath(recordPath);
  1205. _libraryMonitor.ReportFileSystemChangeBeginning(recordPath);
  1206. _fileSystem.CreateDirectory(Path.GetDirectoryName(recordPath));
  1207. activeRecordingInfo.Path = recordPath;
  1208. var duration = recordingEndDate - DateTime.UtcNow;
  1209. _logger.Info("Beginning recording. Will record for {0} minutes.",
  1210. duration.TotalMinutes.ToString(CultureInfo.InvariantCulture));
  1211. _logger.Info("Writing file to path: " + recordPath);
  1212. _logger.Info("Opening recording stream from tuner provider");
  1213. Action onStarted = () =>
  1214. {
  1215. timer.Status = RecordingStatus.InProgress;
  1216. _timerProvider.AddOrUpdate(timer, false);
  1217. SaveRecordingMetadata(timer, recordPath, seriesPath);
  1218. EnforceKeepUpTo(timer);
  1219. };
  1220. await recorder.Record(mediaStreamInfo, recordPath, duration, onStarted, cancellationToken)
  1221. .ConfigureAwait(false);
  1222. recordingStatus = RecordingStatus.Completed;
  1223. _logger.Info("Recording completed: {0}", recordPath);
  1224. }
  1225. catch (OperationCanceledException)
  1226. {
  1227. _logger.Info("Recording stopped: {0}", recordPath);
  1228. recordingStatus = RecordingStatus.Completed;
  1229. }
  1230. catch (Exception ex)
  1231. {
  1232. _logger.ErrorException("Error recording to {0}", ex, recordPath);
  1233. recordingStatus = RecordingStatus.Error;
  1234. }
  1235. if (!string.IsNullOrWhiteSpace(liveStreamId))
  1236. {
  1237. try
  1238. {
  1239. await CloseLiveStream(liveStreamId, CancellationToken.None).ConfigureAwait(false);
  1240. }
  1241. catch (Exception ex)
  1242. {
  1243. _logger.ErrorException("Error closing live stream", ex);
  1244. }
  1245. }
  1246. _libraryManager.UnRegisterIgnoredPath(recordPath);
  1247. _libraryMonitor.ReportFileSystemChangeComplete(recordPath, true);
  1248. ActiveRecordingInfo removed;
  1249. _activeRecordings.TryRemove(timer.Id, out removed);
  1250. if (recordingStatus != RecordingStatus.Completed && DateTime.UtcNow < timer.EndDate && timer.RetryCount < 10)
  1251. {
  1252. const int retryIntervalSeconds = 60;
  1253. _logger.Info("Retrying recording in {0} seconds.", retryIntervalSeconds);
  1254. timer.Status = RecordingStatus.New;
  1255. timer.StartDate = DateTime.UtcNow.AddSeconds(retryIntervalSeconds);
  1256. timer.RetryCount++;
  1257. _timerProvider.AddOrUpdate(timer);
  1258. }
  1259. else if (_fileSystem.FileExists(recordPath))
  1260. {
  1261. timer.RecordingPath = recordPath;
  1262. timer.Status = RecordingStatus.Completed;
  1263. _timerProvider.AddOrUpdate(timer, false);
  1264. OnSuccessfulRecording(timer, recordPath);
  1265. }
  1266. else
  1267. {
  1268. _timerProvider.Delete(timer);
  1269. }
  1270. OnRecordingStatusChanged();
  1271. }
  1272. private void OnRecordingStatusChanged()
  1273. {
  1274. EventHelper.FireEventIfNotNull(RecordingStatusChanged, this, new RecordingStatusChangedEventArgs
  1275. {
  1276. }, _logger);
  1277. }
  1278. private async void EnforceKeepUpTo(TimerInfo timer)
  1279. {
  1280. if (string.IsNullOrWhiteSpace(timer.SeriesTimerId))
  1281. {
  1282. return;
  1283. }
  1284. var seriesTimerId = timer.SeriesTimerId;
  1285. var seriesTimer = _seriesTimerProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, seriesTimerId, StringComparison.OrdinalIgnoreCase));
  1286. if (seriesTimer == null || seriesTimer.KeepUpTo <= 1)
  1287. {
  1288. return;
  1289. }
  1290. if (_disposed)
  1291. {
  1292. return;
  1293. }
  1294. await _recordingDeleteSemaphore.WaitAsync().ConfigureAwait(false);
  1295. try
  1296. {
  1297. if (_disposed)
  1298. {
  1299. return;
  1300. }
  1301. var timersToDelete = _timerProvider.GetAll()
  1302. .Where(i => i.Status == RecordingStatus.Completed && !string.IsNullOrWhiteSpace(i.RecordingPath))
  1303. .Where(i => string.Equals(i.SeriesTimerId, seriesTimerId, StringComparison.OrdinalIgnoreCase))
  1304. .OrderByDescending(i => i.EndDate)
  1305. .Where(i => _fileSystem.FileExists(i.RecordingPath))
  1306. .Skip(seriesTimer.KeepUpTo - 1)
  1307. .ToList();
  1308. await DeleteLibraryItemsForTimers(timersToDelete).ConfigureAwait(false);
  1309. }
  1310. finally
  1311. {
  1312. _recordingDeleteSemaphore.Release();
  1313. }
  1314. }
  1315. private readonly SemaphoreSlim _recordingDeleteSemaphore = new SemaphoreSlim(1, 1);
  1316. private async Task DeleteLibraryItemsForTimers(List<TimerInfo> timers)
  1317. {
  1318. foreach (var timer in timers)
  1319. {
  1320. if (_disposed)
  1321. {
  1322. return;
  1323. }
  1324. try
  1325. {
  1326. await DeleteLibraryItemForTimer(timer).ConfigureAwait(false);
  1327. }
  1328. catch (Exception ex)
  1329. {
  1330. _logger.ErrorException("Error deleting recording", ex);
  1331. }
  1332. }
  1333. }
  1334. private async Task DeleteLibraryItemForTimer(TimerInfo timer)
  1335. {
  1336. var libraryItem = _libraryManager.FindByPath(timer.RecordingPath, false);
  1337. if (libraryItem != null)
  1338. {
  1339. await _libraryManager.DeleteItem(libraryItem, new DeleteOptions
  1340. {
  1341. DeleteFileLocation = true
  1342. });
  1343. }
  1344. else
  1345. {
  1346. try
  1347. {
  1348. _fileSystem.DeleteFile(timer.RecordingPath);
  1349. }
  1350. catch (IOException)
  1351. {
  1352. }
  1353. }
  1354. _timerProvider.Delete(timer);
  1355. }
  1356. private string EnsureFileUnique(string path, string timerId)
  1357. {
  1358. var originalPath = path;
  1359. var index = 1;
  1360. while (FileExists(path, timerId))
  1361. {
  1362. var parent = Path.GetDirectoryName(originalPath);
  1363. var name = Path.GetFileNameWithoutExtension(originalPath);
  1364. name += "-" + index.ToString(CultureInfo.InvariantCulture);
  1365. path = Path.ChangeExtension(Path.Combine(parent, name), Path.GetExtension(originalPath));
  1366. index++;
  1367. }
  1368. return path;
  1369. }
  1370. private bool FileExists(string path, string timerId)
  1371. {
  1372. if (_fileSystem.FileExists(path))
  1373. {
  1374. return true;
  1375. }
  1376. var hasRecordingAtPath = _activeRecordings
  1377. .Values
  1378. .ToList()
  1379. .Any(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase) && !string.Equals(i.Timer.Id, timerId, StringComparison.OrdinalIgnoreCase));
  1380. if (hasRecordingAtPath)
  1381. {
  1382. return true;
  1383. }
  1384. return false;
  1385. }
  1386. private async Task<IRecorder> GetRecorder()
  1387. {
  1388. var config = GetConfiguration();
  1389. if (config.EnableRecordingEncoding)
  1390. {
  1391. var regInfo = await _liveTvManager.GetRegistrationInfo("embytvrecordingconversion").ConfigureAwait(false);
  1392. if (regInfo.IsValid)
  1393. {
  1394. return new EncodedRecorder(_logger, _fileSystem, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, config, _httpClient, _processFactory);
  1395. }
  1396. }
  1397. return new DirectRecorder(_logger, _httpClient, _fileSystem);
  1398. }
  1399. private async void OnSuccessfulRecording(TimerInfo timer, string path)
  1400. {
  1401. //if (timer.IsProgramSeries && GetConfiguration().EnableAutoOrganize)
  1402. //{
  1403. // try
  1404. // {
  1405. // // this is to account for the library monitor holding a lock for additional time after the change is complete.
  1406. // // ideally this shouldn't be hard-coded
  1407. // await Task.Delay(30000).ConfigureAwait(false);
  1408. // var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager);
  1409. // var result = await organize.OrganizeEpisodeFile(path, _config.GetAutoOrganizeOptions(), false, CancellationToken.None).ConfigureAwait(false);
  1410. // if (result.Status == FileSortingStatus.Success)
  1411. // {
  1412. // return;
  1413. // }
  1414. // }
  1415. // catch (Exception ex)
  1416. // {
  1417. // _logger.ErrorException("Error processing new recording", ex);
  1418. // }
  1419. //}
  1420. PostProcessRecording(timer, path);
  1421. }
  1422. private void PostProcessRecording(TimerInfo timer, string path)
  1423. {
  1424. var options = GetConfiguration();
  1425. if (string.IsNullOrWhiteSpace(options.RecordingPostProcessor))
  1426. {
  1427. return;
  1428. }
  1429. try
  1430. {
  1431. var process = _processFactory.Create(new ProcessOptions
  1432. {
  1433. Arguments = GetPostProcessArguments(path, options.RecordingPostProcessorArguments),
  1434. CreateNoWindow = true,
  1435. EnableRaisingEvents = true,
  1436. ErrorDialog = false,
  1437. FileName = options.RecordingPostProcessor,
  1438. IsHidden = true,
  1439. UseShellExecute = false
  1440. });
  1441. _logger.Info("Running recording post processor {0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments);
  1442. process.Exited += Process_Exited;
  1443. process.Start();
  1444. }
  1445. catch (Exception ex)
  1446. {
  1447. _logger.ErrorException("Error running recording post processor", ex);
  1448. }
  1449. }
  1450. private string GetPostProcessArguments(string path, string arguments)
  1451. {
  1452. return arguments.Replace("{path}", path, StringComparison.OrdinalIgnoreCase);
  1453. }
  1454. private void Process_Exited(object sender, EventArgs e)
  1455. {
  1456. var process = (IProcess)sender;
  1457. try
  1458. {
  1459. _logger.Info("Recording post-processing script completed with exit code {0}", process.ExitCode);
  1460. }
  1461. catch
  1462. {
  1463. }
  1464. process.Dispose();
  1465. }
  1466. private async Task SaveRecordingImage(string recordingPath, LiveTvProgram program, ItemImageInfo image)
  1467. {
  1468. if (!image.IsLocalFile)
  1469. {
  1470. image = await _libraryManager.ConvertImageToLocal(program, image, 0).ConfigureAwait(false);
  1471. }
  1472. string imageSaveFilenameWithoutExtension = null;
  1473. switch (image.Type)
  1474. {
  1475. case ImageType.Primary:
  1476. if (program.IsSeries)
  1477. {
  1478. imageSaveFilenameWithoutExtension = Path.GetFileNameWithoutExtension(recordingPath) + "-thumb";
  1479. }
  1480. else
  1481. {
  1482. imageSaveFilenameWithoutExtension = "poster";
  1483. }
  1484. break;
  1485. case ImageType.Logo:
  1486. imageSaveFilenameWithoutExtension = "logo";
  1487. break;
  1488. case ImageType.Thumb:
  1489. imageSaveFilenameWithoutExtension = "landscape";
  1490. break;
  1491. case ImageType.Backdrop:
  1492. imageSaveFilenameWithoutExtension = "fanart";
  1493. break;
  1494. default:
  1495. break;
  1496. }
  1497. if (string.IsNullOrWhiteSpace(imageSaveFilenameWithoutExtension))
  1498. {
  1499. return;
  1500. }
  1501. var imageSavePath = Path.Combine(Path.GetDirectoryName(recordingPath), imageSaveFilenameWithoutExtension);
  1502. // preserve original image extension
  1503. imageSavePath = Path.ChangeExtension(imageSavePath, Path.GetExtension(image.Path));
  1504. _fileSystem.CopyFile(image.Path, imageSavePath, true);
  1505. }
  1506. private async Task SaveRecordingImages(string recordingPath, LiveTvProgram program)
  1507. {
  1508. var image = program.GetImageInfo(ImageType.Primary, 0);
  1509. if (image != null && program.IsMovie)
  1510. {
  1511. try
  1512. {
  1513. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1514. }
  1515. catch (Exception ex)
  1516. {
  1517. _logger.ErrorException("Error saving recording image", ex);
  1518. }
  1519. }
  1520. if (!program.IsSeries)
  1521. {
  1522. image = program.GetImageInfo(ImageType.Backdrop, 0);
  1523. if (image != null)
  1524. {
  1525. try
  1526. {
  1527. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1528. }
  1529. catch (Exception ex)
  1530. {
  1531. _logger.ErrorException("Error saving recording image", ex);
  1532. }
  1533. }
  1534. image = program.GetImageInfo(ImageType.Thumb, 0);
  1535. if (image != null)
  1536. {
  1537. try
  1538. {
  1539. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1540. }
  1541. catch (Exception ex)
  1542. {
  1543. _logger.ErrorException("Error saving recording image", ex);
  1544. }
  1545. }
  1546. image = program.GetImageInfo(ImageType.Logo, 0);
  1547. if (image != null)
  1548. {
  1549. try
  1550. {
  1551. await SaveRecordingImage(recordingPath, program, image).ConfigureAwait(false);
  1552. }
  1553. catch (Exception ex)
  1554. {
  1555. _logger.ErrorException("Error saving recording image", ex);
  1556. }
  1557. }
  1558. }
  1559. }
  1560. private async void SaveRecordingMetadata(TimerInfo timer, string recordingPath, string seriesPath)
  1561. {
  1562. try
  1563. {
  1564. var program = string.IsNullOrWhiteSpace(timer.ProgramId) ? null : _libraryManager.GetItemList(new InternalItemsQuery
  1565. {
  1566. IncludeItemTypes = new[] { typeof(LiveTvProgram).Name },
  1567. Limit = 1,
  1568. ExternalId = timer.ProgramId
  1569. }).FirstOrDefault() as LiveTvProgram;
  1570. // dummy this up
  1571. if (program == null)
  1572. {
  1573. program = new LiveTvProgram
  1574. {
  1575. Name = timer.Name,
  1576. HomePageUrl = timer.HomePageUrl,
  1577. Overview = timer.Overview,
  1578. Genres = timer.Genres,
  1579. CommunityRating = timer.CommunityRating,
  1580. OfficialRating = timer.OfficialRating,
  1581. ProductionYear = timer.ProductionYear,
  1582. PremiereDate = timer.OriginalAirDate,
  1583. IndexNumber = timer.EpisodeNumber,
  1584. ParentIndexNumber = timer.SeasonNumber
  1585. };
  1586. }
  1587. if (timer.IsSports)
  1588. {
  1589. AddGenre(program.Genres, "Sports");
  1590. }
  1591. if (timer.IsKids)
  1592. {
  1593. AddGenre(program.Genres, "Kids");
  1594. AddGenre(program.Genres, "Children");
  1595. }
  1596. if (timer.IsNews)
  1597. {
  1598. AddGenre(program.Genres, "News");
  1599. }
  1600. if (timer.IsProgramSeries)
  1601. {
  1602. SaveSeriesNfo(timer, seriesPath);
  1603. SaveVideoNfo(timer, recordingPath, program, false);
  1604. }
  1605. else if (!timer.IsMovie || timer.IsSports || timer.IsNews)
  1606. {
  1607. SaveVideoNfo(timer, recordingPath, program, true);
  1608. }
  1609. else
  1610. {
  1611. SaveVideoNfo(timer, recordingPath, program, false);
  1612. }
  1613. await SaveRecordingImages(recordingPath, program).ConfigureAwait(false);
  1614. }
  1615. catch (Exception ex)
  1616. {
  1617. _logger.ErrorException("Error saving nfo", ex);
  1618. }
  1619. }
  1620. private void SaveSeriesNfo(TimerInfo timer, string seriesPath)
  1621. {
  1622. var nfoPath = Path.Combine(seriesPath, "tvshow.nfo");
  1623. if (_fileSystem.FileExists(nfoPath))
  1624. {
  1625. return;
  1626. }
  1627. using (var stream = _fileSystem.GetFileStream(nfoPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  1628. {
  1629. var settings = new XmlWriterSettings
  1630. {
  1631. Indent = true,
  1632. Encoding = Encoding.UTF8,
  1633. CloseOutput = false
  1634. };
  1635. using (XmlWriter writer = XmlWriter.Create(stream, settings))
  1636. {
  1637. writer.WriteStartDocument(true);
  1638. writer.WriteStartElement("tvshow");
  1639. if (!string.IsNullOrWhiteSpace(timer.Name))
  1640. {
  1641. writer.WriteElementString("title", timer.Name);
  1642. }
  1643. if (!string.IsNullOrEmpty(timer.OfficialRating))
  1644. {
  1645. writer.WriteElementString("mpaa", timer.OfficialRating);
  1646. }
  1647. foreach (var genre in timer.Genres)
  1648. {
  1649. writer.WriteElementString("genre", genre);
  1650. }
  1651. writer.WriteEndElement();
  1652. writer.WriteEndDocument();
  1653. }
  1654. }
  1655. }
  1656. public const string DateAddedFormat = "yyyy-MM-dd HH:mm:ss";
  1657. private void SaveVideoNfo(TimerInfo timer, string recordingPath, BaseItem item, bool lockData)
  1658. {
  1659. var nfoPath = Path.ChangeExtension(recordingPath, ".nfo");
  1660. if (_fileSystem.FileExists(nfoPath))
  1661. {
  1662. return;
  1663. }
  1664. using (var stream = _fileSystem.GetFileStream(nfoPath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  1665. {
  1666. var settings = new XmlWriterSettings
  1667. {
  1668. Indent = true,
  1669. Encoding = Encoding.UTF8,
  1670. CloseOutput = false
  1671. };
  1672. var options = _config.GetNfoConfiguration();
  1673. using (XmlWriter writer = XmlWriter.Create(stream, settings))
  1674. {
  1675. writer.WriteStartDocument(true);
  1676. if (timer.IsProgramSeries)
  1677. {
  1678. writer.WriteStartElement("episodedetails");
  1679. if (!string.IsNullOrWhiteSpace(timer.EpisodeTitle))
  1680. {
  1681. writer.WriteElementString("title", timer.EpisodeTitle);
  1682. }
  1683. if (item.PremiereDate.HasValue)
  1684. {
  1685. var formatString = options.ReleaseDateFormat;
  1686. writer.WriteElementString("aired", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
  1687. }
  1688. if (item.IndexNumber.HasValue)
  1689. {
  1690. writer.WriteElementString("episode", item.IndexNumber.Value.ToString(CultureInfo.InvariantCulture));
  1691. }
  1692. if (item.ParentIndexNumber.HasValue)
  1693. {
  1694. writer.WriteElementString("season", item.ParentIndexNumber.Value.ToString(CultureInfo.InvariantCulture));
  1695. }
  1696. }
  1697. else
  1698. {
  1699. writer.WriteStartElement("movie");
  1700. if (!string.IsNullOrWhiteSpace(item.Name))
  1701. {
  1702. writer.WriteElementString("title", item.Name);
  1703. }
  1704. if (!string.IsNullOrWhiteSpace(item.OriginalTitle))
  1705. {
  1706. writer.WriteElementString("originaltitle", item.OriginalTitle);
  1707. }
  1708. if (item.PremiereDate.HasValue)
  1709. {
  1710. var formatString = options.ReleaseDateFormat;
  1711. writer.WriteElementString("premiered", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
  1712. writer.WriteElementString("releasedate", item.PremiereDate.Value.ToLocalTime().ToString(formatString));
  1713. }
  1714. }
  1715. writer.WriteElementString("dateadded", DateTime.UtcNow.ToLocalTime().ToString(DateAddedFormat));
  1716. if (item.ProductionYear.HasValue)
  1717. {
  1718. writer.WriteElementString("year", item.ProductionYear.Value.ToString(CultureInfo.InvariantCulture));
  1719. }
  1720. if (!string.IsNullOrEmpty(item.OfficialRating))
  1721. {
  1722. writer.WriteElementString("mpaa", item.OfficialRating);
  1723. }
  1724. if (!string.IsNullOrEmpty(item.OfficialRatingDescription))
  1725. {
  1726. writer.WriteElementString("mpaadescription", item.OfficialRatingDescription);
  1727. }
  1728. var overview = (item.Overview ?? string.Empty)
  1729. .StripHtml()
  1730. .Replace("&quot;", "'");
  1731. writer.WriteElementString("plot", overview);
  1732. if (lockData)
  1733. {
  1734. writer.WriteElementString("lockdata", true.ToString().ToLower());
  1735. }
  1736. if (item.CommunityRating.HasValue)
  1737. {
  1738. writer.WriteElementString("rating", item.CommunityRating.Value.ToString(CultureInfo.InvariantCulture));
  1739. }
  1740. foreach (var genre in item.Genres)
  1741. {
  1742. writer.WriteElementString("genre", genre);
  1743. }
  1744. if (!string.IsNullOrWhiteSpace(item.HomePageUrl))
  1745. {
  1746. writer.WriteElementString("website", item.HomePageUrl);
  1747. }
  1748. var people = item.Id == Guid.Empty ? new List<PersonInfo>() : _libraryManager.GetPeople(item);
  1749. var directors = people
  1750. .Where(i => IsPersonType(i, PersonType.Director))
  1751. .Select(i => i.Name)
  1752. .ToList();
  1753. foreach (var person in directors)
  1754. {
  1755. writer.WriteElementString("director", person);
  1756. }
  1757. var writers = people
  1758. .Where(i => IsPersonType(i, PersonType.Writer))
  1759. .Select(i => i.Name)
  1760. .Distinct(StringComparer.OrdinalIgnoreCase)
  1761. .ToList();
  1762. foreach (var person in writers)
  1763. {
  1764. writer.WriteElementString("writer", person);
  1765. }
  1766. foreach (var person in writers)
  1767. {
  1768. writer.WriteElementString("credits", person);
  1769. }
  1770. var tmdbCollection = item.GetProviderId(MetadataProviders.TmdbCollection);
  1771. if (!string.IsNullOrEmpty(tmdbCollection))
  1772. {
  1773. writer.WriteElementString("collectionnumber", tmdbCollection);
  1774. }
  1775. var imdb = item.GetProviderId(MetadataProviders.Imdb);
  1776. if (!string.IsNullOrEmpty(imdb))
  1777. {
  1778. if (item is Series)
  1779. {
  1780. writer.WriteElementString("imdb_id", imdb);
  1781. }
  1782. else
  1783. {
  1784. writer.WriteElementString("imdbid", imdb);
  1785. }
  1786. }
  1787. var tvdb = item.GetProviderId(MetadataProviders.Tvdb);
  1788. if (!string.IsNullOrEmpty(tvdb))
  1789. {
  1790. writer.WriteElementString("tvdbid", tvdb);
  1791. }
  1792. var tmdb = item.GetProviderId(MetadataProviders.Tmdb);
  1793. if (!string.IsNullOrEmpty(tmdb))
  1794. {
  1795. writer.WriteElementString("tmdbid", tmdb);
  1796. }
  1797. if (item.CriticRating.HasValue)
  1798. {
  1799. writer.WriteElementString("criticrating", item.CriticRating.Value.ToString(CultureInfo.InvariantCulture));
  1800. }
  1801. if (!string.IsNullOrEmpty(item.CriticRatingSummary))
  1802. {
  1803. writer.WriteElementString("criticratingsummary", item.CriticRatingSummary);
  1804. }
  1805. if (!string.IsNullOrWhiteSpace(item.Tagline))
  1806. {
  1807. writer.WriteElementString("tagline", item.Tagline);
  1808. }
  1809. foreach (var studio in item.Studios)
  1810. {
  1811. writer.WriteElementString("studio", studio);
  1812. }
  1813. if (item.VoteCount.HasValue)
  1814. {
  1815. writer.WriteElementString("votes", item.VoteCount.Value.ToString(CultureInfo.InvariantCulture));
  1816. }
  1817. writer.WriteEndElement();
  1818. writer.WriteEndDocument();
  1819. }
  1820. }
  1821. }
  1822. private static bool IsPersonType(PersonInfo person, string type)
  1823. {
  1824. return string.Equals(person.Type, type, StringComparison.OrdinalIgnoreCase) || string.Equals(person.Role, type, StringComparison.OrdinalIgnoreCase);
  1825. }
  1826. private void AddGenre(List<string> genres, string genre)
  1827. {
  1828. if (!genres.Contains(genre, StringComparer.OrdinalIgnoreCase))
  1829. {
  1830. genres.Add(genre);
  1831. }
  1832. }
  1833. private ProgramInfo GetProgramInfoFromCache(string channelId, string programId)
  1834. {
  1835. var epgData = GetEpgDataForChannel(channelId);
  1836. return epgData.FirstOrDefault(p => string.Equals(p.Id, programId, StringComparison.OrdinalIgnoreCase));
  1837. }
  1838. private ProgramInfo GetProgramInfoFromCache(string channelId, DateTime startDateUtc)
  1839. {
  1840. var epgData = GetEpgDataForChannel(channelId);
  1841. var startDateTicks = startDateUtc.Ticks;
  1842. // Find the first program that starts within 3 minutes
  1843. return epgData.FirstOrDefault(p => Math.Abs(startDateTicks - p.StartDate.Ticks) <= TimeSpan.FromMinutes(3).Ticks);
  1844. }
  1845. private LiveTvOptions GetConfiguration()
  1846. {
  1847. return _config.GetConfiguration<LiveTvOptions>("livetv");
  1848. }
  1849. private bool ShouldCancelTimerForSeriesTimer(SeriesTimerInfo seriesTimer, TimerInfo timer)
  1850. {
  1851. if (timer.IsManual)
  1852. {
  1853. return false;
  1854. }
  1855. if (!seriesTimer.RecordAnyTime)
  1856. {
  1857. if (Math.Abs(seriesTimer.StartDate.TimeOfDay.Ticks - timer.StartDate.TimeOfDay.Ticks) >= TimeSpan.FromMinutes(5).Ticks)
  1858. {
  1859. return true;
  1860. }
  1861. }
  1862. //if (!seriesTimer.Days.Contains(timer.StartDate.ToLocalTime().DayOfWeek))
  1863. //{
  1864. // return true;
  1865. //}
  1866. if (seriesTimer.RecordNewOnly && timer.IsRepeat)
  1867. {
  1868. return true;
  1869. }
  1870. if (!seriesTimer.RecordAnyChannel && !string.Equals(timer.ChannelId, seriesTimer.ChannelId, StringComparison.OrdinalIgnoreCase))
  1871. {
  1872. return true;
  1873. }
  1874. return seriesTimer.SkipEpisodesInLibrary && IsProgramAlreadyInLibrary(timer);
  1875. }
  1876. private void HandleDuplicateShowIds(List<TimerInfo> timers)
  1877. {
  1878. foreach (var timer in timers.Skip(1))
  1879. {
  1880. // TODO: Get smarter, prefer HD, etc
  1881. timer.Status = RecordingStatus.Cancelled;
  1882. _timerProvider.Update(timer);
  1883. }
  1884. }
  1885. private void SearchForDuplicateShowIds(List<TimerInfo> timers)
  1886. {
  1887. var groups = timers.ToLookup(i => i.ShowId ?? string.Empty).ToList();
  1888. foreach (var group in groups)
  1889. {
  1890. if (string.IsNullOrWhiteSpace(group.Key))
  1891. {
  1892. continue;
  1893. }
  1894. var groupTimers = group.ToList();
  1895. if (groupTimers.Count < 2)
  1896. {
  1897. continue;
  1898. }
  1899. HandleDuplicateShowIds(groupTimers);
  1900. }
  1901. }
  1902. private async Task UpdateTimersForSeriesTimer(List<ProgramInfo> epgData, SeriesTimerInfo seriesTimer, bool updateTimerSettings, bool deleteInvalidTimers)
  1903. {
  1904. var allTimers = GetTimersForSeries(seriesTimer, epgData)
  1905. .ToList();
  1906. var registration = await _liveTvManager.GetRegistrationInfo("seriesrecordings").ConfigureAwait(false);
  1907. var enabledTimersForSeries = new List<TimerInfo>();
  1908. if (registration.IsValid)
  1909. {
  1910. foreach (var timer in allTimers)
  1911. {
  1912. var existingTimer = _timerProvider.GetTimer(timer.Id);
  1913. if (existingTimer == null)
  1914. {
  1915. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1916. {
  1917. timer.Status = RecordingStatus.Cancelled;
  1918. }
  1919. else
  1920. {
  1921. enabledTimersForSeries.Add(timer);
  1922. }
  1923. _timerProvider.Add(timer);
  1924. }
  1925. else
  1926. {
  1927. // Only update if not currently active
  1928. ActiveRecordingInfo activeRecordingInfo;
  1929. if (!_activeRecordings.TryGetValue(timer.Id, out activeRecordingInfo))
  1930. {
  1931. UpdateExistingTimerWithNewMetadata(existingTimer, timer);
  1932. if (ShouldCancelTimerForSeriesTimer(seriesTimer, timer))
  1933. {
  1934. existingTimer.Status = RecordingStatus.Cancelled;
  1935. }
  1936. if (existingTimer.Status != RecordingStatus.Cancelled)
  1937. {
  1938. enabledTimersForSeries.Add(existingTimer);
  1939. }
  1940. if (updateTimerSettings)
  1941. {
  1942. existingTimer.KeepUntil = seriesTimer.KeepUntil;
  1943. existingTimer.IsPostPaddingRequired = seriesTimer.IsPostPaddingRequired;
  1944. existingTimer.IsPrePaddingRequired = seriesTimer.IsPrePaddingRequired;
  1945. existingTimer.PostPaddingSeconds = seriesTimer.PostPaddingSeconds;
  1946. existingTimer.PrePaddingSeconds = seriesTimer.PrePaddingSeconds;
  1947. existingTimer.Priority = seriesTimer.Priority;
  1948. }
  1949. existingTimer.SeriesTimerId = seriesTimer.Id;
  1950. _timerProvider.Update(existingTimer);
  1951. }
  1952. }
  1953. }
  1954. }
  1955. SearchForDuplicateShowIds(enabledTimersForSeries);
  1956. if (deleteInvalidTimers)
  1957. {
  1958. var allTimerIds = allTimers
  1959. .Select(i => i.Id)
  1960. .ToList();
  1961. var deleteStatuses = new List<RecordingStatus>
  1962. {
  1963. RecordingStatus.New
  1964. };
  1965. var deletes = _timerProvider.GetAll()
  1966. .Where(i => string.Equals(i.SeriesTimerId, seriesTimer.Id, StringComparison.OrdinalIgnoreCase))
  1967. .Where(i => !allTimerIds.Contains(i.Id, StringComparer.OrdinalIgnoreCase) && i.StartDate > DateTime.UtcNow)
  1968. .Where(i => deleteStatuses.Contains(i.Status))
  1969. .ToList();
  1970. foreach (var timer in deletes)
  1971. {
  1972. CancelTimerInternal(timer.Id, false);
  1973. }
  1974. }
  1975. }
  1976. private IEnumerable<TimerInfo> GetTimersForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  1977. {
  1978. if (seriesTimer == null)
  1979. {
  1980. throw new ArgumentNullException("seriesTimer");
  1981. }
  1982. if (allPrograms == null)
  1983. {
  1984. throw new ArgumentNullException("allPrograms");
  1985. }
  1986. // Exclude programs that have already ended
  1987. allPrograms = allPrograms.Where(i => i.EndDate > DateTime.UtcNow);
  1988. allPrograms = GetProgramsForSeries(seriesTimer, allPrograms);
  1989. return allPrograms.Select(i => RecordingHelper.CreateTimer(i, seriesTimer));
  1990. }
  1991. private bool IsProgramAlreadyInLibrary(TimerInfo program)
  1992. {
  1993. if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle))
  1994. {
  1995. var seriesIds = _libraryManager.GetItemIds(new InternalItemsQuery
  1996. {
  1997. IncludeItemTypes = new[] { typeof(Series).Name },
  1998. Name = program.Name
  1999. }).Select(i => i.ToString("N")).ToArray();
  2000. if (seriesIds.Length == 0)
  2001. {
  2002. return false;
  2003. }
  2004. if (program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue)
  2005. {
  2006. var result = _libraryManager.GetItemsResult(new InternalItemsQuery
  2007. {
  2008. IncludeItemTypes = new[] { typeof(Episode).Name },
  2009. ParentIndexNumber = program.SeasonNumber.Value,
  2010. IndexNumber = program.EpisodeNumber.Value,
  2011. AncestorIds = seriesIds,
  2012. IsVirtualItem = false
  2013. });
  2014. if (result.TotalRecordCount > 0)
  2015. {
  2016. return true;
  2017. }
  2018. }
  2019. }
  2020. return false;
  2021. }
  2022. private IEnumerable<ProgramInfo> GetProgramsForSeries(SeriesTimerInfo seriesTimer, IEnumerable<ProgramInfo> allPrograms)
  2023. {
  2024. if (string.IsNullOrWhiteSpace(seriesTimer.SeriesId))
  2025. {
  2026. _logger.Error("seriesTimer.SeriesId is null. Cannot find programs for series");
  2027. return new List<ProgramInfo>();
  2028. }
  2029. return allPrograms.Where(i => string.Equals(i.SeriesId, seriesTimer.SeriesId, StringComparison.OrdinalIgnoreCase));
  2030. }
  2031. private string GetChannelEpgCachePath(string channelId)
  2032. {
  2033. return Path.Combine(_config.CommonApplicationPaths.CachePath, "embytvepg", channelId + ".json");
  2034. }
  2035. private readonly object _epgLock = new object();
  2036. private void SaveEpgDataForChannel(string channelId, List<ProgramInfo> epgData)
  2037. {
  2038. var path = GetChannelEpgCachePath(channelId);
  2039. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  2040. lock (_epgLock)
  2041. {
  2042. _jsonSerializer.SerializeToFile(epgData, path);
  2043. }
  2044. }
  2045. private List<ProgramInfo> GetEpgDataForChannel(string channelId)
  2046. {
  2047. try
  2048. {
  2049. lock (_epgLock)
  2050. {
  2051. return _jsonSerializer.DeserializeFromFile<List<ProgramInfo>>(GetChannelEpgCachePath(channelId));
  2052. }
  2053. }
  2054. catch
  2055. {
  2056. return new List<ProgramInfo>();
  2057. }
  2058. }
  2059. private List<ProgramInfo> GetEpgDataForChannels(List<string> channelIds)
  2060. {
  2061. return channelIds.SelectMany(GetEpgDataForChannel).ToList();
  2062. }
  2063. private bool _disposed;
  2064. public void Dispose()
  2065. {
  2066. _disposed = true;
  2067. foreach (var pair in _activeRecordings.ToList())
  2068. {
  2069. pair.Value.CancellationTokenSource.Cancel();
  2070. }
  2071. }
  2072. public List<VirtualFolderInfo> GetRecordingFolders()
  2073. {
  2074. var list = new List<VirtualFolderInfo>();
  2075. var defaultFolder = RecordingPath;
  2076. var defaultName = "Recordings";
  2077. if (_fileSystem.DirectoryExists(defaultFolder))
  2078. {
  2079. list.Add(new VirtualFolderInfo
  2080. {
  2081. Locations = new List<string> { defaultFolder },
  2082. Name = defaultName
  2083. });
  2084. }
  2085. var customPath = GetConfiguration().MovieRecordingPath;
  2086. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && _fileSystem.DirectoryExists(customPath))
  2087. {
  2088. list.Add(new VirtualFolderInfo
  2089. {
  2090. Locations = new List<string> { customPath },
  2091. Name = "Recorded Movies",
  2092. CollectionType = CollectionType.Movies
  2093. });
  2094. }
  2095. customPath = GetConfiguration().SeriesRecordingPath;
  2096. if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && _fileSystem.DirectoryExists(customPath))
  2097. {
  2098. list.Add(new VirtualFolderInfo
  2099. {
  2100. Locations = new List<string> { customPath },
  2101. Name = "Recorded Series",
  2102. CollectionType = CollectionType.TvShows
  2103. });
  2104. }
  2105. return list;
  2106. }
  2107. class ActiveRecordingInfo
  2108. {
  2109. public string Path { get; set; }
  2110. public TimerInfo Timer { get; set; }
  2111. public ProgramInfo Program { get; set; }
  2112. public CancellationTokenSource CancellationTokenSource { get; set; }
  2113. }
  2114. }
  2115. public static class ConfigurationExtension
  2116. {
  2117. public static XbmcMetadataOptions GetNfoConfiguration(this IConfigurationManager manager)
  2118. {
  2119. return manager.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata");
  2120. }
  2121. }
  2122. }