PackageCreator.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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. }
  226. else if (!string.IsNullOrWhiteSpace(path) && !string.Equals(path, "index.html", StringComparison.OrdinalIgnoreCase))
  227. {
  228. var index = html.IndexOf("<body", StringComparison.OrdinalIgnoreCase);
  229. if (index != -1)
  230. {
  231. html = html.Substring(index);
  232. index = html.IndexOf("</body>", StringComparison.OrdinalIgnoreCase);
  233. if (index != -1)
  234. {
  235. html = html.Substring(0, index+7);
  236. }
  237. }
  238. var mainFile = File.ReadAllText(GetDashboardResourcePath("index.html"));
  239. html = ReplaceFirst(mainFile, "<div class=\"mainAnimatedPages skinBody\"></div>", "<div class=\"mainAnimatedPages skinBody hide\">" + html + "</div>");
  240. }
  241. if (!string.IsNullOrWhiteSpace(localizationCulture))
  242. {
  243. var lang = localizationCulture.Split('-').FirstOrDefault();
  244. html = html.Replace("<html", "<html data-culture=\"" + localizationCulture + "\" lang=\"" + lang + "\"");
  245. }
  246. if (enableMinification)
  247. {
  248. try
  249. {
  250. var minifier = new HtmlMinifier(new HtmlMinificationSettings
  251. {
  252. AttributeQuotesRemovalMode = HtmlAttributeQuotesRemovalMode.KeepQuotes,
  253. RemoveOptionalEndTags = false,
  254. RemoveTagsWithoutContent = false
  255. });
  256. var result = minifier.Minify(html, false);
  257. if (result.Errors.Count > 0)
  258. {
  259. _logger.Error("Error minifying html: " + result.Errors[0].Message);
  260. }
  261. else
  262. {
  263. html = result.MinifiedContent;
  264. }
  265. }
  266. catch (Exception ex)
  267. {
  268. _logger.ErrorException("Error minifying html", ex);
  269. }
  270. }
  271. }
  272. html = html.Replace("<head>", "<head>" + GetMetaTags(mode) + GetCommonCss(mode, appVersion));
  273. // Disable embedded scripts from plugins. We'll run them later once resources have loaded
  274. if (html.IndexOf("<script", StringComparison.OrdinalIgnoreCase) != -1)
  275. {
  276. html = html.Replace("<script", "<!--<script");
  277. html = html.Replace("</script>", "</script>-->");
  278. }
  279. html = html.Replace("</body>", GetCommonJavascript(mode, appVersion) + "</body>");
  280. var bytes = Encoding.UTF8.GetBytes(html);
  281. return new MemoryStream(bytes);
  282. }
  283. }
  284. public string ReplaceFirst(string text, string search, string replace)
  285. {
  286. int pos = text.IndexOf(search, StringComparison.OrdinalIgnoreCase);
  287. if (pos < 0)
  288. {
  289. return text;
  290. }
  291. return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
  292. }
  293. /// <summary>
  294. /// Gets the meta tags.
  295. /// </summary>
  296. /// <returns>System.String.</returns>
  297. private static string GetMetaTags(string mode)
  298. {
  299. var sb = new StringBuilder();
  300. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  301. {
  302. sb.Append("<meta http-equiv=\"Content-Security-Policy\" content=\"default-src * 'unsafe-inline' 'unsafe-eval' data: filesystem:;\">");
  303. }
  304. sb.Append("<link rel=\"manifest\" href=\"manifest.json\">");
  305. sb.Append("<meta http-equiv=\"X-UA-Compatibility\" content=\"IE=Edge\">");
  306. sb.Append("<meta name=\"format-detection\" content=\"telephone=no\">");
  307. sb.Append("<meta name=\"msapplication-tap-highlight\" content=\"no\">");
  308. sb.Append("<meta name=\"viewport\" content=\"user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width\">");
  309. sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  310. sb.Append("<meta name=\"mobile-web-app-capable\" content=\"yes\">");
  311. sb.Append("<meta name=\"application-name\" content=\"Emby\">");
  312. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  313. sb.Append("<meta name=\"robots\" content=\"noindex, nofollow, noarchive\">");
  314. // Open graph tags
  315. sb.Append("<meta property=\"og:title\" content=\"Emby\">");
  316. sb.Append("<meta property=\"og:site_name\" content=\"Emby\">");
  317. sb.Append("<meta property=\"og:url\" content=\"http://emby.media\">");
  318. sb.Append("<meta property=\"og:description\" content=\"Energize your media.\">");
  319. sb.Append("<meta property=\"og:type\" content=\"article\">");
  320. sb.Append("<meta property=\"fb:app_id\" content=\"1618309211750238\">");
  321. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  322. sb.Append("<link rel=\"apple-touch-icon\" href=\"css/images/touchicon.png\">");
  323. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"css/images/touchicon72.png\">");
  324. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\">");
  325. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\">");
  326. sb.Append("<link rel=\"shortcut icon\" href=\"css/images/favicon.ico\">");
  327. sb.Append("<meta name=\"msapplication-TileImage\" content=\"css/images/touchicon144.png\">");
  328. sb.Append("<meta name=\"msapplication-TileColor\" content=\"#333333\">");
  329. sb.Append("<meta name=\"theme-color\" content=\"#43A047\">");
  330. return sb.ToString();
  331. }
  332. /// <summary>
  333. /// Gets the common CSS.
  334. /// </summary>
  335. /// <param name="mode">The mode.</param>
  336. /// <param name="version">The version.</param>
  337. /// <returns>System.String.</returns>
  338. private string GetCommonCss(string mode, string version)
  339. {
  340. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  341. var files = new[]
  342. {
  343. "css/all.css" + versionString
  344. };
  345. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" async />", s)).ToArray();
  346. return string.Join(string.Empty, tags);
  347. }
  348. /// <summary>
  349. /// Gets the common javascript.
  350. /// </summary>
  351. /// <param name="mode">The mode.</param>
  352. /// <param name="version">The version.</param>
  353. /// <returns>System.String.</returns>
  354. private string GetCommonJavascript(string mode, string version)
  355. {
  356. var builder = new StringBuilder();
  357. builder.Append("<script>");
  358. if (!string.IsNullOrWhiteSpace(mode))
  359. {
  360. builder.AppendFormat("window.appMode='{0}';", mode);
  361. }
  362. if (!string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  363. {
  364. builder.AppendFormat("window.dashboardVersion='{0}';", version);
  365. }
  366. builder.Append("</script>");
  367. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  368. var files = new List<string>();
  369. files.Add("bower_components/requirejs/require.js");
  370. files.Add("scripts/site.js" + versionString);
  371. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  372. {
  373. files.Insert(0, "cordova.js");
  374. }
  375. var tags = files.Select(s =>
  376. {
  377. if (s.IndexOf("require", StringComparison.OrdinalIgnoreCase) == -1 && s.IndexOf("alameda", StringComparison.OrdinalIgnoreCase) == -1)
  378. {
  379. return string.Format("<script src=\"{0}\" async></script>", s);
  380. }
  381. return string.Format("<script src=\"{0}\"></script>", s);
  382. }).ToArray();
  383. builder.Append(string.Join(string.Empty, tags));
  384. return builder.ToString();
  385. }
  386. /// <summary>
  387. /// Gets all CSS.
  388. /// </summary>
  389. /// <returns>Task{Stream}.</returns>
  390. private async Task<Stream> GetAllCss(bool enableMinification)
  391. {
  392. var memoryStream = new MemoryStream();
  393. var files = new[]
  394. {
  395. "css/site.css",
  396. "css/librarymenu.css",
  397. "css/librarybrowser.css",
  398. "thirdparty/paper-button-style.css"
  399. };
  400. var builder = new StringBuilder();
  401. foreach (var file in files)
  402. {
  403. var path = GetDashboardResourcePath(file);
  404. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  405. {
  406. using (var streamReader = new StreamReader(fs))
  407. {
  408. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  409. builder.Append(text);
  410. builder.Append(Environment.NewLine);
  411. }
  412. }
  413. }
  414. var css = builder.ToString();
  415. if (enableMinification)
  416. {
  417. try
  418. {
  419. var result = new KristensenCssMinifier().Minify(builder.ToString(), false, Encoding.UTF8);
  420. if (result.Errors.Count > 0)
  421. {
  422. _logger.Error("Error minifying css: " + result.Errors[0].Message);
  423. }
  424. else
  425. {
  426. css = result.MinifiedContent;
  427. }
  428. }
  429. catch (Exception ex)
  430. {
  431. _logger.ErrorException("Error minifying css", ex);
  432. }
  433. }
  434. var bytes = Encoding.UTF8.GetBytes(css);
  435. memoryStream.Write(bytes, 0, bytes.Length);
  436. memoryStream.Position = 0;
  437. return memoryStream;
  438. }
  439. /// <summary>
  440. /// Gets the raw resource stream.
  441. /// </summary>
  442. /// <param name="path">The path.</param>
  443. /// <returns>Task{Stream}.</returns>
  444. private Stream GetRawResourceStream(string path)
  445. {
  446. return _fileSystem.GetFileStream(GetDashboardResourcePath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  447. }
  448. }
  449. }