2
0

DashboardService.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Common.ScheduledTasks;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.Plugins;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.Tasks;
  9. using MediaBrowser.Server.Implementations.HttpServer;
  10. using ServiceStack.ServiceHost;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.ComponentModel.Composition;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Net;
  17. using System.Text;
  18. using System.Text.RegularExpressions;
  19. using System.Threading.Tasks;
  20. namespace MediaBrowser.WebDashboard.Api
  21. {
  22. /// <summary>
  23. /// Class GetDashboardConfigurationPages
  24. /// </summary>
  25. [Route("/dashboard/ConfigurationPages", "GET")]
  26. public class GetDashboardConfigurationPages : IReturn<List<IPluginConfigurationPage>>
  27. {
  28. /// <summary>
  29. /// Gets or sets the type of the page.
  30. /// </summary>
  31. /// <value>The type of the page.</value>
  32. public ConfigurationPageType? PageType { get; set; }
  33. }
  34. /// <summary>
  35. /// Class GetDashboardConfigurationPage
  36. /// </summary>
  37. [Route("/dashboard/ConfigurationPage", "GET")]
  38. public class GetDashboardConfigurationPage : IReturn<IPluginConfigurationPage>
  39. {
  40. /// <summary>
  41. /// Gets or sets the name.
  42. /// </summary>
  43. /// <value>The name.</value>
  44. public string Name { get; set; }
  45. }
  46. /// <summary>
  47. /// Class GetDashboardResource
  48. /// </summary>
  49. [Route("/dashboard/{ResourceName*}", "GET")]
  50. public class GetDashboardResource
  51. {
  52. /// <summary>
  53. /// Gets or sets the name.
  54. /// </summary>
  55. /// <value>The name.</value>
  56. public string ResourceName { get; set; }
  57. /// <summary>
  58. /// Gets or sets the V.
  59. /// </summary>
  60. /// <value>The V.</value>
  61. public string V { get; set; }
  62. }
  63. /// <summary>
  64. /// Class GetDashboardInfo
  65. /// </summary>
  66. [Route("/dashboard/dashboardInfo", "GET")]
  67. public class GetDashboardInfo : IReturn<DashboardInfo>
  68. {
  69. }
  70. /// <summary>
  71. /// Class DashboardService
  72. /// </summary>
  73. [Export(typeof(IRestfulService))]
  74. public class DashboardService : BaseRestService
  75. {
  76. /// <summary>
  77. /// Gets or sets the task manager.
  78. /// </summary>
  79. /// <value>The task manager.</value>
  80. private readonly ITaskManager _taskManager;
  81. /// <summary>
  82. /// The _user manager
  83. /// </summary>
  84. private readonly IUserManager _userManager;
  85. private readonly IServerApplicationHost _appHost;
  86. /// <summary>
  87. /// Initializes a new instance of the <see cref="DashboardService" /> class.
  88. /// </summary>
  89. /// <param name="taskManager">The task manager.</param>
  90. /// <param name="userManager">The user manager.</param>
  91. public DashboardService(ITaskManager taskManager, IUserManager userManager, IServerApplicationHost appHost)
  92. {
  93. _taskManager = taskManager;
  94. _userManager = userManager;
  95. _appHost = appHost;
  96. }
  97. /// <summary>
  98. /// Gets the specified request.
  99. /// </summary>
  100. /// <param name="request">The request.</param>
  101. /// <returns>System.Object.</returns>
  102. public object Get(GetDashboardInfo request)
  103. {
  104. return GetDashboardInfo(_appHost, Logger, _taskManager, _userManager);
  105. }
  106. /// <summary>
  107. /// Gets the dashboard info.
  108. /// </summary>
  109. /// <param name="logger">The logger.</param>
  110. /// <param name="taskManager">The task manager.</param>
  111. /// <param name="userManager">The user manager.</param>
  112. /// <returns>DashboardInfo.</returns>
  113. public static DashboardInfo GetDashboardInfo(IServerApplicationHost appHost, ILogger logger, ITaskManager taskManager, IUserManager userManager)
  114. {
  115. var connections = userManager.ConnectedUsers.ToArray();
  116. var dtoBuilder = new DtoBuilder(logger);
  117. return new DashboardInfo
  118. {
  119. SystemInfo = appHost.GetSystemInfo(),
  120. RunningTasks = taskManager.ScheduledTasks.Where(i => i.State == TaskState.Running || i.State == TaskState.Cancelling)
  121. .Select(ScheduledTaskHelpers.GetTaskInfo)
  122. .ToArray(),
  123. ApplicationUpdateTaskId = taskManager.ScheduledTasks.First(t => t.ScheduledTask.GetType().Name.Equals("SystemUpdateTask", StringComparison.OrdinalIgnoreCase)).Id,
  124. ActiveConnections = connections,
  125. Users = userManager.Users.Where(u => connections.Any(c => c.UserId == u.Id)).Select(dtoBuilder.GetDtoUser).ToArray()
  126. };
  127. }
  128. /// <summary>
  129. /// Gets the specified request.
  130. /// </summary>
  131. /// <param name="request">The request.</param>
  132. /// <returns>System.Object.</returns>
  133. public object Get(GetDashboardConfigurationPage request)
  134. {
  135. var page = ServerEntryPoint.Instance.PluginConfigurationPages.First(p => p.Name.Equals(request.Name, StringComparison.OrdinalIgnoreCase));
  136. return ToStaticResult(page.Plugin.Version.ToString().GetMD5(), page.Plugin.AssemblyDateLastModified, null, MimeTypes.GetMimeType("page.html"), () => ModifyHtml(page.GetHtmlStream()));
  137. }
  138. /// <summary>
  139. /// Gets the specified request.
  140. /// </summary>
  141. /// <param name="request">The request.</param>
  142. /// <returns>System.Object.</returns>
  143. public object Get(GetDashboardConfigurationPages request)
  144. {
  145. var pages = ServerEntryPoint.Instance.PluginConfigurationPages;
  146. if (request.PageType.HasValue)
  147. {
  148. pages = pages.Where(p => p.ConfigurationPageType == request.PageType.Value);
  149. }
  150. return ToOptimizedResult(pages.ToList());
  151. }
  152. /// <summary>
  153. /// Gets the specified request.
  154. /// </summary>
  155. /// <param name="request">The request.</param>
  156. /// <returns>System.Object.</returns>
  157. public object Get(GetDashboardResource request)
  158. {
  159. var path = request.ResourceName;
  160. var contentType = MimeTypes.GetMimeType(path);
  161. TimeSpan? cacheDuration = null;
  162. // Cache images unconditionally - updates to image files will require new filename
  163. // If there's a version number in the query string we can cache this unconditionally
  164. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || !string.IsNullOrEmpty(request.V))
  165. {
  166. cacheDuration = TimeSpan.FromDays(365);
  167. }
  168. var assembly = GetType().Assembly.GetName();
  169. return ToStaticResult(assembly.Version.ToString().GetMD5(), null, cacheDuration, contentType, () => GetResourceStream(path));
  170. }
  171. /// <summary>
  172. /// Gets the resource stream.
  173. /// </summary>
  174. /// <param name="path">The path.</param>
  175. /// <returns>Task{Stream}.</returns>
  176. private async Task<Stream> GetResourceStream(string path)
  177. {
  178. Stream resourceStream;
  179. if (path.Equals("scripts/all.js", StringComparison.OrdinalIgnoreCase))
  180. {
  181. resourceStream = await GetAllJavascript().ConfigureAwait(false);
  182. }
  183. else
  184. {
  185. resourceStream = GetType().Assembly.GetManifestResourceStream("MediaBrowser.WebDashboard.Html." + ConvertUrlToResourcePath(path));
  186. }
  187. if (resourceStream != null)
  188. {
  189. var isHtml = IsHtml(path);
  190. // Don't apply any caching for html pages
  191. // jQuery ajax doesn't seem to handle if-modified-since correctly
  192. if (isHtml)
  193. {
  194. resourceStream = await ModifyHtml(resourceStream).ConfigureAwait(false);
  195. }
  196. }
  197. return resourceStream;
  198. }
  199. /// <summary>
  200. /// Redirects the specified CTX.
  201. /// </summary>
  202. /// <param name="ctx">The CTX.</param>
  203. /// <param name="url">The URL.</param>
  204. private void Redirect(HttpListenerContext ctx, string url)
  205. {
  206. // Try to prevent the browser from caching the redirect response (the right way)
  207. ctx.Response.Headers[HttpResponseHeader.CacheControl] = "no-cache, no-store, must-revalidate";
  208. ctx.Response.Headers[HttpResponseHeader.Pragma] = "no-cache, no-store, must-revalidate";
  209. ctx.Response.Headers[HttpResponseHeader.Expires] = "-1";
  210. ctx.Response.Redirect(url);
  211. ctx.Response.Close();
  212. }
  213. /// <summary>
  214. /// Preserves the current query string when redirecting
  215. /// </summary>
  216. /// <param name="request">The request.</param>
  217. /// <param name="newUrl">The new URL.</param>
  218. /// <returns>System.String.</returns>
  219. private string GetRedirectUrl(HttpListenerRequest request, string newUrl)
  220. {
  221. var query = request.Url.Query;
  222. return string.IsNullOrEmpty(query) ? newUrl : newUrl + query;
  223. }
  224. /// <summary>
  225. /// Converts the URL to a manifest resource path.
  226. /// </summary>
  227. /// <param name="url">The URL.</param>
  228. /// <returns>System.String.</returns>
  229. private string ConvertUrlToResourcePath(string url)
  230. {
  231. var parts = url.Split('/');
  232. var normalizedParts = new string[parts.Length];
  233. for (var i = 0; i < parts.Length; i++)
  234. {
  235. // We have to do some tricky string replacements for all parts of the path except the last
  236. if (i < parts.Length - 1)
  237. {
  238. // Find the index of the first period as well as the first dash
  239. var periodIndex = parts[i].IndexOf('.');
  240. var slashIndex = parts[i].IndexOf('-');
  241. // Replace all periods with "._" and dashes with "_"
  242. normalizedParts[i] = parts[i].Replace(".", "._").Replace("-", "_");
  243. // If the first period occurred before the first slash, change it back from "._" to just "."
  244. if (periodIndex < slashIndex)
  245. {
  246. var regex = new Regex("\\._");
  247. normalizedParts[i] = regex.Replace(normalizedParts[i], ".", 1);
  248. }
  249. }
  250. else
  251. {
  252. normalizedParts[i] = parts[i];
  253. }
  254. }
  255. return string.Join(".", normalizedParts);
  256. }
  257. /// <summary>
  258. /// Determines whether the specified path is HTML.
  259. /// </summary>
  260. /// <param name="path">The path.</param>
  261. /// <returns><c>true</c> if the specified path is HTML; otherwise, <c>false</c>.</returns>
  262. private bool IsHtml(string path)
  263. {
  264. return Path.GetExtension(path).EndsWith("html", StringComparison.OrdinalIgnoreCase);
  265. }
  266. /// <summary>
  267. /// Modifies the HTML by adding common meta tags, css and js.
  268. /// </summary>
  269. /// <param name="sourceStream">The source stream.</param>
  270. /// <returns>Task{Stream}.</returns>
  271. internal async Task<Stream> ModifyHtml(Stream sourceStream)
  272. {
  273. string html;
  274. using (var memoryStream = new MemoryStream())
  275. {
  276. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  277. html = Encoding.UTF8.GetString(memoryStream.ToArray());
  278. }
  279. var version = GetType().Assembly.GetName().Version;
  280. html = html.Replace("<head>", "<head>" + GetMetaTags() + GetCommonCss(version) + GetCommonJavascript(version));
  281. var bytes = Encoding.UTF8.GetBytes(html);
  282. sourceStream.Dispose();
  283. return new MemoryStream(bytes);
  284. }
  285. /// <summary>
  286. /// Gets the meta tags.
  287. /// </summary>
  288. /// <returns>System.String.</returns>
  289. private static string GetMetaTags()
  290. {
  291. var sb = new StringBuilder();
  292. sb.Append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">");
  293. sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  294. sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  295. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  296. sb.Append("<link rel=\"apple-touch-icon\" href=\"css/images/touchicon.png\" />");
  297. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"css/images/touchicon72.png\" />");
  298. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\" />");
  299. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\">");
  300. return sb.ToString();
  301. }
  302. /// <summary>
  303. /// Gets the common CSS.
  304. /// </summary>
  305. /// <param name="version">The version.</param>
  306. /// <returns>System.String.</returns>
  307. private static string GetCommonCss(Version version)
  308. {
  309. var versionString = "?v=" + version;
  310. var files = new[]
  311. {
  312. "http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.css",
  313. "thirdparty/jqm-icon-pack-3.0/font-awesome/jqm-icon-pack-3.0.0-fa.css",
  314. "css/site.css" + versionString
  315. };
  316. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" />", s)).ToArray();
  317. return string.Join(string.Empty, tags);
  318. }
  319. /// <summary>
  320. /// Gets the common javascript.
  321. /// </summary>
  322. /// <param name="version">The version.</param>
  323. /// <returns>System.String.</returns>
  324. private static string GetCommonJavascript(Version version)
  325. {
  326. var versionString = "?v=" + version;
  327. var files = new[]
  328. {
  329. "http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js",
  330. "http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js",
  331. "../jsapiclient.js" + versionString,
  332. "scripts/all.js" + versionString
  333. };
  334. var tags = files.Select(s => string.Format("<script src=\"{0}\"></script>", s)).ToArray();
  335. return string.Join(string.Empty, tags);
  336. }
  337. /// <summary>
  338. /// Gets a stream containing all concatenated javascript
  339. /// </summary>
  340. /// <returns>Task{Stream}.</returns>
  341. private async Task<Stream> GetAllJavascript()
  342. {
  343. const string resourcePrefix = "MediaBrowser.WebDashboard.Html.scripts.";
  344. var assembly = GetType().Assembly;
  345. var scriptFiles = new[]
  346. {
  347. "Extensions.js",
  348. "Site.js",
  349. "AddPluginPage.js",
  350. "AdvancedConfigurationPage.js",
  351. "AdvancedMetadataConfigurationPage.js",
  352. "PluginCatalogPage.js",
  353. "DashboardPage.js",
  354. "DisplaySettingsPage.js",
  355. "EditUserPage.js",
  356. "IndexPage.js",
  357. "ItemDetailPage.js",
  358. "ItemListPage.js",
  359. "LoginPage.js",
  360. "LogPage.js",
  361. "MediaLibraryPage.js",
  362. "MediaPlayer.js",
  363. "MetadataConfigurationPage.js",
  364. "MetadataImagesPage.js",
  365. "PluginsPage.js",
  366. "PluginUpdatesPage.js",
  367. "ScheduledTaskPage.js",
  368. "ScheduledTasksPage.js",
  369. "UpdatePasswordPage.js",
  370. "UserImagePage.js",
  371. "UserProfilesPage.js",
  372. "WizardFinishPage.js",
  373. "WizardStartPage.js",
  374. "WizardUserPage.js",
  375. "SupporterKeyPage.js",
  376. "SupporterPage.js"
  377. };
  378. var memoryStream = new MemoryStream();
  379. var newLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
  380. foreach (var file in scriptFiles)
  381. {
  382. using (var stream = assembly.GetManifestResourceStream(resourcePrefix + file))
  383. {
  384. await stream.CopyToAsync(memoryStream).ConfigureAwait(false);
  385. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  386. }
  387. }
  388. memoryStream.Position = 0;
  389. return memoryStream;
  390. }
  391. }
  392. }