DashboardService.cs 16 KB

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