DashboardService.cs 22 KB

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