DashboardService.cs 24 KB

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