DashboardService.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  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;
  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/staticfiles", "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 allFiles = GetCacheFileList();
  135. return ResultFactory.GetOptimizedResult(Request, _jsonSerializer.SerializeToString(allFiles));
  136. }
  137. private List<string> GetCacheFileList()
  138. {
  139. var creator = GetPackageCreator();
  140. var directory = creator.DashboardUIPath;
  141. var skipExtensions = GetDeployIgnoreExtensions();
  142. var skipNames = GetDeployIgnoreFilenames();
  143. return
  144. Directory.GetFiles(directory, "*", SearchOption.AllDirectories)
  145. .Where(i => !skipExtensions.Contains(Path.GetExtension(i) ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  146. .Where(i => !skipNames.Any(s =>
  147. {
  148. if (s.Item2)
  149. {
  150. return string.Equals(s.Item1, Path.GetFileName(i), StringComparison.OrdinalIgnoreCase);
  151. }
  152. return (Path.GetFileName(i) ?? string.Empty).IndexOf(s.Item1, StringComparison.OrdinalIgnoreCase) != -1;
  153. }))
  154. .Select(i => i.Replace(directory, string.Empty, StringComparison.OrdinalIgnoreCase).Replace("\\", "/").TrimStart('/') + "?v=" + _appHost.ApplicationVersion.ToString())
  155. .ToList();
  156. }
  157. /// <summary>
  158. /// Gets the specified request.
  159. /// </summary>
  160. /// <param name="request">The request.</param>
  161. /// <returns>System.Object.</returns>
  162. public object Get(GetDashboardConfigurationPages request)
  163. {
  164. const string unavilableMessage = "The server is still loading. Please try again momentarily.";
  165. var instance = ServerEntryPoint.Instance;
  166. if (instance == null)
  167. {
  168. throw new InvalidOperationException(unavilableMessage);
  169. }
  170. var pages = instance.PluginConfigurationPages;
  171. if (pages == null)
  172. {
  173. throw new InvalidOperationException(unavilableMessage);
  174. }
  175. if (request.PageType.HasValue)
  176. {
  177. pages = pages.Where(p => p.ConfigurationPageType == request.PageType.Value);
  178. }
  179. // Don't allow a failing plugin to fail them all
  180. var configPages = pages.Select(p =>
  181. {
  182. try
  183. {
  184. return new ConfigurationPageInfo(p);
  185. }
  186. catch (Exception ex)
  187. {
  188. Logger.ErrorException("Error getting plugin information from {0}", ex, p.GetType().Name);
  189. return null;
  190. }
  191. })
  192. .Where(i => i != null)
  193. .ToList();
  194. return ResultFactory.GetOptimizedResult(Request, configPages);
  195. }
  196. public object Get(GetRobotsTxt request)
  197. {
  198. return Get(new GetDashboardResource
  199. {
  200. ResourceName = "robots.txt"
  201. });
  202. }
  203. /// <summary>
  204. /// Gets the specified request.
  205. /// </summary>
  206. /// <param name="request">The request.</param>
  207. /// <returns>System.Object.</returns>
  208. public async Task<object> Get(GetDashboardResource request)
  209. {
  210. var path = request.ResourceName;
  211. path = path.Replace("bower_components" + _appHost.ApplicationVersion, "bower_components", StringComparison.OrdinalIgnoreCase);
  212. var contentType = MimeTypes.GetMimeType(path);
  213. // Bounce them to the startup wizard if it hasn't been completed yet
  214. if (!_serverConfigurationManager.Configuration.IsStartupWizardCompleted && path.IndexOf("wizard", StringComparison.OrdinalIgnoreCase) == -1 && GetPackageCreator().IsCoreHtml(path))
  215. {
  216. // But don't redirect if an html import is being requested.
  217. if (path.IndexOf("bower_components", StringComparison.OrdinalIgnoreCase) == -1)
  218. {
  219. Request.Response.Redirect("wizardstart.html");
  220. return null;
  221. }
  222. }
  223. 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);
  224. var localizationCulture = GetLocalizationCulture();
  225. // Don't cache if not configured to do so
  226. // But always cache images to simulate production
  227. if (!_serverConfigurationManager.Configuration.EnableDashboardResponseCaching &&
  228. !contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) &&
  229. !contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  230. {
  231. var stream = await GetResourceStream(path, localizationCulture).ConfigureAwait(false);
  232. return ResultFactory.GetResult(stream, contentType);
  233. }
  234. TimeSpan? cacheDuration = null;
  235. // Cache images unconditionally - updates to image files will require new filename
  236. // If there's a version number in the query string we can cache this unconditionally
  237. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase) || !string.IsNullOrEmpty(request.V))
  238. {
  239. cacheDuration = TimeSpan.FromDays(365);
  240. }
  241. var assembly = GetType().Assembly.GetName();
  242. var cacheKey = (assembly.Version + (localizationCulture ?? string.Empty) + path).GetMD5();
  243. return await ResultFactory.GetStaticResult(Request, cacheKey, null, cacheDuration, contentType, () => GetResourceStream(path, localizationCulture)).ConfigureAwait(false);
  244. }
  245. private string GetLocalizationCulture()
  246. {
  247. return _serverConfigurationManager.Configuration.UICulture;
  248. }
  249. /// <summary>
  250. /// Gets the resource stream.
  251. /// </summary>
  252. /// <param name="path">The path.</param>
  253. /// <param name="localizationCulture">The localization culture.</param>
  254. /// <returns>Task{Stream}.</returns>
  255. private Task<Stream> GetResourceStream(string path, string localizationCulture)
  256. {
  257. var minify = _serverConfigurationManager.Configuration.EnableDashboardResourceMinification;
  258. return GetPackageCreator()
  259. .GetResource(path, null, localizationCulture, _appHost.ApplicationVersion.ToString(), minify);
  260. }
  261. private PackageCreator GetPackageCreator()
  262. {
  263. return new PackageCreator(_fileSystem, _localization, Logger, _serverConfigurationManager, _jsonSerializer);
  264. }
  265. private List<string> GetDeployIgnoreExtensions()
  266. {
  267. var list = new List<string>();
  268. list.Add(".log");
  269. list.Add(".txt");
  270. list.Add(".map");
  271. list.Add(".md");
  272. list.Add(".gz");
  273. list.Add(".bat");
  274. list.Add(".sh");
  275. return list;
  276. }
  277. private List<Tuple<string,bool>> GetDeployIgnoreFilenames()
  278. {
  279. var list = new List<Tuple<string, bool>>();
  280. list.Add(new Tuple<string, bool>("copying", true));
  281. list.Add(new Tuple<string, bool>("license", true));
  282. list.Add(new Tuple<string, bool>("license-mit", true));
  283. list.Add(new Tuple<string, bool>("gitignore", false));
  284. list.Add(new Tuple<string, bool>("npmignore", false));
  285. list.Add(new Tuple<string, bool>("jshintrc", false));
  286. list.Add(new Tuple<string, bool>("gruntfile", false));
  287. list.Add(new Tuple<string, bool>("bowerrc", false));
  288. list.Add(new Tuple<string, bool>("jscsrc", false));
  289. list.Add(new Tuple<string, bool>("hero.svg", false));
  290. list.Add(new Tuple<string, bool>("travis.yml", false));
  291. list.Add(new Tuple<string, bool>("build.js", false));
  292. list.Add(new Tuple<string, bool>("editorconfig", false));
  293. list.Add(new Tuple<string, bool>("gitattributes", false));
  294. return list;
  295. }
  296. public async Task<object> Get(GetDashboardPackage request)
  297. {
  298. var path = Path.Combine(_serverConfigurationManager.ApplicationPaths.ProgramDataPath,
  299. "webclient-dump");
  300. try
  301. {
  302. _fileSystem.DeleteDirectory(path, true);
  303. }
  304. catch (IOException)
  305. {
  306. }
  307. var creator = GetPackageCreator();
  308. CopyDirectory(creator.DashboardUIPath, path);
  309. string culture = null;
  310. var appVersion = _appHost.ApplicationVersion.ToString();
  311. File.WriteAllText(Path.Combine(path, "staticfiles"), _jsonSerializer.SerializeToString(GetCacheFileList()));
  312. var mode = request.Mode;
  313. // Try to trim the output size a bit
  314. var bowerPath = Path.Combine(path, "bower_components");
  315. GetDeployIgnoreExtensions().ForEach(i => DeleteFilesByExtension(bowerPath, i));
  316. DeleteFilesByExtension(bowerPath, ".json", "strings\\");
  317. GetDeployIgnoreFilenames().ForEach(i => DeleteFilesByName(bowerPath, i.Item1, i.Item2));
  318. DeleteFoldersByName(bowerPath, "demo");
  319. DeleteFoldersByName(bowerPath, "test");
  320. DeleteFoldersByName(bowerPath, "guides");
  321. DeleteFoldersByName(bowerPath, "grunt");
  322. DeleteFoldersByName(bowerPath, "rollups");
  323. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  324. {
  325. DeleteFoldersByName(Path.Combine(bowerPath, "emby-webcomponents", "fonts"), "montserrat");
  326. DeleteFoldersByName(Path.Combine(bowerPath, "emby-webcomponents", "fonts"), "opensans");
  327. DeleteFoldersByName(Path.Combine(bowerPath, "emby-webcomponents", "fonts"), "roboto");
  328. }
  329. _fileSystem.DeleteDirectory(Path.Combine(bowerPath, "jquery", "src"), true);
  330. DeleteCryptoFiles(Path.Combine(bowerPath, "cryptojslib", "components"));
  331. DeleteFoldersByName(Path.Combine(bowerPath, "jquery"), "src");
  332. DeleteFoldersByName(Path.Combine(bowerPath, "jstree"), "src");
  333. //DeleteFoldersByName(Path.Combine(bowerPath, "Sortable"), "meteor");
  334. //DeleteFoldersByName(Path.Combine(bowerPath, "Sortable"), "st");
  335. //DeleteFoldersByName(Path.Combine(bowerPath, "Swiper"), "src");
  336. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  337. {
  338. // Delete things that are unneeded in an attempt to keep the output as trim as possible
  339. _fileSystem.DeleteDirectory(Path.Combine(path, "css", "images", "tour"), true);
  340. }
  341. else
  342. {
  343. MinifyCssDirectory(path);
  344. MinifyJsDirectory(path);
  345. }
  346. await DumpHtml(creator.DashboardUIPath, path, mode, culture, appVersion);
  347. await DumpFile("css/all.css", Path.Combine(path, "css", "all.css"), mode, culture, appVersion).ConfigureAwait(false);
  348. return "";
  349. }
  350. private void DeleteCryptoFiles(string path)
  351. {
  352. var files = _fileSystem.GetFiles(path)
  353. .ToList();
  354. var keepFiles = new[] { "core-min.js", "md5-min.js", "sha1-min.js" };
  355. foreach (var file in files)
  356. {
  357. if (!keepFiles.Contains(file.Name, StringComparer.OrdinalIgnoreCase))
  358. {
  359. _fileSystem.DeleteFile(file.FullName);
  360. }
  361. }
  362. }
  363. private void DeleteFilesByExtension(string path, string extension, string exclude = null)
  364. {
  365. var files = _fileSystem.GetFiles(path, true)
  366. .Where(i => string.Equals(i.Extension, extension, StringComparison.OrdinalIgnoreCase))
  367. .ToList();
  368. foreach (var file in files)
  369. {
  370. if (!string.IsNullOrWhiteSpace(exclude))
  371. {
  372. if (file.FullName.IndexOf(exclude, StringComparison.OrdinalIgnoreCase) != -1)
  373. {
  374. continue;
  375. }
  376. }
  377. _fileSystem.DeleteFile(file.FullName);
  378. }
  379. }
  380. private void DeleteFilesByName(string path, string name, bool exact = false)
  381. {
  382. var files = _fileSystem.GetFiles(path, true)
  383. .Where(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase) || (!exact && i.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1))
  384. .ToList();
  385. foreach (var file in files)
  386. {
  387. _fileSystem.DeleteFile(file.FullName);
  388. }
  389. }
  390. private void DeleteFoldersByName(string path, string name)
  391. {
  392. var directories = _fileSystem.GetDirectories(path, true)
  393. .Where(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase))
  394. .ToList();
  395. foreach (var directory in directories)
  396. {
  397. _fileSystem.DeleteDirectory(directory.FullName, true);
  398. }
  399. }
  400. private void MinifyCssDirectory(string path)
  401. {
  402. foreach (var file in Directory.GetFiles(path, "*.css", SearchOption.AllDirectories))
  403. {
  404. if (file.IndexOf(".min.", StringComparison.OrdinalIgnoreCase) != -1)
  405. {
  406. continue;
  407. }
  408. if (file.IndexOf("bower_", StringComparison.OrdinalIgnoreCase) != -1)
  409. {
  410. continue;
  411. }
  412. try
  413. {
  414. var text = _fileSystem.ReadAllText(file, Encoding.UTF8);
  415. var result = new KristensenCssMinifier().Minify(text, false, Encoding.UTF8);
  416. if (result.Errors.Count > 0)
  417. {
  418. Logger.Error("Error minifying css: " + result.Errors[0].Message);
  419. }
  420. else
  421. {
  422. text = result.MinifiedContent;
  423. _fileSystem.WriteAllText(file, text, Encoding.UTF8);
  424. }
  425. }
  426. catch (Exception ex)
  427. {
  428. Logger.ErrorException("Error minifying css", ex);
  429. }
  430. }
  431. }
  432. private void MinifyJsDirectory(string path)
  433. {
  434. foreach (var file in Directory.GetFiles(path, "*.js", SearchOption.AllDirectories))
  435. {
  436. if (file.IndexOf(".min.", StringComparison.OrdinalIgnoreCase) != -1)
  437. {
  438. continue;
  439. }
  440. if (file.IndexOf("bower_", StringComparison.OrdinalIgnoreCase) != -1)
  441. {
  442. continue;
  443. }
  444. try
  445. {
  446. var text = _fileSystem.ReadAllText(file, Encoding.UTF8);
  447. var result = new CrockfordJsMinifier().Minify(text, false, Encoding.UTF8);
  448. if (result.Errors.Count > 0)
  449. {
  450. Logger.Error("Error minifying javascript: " + result.Errors[0].Message);
  451. }
  452. else
  453. {
  454. text = result.MinifiedContent;
  455. _fileSystem.WriteAllText(file, text, Encoding.UTF8);
  456. }
  457. }
  458. catch (Exception ex)
  459. {
  460. Logger.ErrorException("Error minifying css", ex);
  461. }
  462. }
  463. }
  464. private async Task DumpHtml(string source, string destination, string mode, string culture, string appVersion)
  465. {
  466. foreach (var file in Directory.GetFiles(source, "*", SearchOption.TopDirectoryOnly))
  467. {
  468. var filename = Path.GetFileName(file);
  469. await DumpFile(filename, Path.Combine(destination, filename), mode, culture, appVersion).ConfigureAwait(false);
  470. }
  471. }
  472. private async Task DumpFile(string resourceVirtualPath, string destinationFilePath, string mode, string culture, string appVersion)
  473. {
  474. using (var stream = await GetPackageCreator().GetResource(resourceVirtualPath, mode, culture, appVersion, true).ConfigureAwait(false))
  475. {
  476. using (var fs = _fileSystem.GetFileStream(destinationFilePath, FileMode.Create, FileAccess.Write, FileShare.Read))
  477. {
  478. stream.CopyTo(fs);
  479. }
  480. }
  481. }
  482. private void CopyDirectory(string source, string destination)
  483. {
  484. _fileSystem.CreateDirectory(destination);
  485. //Now Create all of the directories
  486. foreach (string dirPath in Directory.GetDirectories(source, "*",
  487. SearchOption.AllDirectories))
  488. _fileSystem.CreateDirectory(dirPath.Replace(source, destination));
  489. //Copy all the files & Replaces any files with the same name
  490. foreach (string newPath in Directory.GetFiles(source, "*.*",
  491. SearchOption.AllDirectories))
  492. _fileSystem.CopyFile(newPath, newPath.Replace(source, destination), true);
  493. }
  494. }
  495. }