PackageCreator.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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(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="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(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. if (!string.IsNullOrWhiteSpace(localizationCulture))
  228. {
  229. var lang = localizationCulture.Split('-').FirstOrDefault();
  230. html = html.Replace("<html>", "<html data-culture=\"" + localizationCulture + "\" lang=\"" + lang + "\">");
  231. }
  232. if (enableMinification)
  233. {
  234. try
  235. {
  236. var minifier = new HtmlMinifier(new HtmlMinificationSettings
  237. {
  238. AttributeQuotesRemovalMode = HtmlAttributeQuotesRemovalMode.KeepQuotes,
  239. RemoveOptionalEndTags = false,
  240. RemoveTagsWithoutContent = false
  241. });
  242. var result = minifier.Minify(html, false);
  243. if (result.Errors.Count > 0)
  244. {
  245. _logger.Error("Error minifying html: " + result.Errors[0].Message);
  246. }
  247. else
  248. {
  249. html = result.MinifiedContent;
  250. }
  251. }
  252. catch (Exception ex)
  253. {
  254. _logger.ErrorException("Error minifying html", ex);
  255. }
  256. }
  257. html = html.Replace("<body>", "<body><paper-drawer-panel class=\"mainDrawerPanel mainDrawerPanelPreInit\" forceNarrow><div class=\"mainDrawer\" drawer></div><div class=\"mainDrawerPanelContent\" main><!--<div class=\"pageContainer\">")
  258. .Replace("</body>", "</div>--></div></paper-drawer-panel></body>");
  259. }
  260. html = html.Replace("<head>", "<head>" + GetMetaTags(mode) + GetCommonCss(mode, appVersion));
  261. html = html.Replace("</body>", GetCommonJavascript(mode, appVersion) + "</body>");
  262. var bytes = Encoding.UTF8.GetBytes(html);
  263. return new MemoryStream(bytes);
  264. }
  265. }
  266. private string ModifyForCordova(string html)
  267. {
  268. // Replace CORDOVA_REPLACE_SUPPORTER_SUBMIT_START
  269. html = ReplaceBetween(html, "<!--CORDOVA_REPLACE_SUPPORTER_SUBMIT_START-->", "<!--CORDOVA_REPLACE_SUPPORTER_SUBMIT_END-->", "<i class=\"fa fa-check\"></i><span>${ButtonPurchase}</span>");
  270. return html;
  271. }
  272. private string ReplaceBetween(string html, string startToken, string endToken, string newHtml)
  273. {
  274. var start = html.IndexOf(startToken, StringComparison.OrdinalIgnoreCase);
  275. if (start == -1)
  276. {
  277. return html;
  278. }
  279. var end = html.IndexOf(endToken, start, StringComparison.OrdinalIgnoreCase);
  280. if (end == -1)
  281. {
  282. return html;
  283. }
  284. string result = html.Substring(start, end - start);
  285. html = html.Replace(result, newHtml);
  286. return ReplaceBetween(html, startToken, endToken, newHtml);
  287. }
  288. private string GetLocalizationToken(string phrase)
  289. {
  290. return "${" + phrase + "}";
  291. }
  292. /// <summary>
  293. /// Gets the meta tags.
  294. /// </summary>
  295. /// <returns>System.String.</returns>
  296. private static string GetMetaTags(string mode)
  297. {
  298. var sb = new StringBuilder();
  299. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  300. {
  301. sb.Append("<meta http-equiv=\"Content-Security-Policy\" content=\"default-src * 'unsafe-inline' 'unsafe-eval'\">");
  302. }
  303. sb.Append("<link rel=\"manifest\" href=\"manifest.json\">");
  304. sb.Append("<meta http-equiv=\"X-UA-Compatibility\" content=\"IE=Edge\">");
  305. sb.Append("<meta name=\"format-detection\" content=\"telephone=no\">");
  306. sb.Append("<meta name=\"msapplication-tap-highlight\" content=\"no\">");
  307. sb.Append("<meta name=\"viewport\" content=\"user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width\">");
  308. sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  309. sb.Append("<meta name=\"mobile-web-app-capable\" content=\"yes\">");
  310. sb.Append("<meta name=\"application-name\" content=\"Emby\">");
  311. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  312. sb.Append("<meta name=\"robots\" content=\"noindex, nofollow, noarchive\">");
  313. // Open graph tags
  314. sb.Append("<meta property=\"og:title\" content=\"Emby\">");
  315. sb.Append("<meta property=\"og:site_name\" content=\"Emby\">");
  316. sb.Append("<meta property=\"og:url\" content=\"http://emby.media\">");
  317. sb.Append("<meta property=\"og:description\" content=\"Energize your media.\">");
  318. sb.Append("<meta property=\"og:type\" content=\"article\">");
  319. sb.Append("<meta property=\"fb:app_id\" content=\"1618309211750238\">");
  320. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  321. sb.Append("<link rel=\"apple-touch-icon\" href=\"css/images/touchicon.png\">");
  322. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"css/images/touchicon72.png\">");
  323. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\">");
  324. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\">");
  325. sb.Append("<link rel=\"shortcut icon\" href=\"css/images/favicon.ico\">");
  326. sb.Append("<meta name=\"msapplication-TileImage\" content=\"css/images/touchicon144.png\">");
  327. sb.Append("<meta name=\"msapplication-TileColor\" content=\"#333333\">");
  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. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  368. {
  369. files.Add("bower_components/requirejs/require.js");
  370. }
  371. else
  372. {
  373. files.Add("bower_components" + version + "/requirejs/require.js");
  374. }
  375. files.Add("scripts/site.js" + versionString);
  376. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  377. {
  378. files.Insert(0, "cordova.js");
  379. }
  380. var tags = files.Select(s =>
  381. {
  382. if (s.IndexOf("require", StringComparison.OrdinalIgnoreCase) == -1)
  383. {
  384. return string.Format("<script src=\"{0}\" async></script>", s);
  385. }
  386. return string.Format("<script src=\"{0}\"></script>", s);
  387. }).ToArray();
  388. builder.Append(string.Join(string.Empty, tags));
  389. return builder.ToString();
  390. }
  391. /// <summary>
  392. /// Gets all CSS.
  393. /// </summary>
  394. /// <returns>Task{Stream}.</returns>
  395. private async Task<Stream> GetAllCss(bool enableMinification)
  396. {
  397. var memoryStream = new MemoryStream();
  398. var files = new[]
  399. {
  400. "thirdparty/jquerymobile-1.4.5/jquery.mobile.custom.theme.css",
  401. "css/site.css",
  402. "css/librarymenu.css",
  403. "css/librarybrowser.css",
  404. "thirdparty/paper-button-style.css"
  405. };
  406. var builder = new StringBuilder();
  407. foreach (var file in files)
  408. {
  409. var path = GetDashboardResourcePath(file);
  410. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  411. {
  412. using (var streamReader = new StreamReader(fs))
  413. {
  414. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  415. builder.Append(text);
  416. builder.Append(Environment.NewLine);
  417. }
  418. }
  419. }
  420. var css = builder.ToString();
  421. if (enableMinification)
  422. {
  423. try
  424. {
  425. var result = new KristensenCssMinifier().Minify(builder.ToString(), false, Encoding.UTF8);
  426. if (result.Errors.Count > 0)
  427. {
  428. _logger.Error("Error minifying css: " + result.Errors[0].Message);
  429. }
  430. else
  431. {
  432. css = result.MinifiedContent;
  433. }
  434. }
  435. catch (Exception ex)
  436. {
  437. _logger.ErrorException("Error minifying css", ex);
  438. }
  439. }
  440. var bytes = Encoding.UTF8.GetBytes(css);
  441. memoryStream.Write(bytes, 0, bytes.Length);
  442. memoryStream.Position = 0;
  443. return memoryStream;
  444. }
  445. /// <summary>
  446. /// Gets the raw resource stream.
  447. /// </summary>
  448. /// <param name="path">The path.</param>
  449. /// <returns>Task{Stream}.</returns>
  450. private Stream GetRawResourceStream(string path)
  451. {
  452. return _fileSystem.GetFileStream(GetDashboardResourcePath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  453. }
  454. }
  455. }