PackageCreator.cs 29 KB

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