DashboardService.cs 20 KB

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