DashboardService.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Net;
  7. using MediaBrowser.Controller.Plugins;
  8. using MediaBrowser.Model.Logging;
  9. using ServiceStack;
  10. using ServiceStack.Web;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Reflection;
  16. using System.Text;
  17. using System.Threading.Tasks;
  18. namespace MediaBrowser.WebDashboard.Api
  19. {
  20. /// <summary>
  21. /// Class GetDashboardConfigurationPages
  22. /// </summary>
  23. [Route("/dashboard/ConfigurationPages", "GET")]
  24. public class GetDashboardConfigurationPages : IReturn<List<ConfigurationPageInfo>>
  25. {
  26. /// <summary>
  27. /// Gets or sets the type of the page.
  28. /// </summary>
  29. /// <value>The type of the page.</value>
  30. public ConfigurationPageType? PageType { get; set; }
  31. }
  32. /// <summary>
  33. /// Class GetDashboardConfigurationPage
  34. /// </summary>
  35. [Route("/dashboard/ConfigurationPage", "GET")]
  36. public class GetDashboardConfigurationPage
  37. {
  38. /// <summary>
  39. /// Gets or sets the name.
  40. /// </summary>
  41. /// <value>The name.</value>
  42. public string Name { get; set; }
  43. }
  44. /// <summary>
  45. /// Class GetDashboardResource
  46. /// </summary>
  47. [Route("/dashboard/{ResourceName*}", "GET")]
  48. public class GetDashboardResource
  49. {
  50. /// <summary>
  51. /// Gets or sets the name.
  52. /// </summary>
  53. /// <value>The name.</value>
  54. public string ResourceName { get; set; }
  55. /// <summary>
  56. /// Gets or sets the V.
  57. /// </summary>
  58. /// <value>The V.</value>
  59. public string V { get; set; }
  60. }
  61. /// <summary>
  62. /// Class DashboardService
  63. /// </summary>
  64. public class DashboardService : IRestfulService, IHasResultFactory
  65. {
  66. /// <summary>
  67. /// Gets or sets the logger.
  68. /// </summary>
  69. /// <value>The logger.</value>
  70. public ILogger Logger { get; set; }
  71. /// <summary>
  72. /// Gets or sets the HTTP result factory.
  73. /// </summary>
  74. /// <value>The HTTP result factory.</value>
  75. public IHttpResultFactory ResultFactory { get; set; }
  76. /// <summary>
  77. /// Gets or sets the request context.
  78. /// </summary>
  79. /// <value>The request context.</value>
  80. public IRequest Request { get; set; }
  81. /// <summary>
  82. /// The _app host
  83. /// </summary>
  84. private readonly IServerApplicationHost _appHost;
  85. /// <summary>
  86. /// The _server configuration manager
  87. /// </summary>
  88. private readonly IServerConfigurationManager _serverConfigurationManager;
  89. private readonly IFileSystem _fileSystem;
  90. /// <summary>
  91. /// Initializes a new instance of the <see cref="DashboardService" /> class.
  92. /// </summary>
  93. /// <param name="appHost">The app host.</param>
  94. /// <param name="serverConfigurationManager">The server configuration manager.</param>
  95. /// <param name="fileSystem">The file system.</param>
  96. public DashboardService(IServerApplicationHost appHost, IServerConfigurationManager serverConfigurationManager, IFileSystem fileSystem)
  97. {
  98. _appHost = appHost;
  99. _serverConfigurationManager = serverConfigurationManager;
  100. _fileSystem = fileSystem;
  101. }
  102. /// <summary>
  103. /// Gets the dashboard UI path.
  104. /// </summary>
  105. /// <value>The dashboard UI path.</value>
  106. public string DashboardUIPath
  107. {
  108. get
  109. {
  110. if (!string.IsNullOrEmpty(_serverConfigurationManager.Configuration.DashboardSourcePath))
  111. {
  112. return _serverConfigurationManager.Configuration.DashboardSourcePath;
  113. }
  114. var runningDirectory = Path.GetDirectoryName(_serverConfigurationManager.ApplicationPaths.ApplicationPath);
  115. return Path.Combine(runningDirectory, "dashboard-ui");
  116. }
  117. }
  118. /// <summary>
  119. /// Gets the dashboard resource path.
  120. /// </summary>
  121. /// <param name="virtualPath">The virtual path.</param>
  122. /// <returns>System.String.</returns>
  123. private string GetDashboardResourcePath(string virtualPath)
  124. {
  125. return Path.Combine(DashboardUIPath, virtualPath.Replace('/', Path.DirectorySeparatorChar));
  126. }
  127. /// <summary>
  128. /// Gets the specified request.
  129. /// </summary>
  130. /// <param name="request">The request.</param>
  131. /// <returns>System.Object.</returns>
  132. public object Get(GetDashboardConfigurationPage request)
  133. {
  134. var page = ServerEntryPoint.Instance.PluginConfigurationPages.First(p => p.Name.Equals(request.Name, StringComparison.OrdinalIgnoreCase));
  135. return ResultFactory.GetStaticResult(Request, page.Plugin.Version.ToString().GetMD5(), page.Plugin.AssemblyDateLastModified, null, MimeTypes.GetMimeType("page.html"), () => ModifyHtml(page.GetHtmlStream()));
  136. }
  137. /// <summary>
  138. /// Gets the specified request.
  139. /// </summary>
  140. /// <param name="request">The request.</param>
  141. /// <returns>System.Object.</returns>
  142. public object Get(GetDashboardConfigurationPages request)
  143. {
  144. const string unavilableMessage = "The server is still loading. Please try again momentarily.";
  145. var instance = ServerEntryPoint.Instance;
  146. if (instance == null)
  147. {
  148. throw new InvalidOperationException(unavilableMessage);
  149. }
  150. var pages = instance.PluginConfigurationPages;
  151. if (pages == null)
  152. {
  153. throw new InvalidOperationException(unavilableMessage);
  154. }
  155. if (request.PageType.HasValue)
  156. {
  157. pages = pages.Where(p => p.ConfigurationPageType == request.PageType.Value);
  158. }
  159. // Don't allow a failing plugin to fail them all
  160. var configPages = pages.Select(p =>
  161. {
  162. try
  163. {
  164. return new ConfigurationPageInfo(p);
  165. }
  166. catch (Exception ex)
  167. {
  168. Logger.ErrorException("Error getting plugin information from {0}", ex, p.GetType().Name);
  169. return null;
  170. }
  171. })
  172. .Where(i => i != null)
  173. .ToList();
  174. return ResultFactory.GetOptimizedResult(Request, configPages);
  175. }
  176. /// <summary>
  177. /// Gets the specified request.
  178. /// </summary>
  179. /// <param name="request">The request.</param>
  180. /// <returns>System.Object.</returns>
  181. public object Get(GetDashboardResource request)
  182. {
  183. var path = request.ResourceName;
  184. var contentType = MimeTypes.GetMimeType(path);
  185. // Don't cache if not configured to do so
  186. // But always cache images to simulate production
  187. if (!_serverConfigurationManager.Configuration.EnableDashboardResponseCaching &&
  188. !contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) &&
  189. !contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  190. {
  191. return ResultFactory.GetResult(GetResourceStream(path).Result, contentType);
  192. }
  193. TimeSpan? cacheDuration = null;
  194. // Cache images unconditionally - updates to image files will require new filename
  195. // If there's a version number in the query string we can cache this unconditionally
  196. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase) || !string.IsNullOrEmpty(request.V))
  197. {
  198. cacheDuration = TimeSpan.FromDays(365);
  199. }
  200. var assembly = GetType().Assembly.GetName();
  201. var cacheKey = (assembly.Version + path).GetMD5();
  202. return ResultFactory.GetStaticResult(Request, cacheKey, null, cacheDuration, contentType, () => GetResourceStream(path));
  203. }
  204. /// <summary>
  205. /// Gets the resource stream.
  206. /// </summary>
  207. /// <param name="path">The path.</param>
  208. /// <returns>Task{Stream}.</returns>
  209. private async Task<Stream> GetResourceStream(string path)
  210. {
  211. Stream resourceStream;
  212. if (path.Equals("scripts/all.js", StringComparison.OrdinalIgnoreCase))
  213. {
  214. resourceStream = await GetAllJavascript().ConfigureAwait(false);
  215. }
  216. else if (path.Equals("css/all.css", StringComparison.OrdinalIgnoreCase))
  217. {
  218. resourceStream = await GetAllCss().ConfigureAwait(false);
  219. }
  220. else
  221. {
  222. resourceStream = GetRawResourceStream(path);
  223. }
  224. if (resourceStream != null)
  225. {
  226. var isHtml = IsHtml(path);
  227. // Don't apply any caching for html pages
  228. // jQuery ajax doesn't seem to handle if-modified-since correctly
  229. if (isHtml)
  230. {
  231. resourceStream = await ModifyHtml(resourceStream).ConfigureAwait(false);
  232. }
  233. }
  234. return resourceStream;
  235. }
  236. /// <summary>
  237. /// Gets the raw resource stream.
  238. /// </summary>
  239. /// <param name="path">The path.</param>
  240. /// <returns>Task{Stream}.</returns>
  241. private Stream GetRawResourceStream(string path)
  242. {
  243. return _fileSystem.GetFileStream(GetDashboardResourcePath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  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 http-equiv=\"X-UA-Compatibility\" content=\"IE=Edge\">");
  281. sb.Append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">");
  282. sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  283. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  284. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  285. sb.Append("<link rel=\"apple-touch-icon\" href=\"css/images/touchicon.png\" />");
  286. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"css/images/touchicon72.png\" />");
  287. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\" />");
  288. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\" />");
  289. sb.Append("<link rel=\"shortcut icon\" href=\"favicon.ico\" />");
  290. return sb.ToString();
  291. }
  292. /// <summary>
  293. /// Gets the common CSS.
  294. /// </summary>
  295. /// <param name="version">The version.</param>
  296. /// <returns>System.String.</returns>
  297. private static string GetCommonCss(Version version)
  298. {
  299. var versionString = "?v=" + version;
  300. var files = new[]
  301. {
  302. "thirdparty/jquerymobile-1.4.2/jquery.mobile-1.4.2.min.css",
  303. "css/all.css" + versionString
  304. };
  305. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" />", s)).ToArray();
  306. return string.Join(string.Empty, tags);
  307. }
  308. /// <summary>
  309. /// Gets the common javascript.
  310. /// </summary>
  311. /// <param name="version">The version.</param>
  312. /// <returns>System.String.</returns>
  313. private static string GetCommonJavascript(Version version)
  314. {
  315. var builder = new StringBuilder();
  316. var versionString = "?v=" + version;
  317. var files = new[]
  318. {
  319. "scripts/all.js" + versionString,
  320. "thirdparty/jstree1.0/jquery.jstree.min.js",
  321. "https://www.gstatic.com/cv/js/sender/v1/cast_sender.js"
  322. };
  323. var tags = files.Select(s => string.Format("<script src=\"{0}\"></script>", s)).ToArray();
  324. builder.Append(string.Join(string.Empty, tags));
  325. return builder.ToString();
  326. }
  327. /// <summary>
  328. /// Gets a stream containing all concatenated javascript
  329. /// </summary>
  330. /// <returns>Task{Stream}.</returns>
  331. private async Task<Stream> GetAllJavascript()
  332. {
  333. var scriptFiles = new[]
  334. {
  335. "extensions.js",
  336. "site.js",
  337. "librarybrowser.js",
  338. "librarylist.js",
  339. "editorsidebar.js",
  340. "librarymenu.js",
  341. "chromecast.js",
  342. "contextmenu.js",
  343. "mediacontroller.js",
  344. "mediaplayer.js",
  345. "mediaplayer-video.js",
  346. "ratingdialog.js",
  347. "aboutpage.js",
  348. "allusersettings.js",
  349. "alphapicker.js",
  350. "addpluginpage.js",
  351. "advancedconfigurationpage.js",
  352. "advancedpaths.js",
  353. "advancedserversettings.js",
  354. "metadataadvanced.js",
  355. "appsplayback.js",
  356. "appsweather.js",
  357. "autoorganizetv.js",
  358. "autoorganizelog.js",
  359. "channels.js",
  360. "channelitems.js",
  361. "dashboardinfo.js",
  362. "dashboardpage.js",
  363. "directorybrowser.js",
  364. "dlnaprofile.js",
  365. "dlnaprofiles.js",
  366. "dlnasettings.js",
  367. "editcollectionitems.js",
  368. "edititemmetadata.js",
  369. "edititempeople.js",
  370. "edititemimages.js",
  371. "encodingsettings.js",
  372. "gamesrecommendedpage.js",
  373. "gamesystemspage.js",
  374. "gamespage.js",
  375. "gamegenrepage.js",
  376. "gamestudiospage.js",
  377. "indexpage.js",
  378. "itembynamedetailpage.js",
  379. "itemdetailpage.js",
  380. "itemgallery.js",
  381. "itemlistpage.js",
  382. "librarypathmapping.js",
  383. "libraryreport.js",
  384. "librarysettings.js",
  385. "livetvchannel.js",
  386. "livetvchannels.js",
  387. "livetvguide.js",
  388. "livetvnewrecording.js",
  389. "livetvprogram.js",
  390. "livetvrecording.js",
  391. "livetvrecordinglist.js",
  392. "livetvrecordings.js",
  393. "livetvtimer.js",
  394. "livetvseriestimer.js",
  395. "livetvseriestimers.js",
  396. "livetvsettings.js",
  397. "livetvsuggested.js",
  398. "livetvstatus.js",
  399. "livetvtimers.js",
  400. "loginpage.js",
  401. "logpage.js",
  402. "medialibrarypage.js",
  403. "metadataconfigurationpage.js",
  404. "metadataimagespage.js",
  405. "moviegenres.js",
  406. "moviecollections.js",
  407. "movies.js",
  408. "movieslatest.js",
  409. "moviepeople.js",
  410. "moviesrecommended.js",
  411. "moviestudios.js",
  412. "movietrailers.js",
  413. "musicalbums.js",
  414. "musicalbumartists.js",
  415. "musicartists.js",
  416. "musicgenres.js",
  417. "musicrecommended.js",
  418. "musicvideos.js",
  419. "notifications.js",
  420. "playlist.js",
  421. "plugincatalogpage.js",
  422. "pluginspage.js",
  423. "pluginupdatespage.js",
  424. "remotecontrol.js",
  425. "scheduledtaskpage.js",
  426. "scheduledtaskspage.js",
  427. "search.js",
  428. "songs.js",
  429. "supporterkeypage.js",
  430. "supporterpage.js",
  431. "episodes.js",
  432. "tvgenres.js",
  433. "tvlatest.js",
  434. "tvpeople.js",
  435. "tvrecommended.js",
  436. "tvshows.js",
  437. "tvstudios.js",
  438. "tvupcoming.js",
  439. "useredit.js",
  440. "userpassword.js",
  441. "userimagepage.js",
  442. "userprofilespage.js",
  443. "usersettings.js",
  444. "userparentalcontrol.js",
  445. "wizardfinishpage.js",
  446. "wizardimagesettings.js",
  447. "wizardservice.js",
  448. "wizardstartpage.js",
  449. "wizardsettings.js",
  450. "wizarduserpage.js"
  451. };
  452. var memoryStream = new MemoryStream();
  453. var newLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
  454. await AppendResource(memoryStream, "thirdparty/jquery-2.0.3.min.js", newLineBytes).ConfigureAwait(false);
  455. await AppendResource(memoryStream, "thirdparty/jquerymobile-1.4.2/jquery.mobile-1.4.2.min.js", newLineBytes).ConfigureAwait(false);
  456. var versionString = string.Format("window.dashboardVersion='{0}';", _appHost.ApplicationVersion);
  457. var versionBytes = Encoding.UTF8.GetBytes(versionString);
  458. await memoryStream.WriteAsync(versionBytes, 0, versionBytes.Length).ConfigureAwait(false);
  459. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  460. await AppendResource(memoryStream, "thirdparty/autonumeric/autoNumeric.min.js", newLineBytes).ConfigureAwait(false);
  461. var assembly = GetType().Assembly;
  462. await AppendResource(assembly, memoryStream, "MediaBrowser.WebDashboard.ApiClient.js", newLineBytes).ConfigureAwait(false);
  463. foreach (var file in scriptFiles)
  464. {
  465. await AppendResource(memoryStream, "scripts/" + file, newLineBytes).ConfigureAwait(false);
  466. }
  467. memoryStream.Position = 0;
  468. return memoryStream;
  469. }
  470. /// <summary>
  471. /// Gets all CSS.
  472. /// </summary>
  473. /// <returns>Task{Stream}.</returns>
  474. private async Task<Stream> GetAllCss()
  475. {
  476. var files = new[]
  477. {
  478. "site.css",
  479. "chromecast.css",
  480. "contextmenu.css",
  481. "mediaplayer.css",
  482. "mediaplayer-video.css",
  483. "librarybrowser.css",
  484. "detailtable.css",
  485. "posteritem.css",
  486. "tileitem.css",
  487. "metadataeditor.css",
  488. "notifications.css",
  489. "search.css",
  490. "pluginupdates.css",
  491. "remotecontrol.css",
  492. "userimage.css",
  493. "livetv.css",
  494. "icons.css"
  495. };
  496. var memoryStream = new MemoryStream();
  497. var newLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
  498. foreach (var file in files)
  499. {
  500. await AppendResource(memoryStream, "css/" + file, newLineBytes).ConfigureAwait(false);
  501. }
  502. memoryStream.Position = 0;
  503. return memoryStream;
  504. }
  505. /// <summary>
  506. /// Appends the resource.
  507. /// </summary>
  508. /// <param name="assembly">The assembly.</param>
  509. /// <param name="outputStream">The output stream.</param>
  510. /// <param name="path">The path.</param>
  511. /// <param name="newLineBytes">The new line bytes.</param>
  512. /// <returns>Task.</returns>
  513. private async Task AppendResource(Assembly assembly, Stream outputStream, string path, byte[] newLineBytes)
  514. {
  515. using (var stream = assembly.GetManifestResourceStream(path))
  516. {
  517. await stream.CopyToAsync(outputStream).ConfigureAwait(false);
  518. await outputStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  519. }
  520. }
  521. /// <summary>
  522. /// Appends the resource.
  523. /// </summary>
  524. /// <param name="outputStream">The output stream.</param>
  525. /// <param name="path">The path.</param>
  526. /// <param name="newLineBytes">The new line bytes.</param>
  527. /// <returns>Task.</returns>
  528. private async Task AppendResource(Stream outputStream, string path, byte[] newLineBytes)
  529. {
  530. path = GetDashboardResourcePath(path);
  531. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  532. {
  533. using (var streamReader = new StreamReader(fs))
  534. {
  535. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  536. var bytes = Encoding.UTF8.GetBytes(text);
  537. await outputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  538. }
  539. }
  540. await outputStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  541. }
  542. }
  543. }