DashboardService.cs 13 KB

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