DashboardService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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. [Route("/favicon.ico", "GET")]
  74. public class GetFavIcon
  75. {
  76. }
  77. /// <summary>
  78. /// Class DashboardService
  79. /// </summary>
  80. public class DashboardService : IService, IRequiresRequest
  81. {
  82. /// <summary>
  83. /// Gets or sets the logger.
  84. /// </summary>
  85. /// <value>The logger.</value>
  86. private readonly ILogger _logger;
  87. /// <summary>
  88. /// Gets or sets the HTTP result factory.
  89. /// </summary>
  90. /// <value>The HTTP result factory.</value>
  91. private readonly IHttpResultFactory _resultFactory;
  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. private readonly IAssemblyInfo _assemblyInfo;
  109. private readonly IMemoryStreamFactory _memoryStreamFactory;
  110. /// <summary>
  111. /// Initializes a new instance of the <see cref="DashboardService" /> class.
  112. /// </summary>
  113. /// <param name="appHost">The app host.</param>
  114. /// <param name="serverConfigurationManager">The server configuration manager.</param>
  115. /// <param name="fileSystem">The file system.</param>
  116. public DashboardService(IServerApplicationHost appHost, IServerConfigurationManager serverConfigurationManager, IFileSystem fileSystem, ILocalizationManager localization, IJsonSerializer jsonSerializer, IAssemblyInfo assemblyInfo, ILogger logger, IHttpResultFactory resultFactory, IMemoryStreamFactory memoryStreamFactory)
  117. {
  118. _appHost = appHost;
  119. _serverConfigurationManager = serverConfigurationManager;
  120. _fileSystem = fileSystem;
  121. _localization = localization;
  122. _jsonSerializer = jsonSerializer;
  123. _assemblyInfo = assemblyInfo;
  124. _logger = logger;
  125. _resultFactory = resultFactory;
  126. _memoryStreamFactory = memoryStreamFactory;
  127. }
  128. public object Get(GetFavIcon request)
  129. {
  130. return Get(new GetDashboardResource
  131. {
  132. ResourceName = "favicon.ico"
  133. });
  134. }
  135. /// <summary>
  136. /// Gets the specified request.
  137. /// </summary>
  138. /// <param name="request">The request.</param>
  139. /// <returns>System.Object.</returns>
  140. public Task<object> Get(GetDashboardConfigurationPage request)
  141. {
  142. IPlugin plugin = null;
  143. Stream stream = null;
  144. var page = ServerEntryPoint.Instance.PluginConfigurationPages.FirstOrDefault(p => string.Equals(p.Name, request.Name, StringComparison.OrdinalIgnoreCase));
  145. if (page != null)
  146. {
  147. plugin = page.Plugin;
  148. stream = page.GetHtmlStream();
  149. }
  150. if (plugin == null)
  151. {
  152. var altPage = GetPluginPages().FirstOrDefault(p => string.Equals(p.Item1.Name, request.Name, StringComparison.OrdinalIgnoreCase));
  153. if (altPage != null)
  154. {
  155. plugin = altPage.Item2;
  156. stream = _assemblyInfo.GetManifestResourceStream(plugin.GetType(), altPage.Item1.EmbeddedResourcePath);
  157. }
  158. }
  159. if (plugin != null && stream != null)
  160. {
  161. return _resultFactory.GetStaticResult(Request, plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => GetPackageCreator().ModifyHtml("dummy.html", stream, null, _appHost.ApplicationVersion.ToString(), null));
  162. }
  163. throw new ResourceNotFoundException();
  164. }
  165. /// <summary>
  166. /// Gets the specified request.
  167. /// </summary>
  168. /// <param name="request">The request.</param>
  169. /// <returns>System.Object.</returns>
  170. public object Get(GetDashboardConfigurationPages request)
  171. {
  172. const string unavilableMessage = "The server is still loading. Please try again momentarily.";
  173. var instance = ServerEntryPoint.Instance;
  174. if (instance == null)
  175. {
  176. throw new InvalidOperationException(unavilableMessage);
  177. }
  178. var pages = instance.PluginConfigurationPages;
  179. if (pages == null)
  180. {
  181. throw new InvalidOperationException(unavilableMessage);
  182. }
  183. if (request.PageType.HasValue)
  184. {
  185. pages = pages.Where(p => p.ConfigurationPageType == request.PageType.Value).ToList();
  186. }
  187. // Don't allow a failing plugin to fail them all
  188. var configPages = pages.Select(p =>
  189. {
  190. try
  191. {
  192. return new ConfigurationPageInfo(p);
  193. }
  194. catch (Exception ex)
  195. {
  196. _logger.ErrorException("Error getting plugin information from {0}", ex, p.GetType().Name);
  197. return null;
  198. }
  199. })
  200. .Where(i => i != null)
  201. .ToList();
  202. configPages.AddRange(_appHost.Plugins.SelectMany(GetConfigPages));
  203. return _resultFactory.GetOptimizedResult(Request, configPages);
  204. }
  205. private IEnumerable<Tuple<PluginPageInfo, IPlugin>> GetPluginPages()
  206. {
  207. return _appHost.Plugins.SelectMany(GetPluginPages);
  208. }
  209. private IEnumerable<Tuple<PluginPageInfo, IPlugin>> GetPluginPages(IPlugin plugin)
  210. {
  211. var hasConfig = plugin as IHasWebPages;
  212. if (hasConfig == null)
  213. {
  214. return new List<Tuple<PluginPageInfo, IPlugin>>();
  215. }
  216. return hasConfig.GetPages().Select(i => new Tuple<PluginPageInfo, IPlugin>(i, plugin));
  217. }
  218. private IEnumerable<ConfigurationPageInfo> GetConfigPages(IPlugin plugin)
  219. {
  220. return GetPluginPages(plugin).Select(i => new ConfigurationPageInfo(plugin, i.Item1));
  221. }
  222. public object Get(GetRobotsTxt request)
  223. {
  224. return Get(new GetDashboardResource
  225. {
  226. ResourceName = "robots.txt"
  227. });
  228. }
  229. /// <summary>
  230. /// Gets the specified request.
  231. /// </summary>
  232. /// <param name="request">The request.</param>
  233. /// <returns>System.Object.</returns>
  234. public async Task<object> Get(GetDashboardResource request)
  235. {
  236. var path = request.ResourceName;
  237. path = path.Replace("bower_components" + _appHost.ApplicationVersion, "bower_components", StringComparison.OrdinalIgnoreCase);
  238. var contentType = MimeTypes.GetMimeType(path);
  239. // Bounce them to the startup wizard if it hasn't been completed yet
  240. if (!_serverConfigurationManager.Configuration.IsStartupWizardCompleted && path.IndexOf("wizard", StringComparison.OrdinalIgnoreCase) == -1 && GetPackageCreator().IsCoreHtml(path))
  241. {
  242. // But don't redirect if an html import is being requested.
  243. if (path.IndexOf("bower_components", StringComparison.OrdinalIgnoreCase) == -1)
  244. {
  245. Request.Response.Redirect("wizardstart.html");
  246. return null;
  247. }
  248. }
  249. 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);
  250. var localizationCulture = GetLocalizationCulture();
  251. // Don't cache if not configured to do so
  252. // But always cache images to simulate production
  253. if (!_serverConfigurationManager.Configuration.EnableDashboardResponseCaching &&
  254. !contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) &&
  255. !contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  256. {
  257. var stream = await GetResourceStream(path, localizationCulture).ConfigureAwait(false);
  258. return _resultFactory.GetResult(stream, contentType);
  259. }
  260. TimeSpan? cacheDuration = null;
  261. // Cache images unconditionally - updates to image files will require new filename
  262. // If there's a version number in the query string we can cache this unconditionally
  263. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase) || !string.IsNullOrEmpty(request.V))
  264. {
  265. cacheDuration = TimeSpan.FromDays(365);
  266. }
  267. var cacheKey = (_appHost.ApplicationVersion + (localizationCulture ?? string.Empty) + path).GetMD5();
  268. return await _resultFactory.GetStaticResult(Request, cacheKey, null, cacheDuration, contentType, () => GetResourceStream(path, localizationCulture)).ConfigureAwait(false);
  269. }
  270. private string GetLocalizationCulture()
  271. {
  272. return _serverConfigurationManager.Configuration.UICulture;
  273. }
  274. /// <summary>
  275. /// Gets the resource stream.
  276. /// </summary>
  277. /// <param name="path">The path.</param>
  278. /// <param name="localizationCulture">The localization culture.</param>
  279. /// <returns>Task{Stream}.</returns>
  280. private Task<Stream> GetResourceStream(string path, string localizationCulture)
  281. {
  282. return GetPackageCreator()
  283. .GetResource(path, null, localizationCulture, _appHost.ApplicationVersion.ToString());
  284. }
  285. private PackageCreator GetPackageCreator()
  286. {
  287. return new PackageCreator(_fileSystem, _logger, _serverConfigurationManager, _memoryStreamFactory);
  288. }
  289. public async Task<object> Get(GetDashboardPackage request)
  290. {
  291. var mode = request.Mode;
  292. var path = string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ?
  293. Path.Combine(_serverConfigurationManager.ApplicationPaths.ProgramDataPath, "webclient-dump")
  294. : "C:\\dev\\emby-web-mobile\\src";
  295. try
  296. {
  297. _fileSystem.DeleteDirectory(path, true);
  298. }
  299. catch (IOException)
  300. {
  301. }
  302. var creator = GetPackageCreator();
  303. CopyDirectory(creator.DashboardUIPath, path);
  304. string culture = null;
  305. var appVersion = _appHost.ApplicationVersion.ToString();
  306. // Try to trim the output size a bit
  307. var bowerPath = Path.Combine(path, "bower_components");
  308. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  309. {
  310. DeleteFoldersByName(Path.Combine(bowerPath, "emby-webcomponents", "fonts"), "roboto");
  311. }
  312. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  313. {
  314. // Delete things that are unneeded in an attempt to keep the output as trim as possible
  315. _fileSystem.DeleteDirectory(Path.Combine(path, "css", "images", "tour"), true);
  316. }
  317. await DumpHtml(creator.DashboardUIPath, path, mode, culture, appVersion);
  318. return "";
  319. }
  320. private void DeleteFoldersByName(string path, string name)
  321. {
  322. var directories = _fileSystem.GetDirectories(path, true)
  323. .Where(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase))
  324. .ToList();
  325. foreach (var directory in directories)
  326. {
  327. _fileSystem.DeleteDirectory(directory.FullName, true);
  328. }
  329. }
  330. private async Task DumpHtml(string source, string destination, string mode, string culture, string appVersion)
  331. {
  332. foreach (var file in _fileSystem.GetFiles(source))
  333. {
  334. var filename = file.Name;
  335. await DumpFile(filename, Path.Combine(destination, filename), mode, culture, appVersion).ConfigureAwait(false);
  336. }
  337. }
  338. private async Task DumpFile(string resourceVirtualPath, string destinationFilePath, string mode, string culture, string appVersion)
  339. {
  340. using (var stream = await GetPackageCreator().GetResource(resourceVirtualPath, mode, culture, appVersion).ConfigureAwait(false))
  341. {
  342. using (var fs = _fileSystem.GetFileStream(destinationFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  343. {
  344. stream.CopyTo(fs);
  345. }
  346. }
  347. }
  348. private void CopyDirectory(string source, string destination)
  349. {
  350. _fileSystem.CreateDirectory(destination);
  351. //Now Create all of the directories
  352. foreach (var dirPath in _fileSystem.GetDirectories(source, true))
  353. _fileSystem.CreateDirectory(dirPath.FullName.Replace(source, destination));
  354. //Copy all the files & Replaces any files with the same name
  355. foreach (var newPath in _fileSystem.GetFiles(source, true))
  356. _fileSystem.CopyFile(newPath.FullName, newPath.FullName.Replace(source, destination), true);
  357. }
  358. }
  359. }