2
0

DashboardService.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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("/web/Package", "GET", IsHidden = true)]
  51. public class GetDashboardPackage
  52. {
  53. public string Mode { get; set; }
  54. }
  55. [Route("/robots.txt", "GET", IsHidden = true)]
  56. public class GetRobotsTxt
  57. {
  58. }
  59. /// <summary>
  60. /// Class GetDashboardResource.
  61. /// </summary>
  62. [Route("/web/{ResourceName*}", "GET", IsHidden = true)]
  63. public class GetDashboardResource
  64. {
  65. /// <summary>
  66. /// Gets or sets the name.
  67. /// </summary>
  68. /// <value>The name.</value>
  69. public string ResourceName { get; set; }
  70. /// <summary>
  71. /// Gets or sets the V.
  72. /// </summary>
  73. /// <value>The V.</value>
  74. public string V { get; set; }
  75. }
  76. [Route("/favicon.ico", "GET", IsHidden = true)]
  77. public class GetFavIcon
  78. {
  79. }
  80. /// <summary>
  81. /// Class DashboardService.
  82. /// </summary>
  83. public class DashboardService : IService, IRequiresRequest
  84. {
  85. /// <summary>
  86. /// Gets or sets the logger.
  87. /// </summary>
  88. /// <value>The logger.</value>
  89. private readonly ILogger _logger;
  90. /// <summary>
  91. /// Gets or sets the HTTP result factory.
  92. /// </summary>
  93. /// <value>The HTTP result factory.</value>
  94. private readonly IHttpResultFactory _resultFactory;
  95. private readonly IServerApplicationHost _appHost;
  96. private readonly IConfiguration _appConfig;
  97. private readonly IServerConfigurationManager _serverConfigurationManager;
  98. private readonly IFileSystem _fileSystem;
  99. private readonly IResourceFileManager _resourceFileManager;
  100. /// <summary>
  101. /// Initializes a new instance of the <see cref="DashboardService" /> class.
  102. /// </summary>
  103. /// <param name="logger">The logger.</param>
  104. /// <param name="appHost">The application host.</param>
  105. /// <param name="appConfig">The application configuration.</param>
  106. /// <param name="resourceFileManager">The resource file manager.</param>
  107. /// <param name="serverConfigurationManager">The server configuration manager.</param>
  108. /// <param name="fileSystem">The file system.</param>
  109. /// <param name="resultFactory">The result factory.</param>
  110. public DashboardService(
  111. ILogger<DashboardService> logger,
  112. IServerApplicationHost appHost,
  113. IConfiguration appConfig,
  114. IResourceFileManager resourceFileManager,
  115. IServerConfigurationManager serverConfigurationManager,
  116. IFileSystem fileSystem,
  117. IHttpResultFactory resultFactory)
  118. {
  119. _logger = logger;
  120. _appHost = appHost;
  121. _appConfig = appConfig;
  122. _resourceFileManager = resourceFileManager;
  123. _serverConfigurationManager = serverConfigurationManager;
  124. _fileSystem = fileSystem;
  125. _resultFactory = resultFactory;
  126. // If hosting the web client, validate the client content path
  127. if (appConfig.HostWebClient())
  128. {
  129. string webContentPath = DashboardUIPath;
  130. if (!Directory.Exists(webContentPath) || Directory.GetFiles(webContentPath).Length == 0)
  131. {
  132. throw new InvalidOperationException(
  133. "The server is expected to host the web client, but the provided content directory is either " +
  134. $"invalid or empty: {webContentPath}. If you do not want to host the web client with the " +
  135. "server, you may set the '--nowebclient' command line flag, or set" +
  136. $"'{Controller.Extensions.ConfigurationExtensions.HostWebClientKey}=false' in your config settings.");
  137. }
  138. }
  139. }
  140. /// <summary>
  141. /// Gets or sets the request context.
  142. /// </summary>
  143. /// <value>The request context.</value>
  144. public IRequest Request { get; set; }
  145. /// <summary>
  146. /// Gets the path of the directory containing the static web interface content, or null if the server is not
  147. /// hosting the web client.
  148. /// </summary>
  149. public string DashboardUIPath => GetDashboardUIPath(_appConfig, _serverConfigurationManager);
  150. /// <summary>
  151. /// Gets the path of the directory containing the static web interface content.
  152. /// </summary>
  153. /// <param name="appConfig">The app configuration.</param>
  154. /// <param name="serverConfigManager">The server configuration manager.</param>
  155. /// <returns>The directory path, or null if the server is not hosting the web client.</returns>
  156. public static string GetDashboardUIPath(IConfiguration appConfig, IServerConfigurationManager serverConfigManager)
  157. {
  158. if (!appConfig.HostWebClient())
  159. {
  160. return null;
  161. }
  162. if (!string.IsNullOrEmpty(serverConfigManager.Configuration.DashboardSourcePath))
  163. {
  164. return serverConfigManager.Configuration.DashboardSourcePath;
  165. }
  166. return serverConfigManager.ApplicationPaths.WebPath;
  167. }
  168. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request", Justification = "Required for ServiceStack")]
  169. public object Get(GetFavIcon request)
  170. {
  171. return Get(new GetDashboardResource
  172. {
  173. ResourceName = "favicon.ico"
  174. });
  175. }
  176. /// <summary>
  177. /// Gets the specified request.
  178. /// </summary>
  179. /// <param name="request">The request.</param>
  180. /// <returns>System.Object.</returns>
  181. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request", Justification = "Required for ServiceStack")]
  182. public Task<object> Get(GetDashboardConfigurationPage request)
  183. {
  184. IPlugin plugin = null;
  185. Stream stream = null;
  186. var isJs = false;
  187. var isTemplate = false;
  188. var page = ServerEntryPoint.Instance.PluginConfigurationPages.FirstOrDefault(p => string.Equals(p.Name, request.Name, StringComparison.OrdinalIgnoreCase));
  189. if (page != null)
  190. {
  191. plugin = page.Plugin;
  192. stream = page.GetHtmlStream();
  193. }
  194. if (plugin == null)
  195. {
  196. var altPage = GetPluginPages().FirstOrDefault(p => string.Equals(p.Item1.Name, request.Name, StringComparison.OrdinalIgnoreCase));
  197. if (altPage != null)
  198. {
  199. plugin = altPage.Item2;
  200. stream = plugin.GetType().Assembly.GetManifestResourceStream(altPage.Item1.EmbeddedResourcePath);
  201. isJs = string.Equals(Path.GetExtension(altPage.Item1.EmbeddedResourcePath), ".js", StringComparison.OrdinalIgnoreCase);
  202. isTemplate = altPage.Item1.EmbeddedResourcePath.EndsWith(".template.html", StringComparison.Ordinal);
  203. }
  204. }
  205. if (plugin != null && stream != null)
  206. {
  207. if (isJs)
  208. {
  209. return _resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.js"), () => Task.FromResult(stream));
  210. }
  211. if (isTemplate)
  212. {
  213. return _resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => Task.FromResult(stream));
  214. }
  215. return _resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => PackageCreator.ModifyHtml(false, stream, null, _appHost.ApplicationVersionString, null));
  216. }
  217. throw new ResourceNotFoundException();
  218. }
  219. /// <summary>
  220. /// Gets the specified request.
  221. /// </summary>
  222. /// <param name="request">The request.</param>
  223. /// <returns>System.Object.</returns>
  224. public object Get(GetDashboardConfigurationPages request)
  225. {
  226. const string unavailableMessage = "The server is still loading. Please try again momentarily.";
  227. var instance = ServerEntryPoint.Instance;
  228. if (instance == null)
  229. {
  230. throw new InvalidOperationException(unavailableMessage);
  231. }
  232. var pages = instance.PluginConfigurationPages;
  233. if (pages == null)
  234. {
  235. throw new InvalidOperationException(unavailableMessage);
  236. }
  237. // Don't allow a failing plugin to fail them all
  238. var configPages = pages.Select(p =>
  239. {
  240. try
  241. {
  242. return new ConfigurationPageInfo(p);
  243. }
  244. catch (Exception ex)
  245. {
  246. _logger.LogError(ex, "Error getting plugin information from {Plugin}", p.GetType().Name);
  247. return null;
  248. }
  249. })
  250. .Where(i => i != null)
  251. .ToList();
  252. configPages.AddRange(_appHost.Plugins.SelectMany(GetConfigPages));
  253. if (request.PageType.HasValue)
  254. {
  255. configPages = configPages.Where(p => p.ConfigurationPageType == request.PageType.Value).ToList();
  256. }
  257. if (request.EnableInMainMenu.HasValue)
  258. {
  259. configPages = configPages.Where(p => p.EnableInMainMenu == request.EnableInMainMenu.Value).ToList();
  260. }
  261. return configPages;
  262. }
  263. private IEnumerable<Tuple<PluginPageInfo, IPlugin>> GetPluginPages()
  264. {
  265. return _appHost.Plugins.SelectMany(GetPluginPages);
  266. }
  267. private IEnumerable<Tuple<PluginPageInfo, IPlugin>> GetPluginPages(IPlugin plugin)
  268. {
  269. var hasConfig = plugin as IHasWebPages;
  270. if (hasConfig == null)
  271. {
  272. return new List<Tuple<PluginPageInfo, IPlugin>>();
  273. }
  274. return hasConfig.GetPages().Select(i => new Tuple<PluginPageInfo, IPlugin>(i, plugin));
  275. }
  276. private IEnumerable<ConfigurationPageInfo> GetConfigPages(IPlugin plugin)
  277. {
  278. return GetPluginPages(plugin).Select(i => new ConfigurationPageInfo(plugin, i.Item1));
  279. }
  280. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "request", Justification = "Required for ServiceStack")]
  281. public object Get(GetRobotsTxt request)
  282. {
  283. return Get(new GetDashboardResource
  284. {
  285. ResourceName = "robots.txt"
  286. });
  287. }
  288. /// <summary>
  289. /// Gets the specified request.
  290. /// </summary>
  291. /// <param name="request">The request.</param>
  292. /// <returns>System.Object.</returns>
  293. public async Task<object> Get(GetDashboardResource request)
  294. {
  295. if (!_appConfig.HostWebClient() || DashboardUIPath == null)
  296. {
  297. throw new ResourceNotFoundException();
  298. }
  299. var path = request.ResourceName;
  300. var contentType = MimeTypes.GetMimeType(path);
  301. var basePath = DashboardUIPath;
  302. // Bounce them to the startup wizard if it hasn't been completed yet
  303. if (!_serverConfigurationManager.Configuration.IsStartupWizardCompleted &&
  304. Request.RawUrl.IndexOf("wizard", StringComparison.OrdinalIgnoreCase) == -1 &&
  305. PackageCreator.IsCoreHtml(path))
  306. {
  307. // But don't redirect if an html import is being requested.
  308. if (path.IndexOf("bower_components", StringComparison.OrdinalIgnoreCase) == -1)
  309. {
  310. Request.Response.Redirect("index.html?start=wizard#!/wizardstart.html");
  311. return null;
  312. }
  313. }
  314. var localizationCulture = GetLocalizationCulture();
  315. // Don't cache if not configured to do so
  316. // But always cache images to simulate production
  317. if (!_serverConfigurationManager.Configuration.EnableDashboardResponseCaching &&
  318. !contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) &&
  319. !contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  320. {
  321. var stream = await GetResourceStream(basePath, path, localizationCulture).ConfigureAwait(false);
  322. return _resultFactory.GetResult(Request, stream, contentType);
  323. }
  324. TimeSpan? cacheDuration = null;
  325. // Cache images unconditionally - updates to image files will require new filename
  326. // If there's a version number in the query string we can cache this unconditionally
  327. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase) || !string.IsNullOrEmpty(request.V))
  328. {
  329. cacheDuration = TimeSpan.FromDays(365);
  330. }
  331. var cacheKey = (_appHost.ApplicationVersionString + (localizationCulture ?? string.Empty) + path).GetMD5();
  332. // html gets modified on the fly
  333. if (contentType.StartsWith("text/html", StringComparison.OrdinalIgnoreCase))
  334. {
  335. return await _resultFactory.GetStaticResult(Request, cacheKey, null, cacheDuration, contentType, () => GetResourceStream(basePath, path, localizationCulture)).ConfigureAwait(false);
  336. }
  337. return await _resultFactory.GetStaticFileResult(Request, _resourceFileManager.GetResourcePath(basePath, path)).ConfigureAwait(false);
  338. }
  339. private string GetLocalizationCulture()
  340. {
  341. return _serverConfigurationManager.Configuration.UICulture;
  342. }
  343. /// <summary>
  344. /// Gets the resource stream.
  345. /// </summary>
  346. private Task<Stream> GetResourceStream(string basePath, string virtualPath, string localizationCulture)
  347. {
  348. return GetPackageCreator(basePath)
  349. .GetResource(virtualPath, null, localizationCulture, _appHost.ApplicationVersionString);
  350. }
  351. private PackageCreator GetPackageCreator(string basePath)
  352. {
  353. return new PackageCreator(basePath, _resourceFileManager);
  354. }
  355. public async Task<object> Get(GetDashboardPackage request)
  356. {
  357. if (!_appConfig.HostWebClient() || DashboardUIPath == null)
  358. {
  359. throw new ResourceNotFoundException();
  360. }
  361. var mode = request.Mode;
  362. var inputPath = string.IsNullOrWhiteSpace(mode) ?
  363. DashboardUIPath
  364. : "C:\\dev\\emby-web-mobile-master\\dist";
  365. var targetPath = !string.IsNullOrWhiteSpace(mode) ?
  366. inputPath
  367. : "C:\\dev\\emby-web-mobile\\src";
  368. var packageCreator = GetPackageCreator(inputPath);
  369. if (!string.Equals(inputPath, targetPath, StringComparison.OrdinalIgnoreCase))
  370. {
  371. try
  372. {
  373. Directory.Delete(targetPath, true);
  374. }
  375. catch (IOException ex)
  376. {
  377. _logger.LogError(ex, "Error deleting {Path}", targetPath);
  378. }
  379. CopyDirectory(inputPath, targetPath);
  380. }
  381. var appVersion = _appHost.ApplicationVersionString;
  382. await DumpHtml(packageCreator, inputPath, targetPath, mode, appVersion).ConfigureAwait(false);
  383. return string.Empty;
  384. }
  385. private async Task DumpHtml(PackageCreator packageCreator, string source, string destination, string mode, string appVersion)
  386. {
  387. foreach (var file in _fileSystem.GetFiles(source))
  388. {
  389. var filename = file.Name;
  390. if (!string.Equals(file.Extension, ".html", StringComparison.OrdinalIgnoreCase))
  391. {
  392. continue;
  393. }
  394. await DumpFile(packageCreator, filename, Path.Combine(destination, filename), mode, appVersion).ConfigureAwait(false);
  395. }
  396. }
  397. private async Task DumpFile(PackageCreator packageCreator, string resourceVirtualPath, string destinationFilePath, string mode, string appVersion)
  398. {
  399. using (var stream = await packageCreator.GetResource(resourceVirtualPath, mode, null, appVersion).ConfigureAwait(false))
  400. using (var fs = new FileStream(destinationFilePath, FileMode.Create, FileAccess.Write, FileShare.Read))
  401. {
  402. await stream.CopyToAsync(fs).ConfigureAwait(false);
  403. }
  404. }
  405. private void CopyDirectory(string source, string destination)
  406. {
  407. Directory.CreateDirectory(destination);
  408. // Now Create all of the directories
  409. foreach (var dirPath in _fileSystem.GetDirectories(source, true))
  410. {
  411. Directory.CreateDirectory(dirPath.FullName.Replace(source, destination, StringComparison.Ordinal));
  412. }
  413. // Copy all the files & Replaces any files with the same name
  414. foreach (var newPath in _fileSystem.GetFiles(source, true))
  415. {
  416. File.Copy(newPath.FullName, newPath.FullName.Replace(source, destination, StringComparison.Ordinal), true);
  417. }
  418. }
  419. }
  420. }