DashboardService.cs 14 KB

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