DashboardService.cs 17 KB

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