PackageCreator.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  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 + "\">").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>", GetInitialJavascript(mode, appVersion) + 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. // Strip everything between CORDOVA_EXCLUDE_START and CORDOVA_EXCLUDE_END
  287. html = ReplaceBetween(html, "<!--CORDOVA_EXCLUDE_START-->", "<!--CORDOVA_EXCLUDE_END-->", string.Empty);
  288. // Replace CORDOVA_REPLACE_SUPPORTER_SUBMIT_START
  289. html = ReplaceBetween(html, "<!--CORDOVA_REPLACE_SUPPORTER_SUBMIT_START-->", "<!--CORDOVA_REPLACE_SUPPORTER_SUBMIT_END-->", "<i class=\"fa fa-check\"></i><span>${ButtonPurchase}</span>");
  290. return html;
  291. }
  292. private string ReplaceBetween(string html, string startToken, string endToken, string newHtml)
  293. {
  294. var start = html.IndexOf(startToken, StringComparison.OrdinalIgnoreCase);
  295. if (start == -1)
  296. {
  297. return html;
  298. }
  299. var end = html.IndexOf(endToken, start, StringComparison.OrdinalIgnoreCase);
  300. if (end == -1)
  301. {
  302. return html;
  303. }
  304. string result = html.Substring(start, end - start);
  305. html = html.Replace(result, newHtml);
  306. return ReplaceBetween(html, startToken, endToken, newHtml);
  307. }
  308. private string GetLocalizationToken(string phrase)
  309. {
  310. return "${" + phrase + "}";
  311. }
  312. /// <summary>
  313. /// Gets the meta tags.
  314. /// </summary>
  315. /// <returns>System.String.</returns>
  316. private static string GetMetaTags(string mode)
  317. {
  318. var sb = new StringBuilder();
  319. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  320. {
  321. //sb.Append("<meta http-equiv=\"Content-Security-Policy\" content=\"default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'\">");
  322. }
  323. sb.Append("<meta http-equiv=\"X-UA-Compatibility\" content=\"IE=Edge\">");
  324. sb.Append("<meta name=\"format-detection\" content=\"telephone=no\">");
  325. sb.Append("<meta name=\"msapplication-tap-highlight\" content=\"no\">");
  326. sb.Append("<meta name=\"viewport\" content=\"user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width\">");
  327. sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  328. sb.Append("<meta name=\"mobile-web-app-capable\" content=\"yes\">");
  329. sb.Append("<meta name=\"application-name\" content=\"Emby\">");
  330. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  331. sb.Append("<meta name=\"robots\" content=\"noindex, nofollow, noarchive\" />");
  332. // Open graph tags
  333. sb.Append("<meta property=\"og:title\" content=\"Emby\" />");
  334. sb.Append("<meta property=\"og:site_name\" content=\"Emby\"/>");
  335. sb.Append("<meta property=\"og:url\" content=\"http://emby.media\" />");
  336. sb.Append("<meta property=\"og:description\" content=\"Energize your media.\" />");
  337. sb.Append("<meta property=\"og:type\" content=\"article\" />");
  338. sb.Append("<meta property=\"fb:app_id\" content=\"1618309211750238\" />");
  339. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  340. sb.Append("<link rel=\"apple-touch-icon\" href=\"css/images/touchicon.png\" />");
  341. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"css/images/touchicon72.png\" />");
  342. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\" />");
  343. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\" />");
  344. sb.Append("<link rel=\"shortcut icon\" href=\"css/images/favicon.ico\" />");
  345. sb.Append("<meta name=\"msapplication-TileImage\" content=\"css/images/touchicon144.png\">");
  346. sb.Append("<meta name=\"msapplication-TileColor\" content=\"#333333\">");
  347. return sb.ToString();
  348. }
  349. /// <summary>
  350. /// Gets the common CSS.
  351. /// </summary>
  352. /// <param name="mode">The mode.</param>
  353. /// <param name="version">The version.</param>
  354. /// <returns>System.String.</returns>
  355. private string GetCommonCss(string mode, string version)
  356. {
  357. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  358. var files = new[]
  359. {
  360. "css/all.css" + versionString
  361. };
  362. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" />", s)).ToArray();
  363. return string.Join(string.Empty, tags);
  364. }
  365. /// <summary>
  366. /// Gets the common javascript.
  367. /// </summary>
  368. /// <param name="mode">The mode.</param>
  369. /// <param name="version">The version.</param>
  370. /// <returns>System.String.</returns>
  371. private string GetInitialJavascript(string mode, string version)
  372. {
  373. var builder = new StringBuilder();
  374. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  375. var files = new List<string>
  376. {
  377. "bower_components/webcomponentsjs/webcomponents-lite.js" + versionString
  378. };
  379. var tags = files.Select(s => string.Format("<script src=\"{0}\"></script>", s)).ToArray();
  380. builder.Append(string.Join(string.Empty, tags));
  381. return builder.ToString();
  382. }
  383. /// <summary>
  384. /// Gets the common javascript.
  385. /// </summary>
  386. /// <param name="mode">The mode.</param>
  387. /// <param name="version">The version.</param>
  388. /// <returns>System.String.</returns>
  389. private string GetCommonJavascript(string mode, string version)
  390. {
  391. var builder = new StringBuilder();
  392. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  393. var files = new List<string>
  394. {
  395. "scripts/all.js" + versionString
  396. };
  397. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  398. {
  399. files.Insert(0, "cordova.js");
  400. }
  401. var tags = files.Select(s => string.Format("<script src=\"{0}\"></script>", s)).ToArray();
  402. builder.Append(string.Join(string.Empty, tags));
  403. return builder.ToString();
  404. }
  405. /// <summary>
  406. /// Gets a stream containing all concatenated javascript
  407. /// </summary>
  408. /// <returns>Task{Stream}.</returns>
  409. private async Task<Stream> GetAllJavascript(string mode, string culture, string version, bool enableMinification)
  410. {
  411. var memoryStream = new MemoryStream();
  412. var newLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
  413. await AppendResource(memoryStream, "bower_components/jquery/dist/jquery.min.js", newLineBytes).ConfigureAwait(false);
  414. //await AppendLocalization(memoryStream, culture, excludePhrases).ConfigureAwait(false);
  415. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  416. if (!string.IsNullOrWhiteSpace(mode))
  417. {
  418. var appModeBytes = Encoding.UTF8.GetBytes(string.Format("window.appMode='{0}';", mode));
  419. await memoryStream.WriteAsync(appModeBytes, 0, appModeBytes.Length).ConfigureAwait(false);
  420. }
  421. // Write the version string for the dashboard comparison function
  422. var versionString = string.Format("window.dashboardVersion='{0}';", version);
  423. var versionBytes = Encoding.UTF8.GetBytes(versionString);
  424. await memoryStream.WriteAsync(versionBytes, 0, versionBytes.Length).ConfigureAwait(false);
  425. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  426. var builder = new StringBuilder();
  427. var commonFiles = new[]
  428. {
  429. "bower_components/requirejs/require.js",
  430. "thirdparty/jquerymobile-1.4.5/jquery.mobile.custom.js",
  431. "thirdparty/browser.js",
  432. "thirdparty/jquery.unveil-custom.js",
  433. "apiclient/logger.js",
  434. "apiclient/md5.js",
  435. "apiclient/store.js",
  436. "apiclient/device.js",
  437. "apiclient/credentials.js",
  438. "apiclient/ajax.js",
  439. "apiclient/events.js",
  440. "apiclient/deferred.js",
  441. "apiclient/apiclient.js"
  442. }.ToList();
  443. commonFiles.Add("apiclient/connectionmanager.js");
  444. foreach (var file in commonFiles)
  445. {
  446. using (var fs = _fileSystem.GetFileStream(GetDashboardResourcePath(file), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  447. {
  448. using (var streamReader = new StreamReader(fs))
  449. {
  450. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  451. builder.Append(text);
  452. builder.Append(Environment.NewLine);
  453. }
  454. }
  455. }
  456. foreach (var file in GetScriptFiles())
  457. {
  458. var path = GetDashboardResourcePath("scripts/" + file);
  459. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  460. {
  461. using (var streamReader = new StreamReader(fs))
  462. {
  463. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  464. builder.Append(text);
  465. builder.Append(Environment.NewLine);
  466. }
  467. }
  468. }
  469. var js = builder.ToString();
  470. if (enableMinification)
  471. {
  472. try
  473. {
  474. var result = new CrockfordJsMinifier().Minify(js, false, Encoding.UTF8);
  475. if (result.Errors.Count > 0)
  476. {
  477. _logger.Error("Error minifying javascript: " + result.Errors[0].Message);
  478. }
  479. else
  480. {
  481. js = result.MinifiedContent;
  482. }
  483. }
  484. catch (Exception ex)
  485. {
  486. _logger.ErrorException("Error minifying javascript", ex);
  487. }
  488. }
  489. var bytes = Encoding.UTF8.GetBytes(js);
  490. await memoryStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  491. memoryStream.Position = 0;
  492. return memoryStream;
  493. }
  494. private IEnumerable<string> GetScriptFiles()
  495. {
  496. return new[]
  497. {
  498. "extensions.js",
  499. "globalize.js",
  500. "site.js",
  501. "librarybrowser.js",
  502. "librarylist.js",
  503. "librarymenu.js",
  504. "mediacontroller.js",
  505. "backdrops.js",
  506. "sync.js",
  507. "playlistmanager.js",
  508. "appsettings.js",
  509. "mediaplayer.js",
  510. "mediaplayer-video.js",
  511. "alphapicker.js",
  512. "notifications.js",
  513. "remotecontrol.js",
  514. "search.js",
  515. "thememediaplayer.js"
  516. };
  517. }
  518. /// <summary>
  519. /// Appends the resource.
  520. /// </summary>
  521. /// <param name="outputStream">The output stream.</param>
  522. /// <param name="path">The path.</param>
  523. /// <param name="newLineBytes">The new line bytes.</param>
  524. /// <returns>Task.</returns>
  525. private async Task AppendResource(Stream outputStream, string path, byte[] newLineBytes)
  526. {
  527. path = GetDashboardResourcePath(path);
  528. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  529. {
  530. using (var streamReader = new StreamReader(fs))
  531. {
  532. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  533. var bytes = Encoding.UTF8.GetBytes(text);
  534. await outputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  535. }
  536. }
  537. await outputStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  538. }
  539. /// <summary>
  540. /// Gets all CSS.
  541. /// </summary>
  542. /// <returns>Task{Stream}.</returns>
  543. private async Task<Stream> GetAllCss(bool enableMinification)
  544. {
  545. var memoryStream = new MemoryStream();
  546. var files = new[]
  547. {
  548. "thirdparty/jquerymobile-1.4.5/jquery.mobile.custom.theme.css",
  549. "thirdparty/jquerymobile-1.4.5/jquery.mobile.custom.structure.css",
  550. "css/site.css",
  551. "css/chromecast.css",
  552. "css/mediaplayer.css",
  553. "css/mediaplayer-video.css",
  554. "css/librarymenu.css",
  555. "css/librarybrowser.css",
  556. "css/card.css",
  557. "css/notifications.css",
  558. "css/search.css",
  559. "css/remotecontrol.css",
  560. "css/userimage.css",
  561. "css/nowplaying.css",
  562. "css/materialize.css",
  563. "thirdparty/paper-button-style.css"
  564. };
  565. var builder = new StringBuilder();
  566. foreach (var file in files)
  567. {
  568. var path = GetDashboardResourcePath(file);
  569. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  570. {
  571. using (var streamReader = new StreamReader(fs))
  572. {
  573. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  574. builder.Append(text);
  575. builder.Append(Environment.NewLine);
  576. }
  577. }
  578. }
  579. var css = builder.ToString();
  580. if (enableMinification)
  581. {
  582. try
  583. {
  584. var result = new KristensenCssMinifier().Minify(builder.ToString(), false, Encoding.UTF8);
  585. if (result.Errors.Count > 0)
  586. {
  587. _logger.Error("Error minifying css: " + result.Errors[0].Message);
  588. }
  589. else
  590. {
  591. css = result.MinifiedContent;
  592. }
  593. }
  594. catch (Exception ex)
  595. {
  596. _logger.ErrorException("Error minifying css", ex);
  597. }
  598. }
  599. var bytes = Encoding.UTF8.GetBytes(css);
  600. memoryStream.Write(bytes, 0, bytes.Length);
  601. memoryStream.Position = 0;
  602. return memoryStream;
  603. }
  604. /// <summary>
  605. /// Gets the raw resource stream.
  606. /// </summary>
  607. /// <param name="path">The path.</param>
  608. /// <returns>Task{Stream}.</returns>
  609. private Stream GetRawResourceStream(string path)
  610. {
  611. return _fileSystem.GetFileStream(GetDashboardResourcePath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  612. }
  613. }
  614. }