PackageCreator.cs 31 KB

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