DashboardService.cs 16 KB

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