DashboardService.cs 20 KB

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