DashboardService.cs 17 KB

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