PackageCreator.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Localization;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Serialization;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using CommonIO;
  13. using MediaBrowser.Controller.Net;
  14. using WebMarkupMin.Core;
  15. using WebMarkupMin.Core.Minifiers;
  16. using WebMarkupMin.Core.Settings;
  17. namespace MediaBrowser.WebDashboard.Api
  18. {
  19. public class PackageCreator
  20. {
  21. private readonly IFileSystem _fileSystem;
  22. private readonly ILocalizationManager _localization;
  23. private readonly ILogger _logger;
  24. private readonly IServerConfigurationManager _config;
  25. private readonly IJsonSerializer _jsonSerializer;
  26. public PackageCreator(IFileSystem fileSystem, ILocalizationManager localization, ILogger logger, IServerConfigurationManager config, IJsonSerializer jsonSerializer)
  27. {
  28. _fileSystem = fileSystem;
  29. _localization = localization;
  30. _logger = logger;
  31. _config = config;
  32. _jsonSerializer = jsonSerializer;
  33. }
  34. public async Task<Stream> GetResource(string path,
  35. string mode,
  36. string localizationCulture,
  37. string appVersion,
  38. bool enableMinification)
  39. {
  40. Stream resourceStream;
  41. if (path.Equals("scripts/all.js", StringComparison.OrdinalIgnoreCase))
  42. {
  43. resourceStream = await GetAllJavascript(mode, localizationCulture, appVersion, enableMinification).ConfigureAwait(false);
  44. enableMinification = false;
  45. }
  46. else if (path.Equals("css/all.css", StringComparison.OrdinalIgnoreCase))
  47. {
  48. resourceStream = await GetAllCss(enableMinification).ConfigureAwait(false);
  49. enableMinification = false;
  50. }
  51. else
  52. {
  53. resourceStream = GetRawResourceStream(path);
  54. }
  55. if (resourceStream != null)
  56. {
  57. // Don't apply any caching for html pages
  58. // jQuery ajax doesn't seem to handle if-modified-since correctly
  59. if (IsFormat(path, "html"))
  60. {
  61. if (IsCoreHtml(path))
  62. {
  63. resourceStream = await ModifyHtml(resourceStream, mode, appVersion, localizationCulture, enableMinification).ConfigureAwait(false);
  64. }
  65. }
  66. else if (IsFormat(path, "js"))
  67. {
  68. if (path.IndexOf("thirdparty", StringComparison.OrdinalIgnoreCase) == -1 && path.IndexOf("bower_components", StringComparison.OrdinalIgnoreCase) == -1)
  69. {
  70. resourceStream = await ModifyJs(resourceStream, enableMinification).ConfigureAwait(false);
  71. }
  72. }
  73. else if (IsFormat(path, "css"))
  74. {
  75. if (path.IndexOf("thirdparty", StringComparison.OrdinalIgnoreCase) == -1 && path.IndexOf("bower_components", StringComparison.OrdinalIgnoreCase) == -1)
  76. {
  77. resourceStream = await ModifyCss(resourceStream, enableMinification).ConfigureAwait(false);
  78. }
  79. }
  80. }
  81. return resourceStream;
  82. }
  83. /// <summary>
  84. /// Determines whether the specified path is HTML.
  85. /// </summary>
  86. /// <param name="path">The path.</param>
  87. /// <param name="format">The format.</param>
  88. /// <returns><c>true</c> if the specified path is HTML; otherwise, <c>false</c>.</returns>
  89. private bool IsFormat(string path, string format)
  90. {
  91. return Path.GetExtension(path).EndsWith(format, StringComparison.OrdinalIgnoreCase);
  92. }
  93. /// <summary>
  94. /// Gets the dashboard UI path.
  95. /// </summary>
  96. /// <value>The dashboard UI path.</value>
  97. public string DashboardUIPath
  98. {
  99. get
  100. {
  101. if (!string.IsNullOrEmpty(_config.Configuration.DashboardSourcePath))
  102. {
  103. return _config.Configuration.DashboardSourcePath;
  104. }
  105. return Path.Combine(_config.ApplicationPaths.ApplicationResourcesPath, "dashboard-ui");
  106. }
  107. }
  108. /// <summary>
  109. /// Gets the dashboard resource path.
  110. /// </summary>
  111. /// <param name="virtualPath">The virtual path.</param>
  112. /// <returns>System.String.</returns>
  113. private string GetDashboardResourcePath(string virtualPath)
  114. {
  115. var rootPath = DashboardUIPath;
  116. var fullPath = Path.Combine(rootPath, virtualPath.Replace('/', Path.DirectorySeparatorChar));
  117. try
  118. {
  119. fullPath = Path.GetFullPath(fullPath);
  120. }
  121. catch (Exception ex)
  122. {
  123. _logger.ErrorException("Error in Path.GetFullPath", ex);
  124. }
  125. // Don't allow file system access outside of the source folder
  126. if (!_fileSystem.ContainsSubPath(rootPath, fullPath))
  127. {
  128. throw new SecurityException("Access denied");
  129. }
  130. return fullPath;
  131. }
  132. public async Task<Stream> ModifyCss(Stream sourceStream, bool enableMinification)
  133. {
  134. using (sourceStream)
  135. {
  136. string content;
  137. using (var memoryStream = new MemoryStream())
  138. {
  139. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  140. content = Encoding.UTF8.GetString(memoryStream.ToArray());
  141. if (enableMinification)
  142. {
  143. try
  144. {
  145. var result = new KristensenCssMinifier().Minify(content, false, Encoding.UTF8);
  146. if (result.Errors.Count > 0)
  147. {
  148. _logger.Error("Error minifying css: " + result.Errors[0].Message);
  149. }
  150. else
  151. {
  152. content = result.MinifiedContent;
  153. }
  154. }
  155. catch (Exception ex)
  156. {
  157. _logger.ErrorException("Error minifying css", ex);
  158. }
  159. }
  160. }
  161. var bytes = Encoding.UTF8.GetBytes(content);
  162. return new MemoryStream(bytes);
  163. }
  164. }
  165. public async Task<Stream> ModifyJs(Stream sourceStream, bool enableMinification)
  166. {
  167. using (sourceStream)
  168. {
  169. string content;
  170. using (var memoryStream = new MemoryStream())
  171. {
  172. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  173. content = Encoding.UTF8.GetString(memoryStream.ToArray());
  174. if (enableMinification)
  175. {
  176. try
  177. {
  178. var result = new CrockfordJsMinifier().Minify(content, false, Encoding.UTF8);
  179. if (result.Errors.Count > 0)
  180. {
  181. _logger.Error("Error minifying javascript: " + result.Errors[0].Message);
  182. }
  183. else
  184. {
  185. content = result.MinifiedContent;
  186. }
  187. }
  188. catch (Exception ex)
  189. {
  190. _logger.ErrorException("Error minifying javascript", ex);
  191. }
  192. }
  193. }
  194. var bytes = Encoding.UTF8.GetBytes(content);
  195. return new MemoryStream(bytes);
  196. }
  197. }
  198. public bool IsCoreHtml(string path)
  199. {
  200. if (path.IndexOf("vulcanize", StringComparison.OrdinalIgnoreCase) != -1)
  201. {
  202. return false;
  203. }
  204. if (path.IndexOf(".template.html", StringComparison.OrdinalIgnoreCase) != -1)
  205. {
  206. return false;
  207. }
  208. path = GetDashboardResourcePath(path);
  209. var parent = Path.GetDirectoryName(path);
  210. var basePath = DashboardUIPath;
  211. return string.Equals(basePath, parent, StringComparison.OrdinalIgnoreCase) ||
  212. string.Equals(Path.Combine(basePath, "voice"), parent, StringComparison.OrdinalIgnoreCase);
  213. }
  214. /// <summary>
  215. /// Modifies the HTML by adding common meta tags, css and js.
  216. /// </summary>
  217. /// <param name="sourceStream">The source stream.</param>
  218. /// <param name="mode">The mode.</param>
  219. /// <param name="appVersion">The application version.</param>
  220. /// <param name="localizationCulture">The localization culture.</param>
  221. /// <param name="enableMinification">if set to <c>true</c> [enable minification].</param>
  222. /// <returns>Task{Stream}.</returns>
  223. public async Task<Stream> ModifyHtml(Stream sourceStream, string mode, string appVersion, string localizationCulture, bool enableMinification)
  224. {
  225. using (sourceStream)
  226. {
  227. string html;
  228. using (var memoryStream = new MemoryStream())
  229. {
  230. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  231. html = Encoding.UTF8.GetString(memoryStream.ToArray());
  232. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  233. {
  234. html = ModifyForCordova(html);
  235. }
  236. if (!string.IsNullOrWhiteSpace(localizationCulture))
  237. {
  238. var lang = localizationCulture.Split('-').FirstOrDefault();
  239. html = html.Replace("<html>", "<html data-culture=\"" + localizationCulture + "\" lang=\"" + lang + "\">");
  240. }
  241. if (enableMinification)
  242. {
  243. try
  244. {
  245. var minifier = new HtmlMinifier(new HtmlMinificationSettings
  246. {
  247. AttributeQuotesRemovalMode = HtmlAttributeQuotesRemovalMode.KeepQuotes,
  248. RemoveOptionalEndTags = false,
  249. RemoveTagsWithoutContent = false
  250. });
  251. var result = minifier.Minify(html, false);
  252. if (result.Errors.Count > 0)
  253. {
  254. _logger.Error("Error minifying html: " + result.Errors[0].Message);
  255. }
  256. else
  257. {
  258. html = result.MinifiedContent;
  259. }
  260. }
  261. catch (Exception ex)
  262. {
  263. _logger.ErrorException("Error minifying html", ex);
  264. }
  265. }
  266. html = html.Replace("<body>", "<body><paper-drawer-panel class=\"mainDrawerPanel mainDrawerPanelPreInit\" forceNarrow><div class=\"mainDrawer\" drawer></div><div class=\"mainDrawerPanelContent\" main><!--<div class=\"pageContainer\">")
  267. .Replace("</body>", "</div>--></div></paper-drawer-panel></body>");
  268. }
  269. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + appVersion : string.Empty;
  270. var imports = new[]
  271. {
  272. "vulcanize-out.html" + versionString
  273. };
  274. var importsHtml = string.Join("", imports.Select(i => "<link rel=\"import\" href=\"" + i + "\" async>").ToArray());
  275. // It would be better to make polymer completely dynamic and loaded on demand, but seeing issues with that
  276. // In chrome it is causing the body to be hidden while loading, which leads to width-check methods to return 0 for everything
  277. //imports = "";
  278. html = html.Replace("<head>", "<head>" + GetMetaTags(mode) + GetCommonCss(mode, appVersion));
  279. html = html.Replace("</body>", importsHtml + GetCommonJavascript(mode, appVersion) + "</body>");
  280. var bytes = Encoding.UTF8.GetBytes(html);
  281. return new MemoryStream(bytes);
  282. }
  283. }
  284. private string ModifyForCordova(string html)
  285. {
  286. // Replace CORDOVA_REPLACE_SUPPORTER_SUBMIT_START
  287. html = ReplaceBetween(html, "<!--CORDOVA_REPLACE_SUPPORTER_SUBMIT_START-->", "<!--CORDOVA_REPLACE_SUPPORTER_SUBMIT_END-->", "<i class=\"fa fa-check\"></i><span>${ButtonPurchase}</span>");
  288. return html;
  289. }
  290. private string ReplaceBetween(string html, string startToken, string endToken, string newHtml)
  291. {
  292. var start = html.IndexOf(startToken, StringComparison.OrdinalIgnoreCase);
  293. if (start == -1)
  294. {
  295. return html;
  296. }
  297. var end = html.IndexOf(endToken, start, StringComparison.OrdinalIgnoreCase);
  298. if (end == -1)
  299. {
  300. return html;
  301. }
  302. string result = html.Substring(start, end - start);
  303. html = html.Replace(result, newHtml);
  304. return ReplaceBetween(html, startToken, endToken, newHtml);
  305. }
  306. private string GetLocalizationToken(string phrase)
  307. {
  308. return "${" + phrase + "}";
  309. }
  310. /// <summary>
  311. /// Gets the meta tags.
  312. /// </summary>
  313. /// <returns>System.String.</returns>
  314. private static string GetMetaTags(string mode)
  315. {
  316. var sb = new StringBuilder();
  317. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  318. {
  319. //sb.Append("<meta http-equiv=\"Content-Security-Policy\" content=\"default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'\">");
  320. }
  321. sb.Append("<link rel=\"manifest\" href=\"manifest.json\">");
  322. sb.Append("<meta http-equiv=\"X-UA-Compatibility\" content=\"IE=Edge\">");
  323. sb.Append("<meta name=\"format-detection\" content=\"telephone=no\">");
  324. sb.Append("<meta name=\"msapplication-tap-highlight\" content=\"no\">");
  325. sb.Append("<meta name=\"viewport\" content=\"user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width\">");
  326. sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  327. sb.Append("<meta name=\"mobile-web-app-capable\" content=\"yes\">");
  328. sb.Append("<meta name=\"application-name\" content=\"Emby\">");
  329. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  330. sb.Append("<meta name=\"robots\" content=\"noindex, nofollow, noarchive\" />");
  331. // Open graph tags
  332. sb.Append("<meta property=\"og:title\" content=\"Emby\" />");
  333. sb.Append("<meta property=\"og:site_name\" content=\"Emby\"/>");
  334. sb.Append("<meta property=\"og:url\" content=\"http://emby.media\" />");
  335. sb.Append("<meta property=\"og:description\" content=\"Energize your media.\" />");
  336. sb.Append("<meta property=\"og:type\" content=\"article\" />");
  337. sb.Append("<meta property=\"fb:app_id\" content=\"1618309211750238\" />");
  338. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  339. sb.Append("<link rel=\"apple-touch-icon\" href=\"css/images/touchicon.png\" />");
  340. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"css/images/touchicon72.png\" />");
  341. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\" />");
  342. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\" />");
  343. sb.Append("<link rel=\"shortcut icon\" href=\"css/images/favicon.ico\" />");
  344. sb.Append("<meta name=\"msapplication-TileImage\" content=\"css/images/touchicon144.png\">");
  345. sb.Append("<meta name=\"msapplication-TileColor\" content=\"#333333\">");
  346. return sb.ToString();
  347. }
  348. /// <summary>
  349. /// Gets the common CSS.
  350. /// </summary>
  351. /// <param name="mode">The mode.</param>
  352. /// <param name="version">The version.</param>
  353. /// <returns>System.String.</returns>
  354. private string GetCommonCss(string mode, string version)
  355. {
  356. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  357. var files = new[]
  358. {
  359. "css/all.css" + versionString
  360. };
  361. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" async />", s)).ToArray();
  362. return string.Join(string.Empty, tags);
  363. }
  364. /// <summary>
  365. /// Gets the common javascript.
  366. /// </summary>
  367. /// <param name="mode">The mode.</param>
  368. /// <param name="version">The version.</param>
  369. /// <returns>System.String.</returns>
  370. private string GetCommonJavascript(string mode, string version)
  371. {
  372. var builder = new StringBuilder();
  373. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  374. var files = new List<string>
  375. {
  376. "scripts/all.js" + versionString
  377. };
  378. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  379. {
  380. files.Insert(0, "cordova.js");
  381. }
  382. var tags = files.Select(s => string.Format("<script src=\"{0}\" async></script>", s)).ToArray();
  383. builder.Append(string.Join(string.Empty, tags));
  384. return builder.ToString();
  385. }
  386. /// <summary>
  387. /// Gets a stream containing all concatenated javascript
  388. /// </summary>
  389. /// <returns>Task{Stream}.</returns>
  390. private async Task<Stream> GetAllJavascript(string mode, string culture, string version, bool enableMinification)
  391. {
  392. var memoryStream = new MemoryStream();
  393. var newLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
  394. await AppendResource(memoryStream, "bower_components/jquery/dist/jquery.min.js", newLineBytes).ConfigureAwait(false);
  395. //await AppendLocalization(memoryStream, culture, excludePhrases).ConfigureAwait(false);
  396. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  397. if (!string.IsNullOrWhiteSpace(mode))
  398. {
  399. var appModeBytes = Encoding.UTF8.GetBytes(string.Format("window.appMode='{0}';", mode));
  400. await memoryStream.WriteAsync(appModeBytes, 0, appModeBytes.Length).ConfigureAwait(false);
  401. }
  402. // Write the version string for the dashboard comparison function
  403. var versionString = string.Format("window.dashboardVersion='{0}';", version);
  404. var versionBytes = Encoding.UTF8.GetBytes(versionString);
  405. await memoryStream.WriteAsync(versionBytes, 0, versionBytes.Length).ConfigureAwait(false);
  406. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  407. var builder = new StringBuilder();
  408. var commonFiles = new[]
  409. {
  410. "bower_components/requirejs/require.js",
  411. "thirdparty/jquerymobile-1.4.5/jquery.mobile.custom.js",
  412. "thirdparty/browser.js",
  413. "apiclient/logger.js",
  414. "apiclient/md5.js",
  415. "apiclient/store.js",
  416. "apiclient/device.js",
  417. "apiclient/credentials.js",
  418. "apiclient/events.js",
  419. "apiclient/deferred.js",
  420. "apiclient/apiclient.js"
  421. }.ToList();
  422. foreach (var file in commonFiles)
  423. {
  424. using (var fs = _fileSystem.GetFileStream(GetDashboardResourcePath(file), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  425. {
  426. using (var streamReader = new StreamReader(fs))
  427. {
  428. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  429. builder.Append(text);
  430. builder.Append(Environment.NewLine);
  431. }
  432. }
  433. }
  434. foreach (var file in GetScriptFiles())
  435. {
  436. var path = GetDashboardResourcePath("scripts/" + file);
  437. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  438. {
  439. using (var streamReader = new StreamReader(fs))
  440. {
  441. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  442. builder.Append(text);
  443. builder.Append(Environment.NewLine);
  444. }
  445. }
  446. }
  447. var js = builder.ToString();
  448. if (enableMinification)
  449. {
  450. try
  451. {
  452. var result = new CrockfordJsMinifier().Minify(js, false, Encoding.UTF8);
  453. if (result.Errors.Count > 0)
  454. {
  455. _logger.Error("Error minifying javascript: " + result.Errors[0].Message);
  456. }
  457. else
  458. {
  459. js = result.MinifiedContent;
  460. }
  461. }
  462. catch (Exception ex)
  463. {
  464. _logger.ErrorException("Error minifying javascript", ex);
  465. }
  466. }
  467. var bytes = Encoding.UTF8.GetBytes(js);
  468. await memoryStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  469. memoryStream.Position = 0;
  470. return memoryStream;
  471. }
  472. private IEnumerable<string> GetScriptFiles()
  473. {
  474. return new[]
  475. {
  476. "extensions.js",
  477. "site.js"
  478. };
  479. }
  480. /// <summary>
  481. /// Appends the resource.
  482. /// </summary>
  483. /// <param name="outputStream">The output stream.</param>
  484. /// <param name="path">The path.</param>
  485. /// <param name="newLineBytes">The new line bytes.</param>
  486. /// <returns>Task.</returns>
  487. private async Task AppendResource(Stream outputStream, string path, byte[] newLineBytes)
  488. {
  489. path = GetDashboardResourcePath(path);
  490. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  491. {
  492. using (var streamReader = new StreamReader(fs))
  493. {
  494. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  495. var bytes = Encoding.UTF8.GetBytes(text);
  496. await outputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  497. }
  498. }
  499. await outputStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  500. }
  501. /// <summary>
  502. /// Gets all CSS.
  503. /// </summary>
  504. /// <returns>Task{Stream}.</returns>
  505. private async Task<Stream> GetAllCss(bool enableMinification)
  506. {
  507. var memoryStream = new MemoryStream();
  508. var files = new[]
  509. {
  510. "thirdparty/jquerymobile-1.4.5/jquery.mobile.custom.theme.css",
  511. "thirdparty/jquerymobile-1.4.5/jquery.mobile.custom.structure.css",
  512. "css/site.css",
  513. "css/chromecast.css",
  514. "css/librarymenu.css",
  515. "css/librarybrowser.css",
  516. "css/card.css",
  517. "css/notifications.css",
  518. "css/userimage.css",
  519. "thirdparty/paper-button-style.css"
  520. };
  521. var builder = new StringBuilder();
  522. foreach (var file in files)
  523. {
  524. var path = GetDashboardResourcePath(file);
  525. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  526. {
  527. using (var streamReader = new StreamReader(fs))
  528. {
  529. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  530. builder.Append(text);
  531. builder.Append(Environment.NewLine);
  532. }
  533. }
  534. }
  535. var css = builder.ToString();
  536. if (enableMinification)
  537. {
  538. try
  539. {
  540. var result = new KristensenCssMinifier().Minify(builder.ToString(), false, Encoding.UTF8);
  541. if (result.Errors.Count > 0)
  542. {
  543. _logger.Error("Error minifying css: " + result.Errors[0].Message);
  544. }
  545. else
  546. {
  547. css = result.MinifiedContent;
  548. }
  549. }
  550. catch (Exception ex)
  551. {
  552. _logger.ErrorException("Error minifying css", ex);
  553. }
  554. }
  555. var bytes = Encoding.UTF8.GetBytes(css);
  556. memoryStream.Write(bytes, 0, bytes.Length);
  557. memoryStream.Position = 0;
  558. return memoryStream;
  559. }
  560. /// <summary>
  561. /// Gets the raw resource stream.
  562. /// </summary>
  563. /// <param name="path">The path.</param>
  564. /// <returns>Task{Stream}.</returns>
  565. private Stream GetRawResourceStream(string path)
  566. {
  567. return _fileSystem.GetFileStream(GetDashboardResourcePath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  568. }
  569. }
  570. }