PackageCreator.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. using MediaBrowser.Controller.Configuration;
  2. using MediaBrowser.Model.Logging;
  3. using MediaBrowser.Model.Serialization;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Controller.Net;
  11. using MediaBrowser.Model.Globalization;
  12. using MediaBrowser.Model.IO;
  13. namespace MediaBrowser.WebDashboard.Api
  14. {
  15. public class PackageCreator
  16. {
  17. private readonly IFileSystem _fileSystem;
  18. private readonly ILocalizationManager _localization;
  19. private readonly ILogger _logger;
  20. private readonly IServerConfigurationManager _config;
  21. private readonly IJsonSerializer _jsonSerializer;
  22. public PackageCreator(IFileSystem fileSystem, ILocalizationManager localization, ILogger logger, IServerConfigurationManager config, IJsonSerializer jsonSerializer)
  23. {
  24. _fileSystem = fileSystem;
  25. _localization = localization;
  26. _logger = logger;
  27. _config = config;
  28. _jsonSerializer = jsonSerializer;
  29. }
  30. public async Task<Stream> GetResource(string path,
  31. string mode,
  32. string localizationCulture,
  33. string appVersion,
  34. bool enableMinification)
  35. {
  36. Stream resourceStream;
  37. if (path.Equals("css/all.css", StringComparison.OrdinalIgnoreCase))
  38. {
  39. resourceStream = await GetAllCss(enableMinification).ConfigureAwait(false);
  40. enableMinification = false;
  41. }
  42. else
  43. {
  44. resourceStream = GetRawResourceStream(path);
  45. }
  46. if (resourceStream != null)
  47. {
  48. // Don't apply any caching for html pages
  49. // jQuery ajax doesn't seem to handle if-modified-since correctly
  50. if (IsFormat(path, "html"))
  51. {
  52. if (IsCoreHtml(path))
  53. {
  54. resourceStream = await ModifyHtml(path, resourceStream, mode, appVersion, localizationCulture, enableMinification).ConfigureAwait(false);
  55. }
  56. }
  57. }
  58. return resourceStream;
  59. }
  60. /// <summary>
  61. /// Determines whether the specified path is HTML.
  62. /// </summary>
  63. /// <param name="path">The path.</param>
  64. /// <param name="format">The format.</param>
  65. /// <returns><c>true</c> if the specified path is HTML; otherwise, <c>false</c>.</returns>
  66. private bool IsFormat(string path, string format)
  67. {
  68. return Path.GetExtension(path).EndsWith(format, StringComparison.OrdinalIgnoreCase);
  69. }
  70. /// <summary>
  71. /// Gets the dashboard UI path.
  72. /// </summary>
  73. /// <value>The dashboard UI path.</value>
  74. public string DashboardUIPath
  75. {
  76. get
  77. {
  78. if (!string.IsNullOrEmpty(_config.Configuration.DashboardSourcePath))
  79. {
  80. return _config.Configuration.DashboardSourcePath;
  81. }
  82. return Path.Combine(_config.ApplicationPaths.ApplicationResourcesPath, "dashboard-ui");
  83. }
  84. }
  85. /// <summary>
  86. /// Gets the dashboard resource path.
  87. /// </summary>
  88. /// <param name="virtualPath">The virtual path.</param>
  89. /// <returns>System.String.</returns>
  90. private string GetDashboardResourcePath(string virtualPath)
  91. {
  92. var rootPath = DashboardUIPath;
  93. var fullPath = Path.Combine(rootPath, virtualPath.Replace('/', _fileSystem.DirectorySeparatorChar));
  94. try
  95. {
  96. fullPath = _fileSystem.GetFullPath(fullPath);
  97. }
  98. catch (Exception ex)
  99. {
  100. _logger.ErrorException("Error in Path.GetFullPath", ex);
  101. }
  102. // Don't allow file system access outside of the source folder
  103. if (!_fileSystem.ContainsSubPath(rootPath, fullPath))
  104. {
  105. throw new SecurityException("Access denied");
  106. }
  107. return fullPath;
  108. }
  109. public bool IsCoreHtml(string path)
  110. {
  111. if (path.IndexOf(".template.html", StringComparison.OrdinalIgnoreCase) != -1)
  112. {
  113. return false;
  114. }
  115. path = GetDashboardResourcePath(path);
  116. var parent = Path.GetDirectoryName(path);
  117. var basePath = DashboardUIPath;
  118. return string.Equals(basePath, parent, StringComparison.OrdinalIgnoreCase) ||
  119. string.Equals(Path.Combine(basePath, "voice"), parent, StringComparison.OrdinalIgnoreCase);
  120. }
  121. /// <summary>
  122. /// Modifies the HTML by adding common meta tags, css and js.
  123. /// </summary>
  124. /// <param name="path">The path.</param>
  125. /// <param name="sourceStream">The source stream.</param>
  126. /// <param name="mode">The mode.</param>
  127. /// <param name="appVersion">The application version.</param>
  128. /// <param name="localizationCulture">The localization culture.</param>
  129. /// <param name="enableMinification">if set to <c>true</c> [enable minification].</param>
  130. /// <returns>Task{Stream}.</returns>
  131. public async Task<Stream> ModifyHtml(string path, Stream sourceStream, string mode, string appVersion, string localizationCulture, bool enableMinification)
  132. {
  133. using (sourceStream)
  134. {
  135. string html;
  136. using (var memoryStream = new MemoryStream())
  137. {
  138. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  139. var originalBytes = memoryStream.ToArray();
  140. html = Encoding.UTF8.GetString(originalBytes, 0, originalBytes.Length);
  141. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  142. {
  143. }
  144. else if (!string.IsNullOrWhiteSpace(path) && !string.Equals(path, "index.html", StringComparison.OrdinalIgnoreCase))
  145. {
  146. var index = html.IndexOf("<body", StringComparison.OrdinalIgnoreCase);
  147. if (index != -1)
  148. {
  149. html = html.Substring(index);
  150. index = html.IndexOf("</body>", StringComparison.OrdinalIgnoreCase);
  151. if (index != -1)
  152. {
  153. html = html.Substring(0, index+7);
  154. }
  155. }
  156. var mainFile = _fileSystem.ReadAllText(GetDashboardResourcePath("index.html"));
  157. html = ReplaceFirst(mainFile, "<div class=\"mainAnimatedPages skinBody\"></div>", "<div class=\"mainAnimatedPages skinBody hide\">" + html + "</div>");
  158. }
  159. if (!string.IsNullOrWhiteSpace(localizationCulture))
  160. {
  161. var lang = localizationCulture.Split('-').FirstOrDefault();
  162. html = html.Replace("<html", "<html data-culture=\"" + localizationCulture + "\" lang=\"" + lang + "\"");
  163. }
  164. }
  165. html = html.Replace("<head>", "<head>" + GetMetaTags(mode) + GetCommonCss(mode, appVersion));
  166. // Disable embedded scripts from plugins. We'll run them later once resources have loaded
  167. if (html.IndexOf("<script", StringComparison.OrdinalIgnoreCase) != -1)
  168. {
  169. html = html.Replace("<script", "<!--<script");
  170. html = html.Replace("</script>", "</script>-->");
  171. }
  172. html = html.Replace("</body>", GetCommonJavascript(mode, appVersion) + "</body>");
  173. var bytes = Encoding.UTF8.GetBytes(html);
  174. return new MemoryStream(bytes);
  175. }
  176. }
  177. public string ReplaceFirst(string text, string search, string replace)
  178. {
  179. int pos = text.IndexOf(search, StringComparison.OrdinalIgnoreCase);
  180. if (pos < 0)
  181. {
  182. return text;
  183. }
  184. return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
  185. }
  186. /// <summary>
  187. /// Gets the meta tags.
  188. /// </summary>
  189. /// <returns>System.String.</returns>
  190. private static string GetMetaTags(string mode)
  191. {
  192. var sb = new StringBuilder();
  193. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  194. {
  195. sb.Append("<meta http-equiv=\"Content-Security-Policy\" content=\"default-src * 'self' 'unsafe-inline' 'unsafe-eval' data: gap: file: filesystem: ws: wss:;\">");
  196. }
  197. else
  198. {
  199. sb.Append("<meta http-equiv=\"X-UA-Compatibility\" content=\"IE=Edge\">");
  200. }
  201. sb.Append("<link rel=\"manifest\" href=\"manifest.json\">");
  202. sb.Append("<meta name=\"format-detection\" content=\"telephone=no\">");
  203. sb.Append("<meta name=\"msapplication-tap-highlight\" content=\"no\">");
  204. sb.Append("<meta name=\"viewport\" content=\"user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width\">");
  205. sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  206. sb.Append("<meta name=\"mobile-web-app-capable\" content=\"yes\">");
  207. sb.Append("<meta name=\"application-name\" content=\"Emby\">");
  208. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  209. sb.Append("<meta name=\"robots\" content=\"noindex, nofollow, noarchive\">");
  210. // Open graph tags
  211. sb.Append("<meta property=\"og:title\" content=\"Emby\">");
  212. sb.Append("<meta property=\"og:site_name\" content=\"Emby\">");
  213. sb.Append("<meta property=\"og:url\" content=\"http://emby.media\">");
  214. sb.Append("<meta property=\"og:description\" content=\"Energize your media.\">");
  215. sb.Append("<meta property=\"og:type\" content=\"article\">");
  216. sb.Append("<meta property=\"fb:app_id\" content=\"1618309211750238\">");
  217. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  218. sb.Append("<link rel=\"apple-touch-icon\" href=\"touchicon.png\">");
  219. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"touchicon72.png\">");
  220. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"touchicon114.png\">");
  221. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\">");
  222. sb.Append("<link rel=\"shortcut icon\" href=\"css/images/favicon.ico\">");
  223. sb.Append("<meta name=\"msapplication-TileImage\" content=\"touchicon144.png\">");
  224. sb.Append("<meta name=\"msapplication-TileColor\" content=\"#333333\">");
  225. sb.Append("<meta name=\"theme-color\" content=\"#43A047\">");
  226. return sb.ToString();
  227. }
  228. /// <summary>
  229. /// Gets the common CSS.
  230. /// </summary>
  231. /// <param name="mode">The mode.</param>
  232. /// <param name="version">The version.</param>
  233. /// <returns>System.String.</returns>
  234. private string GetCommonCss(string mode, string version)
  235. {
  236. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  237. var files = new[]
  238. {
  239. "css/all.css" + versionString
  240. };
  241. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" async />", s)).ToArray();
  242. return string.Join(string.Empty, tags);
  243. }
  244. /// <summary>
  245. /// Gets the common javascript.
  246. /// </summary>
  247. /// <param name="mode">The mode.</param>
  248. /// <param name="version">The version.</param>
  249. /// <returns>System.String.</returns>
  250. private string GetCommonJavascript(string mode, string version)
  251. {
  252. var builder = new StringBuilder();
  253. builder.Append("<script>");
  254. if (!string.IsNullOrWhiteSpace(mode))
  255. {
  256. builder.AppendFormat("window.appMode='{0}';", mode);
  257. }
  258. if (!string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  259. {
  260. builder.AppendFormat("window.dashboardVersion='{0}';", version);
  261. }
  262. builder.Append("</script>");
  263. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  264. var files = new List<string>();
  265. files.Add("bower_components/requirejs/require.js" + versionString);
  266. files.Add("scripts/site.js" + versionString);
  267. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  268. {
  269. files.Insert(0, "cordova.js");
  270. }
  271. var tags = files.Select(s => string.Format("<script src=\"{0}\" defer></script>", s)).ToArray();
  272. builder.Append(string.Join(string.Empty, tags));
  273. return builder.ToString();
  274. }
  275. /// <summary>
  276. /// Gets all CSS.
  277. /// </summary>
  278. /// <returns>Task{Stream}.</returns>
  279. private async Task<Stream> GetAllCss(bool enableMinification)
  280. {
  281. var memoryStream = new MemoryStream();
  282. var files = new[]
  283. {
  284. "css/site.css",
  285. "css/librarymenu.css",
  286. "css/librarybrowser.css",
  287. "thirdparty/paper-button-style.css"
  288. };
  289. var builder = new StringBuilder();
  290. foreach (var file in files)
  291. {
  292. var path = GetDashboardResourcePath(file);
  293. using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, true))
  294. {
  295. using (var streamReader = new StreamReader(fs))
  296. {
  297. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  298. builder.Append(text);
  299. builder.Append(Environment.NewLine);
  300. }
  301. }
  302. }
  303. var css = builder.ToString();
  304. var bytes = Encoding.UTF8.GetBytes(css);
  305. memoryStream.Write(bytes, 0, bytes.Length);
  306. memoryStream.Position = 0;
  307. return memoryStream;
  308. }
  309. /// <summary>
  310. /// Gets the raw resource stream.
  311. /// </summary>
  312. /// <param name="path">The path.</param>
  313. /// <returns>Task{Stream}.</returns>
  314. private Stream GetRawResourceStream(string path)
  315. {
  316. return _fileSystem.GetFileStream(GetDashboardResourcePath(path), FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, true);
  317. }
  318. }
  319. }