DashboardService.cs 16 KB

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