DashboardService.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Localization;
  6. using MediaBrowser.Controller.Net;
  7. using MediaBrowser.Controller.Plugins;
  8. using MediaBrowser.Model.Extensions;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.Net;
  11. using MediaBrowser.Model.Serialization;
  12. using ServiceStack;
  13. using ServiceStack.Web;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Globalization;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Threading.Tasks;
  20. namespace MediaBrowser.WebDashboard.Api
  21. {
  22. /// <summary>
  23. /// Class GetDashboardConfigurationPages
  24. /// </summary>
  25. [Route("/dashboard/ConfigurationPages", "GET")]
  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("/dashboard/ConfigurationPage", "GET")]
  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")]
  49. [Route("/dashboard/Package", "GET")]
  50. public class GetDashboardPackage
  51. {
  52. public string Mode { get; set; }
  53. }
  54. /// <summary>
  55. /// Class GetDashboardResource
  56. /// </summary>
  57. [Route("/web/{ResourceName*}", "GET")]
  58. [Route("/dashboard/{ResourceName*}", "GET")]
  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. /// <summary>
  73. /// Class DashboardService
  74. /// </summary>
  75. public class DashboardService : IRestfulService, IHasResultFactory
  76. {
  77. /// <summary>
  78. /// Gets or sets the logger.
  79. /// </summary>
  80. /// <value>The logger.</value>
  81. public ILogger Logger { get; set; }
  82. /// <summary>
  83. /// Gets or sets the HTTP result factory.
  84. /// </summary>
  85. /// <value>The HTTP result factory.</value>
  86. public IHttpResultFactory ResultFactory { get; set; }
  87. /// <summary>
  88. /// Gets or sets the request context.
  89. /// </summary>
  90. /// <value>The request context.</value>
  91. public IRequest Request { get; set; }
  92. /// <summary>
  93. /// The _app host
  94. /// </summary>
  95. private readonly IServerApplicationHost _appHost;
  96. /// <summary>
  97. /// The _server configuration manager
  98. /// </summary>
  99. private readonly IServerConfigurationManager _serverConfigurationManager;
  100. private readonly IFileSystem _fileSystem;
  101. private readonly ILocalizationManager _localization;
  102. private readonly IJsonSerializer _jsonSerializer;
  103. /// <summary>
  104. /// Initializes a new instance of the <see cref="DashboardService" /> class.
  105. /// </summary>
  106. /// <param name="appHost">The app host.</param>
  107. /// <param name="serverConfigurationManager">The server configuration manager.</param>
  108. /// <param name="fileSystem">The file system.</param>
  109. public DashboardService(IServerApplicationHost appHost, IServerConfigurationManager serverConfigurationManager, IFileSystem fileSystem, ILocalizationManager localization, IJsonSerializer jsonSerializer)
  110. {
  111. _appHost = appHost;
  112. _serverConfigurationManager = serverConfigurationManager;
  113. _fileSystem = fileSystem;
  114. _localization = localization;
  115. _jsonSerializer = jsonSerializer;
  116. }
  117. /// <summary>
  118. /// Gets the specified request.
  119. /// </summary>
  120. /// <param name="request">The request.</param>
  121. /// <returns>System.Object.</returns>
  122. public object Get(GetDashboardConfigurationPage request)
  123. {
  124. var page = ServerEntryPoint.Instance.PluginConfigurationPages.First(p => p.Name.Equals(request.Name, StringComparison.OrdinalIgnoreCase));
  125. return ResultFactory.GetStaticResult(Request, page.Plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => GetPackageCreator().ModifyHtml(page.GetHtmlStream(), null, null, false));
  126. }
  127. /// <summary>
  128. /// Gets the specified request.
  129. /// </summary>
  130. /// <param name="request">The request.</param>
  131. /// <returns>System.Object.</returns>
  132. public object Get(GetDashboardConfigurationPages request)
  133. {
  134. const string unavilableMessage = "The server is still loading. Please try again momentarily.";
  135. var instance = ServerEntryPoint.Instance;
  136. if (instance == null)
  137. {
  138. throw new InvalidOperationException(unavilableMessage);
  139. }
  140. var pages = instance.PluginConfigurationPages;
  141. if (pages == null)
  142. {
  143. throw new InvalidOperationException(unavilableMessage);
  144. }
  145. if (request.PageType.HasValue)
  146. {
  147. pages = pages.Where(p => p.ConfigurationPageType == request.PageType.Value);
  148. }
  149. // Don't allow a failing plugin to fail them all
  150. var configPages = pages.Select(p =>
  151. {
  152. try
  153. {
  154. return new ConfigurationPageInfo(p);
  155. }
  156. catch (Exception ex)
  157. {
  158. Logger.ErrorException("Error getting plugin information from {0}", ex, p.GetType().Name);
  159. return null;
  160. }
  161. })
  162. .Where(i => i != null)
  163. .ToList();
  164. return ResultFactory.GetOptimizedResult(Request, configPages);
  165. }
  166. /// <summary>
  167. /// Gets the specified request.
  168. /// </summary>
  169. /// <param name="request">The request.</param>
  170. /// <returns>System.Object.</returns>
  171. public object Get(GetDashboardResource request)
  172. {
  173. var path = request.ResourceName;
  174. var contentType = MimeTypes.GetMimeType(path);
  175. var isHtml = IsHtml(path);
  176. if (isHtml && !_serverConfigurationManager.Configuration.IsStartupWizardCompleted)
  177. {
  178. if (path.IndexOf("wizard", StringComparison.OrdinalIgnoreCase) == -1)
  179. {
  180. Request.Response.Redirect("wizardstart.html");
  181. return null;
  182. }
  183. }
  184. path = path.Replace("scripts/jquery.mobile-1.4.5.min.map", "thirdparty/jquerymobile-1.4.5/jquery.mobile-1.4.5.min.map", StringComparison.OrdinalIgnoreCase);
  185. var localizationCulture = GetLocalizationCulture();
  186. // Don't cache if not configured to do so
  187. // But always cache images to simulate production
  188. if (!_serverConfigurationManager.Configuration.EnableDashboardResponseCaching &&
  189. !contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) &&
  190. !contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  191. {
  192. return ResultFactory.GetResult(GetResourceStream(path, localizationCulture).Result, contentType);
  193. }
  194. TimeSpan? cacheDuration = null;
  195. // Cache images unconditionally - updates to image files will require new filename
  196. // If there's a version number in the query string we can cache this unconditionally
  197. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase) || !string.IsNullOrEmpty(request.V))
  198. {
  199. cacheDuration = TimeSpan.FromDays(365);
  200. }
  201. var assembly = GetType().Assembly.GetName();
  202. var cacheKey = (assembly.Version + (localizationCulture ?? string.Empty) + path).GetMD5();
  203. return ResultFactory.GetStaticResult(Request, cacheKey, null, cacheDuration, contentType, () => GetResourceStream(path, localizationCulture));
  204. }
  205. private string GetLocalizationCulture()
  206. {
  207. return _serverConfigurationManager.Configuration.UICulture;
  208. }
  209. /// <summary>
  210. /// Gets the resource stream.
  211. /// </summary>
  212. /// <param name="path">The path.</param>
  213. /// <param name="localizationCulture">The localization culture.</param>
  214. /// <returns>Task{Stream}.</returns>
  215. private Task<Stream> GetResourceStream(string path, string localizationCulture)
  216. {
  217. var minify = _serverConfigurationManager.Configuration.EnableDashboardResourceMinification;
  218. return GetPackageCreator()
  219. .GetResource(path, null, localizationCulture, _appHost.ApplicationVersion.ToString(), minify);
  220. }
  221. private PackageCreator GetPackageCreator()
  222. {
  223. return new PackageCreator(_fileSystem, _localization, Logger, _serverConfigurationManager, _jsonSerializer);
  224. }
  225. /// <summary>
  226. /// Determines whether the specified path is HTML.
  227. /// </summary>
  228. /// <param name="path">The path.</param>
  229. /// <returns><c>true</c> if the specified path is HTML; otherwise, <c>false</c>.</returns>
  230. private bool IsHtml(string path)
  231. {
  232. return Path.GetExtension(path).EndsWith("html", StringComparison.OrdinalIgnoreCase);
  233. }
  234. public async Task<object> Get(GetDashboardPackage request)
  235. {
  236. var path = Path.Combine(_serverConfigurationManager.ApplicationPaths.ProgramDataPath,
  237. "webclient-dump");
  238. try
  239. {
  240. _fileSystem.DeleteDirectory(path, true);
  241. }
  242. catch (IOException)
  243. {
  244. }
  245. var creator = GetPackageCreator();
  246. CopyDirectory(creator.DashboardUIPath, path);
  247. var culture = "en-US";
  248. var appVersion = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture);
  249. var mode = request.Mode;
  250. await DumpHtml(creator.DashboardUIPath, path, mode, culture, appVersion);
  251. await DumpJs(creator.DashboardUIPath, path, mode, culture, appVersion);
  252. await DumpFile("scripts/all.js", Path.Combine(path, "scripts", "all.js"), mode, culture, appVersion).ConfigureAwait(false);
  253. await DumpFile("css/all.css", Path.Combine(path, "css", "all.css"), mode, culture, appVersion).ConfigureAwait(false);
  254. return "";
  255. }
  256. private async Task DumpHtml(string source, string destination, string mode, string culture, string appVersion)
  257. {
  258. foreach (var file in Directory.GetFiles(source, "*.html", SearchOption.TopDirectoryOnly))
  259. {
  260. var filename = Path.GetFileName(file);
  261. await DumpFile(filename, Path.Combine(destination, filename), mode, culture, appVersion).ConfigureAwait(false);
  262. }
  263. }
  264. private async Task DumpJs(string source, string mode, string destination, string culture, string appVersion)
  265. {
  266. foreach (var file in Directory.GetFiles(source, "*.js", SearchOption.TopDirectoryOnly))
  267. {
  268. var filename = Path.GetFileName(file);
  269. await DumpFile("scripts/" + filename, Path.Combine(destination, "scripts", filename), mode, culture, appVersion).ConfigureAwait(false);
  270. }
  271. }
  272. private async Task DumpFile(string resourceVirtualPath, string destinationFilePath, string mode, string culture, string appVersion)
  273. {
  274. using (var stream = await GetPackageCreator().GetResource(resourceVirtualPath, mode, culture, appVersion, true).ConfigureAwait(false))
  275. {
  276. using (var fs = _fileSystem.GetFileStream(destinationFilePath, FileMode.Create, FileAccess.Write, FileShare.Read))
  277. {
  278. stream.CopyTo(fs);
  279. }
  280. }
  281. }
  282. private void CopyDirectory(string source, string destination)
  283. {
  284. Directory.CreateDirectory(destination);
  285. //Now Create all of the directories
  286. foreach (string dirPath in Directory.GetDirectories(source, "*",
  287. SearchOption.AllDirectories))
  288. Directory.CreateDirectory(dirPath.Replace(source, destination));
  289. //Copy all the files & Replaces any files with the same name
  290. foreach (string newPath in Directory.GetFiles(source, "*.*",
  291. SearchOption.AllDirectories))
  292. File.Copy(newPath, newPath.Replace(source, destination), true);
  293. }
  294. }
  295. }