DashboardService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. #pragma warning disable CS1591
  2. #pragma warning disable SA1402
  3. #pragma warning disable SA1649
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics.CodeAnalysis;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Common.Extensions;
  11. using MediaBrowser.Common.Plugins;
  12. using MediaBrowser.Controller;
  13. using MediaBrowser.Controller.Configuration;
  14. using MediaBrowser.Controller.Extensions;
  15. using MediaBrowser.Controller.Net;
  16. using MediaBrowser.Controller.Plugins;
  17. using MediaBrowser.Model.IO;
  18. using MediaBrowser.Model.Net;
  19. using MediaBrowser.Model.Plugins;
  20. using MediaBrowser.Model.Services;
  21. using Microsoft.Extensions.Configuration;
  22. using Microsoft.Extensions.Logging;
  23. namespace MediaBrowser.WebDashboard.Api
  24. {
  25. /// <summary>
  26. /// Class GetDashboardConfigurationPages.
  27. /// </summary>
  28. [Route("/web/ConfigurationPages", "GET")]
  29. public class GetDashboardConfigurationPages : IReturn<List<ConfigurationPageInfo>>
  30. {
  31. /// <summary>
  32. /// Gets or sets the type of the page.
  33. /// </summary>
  34. /// <value>The type of the page.</value>
  35. public ConfigurationPageType? PageType { get; set; }
  36. public bool? EnableInMainMenu { get; set; }
  37. }
  38. /// <summary>
  39. /// Class GetDashboardConfigurationPage.
  40. /// </summary>
  41. [Route("/web/ConfigurationPage", "GET")]
  42. public class GetDashboardConfigurationPage
  43. {
  44. /// <summary>
  45. /// Gets or sets the name.
  46. /// </summary>
  47. /// <value>The name.</value>
  48. public string Name { get; set; }
  49. }
  50. [Route("/robots.txt", "GET", IsHidden = true)]
  51. public class GetRobotsTxt
  52. {
  53. }
  54. /// <summary>
  55. /// Class GetDashboardResource.
  56. /// </summary>
  57. [Route("/web/{ResourceName*}", "GET", IsHidden = true)]
  58. public class GetDashboardResource
  59. {
  60. /// <summary>
  61. /// Gets or sets the name.
  62. /// </summary>
  63. /// <value>The name.</value>
  64. public string ResourceName { get; set; }
  65. /// <summary>
  66. /// Gets or sets the V.
  67. /// </summary>
  68. /// <value>The V.</value>
  69. public string V { get; set; }
  70. }
  71. [Route("/favicon.ico", "GET", IsHidden = true)]
  72. public class GetFavIcon
  73. {
  74. }
  75. /// <summary>
  76. /// Class DashboardService.
  77. /// </summary>
  78. public class DashboardService : IService, IRequiresRequest
  79. {
  80. /// <summary>
  81. /// Gets or sets the logger.
  82. /// </summary>
  83. /// <value>The logger.</value>
  84. private readonly ILogger<DashboardService> _logger;
  85. /// <summary>
  86. /// Gets or sets the HTTP result factory.
  87. /// </summary>
  88. /// <value>The HTTP result factory.</value>
  89. private readonly IHttpResultFactory _resultFactory;
  90. private readonly IServerApplicationHost _appHost;
  91. private readonly IConfiguration _appConfig;
  92. private readonly IServerConfigurationManager _serverConfigurationManager;
  93. private readonly IFileSystem _fileSystem;
  94. private readonly IResourceFileManager _resourceFileManager;
  95. /// <summary>
  96. /// Initializes a new instance of the <see cref="DashboardService" /> class.
  97. /// </summary>
  98. /// <param name="logger">The logger.</param>
  99. /// <param name="appHost">The application host.</param>
  100. /// <param name="appConfig">The application configuration.</param>
  101. /// <param name="resourceFileManager">The resource file manager.</param>
  102. /// <param name="serverConfigurationManager">The server configuration manager.</param>
  103. /// <param name="fileSystem">The file system.</param>
  104. /// <param name="resultFactory">The result factory.</param>
  105. public DashboardService(
  106. ILogger<DashboardService> logger,
  107. IServerApplicationHost appHost,
  108. IConfiguration appConfig,
  109. IResourceFileManager resourceFileManager,
  110. IServerConfigurationManager serverConfigurationManager,
  111. IFileSystem fileSystem,
  112. IHttpResultFactory resultFactory)
  113. {
  114. _logger = logger;
  115. _appHost = appHost;
  116. _appConfig = appConfig;
  117. _resourceFileManager = resourceFileManager;
  118. _serverConfigurationManager = serverConfigurationManager;
  119. _fileSystem = fileSystem;
  120. _resultFactory = resultFactory;
  121. }
  122. /// <summary>
  123. /// Gets or sets the request context.
  124. /// </summary>
  125. /// <value>The request context.</value>
  126. public IRequest Request { get; set; }
  127. /// <summary>
  128. /// Gets the path of the directory containing the static web interface content, or null if the server is not
  129. /// hosting the web client.
  130. /// </summary>
  131. public string DashboardUIPath => GetDashboardUIPath(_appConfig, _serverConfigurationManager);
  132. /// <summary>
  133. /// Gets the path of the directory containing the static web interface content.
  134. /// </summary>
  135. /// <param name="appConfig">The app configuration.</param>
  136. /// <param name="serverConfigManager">The server configuration manager.</param>
  137. /// <returns>The directory path, or null if the server is not hosting the web client.</returns>
  138. public static string GetDashboardUIPath(IConfiguration appConfig, IServerConfigurationManager serverConfigManager)
  139. {
  140. if (!appConfig.HostWebClient())
  141. {
  142. return null;
  143. }
  144. if (!string.IsNullOrEmpty(serverConfigManager.Configuration.DashboardSourcePath))
  145. {
  146. return serverConfigManager.Configuration.DashboardSourcePath;
  147. }
  148. return serverConfigManager.ApplicationPaths.WebPath;
  149. }
  150. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request", Justification = "Required for ServiceStack")]
  151. public object Get(GetFavIcon request)
  152. {
  153. return Get(new GetDashboardResource
  154. {
  155. ResourceName = "favicon.ico"
  156. });
  157. }
  158. /// <summary>
  159. /// Gets the specified request.
  160. /// </summary>
  161. /// <param name="request">The request.</param>
  162. /// <returns>System.Object.</returns>
  163. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request", Justification = "Required for ServiceStack")]
  164. public Task<object> Get(GetDashboardConfigurationPage request)
  165. {
  166. IPlugin plugin = null;
  167. Stream stream = null;
  168. var isJs = false;
  169. var isTemplate = false;
  170. var page = ServerEntryPoint.Instance.PluginConfigurationPages.FirstOrDefault(p => string.Equals(p.Name, request.Name, StringComparison.OrdinalIgnoreCase));
  171. if (page != null)
  172. {
  173. plugin = page.Plugin;
  174. stream = page.GetHtmlStream();
  175. }
  176. if (plugin == null)
  177. {
  178. var altPage = GetPluginPages().FirstOrDefault(p => string.Equals(p.Item1.Name, request.Name, StringComparison.OrdinalIgnoreCase));
  179. if (altPage != null)
  180. {
  181. plugin = altPage.Item2;
  182. stream = plugin.GetType().Assembly.GetManifestResourceStream(altPage.Item1.EmbeddedResourcePath);
  183. isJs = string.Equals(Path.GetExtension(altPage.Item1.EmbeddedResourcePath), ".js", StringComparison.OrdinalIgnoreCase);
  184. isTemplate = altPage.Item1.EmbeddedResourcePath.EndsWith(".template.html", StringComparison.Ordinal);
  185. }
  186. }
  187. if (plugin != null && stream != null)
  188. {
  189. if (isJs)
  190. {
  191. return _resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.js"), () => Task.FromResult(stream));
  192. }
  193. if (isTemplate)
  194. {
  195. return _resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => Task.FromResult(stream));
  196. }
  197. return _resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => Task.FromResult(stream));
  198. }
  199. throw new ResourceNotFoundException();
  200. }
  201. /// <summary>
  202. /// Gets the specified request.
  203. /// </summary>
  204. /// <param name="request">The request.</param>
  205. /// <returns>System.Object.</returns>
  206. public object Get(GetDashboardConfigurationPages request)
  207. {
  208. const string unavailableMessage = "The server is still loading. Please try again momentarily.";
  209. var instance = ServerEntryPoint.Instance;
  210. if (instance == null)
  211. {
  212. throw new InvalidOperationException(unavailableMessage);
  213. }
  214. var pages = instance.PluginConfigurationPages;
  215. if (pages == null)
  216. {
  217. throw new InvalidOperationException(unavailableMessage);
  218. }
  219. // Don't allow a failing plugin to fail them all
  220. var configPages = pages.Select(p =>
  221. {
  222. try
  223. {
  224. return new ConfigurationPageInfo(p);
  225. }
  226. catch (Exception ex)
  227. {
  228. _logger.LogError(ex, "Error getting plugin information from {Plugin}", p.GetType().Name);
  229. return null;
  230. }
  231. })
  232. .Where(i => i != null)
  233. .ToList();
  234. configPages.AddRange(_appHost.Plugins.SelectMany(GetConfigPages));
  235. if (request.PageType.HasValue)
  236. {
  237. configPages = configPages.Where(p => p.ConfigurationPageType == request.PageType.Value).ToList();
  238. }
  239. if (request.EnableInMainMenu.HasValue)
  240. {
  241. configPages = configPages.Where(p => p.EnableInMainMenu == request.EnableInMainMenu.Value).ToList();
  242. }
  243. return configPages;
  244. }
  245. private IEnumerable<Tuple<PluginPageInfo, IPlugin>> GetPluginPages()
  246. {
  247. return _appHost.Plugins.SelectMany(GetPluginPages);
  248. }
  249. private IEnumerable<Tuple<PluginPageInfo, IPlugin>> GetPluginPages(IPlugin plugin)
  250. {
  251. var hasConfig = plugin as IHasWebPages;
  252. if (hasConfig == null)
  253. {
  254. return new List<Tuple<PluginPageInfo, IPlugin>>();
  255. }
  256. return hasConfig.GetPages().Select(i => new Tuple<PluginPageInfo, IPlugin>(i, plugin));
  257. }
  258. private IEnumerable<ConfigurationPageInfo> GetConfigPages(IPlugin plugin)
  259. {
  260. return GetPluginPages(plugin).Select(i => new ConfigurationPageInfo(plugin, i.Item1));
  261. }
  262. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request", Justification = "Required for ServiceStack")]
  263. public object Get(GetRobotsTxt request)
  264. {
  265. return Get(new GetDashboardResource
  266. {
  267. ResourceName = "robots.txt"
  268. });
  269. }
  270. /// <summary>
  271. /// Gets the specified request.
  272. /// </summary>
  273. /// <param name="request">The request.</param>
  274. /// <returns>System.Object.</returns>
  275. public async Task<object> Get(GetDashboardResource request)
  276. {
  277. if (!_appConfig.HostWebClient() || DashboardUIPath == null)
  278. {
  279. throw new ResourceNotFoundException();
  280. }
  281. var path = request?.ResourceName;
  282. var basePath = DashboardUIPath;
  283. // Bounce them to the startup wizard if it hasn't been completed yet
  284. if (!_serverConfigurationManager.Configuration.IsStartupWizardCompleted
  285. && !Request.RawUrl.Contains("wizard", StringComparison.OrdinalIgnoreCase)
  286. && Request.RawUrl.Contains("index", StringComparison.OrdinalIgnoreCase))
  287. {
  288. Request.Response.Redirect("index.html?start=wizard#!/wizardstart.html");
  289. return null;
  290. }
  291. return await _resultFactory.GetStaticFileResult(Request, _resourceFileManager.GetResourcePath(basePath, path)).ConfigureAwait(false);
  292. }
  293. }
  294. }