PackageCreator.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 ILogger _logger;
  19. private readonly IServerConfigurationManager _config;
  20. private readonly IMemoryStreamFactory _memoryStreamFactory;
  21. private readonly string _basePath;
  22. public PackageCreator(string basePath, IFileSystem fileSystem, ILogger logger, IServerConfigurationManager config, IMemoryStreamFactory memoryStreamFactory)
  23. {
  24. _fileSystem = fileSystem;
  25. _logger = logger;
  26. _config = config;
  27. _memoryStreamFactory = memoryStreamFactory;
  28. _basePath = basePath;
  29. }
  30. public async Task<Stream> GetResource(string virtualPath,
  31. string mode,
  32. string localizationCulture,
  33. string appVersion)
  34. {
  35. var resourceStream = GetRawResourceStream(virtualPath);
  36. if (resourceStream != null)
  37. {
  38. // Don't apply any caching for html pages
  39. // jQuery ajax doesn't seem to handle if-modified-since correctly
  40. if (IsFormat(virtualPath, "html"))
  41. {
  42. if (IsCoreHtml(virtualPath))
  43. {
  44. resourceStream = await ModifyHtml(virtualPath, resourceStream, mode, appVersion, localizationCulture).ConfigureAwait(false);
  45. }
  46. }
  47. }
  48. return resourceStream;
  49. }
  50. /// <summary>
  51. /// Determines whether the specified path is HTML.
  52. /// </summary>
  53. /// <param name="path">The path.</param>
  54. /// <param name="format">The format.</param>
  55. /// <returns><c>true</c> if the specified path is HTML; otherwise, <c>false</c>.</returns>
  56. private bool IsFormat(string path, string format)
  57. {
  58. return Path.GetExtension(path).EndsWith(format, StringComparison.OrdinalIgnoreCase);
  59. }
  60. /// <summary>
  61. /// Gets the dashboard resource path.
  62. /// </summary>
  63. /// <returns>System.String.</returns>
  64. public string GetResourcePath(string virtualPath)
  65. {
  66. var fullPath = Path.Combine(_basePath, virtualPath.Replace('/', _fileSystem.DirectorySeparatorChar));
  67. try
  68. {
  69. fullPath = _fileSystem.GetFullPath(fullPath);
  70. }
  71. catch (Exception ex)
  72. {
  73. _logger.ErrorException("Error in Path.GetFullPath", ex);
  74. }
  75. // Don't allow file system access outside of the source folder
  76. if (!_fileSystem.ContainsSubPath(_basePath, fullPath))
  77. {
  78. throw new SecurityException("Access denied");
  79. }
  80. return fullPath;
  81. }
  82. public bool IsCoreHtml(string path)
  83. {
  84. if (path.IndexOf(".template.html", StringComparison.OrdinalIgnoreCase) != -1)
  85. {
  86. return false;
  87. }
  88. path = GetResourcePath(path);
  89. var parent = _fileSystem.GetDirectoryName(path);
  90. return string.Equals(_basePath, parent, StringComparison.OrdinalIgnoreCase) ||
  91. string.Equals(Path.Combine(_basePath, "offline"), parent, StringComparison.OrdinalIgnoreCase);
  92. }
  93. /// <summary>
  94. /// Modifies the HTML by adding common meta tags, css and js.
  95. /// </summary>
  96. /// <returns>Task{Stream}.</returns>
  97. public async Task<Stream> ModifyHtml(string path, Stream sourceStream, string mode, string appVersion, string localizationCulture)
  98. {
  99. using (sourceStream)
  100. {
  101. string html;
  102. using (var memoryStream = _memoryStreamFactory.CreateNew())
  103. {
  104. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  105. var originalBytes = memoryStream.ToArray();
  106. html = Encoding.UTF8.GetString(originalBytes, 0, originalBytes.Length);
  107. if (!string.IsNullOrWhiteSpace(mode))
  108. {
  109. }
  110. else if (!string.IsNullOrWhiteSpace(path) && !string.Equals(path, "index.html", StringComparison.OrdinalIgnoreCase))
  111. {
  112. var index = html.IndexOf("<body", StringComparison.OrdinalIgnoreCase);
  113. if (index != -1)
  114. {
  115. html = html.Substring(index);
  116. html = html.Substring(html.IndexOf('>') + 1);
  117. index = html.IndexOf("</body>", StringComparison.OrdinalIgnoreCase);
  118. if (index != -1)
  119. {
  120. html = html.Substring(0, index);
  121. }
  122. }
  123. var mainFile = _fileSystem.ReadAllText(GetResourcePath("index.html"));
  124. html = ReplaceFirst(mainFile, "<div class=\"mainAnimatedPages skinBody\"></div>", "<div class=\"mainAnimatedPages skinBody hide\">" + html + "</div>");
  125. }
  126. if (!string.IsNullOrWhiteSpace(localizationCulture))
  127. {
  128. var lang = localizationCulture.Split('-').FirstOrDefault();
  129. html = html.Replace("<html", "<html data-culture=\"" + localizationCulture + "\" lang=\"" + lang + "\"");
  130. }
  131. }
  132. html = html.Replace("<head>", "<head>" + GetMetaTags(mode) + GetCommonCss(mode, appVersion));
  133. // Disable embedded scripts from plugins. We'll run them later once resources have loaded
  134. if (html.IndexOf("<script", StringComparison.OrdinalIgnoreCase) != -1)
  135. {
  136. html = html.Replace("<script", "<!--<script");
  137. html = html.Replace("</script>", "</script>-->");
  138. }
  139. html = html.Replace("</body>", GetCommonJavascript(mode, appVersion) + "</body>");
  140. var bytes = Encoding.UTF8.GetBytes(html);
  141. return _memoryStreamFactory.CreateNew(bytes);
  142. }
  143. }
  144. public string ReplaceFirst(string text, string search, string replace)
  145. {
  146. int pos = text.IndexOf(search, StringComparison.OrdinalIgnoreCase);
  147. if (pos < 0)
  148. {
  149. return text;
  150. }
  151. return text.Substring(0, pos) + replace + text.Substring(pos + search.Length);
  152. }
  153. /// <summary>
  154. /// Gets the meta tags.
  155. /// </summary>
  156. /// <returns>System.String.</returns>
  157. private static string GetMetaTags(string mode)
  158. {
  159. var sb = new StringBuilder();
  160. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ||
  161. string.Equals(mode, "android", StringComparison.OrdinalIgnoreCase))
  162. {
  163. sb.Append("<meta http-equiv=\"Content-Security-Policy\" content=\"default-src * 'self' 'unsafe-inline' 'unsafe-eval' data: gap: file: filesystem: ws: wss:;\">");
  164. }
  165. else
  166. {
  167. sb.Append("<meta http-equiv=\"X-UA-Compatibility\" content=\"IE=Edge\">");
  168. }
  169. sb.Append("<link rel=\"manifest\" href=\"manifest.json\">");
  170. sb.Append("<meta name=\"format-detection\" content=\"telephone=no\">");
  171. sb.Append("<meta name=\"msapplication-tap-highlight\" content=\"no\">");
  172. sb.Append("<meta name=\"viewport\" content=\"user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width\">");
  173. sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  174. sb.Append("<meta name=\"mobile-web-app-capable\" content=\"yes\">");
  175. sb.Append("<meta name=\"application-name\" content=\"Emby\">");
  176. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  177. sb.Append("<meta name=\"robots\" content=\"noindex, nofollow, noarchive\">");
  178. // Open graph tags
  179. sb.Append("<meta property=\"og:title\" content=\"Emby\">");
  180. sb.Append("<meta property=\"og:site_name\" content=\"Emby\">");
  181. sb.Append("<meta property=\"og:url\" content=\"http://emby.media\">");
  182. sb.Append("<meta property=\"og:description\" content=\"Energize your media.\">");
  183. sb.Append("<meta property=\"og:type\" content=\"article\">");
  184. sb.Append("<meta property=\"fb:app_id\" content=\"1618309211750238\">");
  185. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  186. sb.Append("<link rel=\"apple-touch-icon\" href=\"touchicon.png\">");
  187. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"touchicon72.png\">");
  188. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"touchicon114.png\">");
  189. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\">");
  190. sb.Append("<link rel=\"shortcut icon\" href=\"css/images/favicon.ico\">");
  191. sb.Append("<meta name=\"msapplication-TileImage\" content=\"touchicon144.png\">");
  192. sb.Append("<meta name=\"msapplication-TileColor\" content=\"#333333\">");
  193. sb.Append("<meta name=\"theme-color\" content=\"#43A047\">");
  194. return sb.ToString();
  195. }
  196. /// <summary>
  197. /// Gets the common CSS.
  198. /// </summary>
  199. /// <param name="mode">The mode.</param>
  200. /// <param name="version">The version.</param>
  201. /// <returns>System.String.</returns>
  202. private string GetCommonCss(string mode, string version)
  203. {
  204. var versionString = string.IsNullOrWhiteSpace(mode) ? "?v=" + version : string.Empty;
  205. var files = new[]
  206. {
  207. "css/site.css" + versionString
  208. };
  209. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" async />", s)).ToArray();
  210. return string.Join(string.Empty, tags);
  211. }
  212. /// <summary>
  213. /// Gets the common javascript.
  214. /// </summary>
  215. /// <param name="mode">The mode.</param>
  216. /// <param name="version">The version.</param>
  217. /// <returns>System.String.</returns>
  218. private string GetCommonJavascript(string mode, string version)
  219. {
  220. var builder = new StringBuilder();
  221. builder.Append("<script>");
  222. if (!string.IsNullOrWhiteSpace(mode))
  223. {
  224. builder.AppendFormat("window.appMode='{0}';", mode);
  225. }
  226. if (string.IsNullOrWhiteSpace(mode))
  227. {
  228. builder.AppendFormat("window.dashboardVersion='{0}';", version);
  229. }
  230. builder.Append("</script>");
  231. var versionString = string.IsNullOrWhiteSpace(mode) ? "?v=" + version : string.Empty;
  232. var files = new List<string>();
  233. files.Add("scripts/apploader.js" + versionString);
  234. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  235. {
  236. files.Insert(0, "cordova.js");
  237. }
  238. var tags = files.Select(s => string.Format("<script src=\"{0}\" defer></script>", s)).ToArray();
  239. builder.Append(string.Join(string.Empty, tags));
  240. return builder.ToString();
  241. }
  242. /// <summary>
  243. /// Gets the raw resource stream.
  244. /// </summary>
  245. private Stream GetRawResourceStream(string virtualPath)
  246. {
  247. return _fileSystem.GetFileStream(GetResourcePath(virtualPath), FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, true);
  248. }
  249. }
  250. }