DashboardService.cs 16 KB

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