DashboardService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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 readonly ILocalizationManager _localization;
  106. private readonly IJsonSerializer _jsonSerializer;
  107. private IResourceFileManager _resourceFileManager;
  108. /// <summary>
  109. /// Initializes a new instance of the <see cref="DashboardService" /> class.
  110. /// </summary>
  111. public DashboardService(
  112. IServerApplicationHost appHost,
  113. IResourceFileManager resourceFileManager,
  114. IServerConfigurationManager serverConfigurationManager,
  115. IFileSystem fileSystem,
  116. ILocalizationManager localization,
  117. IJsonSerializer jsonSerializer,
  118. ILogger logger,
  119. IHttpResultFactory resultFactory)
  120. {
  121. _appHost = appHost;
  122. _serverConfigurationManager = serverConfigurationManager;
  123. _fileSystem = fileSystem;
  124. _localization = localization;
  125. _jsonSerializer = jsonSerializer;
  126. _logger = logger;
  127. _resultFactory = resultFactory;
  128. _resourceFileManager = resourceFileManager;
  129. }
  130. /// <summary>
  131. /// Gets the path for the web interface.
  132. /// </summary>
  133. /// <value>The path for the web interface.</value>
  134. public string DashboardUIPath
  135. {
  136. get
  137. {
  138. if (!string.IsNullOrEmpty(_serverConfigurationManager.Configuration.DashboardSourcePath))
  139. {
  140. return _serverConfigurationManager.Configuration.DashboardSourcePath;
  141. }
  142. return _serverConfigurationManager.ApplicationPaths.WebPath;
  143. }
  144. }
  145. public object Get(GetFavIcon request)
  146. {
  147. return Get(new GetDashboardResource
  148. {
  149. ResourceName = "favicon.ico"
  150. });
  151. }
  152. /// <summary>
  153. /// Gets the specified request.
  154. /// </summary>
  155. /// <param name="request">The request.</param>
  156. /// <returns>System.Object.</returns>
  157. public Task<object> Get(GetDashboardConfigurationPage request)
  158. {
  159. IPlugin plugin = null;
  160. Stream stream = null;
  161. var isJs = false;
  162. var isTemplate = false;
  163. var page = ServerEntryPoint.Instance.PluginConfigurationPages.FirstOrDefault(p => string.Equals(p.Name, request.Name, StringComparison.OrdinalIgnoreCase));
  164. if (page != null)
  165. {
  166. plugin = page.Plugin;
  167. stream = page.GetHtmlStream();
  168. }
  169. if (plugin == null)
  170. {
  171. var altPage = GetPluginPages().FirstOrDefault(p => string.Equals(p.Item1.Name, request.Name, StringComparison.OrdinalIgnoreCase));
  172. if (altPage != null)
  173. {
  174. plugin = altPage.Item2;
  175. stream = plugin.GetType().Assembly.GetManifestResourceStream(altPage.Item1.EmbeddedResourcePath);
  176. isJs = string.Equals(Path.GetExtension(altPage.Item1.EmbeddedResourcePath), ".js", StringComparison.OrdinalIgnoreCase);
  177. isTemplate = altPage.Item1.EmbeddedResourcePath.EndsWith(".template.html");
  178. }
  179. }
  180. if (plugin != null && stream != null)
  181. {
  182. if (isJs)
  183. {
  184. return _resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.js"), () => Task.FromResult(stream));
  185. }
  186. if (isTemplate)
  187. {
  188. return _resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => Task.FromResult(stream));
  189. }
  190. return _resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => GetPackageCreator(DashboardUIPath).ModifyHtml("dummy.html", stream, null, _appHost.ApplicationVersion, null));
  191. }
  192. throw new ResourceNotFoundException();
  193. }
  194. /// <summary>
  195. /// Gets the specified request.
  196. /// </summary>
  197. /// <param name="request">The request.</param>
  198. /// <returns>System.Object.</returns>
  199. public object Get(GetDashboardConfigurationPages request)
  200. {
  201. const string unavailableMessage = "The server is still loading. Please try again momentarily.";
  202. var instance = ServerEntryPoint.Instance;
  203. if (instance == null)
  204. {
  205. throw new InvalidOperationException(unavailableMessage);
  206. }
  207. var pages = instance.PluginConfigurationPages;
  208. if (pages == null)
  209. {
  210. throw new InvalidOperationException(unavailableMessage);
  211. }
  212. // Don't allow a failing plugin to fail them all
  213. var configPages = pages.Select(p =>
  214. {
  215. try
  216. {
  217. return new ConfigurationPageInfo(p);
  218. }
  219. catch (Exception ex)
  220. {
  221. _logger.LogError(ex, "Error getting plugin information from {Plugin}", p.GetType().Name);
  222. return null;
  223. }
  224. })
  225. .Where(i => i != null)
  226. .ToList();
  227. configPages.AddRange(_appHost.Plugins.SelectMany(GetConfigPages));
  228. if (request.PageType.HasValue)
  229. {
  230. configPages = configPages.Where(p => p.ConfigurationPageType == request.PageType.Value).ToList();
  231. }
  232. if (request.EnableInMainMenu.HasValue)
  233. {
  234. configPages = configPages.Where(p => p.EnableInMainMenu == request.EnableInMainMenu.Value).ToList();
  235. }
  236. return configPages;
  237. }
  238. private IEnumerable<Tuple<PluginPageInfo, IPlugin>> GetPluginPages()
  239. {
  240. return _appHost.Plugins.SelectMany(GetPluginPages);
  241. }
  242. private IEnumerable<Tuple<PluginPageInfo, IPlugin>> GetPluginPages(IPlugin plugin)
  243. {
  244. var hasConfig = plugin as IHasWebPages;
  245. if (hasConfig == null)
  246. {
  247. return new List<Tuple<PluginPageInfo, IPlugin>>();
  248. }
  249. return hasConfig.GetPages().Select(i => new Tuple<PluginPageInfo, IPlugin>(i, plugin));
  250. }
  251. private IEnumerable<ConfigurationPageInfo> GetConfigPages(IPlugin plugin)
  252. {
  253. return GetPluginPages(plugin).Select(i => new ConfigurationPageInfo(plugin, i.Item1));
  254. }
  255. public object Get(GetRobotsTxt request)
  256. {
  257. return Get(new GetDashboardResource
  258. {
  259. ResourceName = "robots.txt"
  260. });
  261. }
  262. /// <summary>
  263. /// Gets the specified request.
  264. /// </summary>
  265. /// <param name="request">The request.</param>
  266. /// <returns>System.Object.</returns>
  267. public async Task<object> Get(GetDashboardResource request)
  268. {
  269. var path = request.ResourceName;
  270. var contentType = MimeTypes.GetMimeType(path);
  271. var basePath = DashboardUIPath;
  272. // Bounce them to the startup wizard if it hasn't been completed yet
  273. if (!_serverConfigurationManager.Configuration.IsStartupWizardCompleted &&
  274. Request.RawUrl.IndexOf("wizard", StringComparison.OrdinalIgnoreCase) == -1 &&
  275. GetPackageCreator(basePath).IsCoreHtml(path))
  276. {
  277. // But don't redirect if an html import is being requested.
  278. if (path.IndexOf("bower_components", StringComparison.OrdinalIgnoreCase) == -1)
  279. {
  280. Request.Response.Redirect("index.html?start=wizard#!/wizardstart.html");
  281. return null;
  282. }
  283. }
  284. var localizationCulture = GetLocalizationCulture();
  285. // Don't cache if not configured to do so
  286. // But always cache images to simulate production
  287. if (!_serverConfigurationManager.Configuration.EnableDashboardResponseCaching &&
  288. !contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) &&
  289. !contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  290. {
  291. var stream = await GetResourceStream(basePath, path, localizationCulture).ConfigureAwait(false);
  292. return _resultFactory.GetResult(Request, stream, contentType);
  293. }
  294. TimeSpan? cacheDuration = null;
  295. // Cache images unconditionally - updates to image files will require new filename
  296. // If there's a version number in the query string we can cache this unconditionally
  297. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase) || !string.IsNullOrEmpty(request.V))
  298. {
  299. cacheDuration = TimeSpan.FromDays(365);
  300. }
  301. var cacheKey = (_appHost.ApplicationVersion + (localizationCulture ?? string.Empty) + path).GetMD5();
  302. // html gets modified on the fly
  303. if (contentType.StartsWith("text/html", StringComparison.OrdinalIgnoreCase))
  304. {
  305. return await _resultFactory.GetStaticResult(Request, cacheKey, null, cacheDuration, contentType, () => GetResourceStream(basePath, path, localizationCulture)).ConfigureAwait(false);
  306. }
  307. return await _resourceFileManager.GetStaticFileResult(Request, basePath, path, contentType, cacheDuration);
  308. }
  309. private string GetLocalizationCulture()
  310. {
  311. return _serverConfigurationManager.Configuration.UICulture;
  312. }
  313. /// <summary>
  314. /// Gets the resource stream.
  315. /// </summary>
  316. private Task<Stream> GetResourceStream(string basePath, string virtualPath, string localizationCulture)
  317. {
  318. return GetPackageCreator(basePath)
  319. .GetResource(virtualPath, null, localizationCulture, _appHost.ApplicationVersion);
  320. }
  321. private PackageCreator GetPackageCreator(string basePath)
  322. {
  323. return new PackageCreator(basePath, _fileSystem, _logger, _serverConfigurationManager, _resourceFileManager);
  324. }
  325. public async Task<object> Get(GetDashboardPackage request)
  326. {
  327. var mode = request.Mode;
  328. var inputPath = string.IsNullOrWhiteSpace(mode) ?
  329. DashboardUIPath
  330. : "C:\\dev\\emby-web-mobile-master\\dist";
  331. var targetPath = !string.IsNullOrWhiteSpace(mode) ?
  332. inputPath
  333. : "C:\\dev\\emby-web-mobile\\src";
  334. var packageCreator = GetPackageCreator(inputPath);
  335. if (!string.Equals(inputPath, targetPath, StringComparison.OrdinalIgnoreCase))
  336. {
  337. try
  338. {
  339. Directory.Delete(targetPath, true);
  340. }
  341. catch (IOException)
  342. {
  343. }
  344. CopyDirectory(inputPath, targetPath);
  345. }
  346. var appVersion = _appHost.ApplicationVersion;
  347. await DumpHtml(packageCreator, inputPath, targetPath, mode, appVersion);
  348. return "";
  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 = _fileSystem.GetFileStream(destinationFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  366. {
  367. await stream.CopyToAsync(fs);
  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. Directory.CreateDirectory(dirPath.FullName.Replace(source, destination));
  376. //Copy all the files & Replaces any files with the same name
  377. foreach (var newPath in _fileSystem.GetFiles(source, true))
  378. File.Copy(newPath.FullName, newPath.FullName.Replace(source, destination), true);
  379. }
  380. }
  381. }