PackageCreator.cs 29 KB

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