DashboardService.cs 20 KB

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