PackageCreator.cs 15 KB

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