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 MediaBrowser.Model.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. }
  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")]
  48. public class GetDashboardPackage
  49. {
  50. public string Mode { get; set; }
  51. }
  52. [Route("/robots.txt", "GET")]
  53. public class GetRobotsTxt
  54. {
  55. }
  56. /// <summary>
  57. /// Class GetDashboardResource
  58. /// </summary>
  59. [Route("/web/{ResourceName*}", "GET")]
  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")]
  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 readonly IMemoryStreamFactory _memoryStreamFactory;
  110. /// <summary>
  111. /// Initializes a new instance of the <see cref="DashboardService" /> class.
  112. /// </summary>
  113. /// <param name="appHost">The app host.</param>
  114. /// <param name="serverConfigurationManager">The server configuration manager.</param>
  115. /// <param name="fileSystem">The file system.</param>
  116. public DashboardService(IServerApplicationHost appHost, IServerConfigurationManager serverConfigurationManager, IFileSystem fileSystem, ILocalizationManager localization, IJsonSerializer jsonSerializer, IAssemblyInfo assemblyInfo, ILogger logger, IHttpResultFactory resultFactory, IMemoryStreamFactory memoryStreamFactory)
  117. {
  118. _appHost = appHost;
  119. _serverConfigurationManager = serverConfigurationManager;
  120. _fileSystem = fileSystem;
  121. _localization = localization;
  122. _jsonSerializer = jsonSerializer;
  123. _assemblyInfo = assemblyInfo;
  124. _logger = logger;
  125. _resultFactory = resultFactory;
  126. _memoryStreamFactory = memoryStreamFactory;
  127. }
  128. /// <summary>
  129. /// Gets the dashboard UI path.
  130. /// </summary>
  131. /// <value>The dashboard UI path.</value>
  132. public string DashboardUIPath
  133. {
  134. get
  135. {
  136. if (!string.IsNullOrEmpty(_serverConfigurationManager.Configuration.DashboardSourcePath))
  137. {
  138. return _serverConfigurationManager.Configuration.DashboardSourcePath;
  139. }
  140. return Path.Combine(_serverConfigurationManager.ApplicationPaths.ApplicationResourcesPath, "dashboard-ui");
  141. }
  142. }
  143. public object Get(GetFavIcon request)
  144. {
  145. return Get(new GetDashboardResource
  146. {
  147. ResourceName = "favicon.ico"
  148. });
  149. }
  150. /// <summary>
  151. /// Gets the specified request.
  152. /// </summary>
  153. /// <param name="request">The request.</param>
  154. /// <returns>System.Object.</returns>
  155. public Task<object> Get(GetDashboardConfigurationPage request)
  156. {
  157. IPlugin plugin = null;
  158. Stream stream = null;
  159. var isJs = false;
  160. var isTemplate = false;
  161. var page = ServerEntryPoint.Instance.PluginConfigurationPages.FirstOrDefault(p => string.Equals(p.Name, request.Name, StringComparison.OrdinalIgnoreCase));
  162. if (page != null)
  163. {
  164. plugin = page.Plugin;
  165. stream = page.GetHtmlStream();
  166. }
  167. if (plugin == null)
  168. {
  169. var altPage = GetPluginPages().FirstOrDefault(p => string.Equals(p.Item1.Name, request.Name, StringComparison.OrdinalIgnoreCase));
  170. if (altPage != null)
  171. {
  172. plugin = altPage.Item2;
  173. stream = _assemblyInfo.GetManifestResourceStream(plugin.GetType(), altPage.Item1.EmbeddedResourcePath);
  174. isJs = string.Equals(Path.GetExtension(altPage.Item1.EmbeddedResourcePath), ".js", StringComparison.OrdinalIgnoreCase);
  175. isTemplate = altPage.Item1.EmbeddedResourcePath.EndsWith(".template.html");
  176. }
  177. }
  178. if (plugin != null && stream != null)
  179. {
  180. if (isJs)
  181. {
  182. return _resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.js"), () => Task.FromResult(stream));
  183. }
  184. if (isTemplate)
  185. {
  186. return _resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => Task.FromResult(stream));
  187. }
  188. 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));
  189. }
  190. throw new ResourceNotFoundException();
  191. }
  192. /// <summary>
  193. /// Gets the specified request.
  194. /// </summary>
  195. /// <param name="request">The request.</param>
  196. /// <returns>System.Object.</returns>
  197. public object Get(GetDashboardConfigurationPages request)
  198. {
  199. const string unavilableMessage = "The server is still loading. Please try again momentarily.";
  200. var instance = ServerEntryPoint.Instance;
  201. if (instance == null)
  202. {
  203. throw new InvalidOperationException(unavilableMessage);
  204. }
  205. var pages = instance.PluginConfigurationPages;
  206. if (pages == null)
  207. {
  208. throw new InvalidOperationException(unavilableMessage);
  209. }
  210. if (request.PageType.HasValue)
  211. {
  212. pages = pages.Where(p => p.ConfigurationPageType == request.PageType.Value).ToList();
  213. }
  214. // Don't allow a failing plugin to fail them all
  215. var configPages = pages.Select(p =>
  216. {
  217. try
  218. {
  219. return new ConfigurationPageInfo(p);
  220. }
  221. catch (Exception ex)
  222. {
  223. _logger.ErrorException("Error getting plugin information from {0}", ex, p.GetType().Name);
  224. return null;
  225. }
  226. })
  227. .Where(i => i != null)
  228. .ToList();
  229. configPages.AddRange(_appHost.Plugins.SelectMany(GetConfigPages));
  230. return _resultFactory.GetOptimizedResult(Request, 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. path = path.Replace("bower_components" + _appHost.ApplicationVersion, "bower_components", StringComparison.OrdinalIgnoreCase);
  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. path.IndexOf("wizard", StringComparison.OrdinalIgnoreCase) == -1 && GetPackageCreator(basePath).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("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(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.ApplicationVersion + (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, GetPackageCreator(basePath).GetResourcePath(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.ApplicationVersion.ToString());
  314. }
  315. private PackageCreator GetPackageCreator(string basePath)
  316. {
  317. return new PackageCreator(basePath, _fileSystem, _logger, _serverConfigurationManager, _memoryStreamFactory);
  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. _fileSystem.DeleteDirectory(targetPath, true);
  334. }
  335. catch (IOException)
  336. {
  337. }
  338. CopyDirectory(inputPath, targetPath);
  339. }
  340. string culture = null;
  341. var appVersion = _appHost.ApplicationVersion.ToString();
  342. await DumpHtml(packageCreator, inputPath, targetPath, mode, culture, appVersion);
  343. return "";
  344. }
  345. private async Task DumpHtml(PackageCreator packageCreator, string source, string destination, string mode, string culture, 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, culture, appVersion).ConfigureAwait(false);
  355. }
  356. }
  357. private async Task DumpFile(PackageCreator packageCreator, string resourceVirtualPath, string destinationFilePath, string mode, string culture, string appVersion)
  358. {
  359. using (var stream = await packageCreator.GetResource(resourceVirtualPath, mode, culture, 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. }