DashboardService.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Net;
  5. using MediaBrowser.Controller.Plugins;
  6. using MediaBrowser.Model.Extensions;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.Net;
  9. using MediaBrowser.Model.Serialization;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Threading.Tasks;
  15. using MediaBrowser.Model.IO;
  16. using MediaBrowser.Model.Globalization;
  17. using MediaBrowser.Model.Services;
  18. namespace MediaBrowser.WebDashboard.Api
  19. {
  20. /// <summary>
  21. /// Class GetDashboardConfigurationPages
  22. /// </summary>
  23. [Route("/web/ConfigurationPages", "GET")]
  24. public class GetDashboardConfigurationPages : IReturn<List<ConfigurationPageInfo>>
  25. {
  26. /// <summary>
  27. /// Gets or sets the type of the page.
  28. /// </summary>
  29. /// <value>The type of the page.</value>
  30. public ConfigurationPageType? PageType { get; set; }
  31. }
  32. /// <summary>
  33. /// Class GetDashboardConfigurationPage
  34. /// </summary>
  35. [Route("/web/ConfigurationPage", "GET")]
  36. public class GetDashboardConfigurationPage
  37. {
  38. /// <summary>
  39. /// Gets or sets the name.
  40. /// </summary>
  41. /// <value>The name.</value>
  42. public string Name { get; set; }
  43. }
  44. [Route("/web/Package", "GET")]
  45. public class GetDashboardPackage
  46. {
  47. public string Mode { get; set; }
  48. }
  49. [Route("/robots.txt", "GET")]
  50. public class GetRobotsTxt
  51. {
  52. }
  53. /// <summary>
  54. /// Class GetDashboardResource
  55. /// </summary>
  56. [Route("/web/{ResourceName*}", "GET")]
  57. public class GetDashboardResource
  58. {
  59. /// <summary>
  60. /// Gets or sets the name.
  61. /// </summary>
  62. /// <value>The name.</value>
  63. public string ResourceName { get; set; }
  64. /// <summary>
  65. /// Gets or sets the V.
  66. /// </summary>
  67. /// <value>The V.</value>
  68. public string V { get; set; }
  69. }
  70. /// <summary>
  71. /// Class DashboardService
  72. /// </summary>
  73. public class DashboardService : IRestfulService, IHasResultFactory
  74. {
  75. /// <summary>
  76. /// Gets or sets the logger.
  77. /// </summary>
  78. /// <value>The logger.</value>
  79. public ILogger Logger { get; set; }
  80. /// <summary>
  81. /// Gets or sets the HTTP result factory.
  82. /// </summary>
  83. /// <value>The HTTP result factory.</value>
  84. public IHttpResultFactory ResultFactory { get; set; }
  85. /// <summary>
  86. /// Gets or sets the request context.
  87. /// </summary>
  88. /// <value>The request context.</value>
  89. public IRequest Request { get; set; }
  90. /// <summary>
  91. /// The _app host
  92. /// </summary>
  93. private readonly IServerApplicationHost _appHost;
  94. /// <summary>
  95. /// The _server configuration manager
  96. /// </summary>
  97. private readonly IServerConfigurationManager _serverConfigurationManager;
  98. private readonly IFileSystem _fileSystem;
  99. private readonly ILocalizationManager _localization;
  100. private readonly IJsonSerializer _jsonSerializer;
  101. /// <summary>
  102. /// Initializes a new instance of the <see cref="DashboardService" /> class.
  103. /// </summary>
  104. /// <param name="appHost">The app host.</param>
  105. /// <param name="serverConfigurationManager">The server configuration manager.</param>
  106. /// <param name="fileSystem">The file system.</param>
  107. public DashboardService(IServerApplicationHost appHost, IServerConfigurationManager serverConfigurationManager, IFileSystem fileSystem, ILocalizationManager localization, IJsonSerializer jsonSerializer)
  108. {
  109. _appHost = appHost;
  110. _serverConfigurationManager = serverConfigurationManager;
  111. _fileSystem = fileSystem;
  112. _localization = localization;
  113. _jsonSerializer = jsonSerializer;
  114. }
  115. /// <summary>
  116. /// Gets the specified request.
  117. /// </summary>
  118. /// <param name="request">The request.</param>
  119. /// <returns>System.Object.</returns>
  120. public Task<object> Get(GetDashboardConfigurationPage request)
  121. {
  122. var page = ServerEntryPoint.Instance.PluginConfigurationPages.First(p => p.Name.Equals(request.Name, StringComparison.OrdinalIgnoreCase));
  123. return ResultFactory.GetStaticResult(Request, page.Plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => GetPackageCreator().ModifyHtml("dummy.html", page.GetHtmlStream(), null, _appHost.ApplicationVersion.ToString(), null, false));
  124. }
  125. /// <summary>
  126. /// Gets the specified request.
  127. /// </summary>
  128. /// <param name="request">The request.</param>
  129. /// <returns>System.Object.</returns>
  130. public object Get(GetDashboardConfigurationPages request)
  131. {
  132. const string unavilableMessage = "The server is still loading. Please try again momentarily.";
  133. var instance = ServerEntryPoint.Instance;
  134. if (instance == null)
  135. {
  136. throw new InvalidOperationException(unavilableMessage);
  137. }
  138. var pages = instance.PluginConfigurationPages;
  139. if (pages == null)
  140. {
  141. throw new InvalidOperationException(unavilableMessage);
  142. }
  143. if (request.PageType.HasValue)
  144. {
  145. pages = pages.Where(p => p.ConfigurationPageType == request.PageType.Value);
  146. }
  147. // Don't allow a failing plugin to fail them all
  148. var configPages = pages.Select(p =>
  149. {
  150. try
  151. {
  152. return new ConfigurationPageInfo(p);
  153. }
  154. catch (Exception ex)
  155. {
  156. Logger.ErrorException("Error getting plugin information from {0}", ex, p.GetType().Name);
  157. return null;
  158. }
  159. })
  160. .Where(i => i != null)
  161. .ToList();
  162. return ResultFactory.GetOptimizedResult(Request, configPages);
  163. }
  164. public object Get(GetRobotsTxt request)
  165. {
  166. return Get(new GetDashboardResource
  167. {
  168. ResourceName = "robots.txt"
  169. });
  170. }
  171. /// <summary>
  172. /// Gets the specified request.
  173. /// </summary>
  174. /// <param name="request">The request.</param>
  175. /// <returns>System.Object.</returns>
  176. public async Task<object> Get(GetDashboardResource request)
  177. {
  178. var path = request.ResourceName;
  179. path = path.Replace("bower_components" + _appHost.ApplicationVersion, "bower_components", StringComparison.OrdinalIgnoreCase);
  180. var contentType = MimeTypes.GetMimeType(path);
  181. // Bounce them to the startup wizard if it hasn't been completed yet
  182. if (!_serverConfigurationManager.Configuration.IsStartupWizardCompleted && path.IndexOf("wizard", StringComparison.OrdinalIgnoreCase) == -1 && GetPackageCreator().IsCoreHtml(path))
  183. {
  184. // But don't redirect if an html import is being requested.
  185. if (path.IndexOf("bower_components", StringComparison.OrdinalIgnoreCase) == -1)
  186. {
  187. Request.Response.Redirect("wizardstart.html");
  188. return null;
  189. }
  190. }
  191. path = path.Replace("scripts/jquery.mobile-1.4.5.min.map", "thirdparty/jquerymobile-1.4.5/jquery.mobile-1.4.5.min.map", StringComparison.OrdinalIgnoreCase);
  192. var localizationCulture = GetLocalizationCulture();
  193. // Don't cache if not configured to do so
  194. // But always cache images to simulate production
  195. if (!_serverConfigurationManager.Configuration.EnableDashboardResponseCaching &&
  196. !contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) &&
  197. !contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  198. {
  199. var stream = await GetResourceStream(path, localizationCulture).ConfigureAwait(false);
  200. return ResultFactory.GetResult(stream, contentType);
  201. }
  202. TimeSpan? cacheDuration = null;
  203. // Cache images unconditionally - updates to image files will require new filename
  204. // If there's a version number in the query string we can cache this unconditionally
  205. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase) || !string.IsNullOrEmpty(request.V))
  206. {
  207. cacheDuration = TimeSpan.FromDays(365);
  208. }
  209. var cacheKey = (_appHost.ApplicationVersion.ToString() + (localizationCulture ?? string.Empty) + path).GetMD5();
  210. return await ResultFactory.GetStaticResult(Request, cacheKey, null, cacheDuration, contentType, () => GetResourceStream(path, localizationCulture)).ConfigureAwait(false);
  211. }
  212. private string GetLocalizationCulture()
  213. {
  214. return _serverConfigurationManager.Configuration.UICulture;
  215. }
  216. /// <summary>
  217. /// Gets the resource stream.
  218. /// </summary>
  219. /// <param name="path">The path.</param>
  220. /// <param name="localizationCulture">The localization culture.</param>
  221. /// <returns>Task{Stream}.</returns>
  222. private Task<Stream> GetResourceStream(string path, string localizationCulture)
  223. {
  224. var minify = _serverConfigurationManager.Configuration.EnableDashboardResourceMinification;
  225. return GetPackageCreator()
  226. .GetResource(path, null, localizationCulture, _appHost.ApplicationVersion.ToString(), minify);
  227. }
  228. private PackageCreator GetPackageCreator()
  229. {
  230. return new PackageCreator(_fileSystem, _localization, Logger, _serverConfigurationManager, _jsonSerializer);
  231. }
  232. private List<string> GetDeployIgnoreExtensions()
  233. {
  234. var list = new List<string>();
  235. list.Add(".log");
  236. list.Add(".txt");
  237. list.Add(".map");
  238. list.Add(".md");
  239. list.Add(".gz");
  240. list.Add(".bat");
  241. list.Add(".sh");
  242. return list;
  243. }
  244. private List<Tuple<string, bool>> GetDeployIgnoreFilenames()
  245. {
  246. var list = new List<Tuple<string, bool>>();
  247. list.Add(new Tuple<string, bool>("copying", true));
  248. list.Add(new Tuple<string, bool>("license", true));
  249. list.Add(new Tuple<string, bool>("license-mit", true));
  250. list.Add(new Tuple<string, bool>("gitignore", false));
  251. list.Add(new Tuple<string, bool>("npmignore", false));
  252. list.Add(new Tuple<string, bool>("jshintrc", false));
  253. list.Add(new Tuple<string, bool>("gruntfile", false));
  254. list.Add(new Tuple<string, bool>("bowerrc", false));
  255. list.Add(new Tuple<string, bool>("jscsrc", false));
  256. list.Add(new Tuple<string, bool>("hero.svg", false));
  257. list.Add(new Tuple<string, bool>("travis.yml", false));
  258. list.Add(new Tuple<string, bool>("build.js", false));
  259. list.Add(new Tuple<string, bool>("editorconfig", false));
  260. list.Add(new Tuple<string, bool>("gitattributes", false));
  261. return list;
  262. }
  263. public async Task<object> Get(GetDashboardPackage request)
  264. {
  265. var mode = request.Mode;
  266. var path = string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ?
  267. Path.Combine(_serverConfigurationManager.ApplicationPaths.ProgramDataPath, "webclient-dump")
  268. : "C:\\dev\\emby-web-mobile\\src";
  269. try
  270. {
  271. _fileSystem.DeleteDirectory(path, true);
  272. }
  273. catch (IOException)
  274. {
  275. }
  276. var creator = GetPackageCreator();
  277. CopyDirectory(creator.DashboardUIPath, path);
  278. string culture = null;
  279. var appVersion = _appHost.ApplicationVersion.ToString();
  280. // Try to trim the output size a bit
  281. var bowerPath = Path.Combine(path, "bower_components");
  282. GetDeployIgnoreExtensions().ForEach(i => DeleteFilesByExtension(bowerPath, i));
  283. DeleteFilesByExtension(bowerPath, ".json", "strings\\");
  284. GetDeployIgnoreFilenames().ForEach(i => DeleteFilesByName(bowerPath, i.Item1, i.Item2));
  285. DeleteFoldersByName(bowerPath, "demo");
  286. DeleteFoldersByName(bowerPath, "test");
  287. DeleteFoldersByName(bowerPath, "guides");
  288. DeleteFoldersByName(bowerPath, "grunt");
  289. DeleteFoldersByName(bowerPath, "rollups");
  290. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  291. {
  292. DeleteFoldersByName(Path.Combine(bowerPath, "emby-webcomponents", "fonts"), "montserrat");
  293. DeleteFoldersByName(Path.Combine(bowerPath, "emby-webcomponents", "fonts"), "opensans");
  294. DeleteFoldersByName(Path.Combine(bowerPath, "emby-webcomponents", "fonts"), "roboto");
  295. }
  296. _fileSystem.DeleteDirectory(Path.Combine(bowerPath, "jquery", "src"), true);
  297. DeleteCryptoFiles(Path.Combine(bowerPath, "cryptojslib", "components"));
  298. DeleteFoldersByName(Path.Combine(bowerPath, "jquery"), "src");
  299. DeleteFoldersByName(Path.Combine(bowerPath, "jstree"), "src");
  300. //DeleteFoldersByName(Path.Combine(bowerPath, "Sortable"), "meteor");
  301. //DeleteFoldersByName(Path.Combine(bowerPath, "Sortable"), "st");
  302. //DeleteFoldersByName(Path.Combine(bowerPath, "Swiper"), "src");
  303. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  304. {
  305. // Delete things that are unneeded in an attempt to keep the output as trim as possible
  306. _fileSystem.DeleteDirectory(Path.Combine(path, "css", "images", "tour"), true);
  307. }
  308. await DumpHtml(creator.DashboardUIPath, path, mode, culture, appVersion);
  309. await DumpFile("css/all.css", Path.Combine(path, "css", "all.css"), mode, culture, appVersion).ConfigureAwait(false);
  310. return "";
  311. }
  312. private void DeleteCryptoFiles(string path)
  313. {
  314. var files = _fileSystem.GetFiles(path)
  315. .ToList();
  316. var keepFiles = new[] { "core-min.js", "md5-min.js", "sha1-min.js" };
  317. foreach (var file in files)
  318. {
  319. if (!keepFiles.Contains(file.Name, StringComparer.OrdinalIgnoreCase))
  320. {
  321. _fileSystem.DeleteFile(file.FullName);
  322. }
  323. }
  324. }
  325. private void DeleteFilesByExtension(string path, string extension, string exclude = null)
  326. {
  327. var files = _fileSystem.GetFiles(path, true)
  328. .Where(i => string.Equals(i.Extension, extension, StringComparison.OrdinalIgnoreCase))
  329. .ToList();
  330. foreach (var file in files)
  331. {
  332. if (!string.IsNullOrWhiteSpace(exclude))
  333. {
  334. if (file.FullName.IndexOf(exclude, StringComparison.OrdinalIgnoreCase) != -1)
  335. {
  336. continue;
  337. }
  338. }
  339. _fileSystem.DeleteFile(file.FullName);
  340. }
  341. }
  342. private void DeleteFilesByName(string path, string name, bool exact = false)
  343. {
  344. var files = _fileSystem.GetFiles(path, true)
  345. .Where(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase) || (!exact && i.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1))
  346. .ToList();
  347. foreach (var file in files)
  348. {
  349. _fileSystem.DeleteFile(file.FullName);
  350. }
  351. }
  352. private void DeleteFoldersByName(string path, string name)
  353. {
  354. var directories = _fileSystem.GetDirectories(path, true)
  355. .Where(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase))
  356. .ToList();
  357. foreach (var directory in directories)
  358. {
  359. _fileSystem.DeleteDirectory(directory.FullName, true);
  360. }
  361. }
  362. private async Task DumpHtml(string source, string destination, string mode, string culture, string appVersion)
  363. {
  364. foreach (var file in _fileSystem.GetFiles(source))
  365. {
  366. var filename = file.Name;
  367. await DumpFile(filename, Path.Combine(destination, filename), mode, culture, appVersion).ConfigureAwait(false);
  368. }
  369. }
  370. private async Task DumpFile(string resourceVirtualPath, string destinationFilePath, string mode, string culture, string appVersion)
  371. {
  372. using (var stream = await GetPackageCreator().GetResource(resourceVirtualPath, mode, culture, appVersion, false).ConfigureAwait(false))
  373. {
  374. using (var fs = _fileSystem.GetFileStream(destinationFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  375. {
  376. stream.CopyTo(fs);
  377. }
  378. }
  379. }
  380. private void CopyDirectory(string source, string destination)
  381. {
  382. _fileSystem.CreateDirectory(destination);
  383. //Now Create all of the directories
  384. foreach (var dirPath in _fileSystem.GetDirectories(source, true))
  385. _fileSystem.CreateDirectory(dirPath.FullName.Replace(source, destination));
  386. //Copy all the files & Replaces any files with the same name
  387. foreach (var newPath in _fileSystem.GetFiles(source, true))
  388. _fileSystem.CopyFile(newPath.FullName, newPath.FullName.Replace(source, destination), true);
  389. }
  390. }
  391. }