DashboardService.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. [Route("/robots.txt", "GET")]
  57. public class GetRobotsTxt
  58. {
  59. }
  60. /// <summary>
  61. /// Class GetDashboardResource
  62. /// </summary>
  63. [Route("/web/{ResourceName*}", "GET")]
  64. [Route("/dashboard/{ResourceName*}", "GET")]
  65. public class GetDashboardResource
  66. {
  67. /// <summary>
  68. /// Gets or sets the name.
  69. /// </summary>
  70. /// <value>The name.</value>
  71. public string ResourceName { get; set; }
  72. /// <summary>
  73. /// Gets or sets the V.
  74. /// </summary>
  75. /// <value>The V.</value>
  76. public string V { get; set; }
  77. }
  78. /// <summary>
  79. /// Class DashboardService
  80. /// </summary>
  81. public class DashboardService : IRestfulService, IHasResultFactory
  82. {
  83. /// <summary>
  84. /// Gets or sets the logger.
  85. /// </summary>
  86. /// <value>The logger.</value>
  87. public ILogger Logger { get; set; }
  88. /// <summary>
  89. /// Gets or sets the HTTP result factory.
  90. /// </summary>
  91. /// <value>The HTTP result factory.</value>
  92. public IHttpResultFactory ResultFactory { get; set; }
  93. /// <summary>
  94. /// Gets or sets the request context.
  95. /// </summary>
  96. /// <value>The request context.</value>
  97. public IRequest Request { get; set; }
  98. /// <summary>
  99. /// The _app host
  100. /// </summary>
  101. private readonly IServerApplicationHost _appHost;
  102. /// <summary>
  103. /// The _server configuration manager
  104. /// </summary>
  105. private readonly IServerConfigurationManager _serverConfigurationManager;
  106. private readonly IFileSystem _fileSystem;
  107. private readonly ILocalizationManager _localization;
  108. private readonly IJsonSerializer _jsonSerializer;
  109. /// <summary>
  110. /// Initializes a new instance of the <see cref="DashboardService" /> class.
  111. /// </summary>
  112. /// <param name="appHost">The app host.</param>
  113. /// <param name="serverConfigurationManager">The server configuration manager.</param>
  114. /// <param name="fileSystem">The file system.</param>
  115. public DashboardService(IServerApplicationHost appHost, IServerConfigurationManager serverConfigurationManager, IFileSystem fileSystem, ILocalizationManager localization, IJsonSerializer jsonSerializer)
  116. {
  117. _appHost = appHost;
  118. _serverConfigurationManager = serverConfigurationManager;
  119. _fileSystem = fileSystem;
  120. _localization = localization;
  121. _jsonSerializer = jsonSerializer;
  122. }
  123. /// <summary>
  124. /// Gets the specified request.
  125. /// </summary>
  126. /// <param name="request">The request.</param>
  127. /// <returns>System.Object.</returns>
  128. public object Get(GetDashboardConfigurationPage request)
  129. {
  130. var page = ServerEntryPoint.Instance.PluginConfigurationPages.First(p => p.Name.Equals(request.Name, StringComparison.OrdinalIgnoreCase));
  131. 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));
  132. }
  133. /// <summary>
  134. /// Gets the specified request.
  135. /// </summary>
  136. /// <param name="request">The request.</param>
  137. /// <returns>System.Object.</returns>
  138. public object Get(GetDashboardConfigurationPages request)
  139. {
  140. const string unavilableMessage = "The server is still loading. Please try again momentarily.";
  141. var instance = ServerEntryPoint.Instance;
  142. if (instance == null)
  143. {
  144. throw new InvalidOperationException(unavilableMessage);
  145. }
  146. var pages = instance.PluginConfigurationPages;
  147. if (pages == null)
  148. {
  149. throw new InvalidOperationException(unavilableMessage);
  150. }
  151. if (request.PageType.HasValue)
  152. {
  153. pages = pages.Where(p => p.ConfigurationPageType == request.PageType.Value);
  154. }
  155. // Don't allow a failing plugin to fail them all
  156. var configPages = pages.Select(p =>
  157. {
  158. try
  159. {
  160. return new ConfigurationPageInfo(p);
  161. }
  162. catch (Exception ex)
  163. {
  164. Logger.ErrorException("Error getting plugin information from {0}", ex, p.GetType().Name);
  165. return null;
  166. }
  167. })
  168. .Where(i => i != null)
  169. .ToList();
  170. return ResultFactory.GetOptimizedResult(Request, configPages);
  171. }
  172. public object Get(GetRobotsTxt request)
  173. {
  174. return Get(new GetDashboardResource
  175. {
  176. ResourceName = "robots.txt"
  177. });
  178. }
  179. /// <summary>
  180. /// Gets the specified request.
  181. /// </summary>
  182. /// <param name="request">The request.</param>
  183. /// <returns>System.Object.</returns>
  184. public object Get(GetDashboardResource request)
  185. {
  186. var path = request.ResourceName;
  187. path = path.Replace("bower_components" + _appHost.ApplicationVersion, "bower_components", StringComparison.OrdinalIgnoreCase);
  188. var contentType = MimeTypes.GetMimeType(path);
  189. // Bounce them to the startup wizard if it hasn't been completed yet
  190. if (!_serverConfigurationManager.Configuration.IsStartupWizardCompleted && path.IndexOf("wizard", StringComparison.OrdinalIgnoreCase) == -1 && GetPackageCreator().IsCoreHtml(path))
  191. {
  192. // But don't redirect if an html import is being requested.
  193. if (path.IndexOf("bower_components", StringComparison.OrdinalIgnoreCase) == -1)
  194. {
  195. Request.Response.Redirect("wizardstart.html");
  196. return null;
  197. }
  198. }
  199. 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);
  200. var localizationCulture = GetLocalizationCulture();
  201. // Don't cache if not configured to do so
  202. // But always cache images to simulate production
  203. if (!_serverConfigurationManager.Configuration.EnableDashboardResponseCaching &&
  204. !contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) &&
  205. !contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  206. {
  207. return ResultFactory.GetResult(GetResourceStream(path, localizationCulture).Result, contentType);
  208. }
  209. TimeSpan? cacheDuration = null;
  210. // Cache images unconditionally - updates to image files will require new filename
  211. // If there's a version number in the query string we can cache this unconditionally
  212. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase) || !string.IsNullOrEmpty(request.V))
  213. {
  214. cacheDuration = TimeSpan.FromDays(365);
  215. }
  216. var assembly = GetType().Assembly.GetName();
  217. var cacheKey = (assembly.Version + (localizationCulture ?? string.Empty) + path).GetMD5();
  218. return ResultFactory.GetStaticResult(Request, cacheKey, null, cacheDuration, contentType, () => GetResourceStream(path, localizationCulture));
  219. }
  220. private string GetLocalizationCulture()
  221. {
  222. return _serverConfigurationManager.Configuration.UICulture;
  223. }
  224. /// <summary>
  225. /// Gets the resource stream.
  226. /// </summary>
  227. /// <param name="path">The path.</param>
  228. /// <param name="localizationCulture">The localization culture.</param>
  229. /// <returns>Task{Stream}.</returns>
  230. private Task<Stream> GetResourceStream(string path, string localizationCulture)
  231. {
  232. var minify = _serverConfigurationManager.Configuration.EnableDashboardResourceMinification;
  233. return GetPackageCreator()
  234. .GetResource(path, null, localizationCulture, _appHost.ApplicationVersion.ToString(), minify);
  235. }
  236. private PackageCreator GetPackageCreator()
  237. {
  238. return new PackageCreator(_fileSystem, _localization, Logger, _serverConfigurationManager, _jsonSerializer);
  239. }
  240. public async Task<object> Get(GetDashboardPackage request)
  241. {
  242. var path = Path.Combine(_serverConfigurationManager.ApplicationPaths.ProgramDataPath,
  243. "webclient-dump");
  244. try
  245. {
  246. _fileSystem.DeleteDirectory(path, true);
  247. }
  248. catch (IOException)
  249. {
  250. }
  251. var creator = GetPackageCreator();
  252. CopyDirectory(creator.DashboardUIPath, path);
  253. string culture = null;
  254. var appVersion = _appHost.ApplicationVersion.ToString();
  255. var mode = request.Mode;
  256. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  257. {
  258. _fileSystem.DeleteFile(Path.Combine(path, "scripts", "registrationservices.js"));
  259. }
  260. // Try to trim the output size a bit
  261. var bowerPath = Path.Combine(path, "bower_components");
  262. if (!string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  263. {
  264. var versionedBowerPath = Path.Combine(Path.GetDirectoryName(bowerPath), "bower_components" + _appHost.ApplicationVersion);
  265. Directory.Move(bowerPath, versionedBowerPath);
  266. bowerPath = versionedBowerPath;
  267. }
  268. DeleteFilesByExtension(bowerPath, ".log");
  269. DeleteFilesByExtension(bowerPath, ".txt");
  270. DeleteFilesByExtension(bowerPath, ".map");
  271. DeleteFilesByExtension(bowerPath, ".md");
  272. DeleteFilesByExtension(bowerPath, ".json");
  273. DeleteFilesByExtension(bowerPath, ".gz");
  274. DeleteFilesByExtension(bowerPath, ".bat");
  275. DeleteFilesByExtension(bowerPath, ".sh");
  276. DeleteFilesByName(bowerPath, "copying", true);
  277. DeleteFilesByName(bowerPath, "license", true);
  278. DeleteFilesByName(bowerPath, "license-mit", true);
  279. DeleteFilesByName(bowerPath, "gitignore");
  280. DeleteFilesByName(bowerPath, "npmignore");
  281. DeleteFilesByName(bowerPath, "jshintrc");
  282. DeleteFilesByName(bowerPath, "gruntfile");
  283. DeleteFilesByName(bowerPath, "bowerrc");
  284. DeleteFilesByName(bowerPath, "jscsrc");
  285. DeleteFilesByName(bowerPath, "hero.svg");
  286. DeleteFilesByName(bowerPath, "travis.yml");
  287. DeleteFilesByName(bowerPath, "build.js");
  288. DeleteFilesByName(bowerPath, "editorconfig");
  289. DeleteFilesByName(bowerPath, "gitattributes");
  290. DeleteFoldersByName(bowerPath, "demo");
  291. DeleteFoldersByName(bowerPath, "test");
  292. DeleteFoldersByName(bowerPath, "guides");
  293. DeleteFoldersByName(bowerPath, "grunt");
  294. DeleteFoldersByName(bowerPath, "rollups");
  295. DeleteFoldersByName(Path.Combine(bowerPath, "emby-webcomponents"), "fonts");
  296. _fileSystem.DeleteDirectory(Path.Combine(bowerPath, "jquery", "src"), true);
  297. DeleteCryptoFiles(Path.Combine(bowerPath, "cryptojslib", "components"));
  298. DeleteFoldersByName(Path.Combine(bowerPath, "jquery"), "src");
  299. DeleteFoldersByName(Path.Combine(bowerPath, "jstree"), "src");
  300. DeleteFoldersByName(Path.Combine(bowerPath, "Sortable"), "meteor");
  301. DeleteFoldersByName(Path.Combine(bowerPath, "Sortable"), "st");
  302. DeleteFoldersByName(Path.Combine(bowerPath, "Swiper"), "src");
  303. DeleteFoldersByName(Path.Combine(bowerPath, "material-design-lite"), "src");
  304. DeleteFoldersByName(Path.Combine(bowerPath, "material-design-lite"), "utils");
  305. _fileSystem.DeleteFile(Path.Combine(bowerPath, "material-design-lite", "gulpfile.babel.js"));
  306. _fileSystem.DeleteDirectory(Path.Combine(bowerPath, "marked"), true);
  307. _fileSystem.DeleteDirectory(Path.Combine(bowerPath, "marked-element"), true);
  308. _fileSystem.DeleteDirectory(Path.Combine(bowerPath, "prism"), true);
  309. _fileSystem.DeleteDirectory(Path.Combine(bowerPath, "prism-element"), true);
  310. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  311. {
  312. // Delete things that are unneeded in an attempt to keep the output as trim as possible
  313. _fileSystem.DeleteDirectory(Path.Combine(path, "css", "images", "tour"), true);
  314. _fileSystem.DeleteFile(Path.Combine(path, "thirdparty", "jquerymobile-1.4.5", "jquery.mobile-1.4.5.min.map"));
  315. }
  316. else
  317. {
  318. MinifyCssDirectory(path);
  319. MinifyJsDirectory(path);
  320. }
  321. await DumpHtml(creator.DashboardUIPath, path, mode, culture, appVersion);
  322. await DumpFile("css/all.css", Path.Combine(path, "css", "all.css"), mode, culture, appVersion).ConfigureAwait(false);
  323. return "";
  324. }
  325. private void DeleteCryptoFiles(string path)
  326. {
  327. var files = _fileSystem.GetFiles(path)
  328. .ToList();
  329. var keepFiles = new[] { "core-min.js", "md5-min.js", "sha1-min.js" };
  330. foreach (var file in files)
  331. {
  332. if (!keepFiles.Contains(file.Name, StringComparer.OrdinalIgnoreCase))
  333. {
  334. _fileSystem.DeleteFile(file.FullName);
  335. }
  336. }
  337. }
  338. private void DeleteFilesByExtension(string path, string extension)
  339. {
  340. var files = _fileSystem.GetFiles(path, true)
  341. .Where(i => string.Equals(i.Extension, extension, StringComparison.OrdinalIgnoreCase))
  342. .ToList();
  343. foreach (var file in files)
  344. {
  345. _fileSystem.DeleteFile(file.FullName);
  346. }
  347. }
  348. private void DeleteFilesByName(string path, string name, bool exact = false)
  349. {
  350. var files = _fileSystem.GetFiles(path, true)
  351. .Where(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase) || (!exact && i.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1))
  352. .ToList();
  353. foreach (var file in files)
  354. {
  355. _fileSystem.DeleteFile(file.FullName);
  356. }
  357. }
  358. private void DeleteFoldersByName(string path, string name)
  359. {
  360. var directories = _fileSystem.GetDirectories(path, true)
  361. .Where(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase))
  362. .ToList();
  363. foreach (var directory in directories)
  364. {
  365. _fileSystem.DeleteDirectory(directory.FullName, true);
  366. }
  367. }
  368. private void MinifyCssDirectory(string path)
  369. {
  370. foreach (var file in Directory.GetFiles(path, "*.css", SearchOption.AllDirectories))
  371. {
  372. if (file.IndexOf(".min.", StringComparison.OrdinalIgnoreCase) != -1)
  373. {
  374. continue;
  375. }
  376. if (file.IndexOf("bower_", StringComparison.OrdinalIgnoreCase) != -1)
  377. {
  378. continue;
  379. }
  380. try
  381. {
  382. var text = _fileSystem.ReadAllText(file, Encoding.UTF8);
  383. var result = new KristensenCssMinifier().Minify(text, false, Encoding.UTF8);
  384. if (result.Errors.Count > 0)
  385. {
  386. Logger.Error("Error minifying css: " + result.Errors[0].Message);
  387. }
  388. else
  389. {
  390. text = result.MinifiedContent;
  391. _fileSystem.WriteAllText(file, text, Encoding.UTF8);
  392. }
  393. }
  394. catch (Exception ex)
  395. {
  396. Logger.ErrorException("Error minifying css", ex);
  397. }
  398. }
  399. }
  400. private void MinifyJsDirectory(string path)
  401. {
  402. foreach (var file in Directory.GetFiles(path, "*.js", SearchOption.AllDirectories))
  403. {
  404. if (file.IndexOf(".min.", StringComparison.OrdinalIgnoreCase) != -1)
  405. {
  406. continue;
  407. }
  408. if (file.IndexOf("bower_", StringComparison.OrdinalIgnoreCase) != -1)
  409. {
  410. continue;
  411. }
  412. try
  413. {
  414. var text = _fileSystem.ReadAllText(file, Encoding.UTF8);
  415. var result = new CrockfordJsMinifier().Minify(text, false, Encoding.UTF8);
  416. if (result.Errors.Count > 0)
  417. {
  418. Logger.Error("Error minifying javascript: " + result.Errors[0].Message);
  419. }
  420. else
  421. {
  422. text = result.MinifiedContent;
  423. _fileSystem.WriteAllText(file, text, Encoding.UTF8);
  424. }
  425. }
  426. catch (Exception ex)
  427. {
  428. Logger.ErrorException("Error minifying css", ex);
  429. }
  430. }
  431. }
  432. private async Task DumpHtml(string source, string destination, string mode, string culture, string appVersion)
  433. {
  434. foreach (var file in Directory.GetFiles(source, "*", SearchOption.TopDirectoryOnly))
  435. {
  436. var filename = Path.GetFileName(file);
  437. await DumpFile(filename, Path.Combine(destination, filename), mode, culture, appVersion).ConfigureAwait(false);
  438. }
  439. var excludeFiles = new List<string>();
  440. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  441. {
  442. excludeFiles.Add("supporterkey.html");
  443. }
  444. foreach (var file in excludeFiles)
  445. {
  446. _fileSystem.DeleteFile(Path.Combine(destination, file));
  447. }
  448. }
  449. private async Task DumpFile(string resourceVirtualPath, string destinationFilePath, string mode, string culture, string appVersion)
  450. {
  451. using (var stream = await GetPackageCreator().GetResource(resourceVirtualPath, mode, culture, appVersion, true).ConfigureAwait(false))
  452. {
  453. using (var fs = _fileSystem.GetFileStream(destinationFilePath, FileMode.Create, FileAccess.Write, FileShare.Read))
  454. {
  455. stream.CopyTo(fs);
  456. }
  457. }
  458. }
  459. private void CopyDirectory(string source, string destination)
  460. {
  461. _fileSystem.CreateDirectory(destination);
  462. //Now Create all of the directories
  463. foreach (string dirPath in Directory.GetDirectories(source, "*",
  464. SearchOption.AllDirectories))
  465. _fileSystem.CreateDirectory(dirPath.Replace(source, destination));
  466. //Copy all the files & Replaces any files with the same name
  467. foreach (string newPath in Directory.GetFiles(source, "*.*",
  468. SearchOption.AllDirectories))
  469. _fileSystem.CopyFile(newPath, newPath.Replace(source, destination), true);
  470. }
  471. }
  472. }