PackageCreator.cs 29 KB

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