PackageCreator.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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("css/all.css", StringComparison.OrdinalIgnoreCase))
  42. {
  43. resourceStream = await GetAllCss(enableMinification).ConfigureAwait(false);
  44. enableMinification = false;
  45. }
  46. else
  47. {
  48. resourceStream = GetRawResourceStream(path);
  49. }
  50. if (resourceStream != null)
  51. {
  52. // Don't apply any caching for html pages
  53. // jQuery ajax doesn't seem to handle if-modified-since correctly
  54. if (IsFormat(path, "html"))
  55. {
  56. if (IsCoreHtml(path))
  57. {
  58. resourceStream = await ModifyHtml(resourceStream, mode, appVersion, localizationCulture, enableMinification).ConfigureAwait(false);
  59. }
  60. }
  61. else if (IsFormat(path, "js"))
  62. {
  63. if (path.IndexOf("thirdparty", StringComparison.OrdinalIgnoreCase) == -1 && path.IndexOf("bower_components", 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 && path.IndexOf("bower_components", 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. try
  113. {
  114. fullPath = Path.GetFullPath(fullPath);
  115. }
  116. catch (Exception ex)
  117. {
  118. _logger.ErrorException("Error in Path.GetFullPath", ex);
  119. }
  120. // Don't allow file system access outside of the source folder
  121. if (!_fileSystem.ContainsSubPath(rootPath, fullPath))
  122. {
  123. throw new SecurityException("Access denied");
  124. }
  125. return fullPath;
  126. }
  127. public async Task<Stream> ModifyCss(Stream sourceStream, bool enableMinification)
  128. {
  129. using (sourceStream)
  130. {
  131. string content;
  132. using (var memoryStream = new MemoryStream())
  133. {
  134. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  135. content = Encoding.UTF8.GetString(memoryStream.ToArray());
  136. if (enableMinification)
  137. {
  138. try
  139. {
  140. var result = new KristensenCssMinifier().Minify(content, false, Encoding.UTF8);
  141. if (result.Errors.Count > 0)
  142. {
  143. _logger.Error("Error minifying css: " + result.Errors[0].Message);
  144. }
  145. else
  146. {
  147. content = result.MinifiedContent;
  148. }
  149. }
  150. catch (Exception ex)
  151. {
  152. _logger.ErrorException("Error minifying css", ex);
  153. }
  154. }
  155. }
  156. var bytes = Encoding.UTF8.GetBytes(content);
  157. return new MemoryStream(bytes);
  158. }
  159. }
  160. public async Task<Stream> ModifyJs(Stream sourceStream, bool enableMinification)
  161. {
  162. using (sourceStream)
  163. {
  164. string content;
  165. using (var memoryStream = new MemoryStream())
  166. {
  167. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  168. content = Encoding.UTF8.GetString(memoryStream.ToArray());
  169. if (enableMinification)
  170. {
  171. try
  172. {
  173. var result = new CrockfordJsMinifier().Minify(content, false, Encoding.UTF8);
  174. if (result.Errors.Count > 0)
  175. {
  176. _logger.Error("Error minifying javascript: " + result.Errors[0].Message);
  177. }
  178. else
  179. {
  180. content = result.MinifiedContent;
  181. }
  182. }
  183. catch (Exception ex)
  184. {
  185. _logger.ErrorException("Error minifying javascript", ex);
  186. }
  187. }
  188. }
  189. var bytes = Encoding.UTF8.GetBytes(content);
  190. return new MemoryStream(bytes);
  191. }
  192. }
  193. public bool IsCoreHtml(string path)
  194. {
  195. if (path.IndexOf("vulcanize", StringComparison.OrdinalIgnoreCase) != -1)
  196. {
  197. return false;
  198. }
  199. if (path.IndexOf(".template.html", StringComparison.OrdinalIgnoreCase) != -1)
  200. {
  201. return false;
  202. }
  203. path = GetDashboardResourcePath(path);
  204. var parent = Path.GetDirectoryName(path);
  205. var basePath = DashboardUIPath;
  206. return string.Equals(basePath, parent, StringComparison.OrdinalIgnoreCase) ||
  207. string.Equals(Path.Combine(basePath, "voice"), parent, StringComparison.OrdinalIgnoreCase);
  208. }
  209. /// <summary>
  210. /// Modifies the HTML by adding common meta tags, css and js.
  211. /// </summary>
  212. /// <param name="sourceStream">The source stream.</param>
  213. /// <param name="mode">The mode.</param>
  214. /// <param name="appVersion">The application version.</param>
  215. /// <param name="localizationCulture">The localization culture.</param>
  216. /// <param name="enableMinification">if set to <c>true</c> [enable minification].</param>
  217. /// <returns>Task{Stream}.</returns>
  218. public async Task<Stream> ModifyHtml(Stream sourceStream, string mode, string appVersion, string localizationCulture, bool enableMinification)
  219. {
  220. using (sourceStream)
  221. {
  222. string html;
  223. using (var memoryStream = new MemoryStream())
  224. {
  225. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  226. html = Encoding.UTF8.GetString(memoryStream.ToArray());
  227. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  228. {
  229. html = ModifyForCordova(html);
  230. }
  231. if (!string.IsNullOrWhiteSpace(localizationCulture))
  232. {
  233. var lang = localizationCulture.Split('-').FirstOrDefault();
  234. html = html.Replace("<html>", "<html data-culture=\"" + localizationCulture + "\" lang=\"" + lang + "\">");
  235. }
  236. if (enableMinification)
  237. {
  238. try
  239. {
  240. var minifier = new HtmlMinifier(new HtmlMinificationSettings
  241. {
  242. AttributeQuotesRemovalMode = HtmlAttributeQuotesRemovalMode.KeepQuotes,
  243. RemoveOptionalEndTags = false,
  244. RemoveTagsWithoutContent = false
  245. });
  246. var result = minifier.Minify(html, false);
  247. if (result.Errors.Count > 0)
  248. {
  249. _logger.Error("Error minifying html: " + result.Errors[0].Message);
  250. }
  251. else
  252. {
  253. html = result.MinifiedContent;
  254. }
  255. }
  256. catch (Exception ex)
  257. {
  258. _logger.ErrorException("Error minifying html", ex);
  259. }
  260. }
  261. html = html.Replace("<body>", "<body><paper-drawer-panel class=\"mainDrawerPanel mainDrawerPanelPreInit\" forceNarrow><div class=\"mainDrawer\" drawer></div><div class=\"mainDrawerPanelContent\" main><!--<div class=\"pageContainer\">")
  262. .Replace("</body>", "</div>--></div></paper-drawer-panel></body>");
  263. }
  264. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + appVersion : string.Empty;
  265. var imports = new[]
  266. {
  267. "vulcanize-out.html" + versionString
  268. };
  269. var importsHtml = string.Join("", imports.Select(i => "<link rel=\"import\" href=\"" + i + "\" async>").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, appVersion));
  274. html = html.Replace("</body>", importsHtml + GetCommonJavascript(mode, appVersion) + "</body>");
  275. var bytes = Encoding.UTF8.GetBytes(html);
  276. return new MemoryStream(bytes);
  277. }
  278. }
  279. private string ModifyForCordova(string html)
  280. {
  281. // Replace CORDOVA_REPLACE_SUPPORTER_SUBMIT_START
  282. html = ReplaceBetween(html, "<!--CORDOVA_REPLACE_SUPPORTER_SUBMIT_START-->", "<!--CORDOVA_REPLACE_SUPPORTER_SUBMIT_END-->", "<i class=\"fa fa-check\"></i><span>${ButtonPurchase}</span>");
  283. return html;
  284. }
  285. private string ReplaceBetween(string html, string startToken, string endToken, string newHtml)
  286. {
  287. var start = html.IndexOf(startToken, StringComparison.OrdinalIgnoreCase);
  288. if (start == -1)
  289. {
  290. return html;
  291. }
  292. var end = html.IndexOf(endToken, start, StringComparison.OrdinalIgnoreCase);
  293. if (end == -1)
  294. {
  295. return html;
  296. }
  297. string result = html.Substring(start, end - start);
  298. html = html.Replace(result, newHtml);
  299. return ReplaceBetween(html, startToken, endToken, newHtml);
  300. }
  301. private string GetLocalizationToken(string phrase)
  302. {
  303. return "${" + phrase + "}";
  304. }
  305. /// <summary>
  306. /// Gets the meta tags.
  307. /// </summary>
  308. /// <returns>System.String.</returns>
  309. private static string GetMetaTags(string mode)
  310. {
  311. var sb = new StringBuilder();
  312. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  313. {
  314. //sb.Append("<meta http-equiv=\"Content-Security-Policy\" content=\"default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'\">");
  315. }
  316. sb.Append("<link rel=\"manifest\" href=\"manifest.json\">");
  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, string version)
  350. {
  351. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  352. var files = new[]
  353. {
  354. "css/all.css" + versionString
  355. };
  356. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" async />", s)).ToArray();
  357. return string.Join(string.Empty, tags);
  358. }
  359. /// <summary>
  360. /// Gets the common javascript.
  361. /// </summary>
  362. /// <param name="mode">The mode.</param>
  363. /// <param name="version">The version.</param>
  364. /// <returns>System.String.</returns>
  365. private string GetCommonJavascript(string mode, string version)
  366. {
  367. var builder = new StringBuilder();
  368. builder.Append("<script>");
  369. if (!string.IsNullOrWhiteSpace(mode))
  370. {
  371. builder.AppendFormat("window.appMode='{0}';", mode);
  372. }
  373. builder.AppendFormat("window.dashboardVersion='{0}';", version);
  374. builder.Append("</script>");
  375. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  376. var files = new List<string>
  377. {
  378. "bower_components/requirejs/require.js" + versionString,
  379. "scripts/site.js" + versionString
  380. };
  381. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  382. {
  383. files.Insert(0, "cordova.js");
  384. }
  385. var tags = files.Select(s =>
  386. {
  387. if (s.IndexOf("require", StringComparison.OrdinalIgnoreCase) == -1)
  388. {
  389. return string.Format("<script src=\"{0}\" async></script>", s);
  390. }
  391. return string.Format("<script src=\"{0}\"></script>", s);
  392. }).ToArray();
  393. builder.Append(string.Join(string.Empty, tags));
  394. return builder.ToString();
  395. }
  396. /// <summary>
  397. /// Appends the resource.
  398. /// </summary>
  399. /// <param name="outputStream">The output stream.</param>
  400. /// <param name="path">The path.</param>
  401. /// <param name="newLineBytes">The new line bytes.</param>
  402. /// <returns>Task.</returns>
  403. private async Task AppendResource(Stream outputStream, string path, byte[] newLineBytes)
  404. {
  405. path = GetDashboardResourcePath(path);
  406. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  407. {
  408. using (var streamReader = new StreamReader(fs))
  409. {
  410. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  411. var bytes = Encoding.UTF8.GetBytes(text);
  412. await outputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  413. }
  414. }
  415. await outputStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  416. }
  417. /// <summary>
  418. /// Gets all CSS.
  419. /// </summary>
  420. /// <returns>Task{Stream}.</returns>
  421. private async Task<Stream> GetAllCss(bool enableMinification)
  422. {
  423. var memoryStream = new MemoryStream();
  424. var files = new[]
  425. {
  426. "thirdparty/jquerymobile-1.4.5/jquery.mobile.custom.theme.css",
  427. "thirdparty/jquerymobile-1.4.5/jquery.mobile.custom.structure.css",
  428. "css/site.css",
  429. "css/librarymenu.css",
  430. "css/librarybrowser.css",
  431. "css/card.css",
  432. "thirdparty/paper-button-style.css"
  433. };
  434. var builder = new StringBuilder();
  435. foreach (var file in files)
  436. {
  437. var path = GetDashboardResourcePath(file);
  438. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  439. {
  440. using (var streamReader = new StreamReader(fs))
  441. {
  442. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  443. builder.Append(text);
  444. builder.Append(Environment.NewLine);
  445. }
  446. }
  447. }
  448. var css = builder.ToString();
  449. if (enableMinification)
  450. {
  451. try
  452. {
  453. var result = new KristensenCssMinifier().Minify(builder.ToString(), false, Encoding.UTF8);
  454. if (result.Errors.Count > 0)
  455. {
  456. _logger.Error("Error minifying css: " + result.Errors[0].Message);
  457. }
  458. else
  459. {
  460. css = result.MinifiedContent;
  461. }
  462. }
  463. catch (Exception ex)
  464. {
  465. _logger.ErrorException("Error minifying css", ex);
  466. }
  467. }
  468. var bytes = Encoding.UTF8.GetBytes(css);
  469. memoryStream.Write(bytes, 0, bytes.Length);
  470. memoryStream.Position = 0;
  471. return memoryStream;
  472. }
  473. /// <summary>
  474. /// Gets the raw resource stream.
  475. /// </summary>
  476. /// <param name="path">The path.</param>
  477. /// <returns>Task{Stream}.</returns>
  478. private Stream GetRawResourceStream(string path)
  479. {
  480. return _fileSystem.GetFileStream(GetDashboardResourcePath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  481. }
  482. }
  483. }