DashboardService.cs 13 KB

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