DashboardService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. public async Task<object> Get(GetDashboardPackage request)
  279. {
  280. var mode = request.Mode;
  281. var path = string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ?
  282. Path.Combine(_serverConfigurationManager.ApplicationPaths.ProgramDataPath, "webclient-dump")
  283. : "C:\\dev\\emby-web-mobile\\src";
  284. try
  285. {
  286. _fileSystem.DeleteDirectory(path, true);
  287. }
  288. catch (IOException)
  289. {
  290. }
  291. var creator = GetPackageCreator();
  292. CopyDirectory(creator.DashboardUIPath, path);
  293. string culture = null;
  294. var appVersion = _appHost.ApplicationVersion.ToString();
  295. // Try to trim the output size a bit
  296. var bowerPath = Path.Combine(path, "bower_components");
  297. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  298. {
  299. DeleteFoldersByName(Path.Combine(bowerPath, "emby-webcomponents", "fonts"), "roboto");
  300. }
  301. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  302. {
  303. // Delete things that are unneeded in an attempt to keep the output as trim as possible
  304. _fileSystem.DeleteDirectory(Path.Combine(path, "css", "images", "tour"), true);
  305. }
  306. await DumpHtml(creator.DashboardUIPath, path, mode, culture, appVersion);
  307. return "";
  308. }
  309. private void DeleteFoldersByName(string path, string name)
  310. {
  311. var directories = _fileSystem.GetDirectories(path, true)
  312. .Where(i => string.Equals(i.Name, name, StringComparison.OrdinalIgnoreCase))
  313. .ToList();
  314. foreach (var directory in directories)
  315. {
  316. _fileSystem.DeleteDirectory(directory.FullName, true);
  317. }
  318. }
  319. private async Task DumpHtml(string source, string destination, string mode, string culture, string appVersion)
  320. {
  321. foreach (var file in _fileSystem.GetFiles(source))
  322. {
  323. var filename = file.Name;
  324. await DumpFile(filename, Path.Combine(destination, filename), mode, culture, appVersion).ConfigureAwait(false);
  325. }
  326. }
  327. private async Task DumpFile(string resourceVirtualPath, string destinationFilePath, string mode, string culture, string appVersion)
  328. {
  329. using (var stream = await GetPackageCreator().GetResource(resourceVirtualPath, mode, culture, appVersion).ConfigureAwait(false))
  330. {
  331. using (var fs = _fileSystem.GetFileStream(destinationFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read))
  332. {
  333. stream.CopyTo(fs);
  334. }
  335. }
  336. }
  337. private void CopyDirectory(string source, string destination)
  338. {
  339. _fileSystem.CreateDirectory(destination);
  340. //Now Create all of the directories
  341. foreach (var dirPath in _fileSystem.GetDirectories(source, true))
  342. _fileSystem.CreateDirectory(dirPath.FullName.Replace(source, destination));
  343. //Copy all the files & Replaces any files with the same name
  344. foreach (var newPath in _fileSystem.GetFiles(source, true))
  345. _fileSystem.CopyFile(newPath.FullName, newPath.FullName.Replace(source, destination), true);
  346. }
  347. }
  348. }