PackageCreator.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. namespace MediaBrowser.WebDashboard.Api
  15. {
  16. public class PackageCreator
  17. {
  18. private readonly IFileSystem _fileSystem;
  19. private readonly ILocalizationManager _localization;
  20. private readonly ILogger _logger;
  21. private readonly IServerConfigurationManager _config;
  22. private readonly IJsonSerializer _jsonSerializer;
  23. public PackageCreator(IFileSystem fileSystem, ILocalizationManager localization, ILogger logger, IServerConfigurationManager config, IJsonSerializer jsonSerializer)
  24. {
  25. _fileSystem = fileSystem;
  26. _localization = localization;
  27. _logger = logger;
  28. _config = config;
  29. _jsonSerializer = jsonSerializer;
  30. }
  31. public async Task<Stream> GetResource(string path,
  32. string mode,
  33. string localizationCulture,
  34. string appVersion,
  35. bool enableMinification)
  36. {
  37. Stream resourceStream;
  38. if (path.Equals("css/all.css", StringComparison.OrdinalIgnoreCase))
  39. {
  40. resourceStream = await GetAllCss(enableMinification).ConfigureAwait(false);
  41. enableMinification = false;
  42. }
  43. else
  44. {
  45. resourceStream = GetRawResourceStream(path);
  46. }
  47. if (resourceStream != null)
  48. {
  49. // Don't apply any caching for html pages
  50. // jQuery ajax doesn't seem to handle if-modified-since correctly
  51. if (IsFormat(path, "html"))
  52. {
  53. if (IsCoreHtml(path))
  54. {
  55. resourceStream = await ModifyHtml(path, resourceStream, mode, appVersion, localizationCulture, enableMinification).ConfigureAwait(false);
  56. }
  57. }
  58. else if (IsFormat(path, "js"))
  59. {
  60. if (path.IndexOf(".min.", StringComparison.OrdinalIgnoreCase) == -1 && path.IndexOf("bower_components", StringComparison.OrdinalIgnoreCase) == -1)
  61. {
  62. resourceStream = await ModifyJs(resourceStream, enableMinification).ConfigureAwait(false);
  63. }
  64. }
  65. else if (IsFormat(path, "css"))
  66. {
  67. if (path.IndexOf(".min.", StringComparison.OrdinalIgnoreCase) == -1 && path.IndexOf("bower_components", StringComparison.OrdinalIgnoreCase) == -1)
  68. {
  69. resourceStream = await ModifyCss(resourceStream, enableMinification).ConfigureAwait(false);
  70. }
  71. }
  72. }
  73. return resourceStream;
  74. }
  75. /// <summary>
  76. /// Determines whether the specified path is HTML.
  77. /// </summary>
  78. /// <param name="path">The path.</param>
  79. /// <param name="format">The format.</param>
  80. /// <returns><c>true</c> if the specified path is HTML; otherwise, <c>false</c>.</returns>
  81. private bool IsFormat(string path, string format)
  82. {
  83. return Path.GetExtension(path).EndsWith(format, StringComparison.OrdinalIgnoreCase);
  84. }
  85. /// <summary>
  86. /// Gets the dashboard UI path.
  87. /// </summary>
  88. /// <value>The dashboard UI path.</value>
  89. public string DashboardUIPath
  90. {
  91. get
  92. {
  93. if (!string.IsNullOrEmpty(_config.Configuration.DashboardSourcePath))
  94. {
  95. return _config.Configuration.DashboardSourcePath;
  96. }
  97. return Path.Combine(_config.ApplicationPaths.ApplicationResourcesPath, "dashboard-ui");
  98. }
  99. }
  100. /// <summary>
  101. /// Gets the dashboard resource path.
  102. /// </summary>
  103. /// <param name="virtualPath">The virtual path.</param>
  104. /// <returns>System.String.</returns>
  105. private string GetDashboardResourcePath(string virtualPath)
  106. {
  107. var rootPath = DashboardUIPath;
  108. var fullPath = Path.Combine(rootPath, virtualPath.Replace('/', Path.DirectorySeparatorChar));
  109. try
  110. {
  111. fullPath = Path.GetFullPath(fullPath);
  112. }
  113. catch (Exception ex)
  114. {
  115. _logger.ErrorException("Error in Path.GetFullPath", ex);
  116. }
  117. // Don't allow file system access outside of the source folder
  118. if (!_fileSystem.ContainsSubPath(rootPath, fullPath))
  119. {
  120. throw new SecurityException("Access denied");
  121. }
  122. return fullPath;
  123. }
  124. public async Task<Stream> ModifyCss(Stream sourceStream, bool enableMinification)
  125. {
  126. using (sourceStream)
  127. {
  128. string content;
  129. using (var memoryStream = new MemoryStream())
  130. {
  131. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  132. content = Encoding.UTF8.GetString(memoryStream.ToArray());
  133. if (enableMinification)
  134. {
  135. try
  136. {
  137. var result = new KristensenCssMinifier().Minify(content, false, Encoding.UTF8);
  138. if (result.Errors.Count > 0)
  139. {
  140. _logger.Error("Error minifying css: " + result.Errors[0].Message);
  141. }
  142. else
  143. {
  144. content = result.MinifiedContent;
  145. }
  146. }
  147. catch (Exception ex)
  148. {
  149. _logger.ErrorException("Error minifying css", ex);
  150. }
  151. }
  152. }
  153. var bytes = Encoding.UTF8.GetBytes(content);
  154. return new MemoryStream(bytes);
  155. }
  156. }
  157. public async Task<Stream> ModifyJs(Stream sourceStream, bool enableMinification)
  158. {
  159. using (sourceStream)
  160. {
  161. string content;
  162. using (var memoryStream = new MemoryStream())
  163. {
  164. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  165. content = Encoding.UTF8.GetString(memoryStream.ToArray());
  166. if (enableMinification)
  167. {
  168. try
  169. {
  170. var result = new CrockfordJsMinifier().Minify(content, false, Encoding.UTF8);
  171. if (result.Errors.Count > 0)
  172. {
  173. _logger.Error("Error minifying javascript: " + result.Errors[0].Message);
  174. }
  175. else
  176. {
  177. content = result.MinifiedContent;
  178. }
  179. }
  180. catch (Exception ex)
  181. {
  182. _logger.ErrorException("Error minifying javascript", ex);
  183. }
  184. }
  185. }
  186. var bytes = Encoding.UTF8.GetBytes(content);
  187. return new MemoryStream(bytes);
  188. }
  189. }
  190. public bool IsCoreHtml(string path)
  191. {
  192. if (path.IndexOf(".template.html", StringComparison.OrdinalIgnoreCase) != -1)
  193. {
  194. return false;
  195. }
  196. path = GetDashboardResourcePath(path);
  197. var parent = Path.GetDirectoryName(path);
  198. var basePath = DashboardUIPath;
  199. return string.Equals(basePath, parent, StringComparison.OrdinalIgnoreCase) ||
  200. string.Equals(Path.Combine(basePath, "voice"), parent, StringComparison.OrdinalIgnoreCase);
  201. }
  202. /// <summary>
  203. /// Modifies the HTML by adding common meta tags, css and js.
  204. /// </summary>
  205. /// <param name="path">The path.</param>
  206. /// <param name="sourceStream">The source stream.</param>
  207. /// <param name="mode">The mode.</param>
  208. /// <param name="appVersion">The application version.</param>
  209. /// <param name="localizationCulture">The localization culture.</param>
  210. /// <param name="enableMinification">if set to <c>true</c> [enable minification].</param>
  211. /// <returns>Task{Stream}.</returns>
  212. public async Task<Stream> ModifyHtml(string path, Stream sourceStream, string mode, string appVersion, string localizationCulture, bool enableMinification)
  213. {
  214. using (sourceStream)
  215. {
  216. string html;
  217. using (var memoryStream = new MemoryStream())
  218. {
  219. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  220. html = Encoding.UTF8.GetString(memoryStream.ToArray());
  221. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  222. {
  223. }
  224. else if (!string.IsNullOrWhiteSpace(path) && !string.Equals(path, "index.html", StringComparison.OrdinalIgnoreCase))
  225. {
  226. var index = html.IndexOf("<body", StringComparison.OrdinalIgnoreCase);
  227. if (index != -1)
  228. {
  229. html = html.Substring(index);
  230. index = html.IndexOf("</body>", StringComparison.OrdinalIgnoreCase);
  231. if (index != -1)
  232. {
  233. html = html.Substring(0, index+7);
  234. }
  235. }
  236. var mainFile = File.ReadAllText(GetDashboardResourcePath("index.html"));
  237. html = ReplaceFirst(mainFile, "<div class=\"mainAnimatedPages skinBody\"></div>", "<div class=\"mainAnimatedPages skinBody hide\">" + html + "</div>");
  238. }
  239. if (!string.IsNullOrWhiteSpace(localizationCulture))
  240. {
  241. var lang = localizationCulture.Split('-').FirstOrDefault();
  242. html = html.Replace("<html", "<html data-culture=\"" + localizationCulture + "\" lang=\"" + lang + "\"");
  243. }
  244. if (enableMinification)
  245. {
  246. try
  247. {
  248. var minifier = new HtmlMinifier(new HtmlMinificationSettings
  249. {
  250. AttributeQuotesRemovalMode = HtmlAttributeQuotesRemovalMode.KeepQuotes,
  251. RemoveOptionalEndTags = false,
  252. RemoveTagsWithoutContent = false
  253. });
  254. var result = minifier.Minify(html, false);
  255. if (result.Errors.Count > 0)
  256. {
  257. _logger.Error("Error minifying html: " + result.Errors[0].Message);
  258. }
  259. else
  260. {
  261. html = result.MinifiedContent;
  262. }
  263. }
  264. catch (Exception ex)
  265. {
  266. _logger.ErrorException("Error minifying html", ex);
  267. }
  268. }
  269. }
  270. html = html.Replace("<head>", "<head>" + GetMetaTags(mode) + GetCommonCss(mode, appVersion));
  271. // Disable embedded scripts from plugins. We'll run them later once resources have loaded
  272. if (html.IndexOf("<script", StringComparison.OrdinalIgnoreCase) != -1)
  273. {
  274. html = html.Replace("<script", "<!--<script");
  275. html = html.Replace("</script>", "</script>-->");
  276. }
  277. html = html.Replace("</body>", GetCommonJavascript(mode, appVersion) + "</body>");
  278. var bytes = Encoding.UTF8.GetBytes(html);
  279. return new MemoryStream(bytes);
  280. }
  281. }
  282. public string ReplaceFirst(string text, string search, string replace)
  283. {
  284. int pos = text.IndexOf(search, StringComparison.OrdinalIgnoreCase);
  285. if (pos < 0)
  286. {
  287. return text;
  288. }
  289. return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
  290. }
  291. /// <summary>
  292. /// Gets the meta tags.
  293. /// </summary>
  294. /// <returns>System.String.</returns>
  295. private static string GetMetaTags(string mode)
  296. {
  297. var sb = new StringBuilder();
  298. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  299. {
  300. sb.Append("<meta http-equiv=\"Content-Security-Policy\" content=\"default-src * 'unsafe-inline' 'unsafe-eval' data: gap: file: filesystem:;\">");
  301. }
  302. sb.Append("<link rel=\"manifest\" href=\"manifest.json\">");
  303. sb.Append("<meta http-equiv=\"X-UA-Compatibility\" content=\"IE=Edge\">");
  304. sb.Append("<meta name=\"format-detection\" content=\"telephone=no\">");
  305. sb.Append("<meta name=\"msapplication-tap-highlight\" content=\"no\">");
  306. sb.Append("<meta name=\"viewport\" content=\"user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width\">");
  307. sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  308. sb.Append("<meta name=\"mobile-web-app-capable\" content=\"yes\">");
  309. sb.Append("<meta name=\"application-name\" content=\"Emby\">");
  310. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  311. sb.Append("<meta name=\"robots\" content=\"noindex, nofollow, noarchive\">");
  312. // Open graph tags
  313. sb.Append("<meta property=\"og:title\" content=\"Emby\">");
  314. sb.Append("<meta property=\"og:site_name\" content=\"Emby\">");
  315. sb.Append("<meta property=\"og:url\" content=\"http://emby.media\">");
  316. sb.Append("<meta property=\"og:description\" content=\"Energize your media.\">");
  317. sb.Append("<meta property=\"og:type\" content=\"article\">");
  318. sb.Append("<meta property=\"fb:app_id\" content=\"1618309211750238\">");
  319. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  320. sb.Append("<link rel=\"apple-touch-icon\" href=\"touchicon.png\">");
  321. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"touchicon72.png\">");
  322. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"touchicon114.png\">");
  323. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\">");
  324. sb.Append("<link rel=\"shortcut icon\" href=\"css/images/favicon.ico\">");
  325. sb.Append("<meta name=\"msapplication-TileImage\" content=\"touchicon144.png\">");
  326. sb.Append("<meta name=\"msapplication-TileColor\" content=\"#333333\">");
  327. sb.Append("<meta name=\"theme-color\" content=\"#43A047\">");
  328. return sb.ToString();
  329. }
  330. /// <summary>
  331. /// Gets the common CSS.
  332. /// </summary>
  333. /// <param name="mode">The mode.</param>
  334. /// <param name="version">The version.</param>
  335. /// <returns>System.String.</returns>
  336. private string GetCommonCss(string mode, string version)
  337. {
  338. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  339. var files = new[]
  340. {
  341. "css/all.css" + versionString
  342. };
  343. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" async />", s)).ToArray();
  344. return string.Join(string.Empty, tags);
  345. }
  346. /// <summary>
  347. /// Gets the common javascript.
  348. /// </summary>
  349. /// <param name="mode">The mode.</param>
  350. /// <param name="version">The version.</param>
  351. /// <returns>System.String.</returns>
  352. private string GetCommonJavascript(string mode, string version)
  353. {
  354. var builder = new StringBuilder();
  355. builder.Append("<script>");
  356. if (!string.IsNullOrWhiteSpace(mode))
  357. {
  358. builder.AppendFormat("window.appMode='{0}';", mode);
  359. }
  360. if (!string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  361. {
  362. builder.AppendFormat("window.dashboardVersion='{0}';", version);
  363. }
  364. builder.Append("</script>");
  365. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  366. var files = new List<string>();
  367. files.Add("bower_components/requirejs/require.js" + versionString);
  368. files.Add("scripts/site.js" + versionString);
  369. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  370. {
  371. files.Insert(0, "cordova.js");
  372. }
  373. var tags = files.Select(s => string.Format("<script src=\"{0}\" defer></script>", s)).ToArray();
  374. builder.Append(string.Join(string.Empty, tags));
  375. return builder.ToString();
  376. }
  377. /// <summary>
  378. /// Gets all CSS.
  379. /// </summary>
  380. /// <returns>Task{Stream}.</returns>
  381. private async Task<Stream> GetAllCss(bool enableMinification)
  382. {
  383. var memoryStream = new MemoryStream();
  384. var files = new[]
  385. {
  386. "css/site.css",
  387. "css/librarymenu.css",
  388. "css/librarybrowser.css",
  389. "thirdparty/paper-button-style.css"
  390. };
  391. var builder = new StringBuilder();
  392. foreach (var file in files)
  393. {
  394. var path = GetDashboardResourcePath(file);
  395. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  396. {
  397. using (var streamReader = new StreamReader(fs))
  398. {
  399. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  400. builder.Append(text);
  401. builder.Append(Environment.NewLine);
  402. }
  403. }
  404. }
  405. var css = builder.ToString();
  406. if (enableMinification)
  407. {
  408. try
  409. {
  410. var result = new KristensenCssMinifier().Minify(builder.ToString(), false, Encoding.UTF8);
  411. if (result.Errors.Count > 0)
  412. {
  413. _logger.Error("Error minifying css: " + result.Errors[0].Message);
  414. }
  415. else
  416. {
  417. css = result.MinifiedContent;
  418. }
  419. }
  420. catch (Exception ex)
  421. {
  422. _logger.ErrorException("Error minifying css", ex);
  423. }
  424. }
  425. var bytes = Encoding.UTF8.GetBytes(css);
  426. memoryStream.Write(bytes, 0, bytes.Length);
  427. memoryStream.Position = 0;
  428. return memoryStream;
  429. }
  430. /// <summary>
  431. /// Gets the raw resource stream.
  432. /// </summary>
  433. /// <param name="path">The path.</param>
  434. /// <returns>Task{Stream}.</returns>
  435. private Stream GetRawResourceStream(string path)
  436. {
  437. return _fileSystem.GetFileStream(GetDashboardResourcePath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  438. }
  439. }
  440. }