PackageCreator.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. using MediaBrowser.Controller.Configuration;
  2. using MediaBrowser.Controller.Localization;
  3. using MediaBrowser.Model.Logging;
  4. using MediaBrowser.Model.Serialization;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using CommonIO;
  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("css/all.css", StringComparison.OrdinalIgnoreCase))
  41. {
  42. resourceStream = await GetAllCss(enableMinification).ConfigureAwait(false);
  43. enableMinification = false;
  44. }
  45. else
  46. {
  47. resourceStream = GetRawResourceStream(path);
  48. }
  49. if (resourceStream != null)
  50. {
  51. // Don't apply any caching for html pages
  52. // jQuery ajax doesn't seem to handle if-modified-since correctly
  53. if (IsFormat(path, "html"))
  54. {
  55. if (IsCoreHtml(path))
  56. {
  57. resourceStream = await ModifyHtml(path, resourceStream, mode, appVersion, localizationCulture, enableMinification).ConfigureAwait(false);
  58. }
  59. }
  60. else if (IsFormat(path, "js"))
  61. {
  62. if (path.IndexOf(".min.", StringComparison.OrdinalIgnoreCase) == -1 && path.IndexOf("bower_components", StringComparison.OrdinalIgnoreCase) == -1)
  63. {
  64. resourceStream = await ModifyJs(resourceStream, enableMinification).ConfigureAwait(false);
  65. }
  66. }
  67. else if (IsFormat(path, "css"))
  68. {
  69. if (path.IndexOf(".min.", StringComparison.OrdinalIgnoreCase) == -1 && path.IndexOf("bower_components", StringComparison.OrdinalIgnoreCase) == -1)
  70. {
  71. resourceStream = await ModifyCss(resourceStream, enableMinification).ConfigureAwait(false);
  72. }
  73. }
  74. }
  75. return resourceStream;
  76. }
  77. /// <summary>
  78. /// Determines whether the specified path is HTML.
  79. /// </summary>
  80. /// <param name="path">The path.</param>
  81. /// <param name="format">The format.</param>
  82. /// <returns><c>true</c> if the specified path is HTML; otherwise, <c>false</c>.</returns>
  83. private bool IsFormat(string path, string format)
  84. {
  85. return Path.GetExtension(path).EndsWith(format, StringComparison.OrdinalIgnoreCase);
  86. }
  87. /// <summary>
  88. /// Gets the dashboard UI path.
  89. /// </summary>
  90. /// <value>The dashboard UI path.</value>
  91. public string DashboardUIPath
  92. {
  93. get
  94. {
  95. if (!string.IsNullOrEmpty(_config.Configuration.DashboardSourcePath))
  96. {
  97. return _config.Configuration.DashboardSourcePath;
  98. }
  99. return Path.Combine(_config.ApplicationPaths.ApplicationResourcesPath, "dashboard-ui");
  100. }
  101. }
  102. /// <summary>
  103. /// Gets the dashboard resource path.
  104. /// </summary>
  105. /// <param name="virtualPath">The virtual path.</param>
  106. /// <returns>System.String.</returns>
  107. private string GetDashboardResourcePath(string virtualPath)
  108. {
  109. var rootPath = DashboardUIPath;
  110. var fullPath = Path.Combine(rootPath, virtualPath.Replace('/', Path.DirectorySeparatorChar));
  111. try
  112. {
  113. fullPath = Path.GetFullPath(fullPath);
  114. }
  115. catch (Exception ex)
  116. {
  117. _logger.ErrorException("Error in Path.GetFullPath", ex);
  118. }
  119. // Don't allow file system access outside of the source folder
  120. if (!_fileSystem.ContainsSubPath(rootPath, fullPath))
  121. {
  122. throw new SecurityException("Access denied");
  123. }
  124. return fullPath;
  125. }
  126. public async Task<Stream> ModifyCss(Stream sourceStream, bool enableMinification)
  127. {
  128. using (sourceStream)
  129. {
  130. string content;
  131. using (var memoryStream = new MemoryStream())
  132. {
  133. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  134. content = Encoding.UTF8.GetString(memoryStream.ToArray());
  135. if (enableMinification)
  136. {
  137. try
  138. {
  139. var result = new KristensenCssMinifier().Minify(content, false, Encoding.UTF8);
  140. if (result.Errors.Count > 0)
  141. {
  142. _logger.Error("Error minifying css: " + result.Errors[0].Message);
  143. }
  144. else
  145. {
  146. content = result.MinifiedContent;
  147. }
  148. }
  149. catch (Exception ex)
  150. {
  151. _logger.ErrorException("Error minifying css", ex);
  152. }
  153. }
  154. }
  155. var bytes = Encoding.UTF8.GetBytes(content);
  156. return new MemoryStream(bytes);
  157. }
  158. }
  159. public async Task<Stream> ModifyJs(Stream sourceStream, bool enableMinification)
  160. {
  161. using (sourceStream)
  162. {
  163. string content;
  164. using (var memoryStream = new MemoryStream())
  165. {
  166. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  167. content = Encoding.UTF8.GetString(memoryStream.ToArray());
  168. if (enableMinification)
  169. {
  170. try
  171. {
  172. var result = new CrockfordJsMinifier().Minify(content, false, Encoding.UTF8);
  173. if (result.Errors.Count > 0)
  174. {
  175. _logger.Error("Error minifying javascript: " + result.Errors[0].Message);
  176. }
  177. else
  178. {
  179. content = result.MinifiedContent;
  180. }
  181. }
  182. catch (Exception ex)
  183. {
  184. _logger.ErrorException("Error minifying javascript", ex);
  185. }
  186. }
  187. }
  188. var bytes = Encoding.UTF8.GetBytes(content);
  189. return new MemoryStream(bytes);
  190. }
  191. }
  192. public bool IsCoreHtml(string path)
  193. {
  194. if (path.IndexOf(".template.html", StringComparison.OrdinalIgnoreCase) != -1)
  195. {
  196. return false;
  197. }
  198. path = GetDashboardResourcePath(path);
  199. var parent = Path.GetDirectoryName(path);
  200. var basePath = DashboardUIPath;
  201. return string.Equals(basePath, parent, StringComparison.OrdinalIgnoreCase) ||
  202. string.Equals(Path.Combine(basePath, "voice"), parent, StringComparison.OrdinalIgnoreCase);
  203. }
  204. /// <summary>
  205. /// Modifies the HTML by adding common meta tags, css and js.
  206. /// </summary>
  207. /// <param name="path">The path.</param>
  208. /// <param name="sourceStream">The source stream.</param>
  209. /// <param name="mode">The mode.</param>
  210. /// <param name="appVersion">The application version.</param>
  211. /// <param name="localizationCulture">The localization culture.</param>
  212. /// <param name="enableMinification">if set to <c>true</c> [enable minification].</param>
  213. /// <returns>Task{Stream}.</returns>
  214. public async Task<Stream> ModifyHtml(string path, Stream sourceStream, string mode, string appVersion, string localizationCulture, bool enableMinification)
  215. {
  216. using (sourceStream)
  217. {
  218. string html;
  219. using (var memoryStream = new MemoryStream())
  220. {
  221. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  222. html = Encoding.UTF8.GetString(memoryStream.ToArray());
  223. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  224. {
  225. html = ModifyForCordova(html);
  226. }
  227. else if (!string.IsNullOrWhiteSpace(path) && !string.Equals(path, "index.html", StringComparison.OrdinalIgnoreCase))
  228. {
  229. var index = html.IndexOf("<body", StringComparison.OrdinalIgnoreCase);
  230. if (index != -1)
  231. {
  232. html = html.Substring(index);
  233. index = html.IndexOf("</body>", StringComparison.OrdinalIgnoreCase);
  234. if (index != -1)
  235. {
  236. html = html.Substring(0, index+7);
  237. }
  238. }
  239. var mainFile = File.ReadAllText(GetDashboardResourcePath("index.html"));
  240. html = ReplaceFirst(mainFile, "<div class=\"mainAnimatedPage hide\"></div>", "<div class=\"mainAnimatedPage hide\">" + html + "</div>");
  241. }
  242. if (!string.IsNullOrWhiteSpace(localizationCulture))
  243. {
  244. var lang = localizationCulture.Split('-').FirstOrDefault();
  245. html = html.Replace("<html", "<html data-culture=\"" + localizationCulture + "\" lang=\"" + lang + "\"");
  246. }
  247. if (enableMinification)
  248. {
  249. try
  250. {
  251. var minifier = new HtmlMinifier(new HtmlMinificationSettings
  252. {
  253. AttributeQuotesRemovalMode = HtmlAttributeQuotesRemovalMode.KeepQuotes,
  254. RemoveOptionalEndTags = false,
  255. RemoveTagsWithoutContent = false
  256. });
  257. var result = minifier.Minify(html, false);
  258. if (result.Errors.Count > 0)
  259. {
  260. _logger.Error("Error minifying html: " + result.Errors[0].Message);
  261. }
  262. else
  263. {
  264. html = result.MinifiedContent;
  265. }
  266. }
  267. catch (Exception ex)
  268. {
  269. _logger.ErrorException("Error minifying html", ex);
  270. }
  271. }
  272. }
  273. html = html.Replace("<head>", "<head>" + GetMetaTags(mode) + GetCommonCss(mode, appVersion));
  274. // Disable embedded scripts from plugins. We'll run them later once resources have loaded
  275. if (html.IndexOf("<script", StringComparison.OrdinalIgnoreCase) != -1)
  276. {
  277. html = html.Replace("<script", "<!--<script");
  278. html = html.Replace("</script>", "</script>-->");
  279. }
  280. html = html.Replace("</body>", GetCommonJavascript(mode, appVersion) + "</body>");
  281. var bytes = Encoding.UTF8.GetBytes(html);
  282. return new MemoryStream(bytes);
  283. }
  284. }
  285. public string ReplaceFirst(string text, string search, string replace)
  286. {
  287. int pos = text.IndexOf(search, StringComparison.OrdinalIgnoreCase);
  288. if (pos < 0)
  289. {
  290. return text;
  291. }
  292. return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
  293. }
  294. private string ModifyForCordova(string html)
  295. {
  296. // Replace CORDOVA_REPLACE_SUPPORTER_SUBMIT_START
  297. html = ReplaceBetween(html, "<!--CORDOVA_REPLACE_SUPPORTER_SUBMIT_START-->", "<!--CORDOVA_REPLACE_SUPPORTER_SUBMIT_END-->", "<i class=\"fa fa-check\"></i><span>${ButtonPurchase}</span>");
  298. return html;
  299. }
  300. private string ReplaceBetween(string html, string startToken, string endToken, string newHtml)
  301. {
  302. var start = html.IndexOf(startToken, StringComparison.OrdinalIgnoreCase);
  303. if (start == -1)
  304. {
  305. return html;
  306. }
  307. var end = html.IndexOf(endToken, start, StringComparison.OrdinalIgnoreCase);
  308. if (end == -1)
  309. {
  310. return html;
  311. }
  312. string result = html.Substring(start, end - start);
  313. html = html.Replace(result, newHtml);
  314. return ReplaceBetween(html, startToken, endToken, newHtml);
  315. }
  316. private string GetLocalizationToken(string phrase)
  317. {
  318. return "${" + phrase + "}";
  319. }
  320. /// <summary>
  321. /// Gets the meta tags.
  322. /// </summary>
  323. /// <returns>System.String.</returns>
  324. private static string GetMetaTags(string mode)
  325. {
  326. var sb = new StringBuilder();
  327. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  328. {
  329. sb.Append("<meta http-equiv=\"Content-Security-Policy\" content=\"default-src * 'unsafe-inline' 'unsafe-eval' data: filesystem:;\">");
  330. }
  331. sb.Append("<link rel=\"manifest\" href=\"manifest.json\">");
  332. sb.Append("<meta http-equiv=\"X-UA-Compatibility\" content=\"IE=Edge\">");
  333. sb.Append("<meta name=\"format-detection\" content=\"telephone=no\">");
  334. sb.Append("<meta name=\"msapplication-tap-highlight\" content=\"no\">");
  335. sb.Append("<meta name=\"viewport\" content=\"user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width\">");
  336. sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  337. sb.Append("<meta name=\"mobile-web-app-capable\" content=\"yes\">");
  338. sb.Append("<meta name=\"application-name\" content=\"Emby\">");
  339. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  340. sb.Append("<meta name=\"robots\" content=\"noindex, nofollow, noarchive\">");
  341. // Open graph tags
  342. sb.Append("<meta property=\"og:title\" content=\"Emby\">");
  343. sb.Append("<meta property=\"og:site_name\" content=\"Emby\">");
  344. sb.Append("<meta property=\"og:url\" content=\"http://emby.media\">");
  345. sb.Append("<meta property=\"og:description\" content=\"Energize your media.\">");
  346. sb.Append("<meta property=\"og:type\" content=\"article\">");
  347. sb.Append("<meta property=\"fb:app_id\" content=\"1618309211750238\">");
  348. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  349. sb.Append("<link rel=\"apple-touch-icon\" href=\"css/images/touchicon.png\">");
  350. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"css/images/touchicon72.png\">");
  351. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\">");
  352. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\">");
  353. sb.Append("<link rel=\"shortcut icon\" href=\"css/images/favicon.ico\">");
  354. sb.Append("<meta name=\"msapplication-TileImage\" content=\"css/images/touchicon144.png\">");
  355. sb.Append("<meta name=\"msapplication-TileColor\" content=\"#333333\">");
  356. sb.Append("<meta name=\"theme-color\" content=\"#43A047\">");
  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 && s.IndexOf("alameda", 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. }