PackageCreator.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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(path, resourceStream, mode, appVersion, localizationCulture, enableMinification).ConfigureAwait(false);
  59. }
  60. }
  61. else if (IsFormat(path, "js"))
  62. {
  63. if (path.IndexOf(".min.", 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(".min.", 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(".template.html", StringComparison.OrdinalIgnoreCase) != -1)
  196. {
  197. return false;
  198. }
  199. path = GetDashboardResourcePath(path);
  200. var parent = Path.GetDirectoryName(path);
  201. var basePath = DashboardUIPath;
  202. return string.Equals(basePath, parent, StringComparison.OrdinalIgnoreCase) ||
  203. string.Equals(Path.Combine(basePath, "voice"), parent, StringComparison.OrdinalIgnoreCase);
  204. }
  205. /// <summary>
  206. /// Modifies the HTML by adding common meta tags, css and js.
  207. /// </summary>
  208. /// <param name="path">The path.</param>
  209. /// <param name="sourceStream">The source stream.</param>
  210. /// <param name="mode">The mode.</param>
  211. /// <param name="appVersion">The application version.</param>
  212. /// <param name="localizationCulture">The localization culture.</param>
  213. /// <param name="enableMinification">if set to <c>true</c> [enable minification].</param>
  214. /// <returns>Task{Stream}.</returns>
  215. public async Task<Stream> ModifyHtml(string path, Stream sourceStream, string mode, string appVersion, string localizationCulture, bool enableMinification)
  216. {
  217. using (sourceStream)
  218. {
  219. string html;
  220. using (var memoryStream = new MemoryStream())
  221. {
  222. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  223. html = Encoding.UTF8.GetString(memoryStream.ToArray());
  224. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  225. {
  226. html = ModifyForCordova(html);
  227. }
  228. else if (!string.IsNullOrWhiteSpace(path) && !string.Equals(path, "index.html", StringComparison.OrdinalIgnoreCase))
  229. {
  230. var index = html.IndexOf("<body", StringComparison.OrdinalIgnoreCase);
  231. if (index != -1)
  232. {
  233. html = html.Substring(index);
  234. index = html.IndexOf("</body>", StringComparison.OrdinalIgnoreCase);
  235. if (index != -1)
  236. {
  237. html = html.Substring(0, index+7);
  238. }
  239. }
  240. var mainFile = File.ReadAllText(GetDashboardResourcePath("index.html"));
  241. html = ReplaceFirst(mainFile, "<div class=\"mainAnimatedPage hide\"></div>", "<div class=\"mainAnimatedPage hide\">" + html + "</div>");
  242. }
  243. if (!string.IsNullOrWhiteSpace(localizationCulture))
  244. {
  245. var lang = localizationCulture.Split('-').FirstOrDefault();
  246. html = html.Replace("<html>", "<html data-culture=\"" + localizationCulture + "\" lang=\"" + lang + "\">");
  247. }
  248. if (enableMinification)
  249. {
  250. try
  251. {
  252. var minifier = new HtmlMinifier(new HtmlMinificationSettings
  253. {
  254. AttributeQuotesRemovalMode = HtmlAttributeQuotesRemovalMode.KeepQuotes,
  255. RemoveOptionalEndTags = false,
  256. RemoveTagsWithoutContent = false
  257. });
  258. var result = minifier.Minify(html, false);
  259. if (result.Errors.Count > 0)
  260. {
  261. _logger.Error("Error minifying html: " + result.Errors[0].Message);
  262. }
  263. else
  264. {
  265. html = result.MinifiedContent;
  266. }
  267. }
  268. catch (Exception ex)
  269. {
  270. _logger.ErrorException("Error minifying html", ex);
  271. }
  272. }
  273. }
  274. html = html.Replace("<head>", "<head>" + GetMetaTags(mode) + GetCommonCss(mode, appVersion));
  275. // Inject sripts before any embedded scripts
  276. if (html.IndexOf("<script", StringComparison.OrdinalIgnoreCase) != -1)
  277. {
  278. html = ReplaceFirst(html, "<script", GetCommonJavascript(mode, appVersion, false) + "<script");
  279. }
  280. else
  281. {
  282. html = html.Replace("</body>", GetCommonJavascript(mode, appVersion, true) + "</body>");
  283. }
  284. var bytes = Encoding.UTF8.GetBytes(html);
  285. return new MemoryStream(bytes);
  286. }
  287. }
  288. public string ReplaceFirst(string text, string search, string replace)
  289. {
  290. int pos = text.IndexOf(search, StringComparison.OrdinalIgnoreCase);
  291. if (pos < 0)
  292. {
  293. return text;
  294. }
  295. return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
  296. }
  297. private string ModifyForCordova(string html)
  298. {
  299. // Replace CORDOVA_REPLACE_SUPPORTER_SUBMIT_START
  300. html = ReplaceBetween(html, "<!--CORDOVA_REPLACE_SUPPORTER_SUBMIT_START-->", "<!--CORDOVA_REPLACE_SUPPORTER_SUBMIT_END-->", "<i class=\"fa fa-check\"></i><span>${ButtonPurchase}</span>");
  301. return html;
  302. }
  303. private string ReplaceBetween(string html, string startToken, string endToken, string newHtml)
  304. {
  305. var start = html.IndexOf(startToken, StringComparison.OrdinalIgnoreCase);
  306. if (start == -1)
  307. {
  308. return html;
  309. }
  310. var end = html.IndexOf(endToken, start, StringComparison.OrdinalIgnoreCase);
  311. if (end == -1)
  312. {
  313. return html;
  314. }
  315. string result = html.Substring(start, end - start);
  316. html = html.Replace(result, newHtml);
  317. return ReplaceBetween(html, startToken, endToken, newHtml);
  318. }
  319. private string GetLocalizationToken(string phrase)
  320. {
  321. return "${" + phrase + "}";
  322. }
  323. /// <summary>
  324. /// Gets the meta tags.
  325. /// </summary>
  326. /// <returns>System.String.</returns>
  327. private static string GetMetaTags(string mode)
  328. {
  329. var sb = new StringBuilder();
  330. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  331. {
  332. sb.Append("<meta http-equiv=\"Content-Security-Policy\" content=\"default-src * 'unsafe-inline' 'unsafe-eval' data:;\">");
  333. }
  334. sb.Append("<link rel=\"manifest\" href=\"manifest.json\">");
  335. sb.Append("<meta http-equiv=\"X-UA-Compatibility\" content=\"IE=Edge\">");
  336. sb.Append("<meta name=\"format-detection\" content=\"telephone=no\">");
  337. sb.Append("<meta name=\"msapplication-tap-highlight\" content=\"no\">");
  338. sb.Append("<meta name=\"viewport\" content=\"user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width\">");
  339. sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  340. sb.Append("<meta name=\"mobile-web-app-capable\" content=\"yes\">");
  341. sb.Append("<meta name=\"application-name\" content=\"Emby\">");
  342. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  343. sb.Append("<meta name=\"robots\" content=\"noindex, nofollow, noarchive\">");
  344. // Open graph tags
  345. sb.Append("<meta property=\"og:title\" content=\"Emby\">");
  346. sb.Append("<meta property=\"og:site_name\" content=\"Emby\">");
  347. sb.Append("<meta property=\"og:url\" content=\"http://emby.media\">");
  348. sb.Append("<meta property=\"og:description\" content=\"Energize your media.\">");
  349. sb.Append("<meta property=\"og:type\" content=\"article\">");
  350. sb.Append("<meta property=\"fb:app_id\" content=\"1618309211750238\">");
  351. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  352. sb.Append("<link rel=\"apple-touch-icon\" href=\"css/images/touchicon.png\">");
  353. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"css/images/touchicon72.png\">");
  354. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\">");
  355. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\">");
  356. sb.Append("<link rel=\"shortcut icon\" href=\"css/images/favicon.ico\">");
  357. sb.Append("<meta name=\"msapplication-TileImage\" content=\"css/images/touchicon144.png\">");
  358. sb.Append("<meta name=\"msapplication-TileColor\" content=\"#333333\">");
  359. return sb.ToString();
  360. }
  361. /// <summary>
  362. /// Gets the common CSS.
  363. /// </summary>
  364. /// <param name="mode">The mode.</param>
  365. /// <param name="version">The version.</param>
  366. /// <returns>System.String.</returns>
  367. private string GetCommonCss(string mode, string version)
  368. {
  369. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  370. var files = new[]
  371. {
  372. "css/all.css" + versionString
  373. };
  374. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" async />", s)).ToArray();
  375. return string.Join(string.Empty, tags);
  376. }
  377. /// <summary>
  378. /// Gets the common javascript.
  379. /// </summary>
  380. /// <param name="mode">The mode.</param>
  381. /// <param name="version">The version.</param>
  382. /// <param name="async">if set to <c>true</c> [asynchronous].</param>
  383. /// <returns>System.String.</returns>
  384. private string GetCommonJavascript(string mode, string version, bool async)
  385. {
  386. var builder = new StringBuilder();
  387. builder.Append("<script>");
  388. if (!string.IsNullOrWhiteSpace(mode))
  389. {
  390. builder.AppendFormat("window.appMode='{0}';", mode);
  391. }
  392. if (!string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  393. {
  394. builder.AppendFormat("window.dashboardVersion='{0}';", version);
  395. }
  396. builder.Append("</script>");
  397. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  398. var files = new List<string>();
  399. files.Add("bower_components/requirejs/require.js");
  400. files.Add("scripts/site.js" + versionString);
  401. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  402. {
  403. files.Insert(0, "cordova.js");
  404. }
  405. var tags = files.Select(s =>
  406. {
  407. if (s.IndexOf("require", StringComparison.OrdinalIgnoreCase) == -1)
  408. {
  409. if (async)
  410. {
  411. return string.Format("<script src=\"{0}\" async></script>", s);
  412. }
  413. return string.Format("<script src=\"{0}\"></script>", s);
  414. }
  415. return string.Format("<script src=\"{0}\"></script>", s);
  416. }).ToArray();
  417. builder.Append(string.Join(string.Empty, tags));
  418. return builder.ToString();
  419. }
  420. /// <summary>
  421. /// Gets all CSS.
  422. /// </summary>
  423. /// <returns>Task{Stream}.</returns>
  424. private async Task<Stream> GetAllCss(bool enableMinification)
  425. {
  426. var memoryStream = new MemoryStream();
  427. var files = new[]
  428. {
  429. "css/site.css",
  430. "css/librarymenu.css",
  431. "css/librarybrowser.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. }