DashboardService.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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.Text;
  19. using System.Threading.Tasks;
  20. using WebMarkupMin.Core.Minifiers;
  21. namespace MediaBrowser.WebDashboard.Api
  22. {
  23. /// <summary>
  24. /// Class GetDashboardConfigurationPages
  25. /// </summary>
  26. [Route("/dashboard/ConfigurationPages", "GET")]
  27. [Route("/web/ConfigurationPages", "GET")]
  28. public class GetDashboardConfigurationPages : IReturn<List<ConfigurationPageInfo>>
  29. {
  30. /// <summary>
  31. /// Gets or sets the type of the page.
  32. /// </summary>
  33. /// <value>The type of the page.</value>
  34. public ConfigurationPageType? PageType { get; set; }
  35. }
  36. /// <summary>
  37. /// Class GetDashboardConfigurationPage
  38. /// </summary>
  39. [Route("/dashboard/ConfigurationPage", "GET")]
  40. [Route("/web/ConfigurationPage", "GET")]
  41. public class GetDashboardConfigurationPage
  42. {
  43. /// <summary>
  44. /// Gets or sets the name.
  45. /// </summary>
  46. /// <value>The name.</value>
  47. public string Name { get; set; }
  48. }
  49. [Route("/web/Package", "GET")]
  50. [Route("/dashboard/Package", "GET")]
  51. public class GetDashboardPackage
  52. {
  53. public string Mode { get; set; }
  54. }
  55. /// <summary>
  56. /// Class GetDashboardResource
  57. /// </summary>
  58. [Route("/web/{ResourceName*}", "GET")]
  59. [Route("/dashboard/{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. /// <summary>
  74. /// Class DashboardService
  75. /// </summary>
  76. public class DashboardService : IRestfulService, IHasResultFactory
  77. {
  78. /// <summary>
  79. /// Gets or sets the logger.
  80. /// </summary>
  81. /// <value>The logger.</value>
  82. public ILogger Logger { get; set; }
  83. /// <summary>
  84. /// Gets or sets the HTTP result factory.
  85. /// </summary>
  86. /// <value>The HTTP result factory.</value>
  87. public IHttpResultFactory ResultFactory { get; set; }
  88. /// <summary>
  89. /// Gets or sets the request context.
  90. /// </summary>
  91. /// <value>The request context.</value>
  92. public IRequest Request { get; set; }
  93. /// <summary>
  94. /// The _app host
  95. /// </summary>
  96. private readonly IServerApplicationHost _appHost;
  97. /// <summary>
  98. /// The _server configuration manager
  99. /// </summary>
  100. private readonly IServerConfigurationManager _serverConfigurationManager;
  101. private readonly IFileSystem _fileSystem;
  102. private readonly ILocalizationManager _localization;
  103. private readonly IJsonSerializer _jsonSerializer;
  104. /// <summary>
  105. /// Initializes a new instance of the <see cref="DashboardService" /> class.
  106. /// </summary>
  107. /// <param name="appHost">The app host.</param>
  108. /// <param name="serverConfigurationManager">The server configuration manager.</param>
  109. /// <param name="fileSystem">The file system.</param>
  110. public DashboardService(IServerApplicationHost appHost, IServerConfigurationManager serverConfigurationManager, IFileSystem fileSystem, ILocalizationManager localization, IJsonSerializer jsonSerializer)
  111. {
  112. _appHost = appHost;
  113. _serverConfigurationManager = serverConfigurationManager;
  114. _fileSystem = fileSystem;
  115. _localization = localization;
  116. _jsonSerializer = jsonSerializer;
  117. }
  118. /// <summary>
  119. /// Gets the specified request.
  120. /// </summary>
  121. /// <param name="request">The request.</param>
  122. /// <returns>System.Object.</returns>
  123. public object Get(GetDashboardConfigurationPage request)
  124. {
  125. var page = ServerEntryPoint.Instance.PluginConfigurationPages.First(p => p.Name.Equals(request.Name, StringComparison.OrdinalIgnoreCase));
  126. return ResultFactory.GetStaticResult(Request, page.Plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => GetPackageCreator().ModifyHtml(page.GetHtmlStream(), null, _appHost.ApplicationVersion.ToString(), null, false));
  127. }
  128. /// <summary>
  129. /// Gets the specified request.
  130. /// </summary>
  131. /// <param name="request">The request.</param>
  132. /// <returns>System.Object.</returns>
  133. public object Get(GetDashboardConfigurationPages request)
  134. {
  135. const string unavilableMessage = "The server is still loading. Please try again momentarily.";
  136. var instance = ServerEntryPoint.Instance;
  137. if (instance == null)
  138. {
  139. throw new InvalidOperationException(unavilableMessage);
  140. }
  141. var pages = instance.PluginConfigurationPages;
  142. if (pages == null)
  143. {
  144. throw new InvalidOperationException(unavilableMessage);
  145. }
  146. if (request.PageType.HasValue)
  147. {
  148. pages = pages.Where(p => p.ConfigurationPageType == request.PageType.Value);
  149. }
  150. // Don't allow a failing plugin to fail them all
  151. var configPages = pages.Select(p =>
  152. {
  153. try
  154. {
  155. return new ConfigurationPageInfo(p);
  156. }
  157. catch (Exception ex)
  158. {
  159. Logger.ErrorException("Error getting plugin information from {0}", ex, p.GetType().Name);
  160. return null;
  161. }
  162. })
  163. .Where(i => i != null)
  164. .ToList();
  165. return ResultFactory.GetOptimizedResult(Request, configPages);
  166. }
  167. /// <summary>
  168. /// Gets the specified request.
  169. /// </summary>
  170. /// <param name="request">The request.</param>
  171. /// <returns>System.Object.</returns>
  172. public object Get(GetDashboardResource request)
  173. {
  174. var path = request.ResourceName;
  175. var contentType = MimeTypes.GetMimeType(path);
  176. // Bounce them to the startup wizard if it hasn't been completed yet
  177. if (!_serverConfigurationManager.Configuration.IsStartupWizardCompleted && path.IndexOf("wizard", StringComparison.OrdinalIgnoreCase) == -1 && GetPackageCreator().IsCoreHtml(path))
  178. {
  179. // But don't redirect if an html import is being requested.
  180. if (path.IndexOf("vulcanize", StringComparison.OrdinalIgnoreCase) == -1 && path.IndexOf("bower_components", StringComparison.OrdinalIgnoreCase) == -1)
  181. {
  182. Request.Response.Redirect("wizardstart.html");
  183. return null;
  184. }
  185. }
  186. 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);
  187. var localizationCulture = GetLocalizationCulture();
  188. // Don't cache if not configured to do so
  189. // But always cache images to simulate production
  190. if (!_serverConfigurationManager.Configuration.EnableDashboardResponseCaching &&
  191. !contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) &&
  192. !contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  193. {
  194. return ResultFactory.GetResult(GetResourceStream(path, localizationCulture).Result, contentType);
  195. }
  196. TimeSpan? cacheDuration = null;
  197. // Cache images unconditionally - updates to image files will require new filename
  198. // If there's a version number in the query string we can cache this unconditionally
  199. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase) || !string.IsNullOrEmpty(request.V))
  200. {
  201. cacheDuration = TimeSpan.FromDays(365);
  202. }
  203. var assembly = GetType().Assembly.GetName();
  204. var cacheKey = (assembly.Version + (localizationCulture ?? string.Empty) + path).GetMD5();
  205. return ResultFactory.GetStaticResult(Request, cacheKey, null, cacheDuration, contentType, () => GetResourceStream(path, localizationCulture));
  206. }
  207. private string GetLocalizationCulture()
  208. {
  209. return _serverConfigurationManager.Configuration.UICulture;
  210. }
  211. /// <summary>
  212. /// Gets the resource stream.
  213. /// </summary>
  214. /// <param name="path">The path.</param>
  215. /// <param name="localizationCulture">The localization culture.</param>
  216. /// <returns>Task{Stream}.</returns>
  217. private Task<Stream> GetResourceStream(string path, string localizationCulture)
  218. {
  219. var minify = _serverConfigurationManager.Configuration.EnableDashboardResourceMinification;
  220. return GetPackageCreator()
  221. .GetResource(path, null, localizationCulture, _appHost.ApplicationVersion.ToString(), minify);
  222. }
  223. private PackageCreator GetPackageCreator()
  224. {
  225. return new PackageCreator(_fileSystem, _localization, Logger, _serverConfigurationManager, _jsonSerializer);
  226. }
  227. /// <summary>
  228. /// Determines whether the specified path is HTML.
  229. /// </summary>
  230. /// <param name="path">The path.</param>
  231. /// <returns><c>true</c> if the specified path is HTML; otherwise, <c>false</c>.</returns>
  232. private bool IsHtml(string path)
  233. {
  234. return Path.GetExtension(path).EndsWith("html", StringComparison.OrdinalIgnoreCase);
  235. }
  236. private void CopyFile(string src, string dst)
  237. {
  238. _fileSystem.CreateDirectory(Path.GetDirectoryName(dst));
  239. _fileSystem.CopyFile(src, dst, true);
  240. }
  241. public async Task<object> Get(GetDashboardPackage request)
  242. {
  243. var path = Path.Combine(_serverConfigurationManager.ApplicationPaths.ProgramDataPath,
  244. "webclient-dump");
  245. try
  246. {
  247. _fileSystem.DeleteDirectory(path, true);
  248. }
  249. catch (IOException)
  250. {
  251. }
  252. var creator = GetPackageCreator();
  253. CopyDirectory(creator.DashboardUIPath, path);
  254. string culture = null;
  255. var appVersion = _appHost.ApplicationVersion.ToString();
  256. var mode = request.Mode;
  257. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  258. {
  259. // Overwrite certain files with cordova specific versions
  260. var cordovaVersion = Path.Combine(path, "cordova", "registrationservices.js");
  261. _fileSystem.CopyFile(cordovaVersion, Path.Combine(path, "scripts", "registrationservices.js"), true);
  262. _fileSystem.DeleteFile(cordovaVersion);
  263. // Delete things that are unneeded in an attempt to keep the output as trim as possible
  264. _fileSystem.DeleteDirectory(Path.Combine(path, "css", "images", "tour"), true);
  265. _fileSystem.DeleteDirectory(Path.Combine(path, "apiclient", "alt"), true);
  266. _fileSystem.DeleteFile(Path.Combine(path, "thirdparty", "jquerymobile-1.4.5", "jquery.mobile-1.4.5.min.map"));
  267. _fileSystem.DeleteDirectory(Path.Combine(path, "bower_components"), true);
  268. _fileSystem.DeleteDirectory(Path.Combine(path, "thirdparty", "viblast"), true);
  269. // But we do need this
  270. CopyFile(Path.Combine(creator.DashboardUIPath, "bower_components", "webcomponentsjs", "webcomponents-lite.js"), Path.Combine(path, "bower_components", "webcomponentsjs", "webcomponents-lite.js"));
  271. CopyFile(Path.Combine(creator.DashboardUIPath, "bower_components", "webcomponentsjs", "webcomponents-lite.min.js"), Path.Combine(path, "bower_components", "webcomponentsjs", "webcomponents-lite.min.js"));
  272. CopyFile(Path.Combine(creator.DashboardUIPath, "bower_components", "velocity", "velocity.min.js"), Path.Combine(path, "bower_components", "velocity", "velocity.min.js"));
  273. CopyFile(Path.Combine(creator.DashboardUIPath, "bower_components", "requirejs", "require.js"), Path.Combine(path, "bower_components", "requirejs", "require.js"));
  274. CopyFile(Path.Combine(creator.DashboardUIPath, "bower_components", "fastclick", "lib", "fastclick.js"), Path.Combine(path, "bower_components", "fastclick", "lib", "fastclick.js"));
  275. CopyFile(Path.Combine(creator.DashboardUIPath, "bower_components", "jquery", "dist", "jquery.min.js"), Path.Combine(path, "bower_components", "jquery", "dist", "jquery.min.js"));
  276. CopyFile(Path.Combine(creator.DashboardUIPath, "bower_components", "jstree", "dist", "jstree.min.js"), Path.Combine(path, "bower_components", "jstree", "dist", "jstree.min.js"));
  277. CopyDirectory(Path.Combine(creator.DashboardUIPath, "bower_components", "swipebox", "src", "css"), Path.Combine(path, "bower_components", "swipebox", "src", "css"));
  278. CopyDirectory(Path.Combine(creator.DashboardUIPath, "bower_components", "swipebox", "src", "js"), Path.Combine(path, "bower_components", "swipebox", "src", "js"));
  279. CopyDirectory(Path.Combine(creator.DashboardUIPath, "bower_components", "swipebox", "src", "img"), Path.Combine(path, "bower_components", "swipebox", "src", "img"));
  280. CopyFile(Path.Combine(creator.DashboardUIPath, "bower_components", "hammerjs", "hammer.min.js"), Path.Combine(path, "bower_components", "hammerjs", "hammer.min.js"));
  281. }
  282. MinifyCssDirectory(Path.Combine(path, "css"));
  283. MinifyJsDirectory(Path.Combine(path, "scripts"));
  284. MinifyJsDirectory(Path.Combine(path, "apiclient"));
  285. MinifyJsDirectory(Path.Combine(path, "voice"));
  286. await DumpHtml(creator.DashboardUIPath, path, mode, culture, appVersion);
  287. await DumpJs(creator.DashboardUIPath, path, mode, culture, appVersion);
  288. await DumpFile("scripts/all.js", Path.Combine(path, "scripts", "all.js"), mode, culture, appVersion).ConfigureAwait(false);
  289. await DumpFile("css/all.css", Path.Combine(path, "css", "all.css"), mode, culture, appVersion).ConfigureAwait(false);
  290. return "";
  291. }
  292. private void MinifyCssDirectory(string path)
  293. {
  294. foreach (var file in Directory.GetFiles(path, "*.css", SearchOption.AllDirectories))
  295. {
  296. try
  297. {
  298. var text = _fileSystem.ReadAllText(file, Encoding.UTF8);
  299. var result = new KristensenCssMinifier().Minify(text, false, Encoding.UTF8);
  300. if (result.Errors.Count > 0)
  301. {
  302. Logger.Error("Error minifying css: " + result.Errors[0].Message);
  303. }
  304. else
  305. {
  306. text = result.MinifiedContent;
  307. _fileSystem.WriteAllText(file, text, Encoding.UTF8);
  308. }
  309. }
  310. catch (Exception ex)
  311. {
  312. Logger.ErrorException("Error minifying css", ex);
  313. }
  314. }
  315. }
  316. private void MinifyJsDirectory(string path)
  317. {
  318. foreach (var file in Directory.GetFiles(path, "*.js", SearchOption.AllDirectories))
  319. {
  320. try
  321. {
  322. var text = _fileSystem.ReadAllText(file, Encoding.UTF8);
  323. var result = new CrockfordJsMinifier().Minify(text, false, Encoding.UTF8);
  324. if (result.Errors.Count > 0)
  325. {
  326. Logger.Error("Error minifying javascript: " + result.Errors[0].Message);
  327. }
  328. else
  329. {
  330. text = result.MinifiedContent;
  331. _fileSystem.WriteAllText(file, text, Encoding.UTF8);
  332. }
  333. }
  334. catch (Exception ex)
  335. {
  336. Logger.ErrorException("Error minifying css", ex);
  337. }
  338. }
  339. }
  340. private async Task DumpHtml(string source, string destination, string mode, string culture, string appVersion)
  341. {
  342. foreach (var file in Directory.GetFiles(source, "*.html", SearchOption.TopDirectoryOnly))
  343. {
  344. var filename = Path.GetFileName(file);
  345. await DumpFile(filename, Path.Combine(destination, filename), mode, culture, appVersion).ConfigureAwait(false);
  346. }
  347. var excludeFiles = new List<string>();
  348. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  349. {
  350. excludeFiles.Add("supporterkey.html");
  351. }
  352. foreach (var file in excludeFiles)
  353. {
  354. _fileSystem.DeleteFile(Path.Combine(destination, file));
  355. }
  356. }
  357. private async Task DumpJs(string source, string mode, string destination, string culture, string appVersion)
  358. {
  359. foreach (var file in Directory.GetFiles(source, "*.js", SearchOption.TopDirectoryOnly))
  360. {
  361. var filename = Path.GetFileName(file);
  362. await DumpFile("scripts/" + filename, Path.Combine(destination, "scripts", filename), mode, culture, appVersion).ConfigureAwait(false);
  363. }
  364. }
  365. private async Task DumpFile(string resourceVirtualPath, string destinationFilePath, string mode, string culture, string appVersion)
  366. {
  367. using (var stream = await GetPackageCreator().GetResource(resourceVirtualPath, mode, culture, appVersion, true).ConfigureAwait(false))
  368. {
  369. using (var fs = _fileSystem.GetFileStream(destinationFilePath, FileMode.Create, FileAccess.Write, FileShare.Read))
  370. {
  371. stream.CopyTo(fs);
  372. }
  373. }
  374. }
  375. private void CopyDirectory(string source, string destination)
  376. {
  377. _fileSystem.CreateDirectory(destination);
  378. //Now Create all of the directories
  379. foreach (string dirPath in Directory.GetDirectories(source, "*",
  380. SearchOption.AllDirectories))
  381. _fileSystem.CreateDirectory(dirPath.Replace(source, destination));
  382. //Copy all the files & Replaces any files with the same name
  383. foreach (string newPath in Directory.GetFiles(source, "*.*",
  384. SearchOption.AllDirectories))
  385. _fileSystem.CopyFile(newPath, newPath.Replace(source, destination), true);
  386. }
  387. }
  388. }