PackageCreator.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. // Disable embedded scripts from plugins. We'll run them later once resources have loaded
  276. if (html.IndexOf("<script", StringComparison.OrdinalIgnoreCase) != -1)
  277. {
  278. html = html.Replace("<script", "<!--<script");
  279. html = html.Replace("</script>", "</script>-->");
  280. }
  281. html = html.Replace("</body>", GetCommonJavascript(mode, appVersion) + "</body>");
  282. var bytes = Encoding.UTF8.GetBytes(html);
  283. return new MemoryStream(bytes);
  284. }
  285. }
  286. public string ReplaceFirst(string text, string search, string replace)
  287. {
  288. int pos = text.IndexOf(search, StringComparison.OrdinalIgnoreCase);
  289. if (pos < 0)
  290. {
  291. return text;
  292. }
  293. return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
  294. }
  295. private string ModifyForCordova(string html)
  296. {
  297. // Replace CORDOVA_REPLACE_SUPPORTER_SUBMIT_START
  298. html = ReplaceBetween(html, "<!--CORDOVA_REPLACE_SUPPORTER_SUBMIT_START-->", "<!--CORDOVA_REPLACE_SUPPORTER_SUBMIT_END-->", "<i class=\"fa fa-check\"></i><span>${ButtonPurchase}</span>");
  299. return html;
  300. }
  301. private string ReplaceBetween(string html, string startToken, string endToken, string newHtml)
  302. {
  303. var start = html.IndexOf(startToken, StringComparison.OrdinalIgnoreCase);
  304. if (start == -1)
  305. {
  306. return html;
  307. }
  308. var end = html.IndexOf(endToken, start, StringComparison.OrdinalIgnoreCase);
  309. if (end == -1)
  310. {
  311. return html;
  312. }
  313. string result = html.Substring(start, end - start);
  314. html = html.Replace(result, newHtml);
  315. return ReplaceBetween(html, startToken, endToken, newHtml);
  316. }
  317. private string GetLocalizationToken(string phrase)
  318. {
  319. return "${" + phrase + "}";
  320. }
  321. /// <summary>
  322. /// Gets the meta tags.
  323. /// </summary>
  324. /// <returns>System.String.</returns>
  325. private static string GetMetaTags(string mode)
  326. {
  327. var sb = new StringBuilder();
  328. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  329. {
  330. sb.Append("<meta http-equiv=\"Content-Security-Policy\" content=\"default-src * 'unsafe-inline' 'unsafe-eval' data:;\">");
  331. }
  332. sb.Append("<link rel=\"manifest\" href=\"manifest.json\">");
  333. sb.Append("<meta http-equiv=\"X-UA-Compatibility\" content=\"IE=Edge\">");
  334. sb.Append("<meta name=\"format-detection\" content=\"telephone=no\">");
  335. sb.Append("<meta name=\"msapplication-tap-highlight\" content=\"no\">");
  336. sb.Append("<meta name=\"viewport\" content=\"user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width\">");
  337. sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  338. sb.Append("<meta name=\"mobile-web-app-capable\" content=\"yes\">");
  339. sb.Append("<meta name=\"application-name\" content=\"Emby\">");
  340. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  341. sb.Append("<meta name=\"robots\" content=\"noindex, nofollow, noarchive\">");
  342. // Open graph tags
  343. sb.Append("<meta property=\"og:title\" content=\"Emby\">");
  344. sb.Append("<meta property=\"og:site_name\" content=\"Emby\">");
  345. sb.Append("<meta property=\"og:url\" content=\"http://emby.media\">");
  346. sb.Append("<meta property=\"og:description\" content=\"Energize your media.\">");
  347. sb.Append("<meta property=\"og:type\" content=\"article\">");
  348. sb.Append("<meta property=\"fb:app_id\" content=\"1618309211750238\">");
  349. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  350. sb.Append("<link rel=\"apple-touch-icon\" href=\"css/images/touchicon.png\">");
  351. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"css/images/touchicon72.png\">");
  352. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\">");
  353. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\">");
  354. sb.Append("<link rel=\"shortcut icon\" href=\"css/images/favicon.ico\">");
  355. sb.Append("<meta name=\"msapplication-TileImage\" content=\"css/images/touchicon144.png\">");
  356. sb.Append("<meta name=\"msapplication-TileColor\" content=\"#333333\">");
  357. return sb.ToString();
  358. }
  359. /// <summary>
  360. /// Gets the common CSS.
  361. /// </summary>
  362. /// <param name="mode">The mode.</param>
  363. /// <param name="version">The version.</param>
  364. /// <returns>System.String.</returns>
  365. private string GetCommonCss(string mode, string version)
  366. {
  367. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  368. var files = new[]
  369. {
  370. "css/all.css" + versionString
  371. };
  372. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" async />", s)).ToArray();
  373. return string.Join(string.Empty, tags);
  374. }
  375. /// <summary>
  376. /// Gets the common javascript.
  377. /// </summary>
  378. /// <param name="mode">The mode.</param>
  379. /// <param name="version">The version.</param>
  380. /// <returns>System.String.</returns>
  381. private string GetCommonJavascript(string mode, string version)
  382. {
  383. var builder = new StringBuilder();
  384. builder.Append("<script>");
  385. if (!string.IsNullOrWhiteSpace(mode))
  386. {
  387. builder.AppendFormat("window.appMode='{0}';", mode);
  388. }
  389. if (!string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  390. {
  391. builder.AppendFormat("window.dashboardVersion='{0}';", version);
  392. }
  393. builder.Append("</script>");
  394. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  395. var files = new List<string>();
  396. files.Add("bower_components/requirejs/require.js");
  397. files.Add("scripts/site.js" + versionString);
  398. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  399. {
  400. files.Insert(0, "cordova.js");
  401. }
  402. var tags = files.Select(s =>
  403. {
  404. if (s.IndexOf("require", StringComparison.OrdinalIgnoreCase) == -1)
  405. {
  406. return string.Format("<script src=\"{0}\" async></script>", s);
  407. }
  408. return string.Format("<script src=\"{0}\"></script>", s);
  409. }).ToArray();
  410. builder.Append(string.Join(string.Empty, tags));
  411. return builder.ToString();
  412. }
  413. /// <summary>
  414. /// Gets all CSS.
  415. /// </summary>
  416. /// <returns>Task{Stream}.</returns>
  417. private async Task<Stream> GetAllCss(bool enableMinification)
  418. {
  419. var memoryStream = new MemoryStream();
  420. var files = new[]
  421. {
  422. "css/site.css",
  423. "css/librarymenu.css",
  424. "css/librarybrowser.css",
  425. "thirdparty/paper-button-style.css"
  426. };
  427. var builder = new StringBuilder();
  428. foreach (var file in files)
  429. {
  430. var path = GetDashboardResourcePath(file);
  431. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  432. {
  433. using (var streamReader = new StreamReader(fs))
  434. {
  435. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  436. builder.Append(text);
  437. builder.Append(Environment.NewLine);
  438. }
  439. }
  440. }
  441. var css = builder.ToString();
  442. if (enableMinification)
  443. {
  444. try
  445. {
  446. var result = new KristensenCssMinifier().Minify(builder.ToString(), false, Encoding.UTF8);
  447. if (result.Errors.Count > 0)
  448. {
  449. _logger.Error("Error minifying css: " + result.Errors[0].Message);
  450. }
  451. else
  452. {
  453. css = result.MinifiedContent;
  454. }
  455. }
  456. catch (Exception ex)
  457. {
  458. _logger.ErrorException("Error minifying css", ex);
  459. }
  460. }
  461. var bytes = Encoding.UTF8.GetBytes(css);
  462. memoryStream.Write(bytes, 0, bytes.Length);
  463. memoryStream.Position = 0;
  464. return memoryStream;
  465. }
  466. /// <summary>
  467. /// Gets the raw resource stream.
  468. /// </summary>
  469. /// <param name="path">The path.</param>
  470. /// <returns>Task{Stream}.</returns>
  471. private Stream GetRawResourceStream(string path)
  472. {
  473. return _fileSystem.GetFileStream(GetDashboardResourcePath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  474. }
  475. }
  476. }