DashboardService.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Common.ScheduledTasks;
  5. using MediaBrowser.Controller;
  6. using MediaBrowser.Controller.Configuration;
  7. using MediaBrowser.Controller.Dto;
  8. using MediaBrowser.Controller.Library;
  9. using MediaBrowser.Controller.Plugins;
  10. using MediaBrowser.Controller.Session;
  11. using MediaBrowser.Model.Logging;
  12. using MediaBrowser.Model.Tasks;
  13. using ServiceStack.ServiceHost;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Diagnostics;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Reflection;
  20. using System.Text;
  21. using System.Threading.Tasks;
  22. namespace MediaBrowser.WebDashboard.Api
  23. {
  24. /// <summary>
  25. /// Class GetDashboardConfigurationPages
  26. /// </summary>
  27. [Route("/dashboard/ConfigurationPages", "GET")]
  28. [Restrict(VisibilityTo = EndpointAttributes.None)]
  29. public class GetDashboardConfigurationPages : IReturn<List<ConfigurationPageInfo>>
  30. {
  31. /// <summary>
  32. /// Gets or sets the type of the page.
  33. /// </summary>
  34. /// <value>The type of the page.</value>
  35. public ConfigurationPageType? PageType { get; set; }
  36. }
  37. /// <summary>
  38. /// Class GetDashboardConfigurationPage
  39. /// </summary>
  40. [Route("/dashboard/ConfigurationPage", "GET")]
  41. [Restrict(VisibilityTo = EndpointAttributes.None)]
  42. public class GetDashboardConfigurationPage
  43. {
  44. /// <summary>
  45. /// Gets or sets the name.
  46. /// </summary>
  47. /// <value>The name.</value>
  48. public string Name { get; set; }
  49. }
  50. /// <summary>
  51. /// Class GetDashboardResource
  52. /// </summary>
  53. [Route("/dashboard/{ResourceName*}", "GET")]
  54. [Restrict(VisibilityTo = EndpointAttributes.None)]
  55. public class GetDashboardResource
  56. {
  57. /// <summary>
  58. /// Gets or sets the name.
  59. /// </summary>
  60. /// <value>The name.</value>
  61. public string ResourceName { get; set; }
  62. /// <summary>
  63. /// Gets or sets the V.
  64. /// </summary>
  65. /// <value>The V.</value>
  66. public string V { get; set; }
  67. }
  68. /// <summary>
  69. /// Class GetDashboardInfo
  70. /// </summary>
  71. [Route("/dashboard/dashboardInfo", "GET")]
  72. [Restrict(VisibilityTo = EndpointAttributes.None)]
  73. public class GetDashboardInfo : IReturn<DashboardInfo>
  74. {
  75. }
  76. /// <summary>
  77. /// Class DashboardService
  78. /// </summary>
  79. public class DashboardService : IRestfulService, IHasResultFactory
  80. {
  81. /// <summary>
  82. /// Gets or sets the logger.
  83. /// </summary>
  84. /// <value>The logger.</value>
  85. public ILogger Logger { get; set; }
  86. /// <summary>
  87. /// Gets or sets the HTTP result factory.
  88. /// </summary>
  89. /// <value>The HTTP result factory.</value>
  90. public IHttpResultFactory ResultFactory { get; set; }
  91. /// <summary>
  92. /// Gets or sets the request context.
  93. /// </summary>
  94. /// <value>The request context.</value>
  95. public IRequestContext RequestContext { get; set; }
  96. /// <summary>
  97. /// Gets or sets the task manager.
  98. /// </summary>
  99. /// <value>The task manager.</value>
  100. private readonly ITaskManager _taskManager;
  101. /// <summary>
  102. /// The _app host
  103. /// </summary>
  104. private readonly IServerApplicationHost _appHost;
  105. /// <summary>
  106. /// The _server configuration manager
  107. /// </summary>
  108. private readonly IServerConfigurationManager _serverConfigurationManager;
  109. private readonly ISessionManager _sessionManager;
  110. /// <summary>
  111. /// Initializes a new instance of the <see cref="DashboardService" /> class.
  112. /// </summary>
  113. /// <param name="taskManager">The task manager.</param>
  114. /// <param name="appHost">The app host.</param>
  115. /// <param name="serverConfigurationManager">The server configuration manager.</param>
  116. /// <param name="sessionManager">The session manager.</param>
  117. public DashboardService(ITaskManager taskManager, IServerApplicationHost appHost, IServerConfigurationManager serverConfigurationManager, ISessionManager sessionManager)
  118. {
  119. _taskManager = taskManager;
  120. _appHost = appHost;
  121. _serverConfigurationManager = serverConfigurationManager;
  122. _sessionManager = sessionManager;
  123. }
  124. /// <summary>
  125. /// Gets the dashboard UI path.
  126. /// </summary>
  127. /// <value>The dashboard UI path.</value>
  128. public string DashboardUIPath
  129. {
  130. get
  131. {
  132. if (!string.IsNullOrEmpty(_serverConfigurationManager.Configuration.DashboardSourcePath))
  133. {
  134. return _serverConfigurationManager.Configuration.DashboardSourcePath;
  135. }
  136. var runningDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
  137. return Path.Combine(runningDirectory, "dashboard-ui");
  138. }
  139. }
  140. /// <summary>
  141. /// Gets the dashboard resource path.
  142. /// </summary>
  143. /// <param name="virtualPath">The virtual path.</param>
  144. /// <returns>System.String.</returns>
  145. private string GetDashboardResourcePath(string virtualPath)
  146. {
  147. return Path.Combine(DashboardUIPath, virtualPath.Replace('/', '\\'));
  148. }
  149. /// <summary>
  150. /// Gets the specified request.
  151. /// </summary>
  152. /// <param name="request">The request.</param>
  153. /// <returns>System.Object.</returns>
  154. public object Get(GetDashboardInfo request)
  155. {
  156. var result = GetDashboardInfo(_appHost, _taskManager, _sessionManager);
  157. return ResultFactory.GetOptimizedResult(RequestContext, result);
  158. }
  159. /// <summary>
  160. /// Gets the dashboard info.
  161. /// </summary>
  162. /// <param name="appHost">The app host.</param>
  163. /// <param name="taskManager">The task manager.</param>
  164. /// <param name="connectionManager">The connection manager.</param>
  165. /// <returns>DashboardInfo.</returns>
  166. public static DashboardInfo GetDashboardInfo(IServerApplicationHost appHost,
  167. ITaskManager taskManager,
  168. ISessionManager connectionManager)
  169. {
  170. var connections = connectionManager.Sessions.Where(i => i.IsActive).ToArray();
  171. return new DashboardInfo
  172. {
  173. SystemInfo = appHost.GetSystemInfo(),
  174. RunningTasks = taskManager.ScheduledTasks.Where(i => i.State == TaskState.Running || i.State == TaskState.Cancelling)
  175. .Select(ScheduledTaskHelpers.GetTaskInfo)
  176. .ToArray(),
  177. ApplicationUpdateTaskId = taskManager.ScheduledTasks.First(t => t.ScheduledTask.GetType().Name.Equals("SystemUpdateTask", StringComparison.OrdinalIgnoreCase)).Id,
  178. ActiveConnections = connections.Select(SessionInfoDtoBuilder.GetSessionInfoDto).ToArray()
  179. };
  180. }
  181. /// <summary>
  182. /// Gets the specified request.
  183. /// </summary>
  184. /// <param name="request">The request.</param>
  185. /// <returns>System.Object.</returns>
  186. public object Get(GetDashboardConfigurationPage request)
  187. {
  188. var page = ServerEntryPoint.Instance.PluginConfigurationPages.First(p => p.Name.Equals(request.Name, StringComparison.OrdinalIgnoreCase));
  189. return ResultFactory.GetStaticResult(RequestContext, page.Plugin.Version.ToString().GetMD5(), page.Plugin.AssemblyDateLastModified, null, MimeTypes.GetMimeType("page.html"), () => ModifyHtml(page.GetHtmlStream()));
  190. }
  191. /// <summary>
  192. /// Gets the specified request.
  193. /// </summary>
  194. /// <param name="request">The request.</param>
  195. /// <returns>System.Object.</returns>
  196. public object Get(GetDashboardConfigurationPages request)
  197. {
  198. var pages = ServerEntryPoint.Instance.PluginConfigurationPages;
  199. if (request.PageType.HasValue)
  200. {
  201. pages = pages.Where(p => p.ConfigurationPageType == request.PageType.Value);
  202. }
  203. return ResultFactory.GetOptimizedResult(RequestContext, pages.Select(p => new ConfigurationPageInfo(p)).ToList());
  204. }
  205. /// <summary>
  206. /// Gets the specified request.
  207. /// </summary>
  208. /// <param name="request">The request.</param>
  209. /// <returns>System.Object.</returns>
  210. public object Get(GetDashboardResource request)
  211. {
  212. var path = request.ResourceName;
  213. var contentType = MimeTypes.GetMimeType(path);
  214. // Don't cache if not configured to do so
  215. // But always cache images to simulate production
  216. if (!_serverConfigurationManager.Configuration.EnableDashboardResponseCaching && !contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase))
  217. {
  218. return ResultFactory.GetResult(GetResourceStream(path).Result, contentType);
  219. }
  220. TimeSpan? cacheDuration = null;
  221. // Cache images unconditionally - updates to image files will require new filename
  222. // If there's a version number in the query string we can cache this unconditionally
  223. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || !string.IsNullOrEmpty(request.V))
  224. {
  225. cacheDuration = TimeSpan.FromDays(365);
  226. }
  227. var assembly = GetType().Assembly.GetName();
  228. var cacheKey = (assembly.Version + path).GetMD5();
  229. return ResultFactory.GetStaticResult(RequestContext, cacheKey, null, cacheDuration, contentType, () => GetResourceStream(path));
  230. }
  231. /// <summary>
  232. /// Gets the resource stream.
  233. /// </summary>
  234. /// <param name="path">The path.</param>
  235. /// <returns>Task{Stream}.</returns>
  236. private async Task<Stream> GetResourceStream(string path)
  237. {
  238. Stream resourceStream;
  239. if (path.Equals("scripts/all.js", StringComparison.OrdinalIgnoreCase))
  240. {
  241. resourceStream = await GetAllJavascript().ConfigureAwait(false);
  242. }
  243. else if (path.Equals("css/all.css", StringComparison.OrdinalIgnoreCase))
  244. {
  245. resourceStream = await GetAllCss().ConfigureAwait(false);
  246. }
  247. else
  248. {
  249. resourceStream = GetRawResourceStream(path);
  250. }
  251. if (resourceStream != null)
  252. {
  253. var isHtml = IsHtml(path);
  254. // Don't apply any caching for html pages
  255. // jQuery ajax doesn't seem to handle if-modified-since correctly
  256. if (isHtml)
  257. {
  258. resourceStream = await ModifyHtml(resourceStream).ConfigureAwait(false);
  259. }
  260. }
  261. return resourceStream;
  262. }
  263. /// <summary>
  264. /// Gets the raw resource stream.
  265. /// </summary>
  266. /// <param name="path">The path.</param>
  267. /// <returns>Task{Stream}.</returns>
  268. private Stream GetRawResourceStream(string path)
  269. {
  270. return new FileStream(GetDashboardResourcePath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, StreamDefaults.DefaultFileStreamBufferSize, true);
  271. }
  272. /// <summary>
  273. /// Determines whether the specified path is HTML.
  274. /// </summary>
  275. /// <param name="path">The path.</param>
  276. /// <returns><c>true</c> if the specified path is HTML; otherwise, <c>false</c>.</returns>
  277. private bool IsHtml(string path)
  278. {
  279. return Path.GetExtension(path).EndsWith("html", StringComparison.OrdinalIgnoreCase);
  280. }
  281. /// <summary>
  282. /// Modifies the HTML by adding common meta tags, css and js.
  283. /// </summary>
  284. /// <param name="sourceStream">The source stream.</param>
  285. /// <returns>Task{Stream}.</returns>
  286. internal async Task<Stream> ModifyHtml(Stream sourceStream)
  287. {
  288. string html;
  289. using (var memoryStream = new MemoryStream())
  290. {
  291. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  292. html = Encoding.UTF8.GetString(memoryStream.ToArray());
  293. }
  294. var version = GetType().Assembly.GetName().Version;
  295. html = html.Replace("<head>", "<head>" + GetMetaTags() + GetCommonCss(version) + GetCommonJavascript(version));
  296. var bytes = Encoding.UTF8.GetBytes(html);
  297. sourceStream.Dispose();
  298. return new MemoryStream(bytes);
  299. }
  300. /// <summary>
  301. /// Gets the meta tags.
  302. /// </summary>
  303. /// <returns>System.String.</returns>
  304. private static string GetMetaTags()
  305. {
  306. var sb = new StringBuilder();
  307. sb.Append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">");
  308. sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  309. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  310. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  311. sb.Append("<link rel=\"apple-touch-icon\" href=\"css/images/touchicon.png\" />");
  312. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"css/images/touchicon72.png\" />");
  313. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\" />");
  314. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\" />");
  315. sb.Append("<link rel=\"shortcut icon\" href=\"favicon.ico\" />");
  316. return sb.ToString();
  317. }
  318. /// <summary>
  319. /// Gets the common CSS.
  320. /// </summary>
  321. /// <param name="version">The version.</param>
  322. /// <returns>System.String.</returns>
  323. private static string GetCommonCss(Version version)
  324. {
  325. var versionString = "?v=" + version;
  326. var files = new[]
  327. {
  328. "http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css",
  329. "thirdparty/jqm-icon-pack-3.0/font-awesome/jqm-icon-pack-3.0.0-fa.css" + versionString,
  330. "css/all.css" + versionString
  331. };
  332. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" />", s)).ToArray();
  333. return string.Join(string.Empty, tags);
  334. }
  335. /// <summary>
  336. /// Gets the common javascript.
  337. /// </summary>
  338. /// <param name="version">The version.</param>
  339. /// <returns>System.String.</returns>
  340. private static string GetCommonJavascript(Version version)
  341. {
  342. var versionString = "?v=" + version;
  343. var files = new[]
  344. {
  345. "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js",
  346. "http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js",
  347. "scripts/all.js" + versionString
  348. };
  349. var tags = files.Select(s => string.Format("<script src=\"{0}\"></script>", s)).ToArray();
  350. return string.Join(string.Empty, tags);
  351. }
  352. /// <summary>
  353. /// Gets a stream containing all concatenated javascript
  354. /// </summary>
  355. /// <returns>Task{Stream}.</returns>
  356. private async Task<Stream> GetAllJavascript()
  357. {
  358. var assembly = GetType().Assembly;
  359. var scriptFiles = new[]
  360. {
  361. "extensions.js",
  362. "site.js",
  363. "librarybrowser.js",
  364. "aboutpage.js",
  365. "alphapicker.js",
  366. "addpluginpage.js",
  367. "advancedconfigurationpage.js",
  368. "advancedmetadataconfigurationpage.js",
  369. "boxsets.js",
  370. "clientsettings.js",
  371. "dashboardpage.js",
  372. "edititemmetadata.js",
  373. "edititempeople.js",
  374. "edititemimages.js",
  375. "edituserpage.js",
  376. "gamesrecommendedpage.js",
  377. "gamesystemspage.js",
  378. "gamespage.js",
  379. "gamegenrepage.js",
  380. "gamestudiospage.js",
  381. "indexpage.js",
  382. "itembynamedetailpage.js",
  383. "itemdetailpage.js",
  384. "itemgallery.js",
  385. "itemlistpage.js",
  386. "librarysettings.js",
  387. "loginpage.js",
  388. "logpage.js",
  389. "medialibrarypage.js",
  390. "mediaplayer.js",
  391. "metadataconfigurationpage.js",
  392. "metadataimagespage.js",
  393. "moviegenres.js",
  394. "movies.js",
  395. "moviepeople.js",
  396. "moviesrecommended.js",
  397. "moviestudios.js",
  398. "movietrailers.js",
  399. "musicalbums.js",
  400. "musicartists.js",
  401. "musicgenres.js",
  402. "musicrecommended.js",
  403. "musicvideos.js",
  404. "playlist.js",
  405. "plugincatalogpage.js",
  406. "pluginspage.js",
  407. "pluginupdatespage.js",
  408. "remotecontrol.js",
  409. "scheduledtaskpage.js",
  410. "scheduledtaskspage.js",
  411. "search.js",
  412. "songs.js",
  413. "supporterkeypage.js",
  414. "supporterpage.js",
  415. "tvgenres.js",
  416. "tvnextup.js",
  417. "tvpeople.js",
  418. "tvrecommended.js",
  419. "tvshows.js",
  420. "tvstudios.js",
  421. "updatepasswordpage.js",
  422. "userimagepage.js",
  423. "userprofilespage.js",
  424. "wizardfinishpage.js",
  425. "wizardstartpage.js",
  426. "wizarduserpage.js"
  427. };
  428. var memoryStream = new MemoryStream();
  429. var newLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
  430. await AppendResource(memoryStream, "thirdparty/autoNumeric.js", newLineBytes).ConfigureAwait(false);
  431. await AppendResource(memoryStream, "thirdparty/html5slider.js", newLineBytes).ConfigureAwait(false);
  432. await AppendResource(assembly, memoryStream, "MediaBrowser.WebDashboard.ApiClient.js", newLineBytes).ConfigureAwait(false);
  433. foreach (var file in scriptFiles)
  434. {
  435. await AppendResource(memoryStream, "scripts/" + file, newLineBytes).ConfigureAwait(false);
  436. }
  437. memoryStream.Position = 0;
  438. return memoryStream;
  439. }
  440. /// <summary>
  441. /// Gets all CSS.
  442. /// </summary>
  443. /// <returns>Task{Stream}.</returns>
  444. private async Task<Stream> GetAllCss()
  445. {
  446. var files = new[]
  447. {
  448. "site.css",
  449. "librarybrowser.css",
  450. "detailtable.css",
  451. "posteritem.css",
  452. "tileitem.css",
  453. "search.css",
  454. "pluginupdates.css",
  455. "remotecontrol.css",
  456. "userimage.css"
  457. };
  458. var memoryStream = new MemoryStream();
  459. var newLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
  460. foreach (var file in files)
  461. {
  462. await AppendResource(memoryStream, "css/" + file, newLineBytes).ConfigureAwait(false);
  463. }
  464. memoryStream.Position = 0;
  465. return memoryStream;
  466. }
  467. /// <summary>
  468. /// Appends the resource.
  469. /// </summary>
  470. /// <param name="assembly">The assembly.</param>
  471. /// <param name="outputStream">The output stream.</param>
  472. /// <param name="path">The path.</param>
  473. /// <param name="newLineBytes">The new line bytes.</param>
  474. /// <returns>Task.</returns>
  475. private async Task AppendResource(Assembly assembly, Stream outputStream, string path, byte[] newLineBytes)
  476. {
  477. using (var stream = assembly.GetManifestResourceStream(path))
  478. {
  479. await stream.CopyToAsync(outputStream).ConfigureAwait(false);
  480. await outputStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  481. }
  482. }
  483. /// <summary>
  484. /// Appends the resource.
  485. /// </summary>
  486. /// <param name="outputStream">The output stream.</param>
  487. /// <param name="path">The path.</param>
  488. /// <param name="newLineBytes">The new line bytes.</param>
  489. /// <returns>Task.</returns>
  490. private async Task AppendResource(Stream outputStream, string path, byte[] newLineBytes)
  491. {
  492. path = GetDashboardResourcePath(path);
  493. using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, StreamDefaults.DefaultFileStreamBufferSize, true))
  494. {
  495. using (var streamReader = new StreamReader(fs))
  496. {
  497. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  498. var bytes = Encoding.UTF8.GetBytes(text);
  499. await outputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  500. }
  501. }
  502. await outputStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  503. }
  504. }
  505. }