PackageCreator.cs 13 KB

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