DashboardService.cs 18 KB

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