DashboardService.cs 17 KB

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