DashboardService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 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. }
  173. }
  174. if (plugin != null && stream != null)
  175. {
  176. 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));
  177. }
  178. throw new ResourceNotFoundException();
  179. }
  180. /// <summary>
  181. /// Gets the specified request.
  182. /// </summary>
  183. /// <param name="request">The request.</param>
  184. /// <returns>System.Object.</returns>
  185. public object Get(GetDashboardConfigurationPages request)
  186. {
  187. const string unavilableMessage = "The server is still loading. Please try again momentarily.";
  188. var instance = ServerEntryPoint.Instance;
  189. if (instance == null)
  190. {
  191. throw new InvalidOperationException(unavilableMessage);
  192. }
  193. var pages = instance.PluginConfigurationPages;
  194. if (pages == null)
  195. {
  196. throw new InvalidOperationException(unavilableMessage);
  197. }
  198. if (request.PageType.HasValue)
  199. {
  200. pages = pages.Where(p => p.ConfigurationPageType == request.PageType.Value).ToList();
  201. }
  202. // Don't allow a failing plugin to fail them all
  203. var configPages = pages.Select(p =>
  204. {
  205. try
  206. {
  207. return new ConfigurationPageInfo(p);
  208. }
  209. catch (Exception ex)
  210. {
  211. _logger.ErrorException("Error getting plugin information from {0}", ex, p.GetType().Name);
  212. return null;
  213. }
  214. })
  215. .Where(i => i != null)
  216. .ToList();
  217. configPages.AddRange(_appHost.Plugins.SelectMany(GetConfigPages));
  218. return _resultFactory.GetOptimizedResult(Request, configPages);
  219. }
  220. private IEnumerable<Tuple<PluginPageInfo, IPlugin>> GetPluginPages()
  221. {
  222. return _appHost.Plugins.SelectMany(GetPluginPages);
  223. }
  224. private IEnumerable<Tuple<PluginPageInfo, IPlugin>> GetPluginPages(IPlugin plugin)
  225. {
  226. var hasConfig = plugin as IHasWebPages;
  227. if (hasConfig == null)
  228. {
  229. return new List<Tuple<PluginPageInfo, IPlugin>>();
  230. }
  231. return hasConfig.GetPages().Select(i => new Tuple<PluginPageInfo, IPlugin>(i, plugin));
  232. }
  233. private IEnumerable<ConfigurationPageInfo> GetConfigPages(IPlugin plugin)
  234. {
  235. return GetPluginPages(plugin).Select(i => new ConfigurationPageInfo(plugin, i.Item1));
  236. }
  237. public object Get(GetRobotsTxt request)
  238. {
  239. return Get(new GetDashboardResource
  240. {
  241. ResourceName = "robots.txt"
  242. });
  243. }
  244. /// <summary>
  245. /// Gets the specified request.
  246. /// </summary>
  247. /// <param name="request">The request.</param>
  248. /// <returns>System.Object.</returns>
  249. public async Task<object> Get(GetDashboardResource request)
  250. {
  251. var path = request.ResourceName;
  252. path = path.Replace("bower_components" + _appHost.ApplicationVersion, "bower_components", StringComparison.OrdinalIgnoreCase);
  253. var contentType = MimeTypes.GetMimeType(path);
  254. var basePath = DashboardUIPath;
  255. // Bounce them to the startup wizard if it hasn't been completed yet
  256. if (!_serverConfigurationManager.Configuration.IsStartupWizardCompleted &&
  257. path.IndexOf("wizard", StringComparison.OrdinalIgnoreCase) == -1 && GetPackageCreator(basePath).IsCoreHtml(path))
  258. {
  259. // But don't redirect if an html import is being requested.
  260. if (path.IndexOf("bower_components", StringComparison.OrdinalIgnoreCase) == -1)
  261. {
  262. Request.Response.Redirect("wizardstart.html");
  263. return null;
  264. }
  265. }
  266. var localizationCulture = GetLocalizationCulture();
  267. // Don't cache if not configured to do so
  268. // But always cache images to simulate production
  269. if (!_serverConfigurationManager.Configuration.EnableDashboardResponseCaching &&
  270. !contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) &&
  271. !contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  272. {
  273. var stream = await GetResourceStream(basePath, path, localizationCulture).ConfigureAwait(false);
  274. return _resultFactory.GetResult(stream, contentType);
  275. }
  276. TimeSpan? cacheDuration = null;
  277. // Cache images unconditionally - updates to image files will require new filename
  278. // If there's a version number in the query string we can cache this unconditionally
  279. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase) || !string.IsNullOrEmpty(request.V))
  280. {
  281. cacheDuration = TimeSpan.FromDays(365);
  282. }
  283. var cacheKey = (_appHost.ApplicationVersion + (localizationCulture ?? string.Empty) + path).GetMD5();
  284. // html gets modified on the fly
  285. if (contentType.StartsWith("text/html", StringComparison.OrdinalIgnoreCase))
  286. {
  287. return await _resultFactory.GetStaticResult(Request, cacheKey, null, cacheDuration, contentType, () => GetResourceStream(basePath, path, localizationCulture)).ConfigureAwait(false);
  288. }
  289. return await _resultFactory.GetStaticFileResult(Request, GetPackageCreator(basePath).GetResourcePath(path));
  290. }
  291. private string GetLocalizationCulture()
  292. {
  293. return _serverConfigurationManager.Configuration.UICulture;
  294. }
  295. /// <summary>
  296. /// Gets the resource stream.
  297. /// </summary>
  298. private Task<Stream> GetResourceStream(string basePath, string virtualPath, string localizationCulture)
  299. {
  300. return GetPackageCreator(basePath)
  301. .GetResource(virtualPath, null, localizationCulture, _appHost.ApplicationVersion.ToString());
  302. }
  303. private PackageCreator GetPackageCreator(string basePath)
  304. {
  305. return new PackageCreator(basePath, _fileSystem, _logger, _serverConfigurationManager, _memoryStreamFactory);
  306. }
  307. public async Task<object> Get(GetDashboardPackage request)
  308. {
  309. var mode = request.Mode;
  310. var inputPath = string.IsNullOrWhiteSpace(mode) ?
  311. DashboardUIPath
  312. : "C:\\dev\\emby-web-mobile-master\\dist";
  313. var targetPath = !string.IsNullOrWhiteSpace(mode) ?
  314. inputPath
  315. : "C:\\dev\\emby-web-mobile\\src";
  316. var packageCreator = GetPackageCreator(inputPath);
  317. if (!string.Equals(inputPath, targetPath, StringComparison.OrdinalIgnoreCase))
  318. {
  319. try
  320. {
  321. _fileSystem.DeleteDirectory(targetPath, true);
  322. }
  323. catch (IOException)
  324. {
  325. }
  326. CopyDirectory(inputPath, targetPath);
  327. }
  328. string culture = null;
  329. var appVersion = _appHost.ApplicationVersion.ToString();
  330. await DumpHtml(packageCreator, inputPath, targetPath, mode, culture, appVersion);
  331. return "";
  332. }
  333. private async Task DumpHtml(PackageCreator packageCreator, string source, string destination, string mode, string culture, string appVersion)
  334. {
  335. foreach (var file in _fileSystem.GetFiles(source))
  336. {
  337. var filename = file.Name;
  338. if (!string.Equals(file.Extension, ".html", StringComparison.OrdinalIgnoreCase))
  339. {
  340. continue;
  341. }
  342. await DumpFile(packageCreator, filename, Path.Combine(destination, filename), mode, culture, appVersion).ConfigureAwait(false);
  343. }
  344. }
  345. private async Task DumpFile(PackageCreator packageCreator, string resourceVirtualPath, string destinationFilePath, string mode, string culture, string appVersion)
  346. {
  347. using (var stream = await packageCreator.GetResource(resourceVirtualPath, mode, culture, appVersion).ConfigureAwait(false))
  348. {
  349. using (var fs = _fileSystem.GetFileStream(destinationFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  350. {
  351. stream.CopyTo(fs);
  352. }
  353. }
  354. }
  355. private void CopyDirectory(string source, string destination)
  356. {
  357. _fileSystem.CreateDirectory(destination);
  358. //Now Create all of the directories
  359. foreach (var dirPath in _fileSystem.GetDirectories(source, true))
  360. _fileSystem.CreateDirectory(dirPath.FullName.Replace(source, destination));
  361. //Copy all the files & Replaces any files with the same name
  362. foreach (var newPath in _fileSystem.GetFiles(source, true))
  363. _fileSystem.CopyFile(newPath.FullName, newPath.FullName.Replace(source, destination), true);
  364. }
  365. }
  366. }