DashboardService.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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.Localization;
  7. using MediaBrowser.Controller.Net;
  8. using MediaBrowser.Controller.Plugins;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.Serialization;
  11. using ServiceStack;
  12. using ServiceStack.Web;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Text;
  18. using System.Threading.Tasks;
  19. using WebMarkupMin.Core.Minifiers;
  20. using WebMarkupMin.Core.Settings;
  21. namespace MediaBrowser.WebDashboard.Api
  22. {
  23. /// <summary>
  24. /// Class GetDashboardConfigurationPages
  25. /// </summary>
  26. [Route("/dashboard/ConfigurationPages", "GET")]
  27. [Route("/web/ConfigurationPages", "GET")]
  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. [Route("/web/ConfigurationPage", "GET")]
  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("/web/{ResourceName*}", "GET")]
  53. [Route("/dashboard/{ResourceName*}", "GET")]
  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 DashboardService
  69. /// </summary>
  70. public class DashboardService : IRestfulService, IHasResultFactory
  71. {
  72. /// <summary>
  73. /// Gets or sets the logger.
  74. /// </summary>
  75. /// <value>The logger.</value>
  76. public ILogger Logger { get; set; }
  77. /// <summary>
  78. /// Gets or sets the HTTP result factory.
  79. /// </summary>
  80. /// <value>The HTTP result factory.</value>
  81. public IHttpResultFactory ResultFactory { get; set; }
  82. /// <summary>
  83. /// Gets or sets the request context.
  84. /// </summary>
  85. /// <value>The request context.</value>
  86. public IRequest Request { get; set; }
  87. /// <summary>
  88. /// The _app host
  89. /// </summary>
  90. private readonly IServerApplicationHost _appHost;
  91. /// <summary>
  92. /// The _server configuration manager
  93. /// </summary>
  94. private readonly IServerConfigurationManager _serverConfigurationManager;
  95. private readonly IFileSystem _fileSystem;
  96. private readonly ILocalizationManager _localization;
  97. private readonly IJsonSerializer _jsonSerializer;
  98. /// <summary>
  99. /// Initializes a new instance of the <see cref="DashboardService" /> class.
  100. /// </summary>
  101. /// <param name="appHost">The app host.</param>
  102. /// <param name="serverConfigurationManager">The server configuration manager.</param>
  103. /// <param name="fileSystem">The file system.</param>
  104. public DashboardService(IServerApplicationHost appHost, IServerConfigurationManager serverConfigurationManager, IFileSystem fileSystem, ILocalizationManager localization, IJsonSerializer jsonSerializer)
  105. {
  106. _appHost = appHost;
  107. _serverConfigurationManager = serverConfigurationManager;
  108. _fileSystem = fileSystem;
  109. _localization = localization;
  110. _jsonSerializer = jsonSerializer;
  111. }
  112. /// <summary>
  113. /// Gets the dashboard UI path.
  114. /// </summary>
  115. /// <value>The dashboard UI path.</value>
  116. public string DashboardUIPath
  117. {
  118. get
  119. {
  120. if (!string.IsNullOrEmpty(_serverConfigurationManager.Configuration.DashboardSourcePath))
  121. {
  122. return _serverConfigurationManager.Configuration.DashboardSourcePath;
  123. }
  124. var runningDirectory = Path.GetDirectoryName(_serverConfigurationManager.ApplicationPaths.ApplicationPath);
  125. return Path.Combine(runningDirectory, "dashboard-ui");
  126. }
  127. }
  128. /// <summary>
  129. /// Gets the dashboard resource path.
  130. /// </summary>
  131. /// <param name="virtualPath">The virtual path.</param>
  132. /// <returns>System.String.</returns>
  133. private string GetDashboardResourcePath(string virtualPath)
  134. {
  135. return Path.Combine(DashboardUIPath, virtualPath.Replace('/', Path.DirectorySeparatorChar));
  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(GetDashboardConfigurationPage request)
  143. {
  144. var page = ServerEntryPoint.Instance.PluginConfigurationPages.First(p => p.Name.Equals(request.Name, StringComparison.OrdinalIgnoreCase));
  145. return ResultFactory.GetStaticResult(Request, page.Plugin.Version.ToString().GetMD5(), null, null, MimeTypes.GetMimeType("page.html"), () => ModifyHtml(page.GetHtmlStream(), null));
  146. }
  147. /// <summary>
  148. /// Gets the specified request.
  149. /// </summary>
  150. /// <param name="request">The request.</param>
  151. /// <returns>System.Object.</returns>
  152. public object Get(GetDashboardConfigurationPages request)
  153. {
  154. const string unavilableMessage = "The server is still loading. Please try again momentarily.";
  155. var instance = ServerEntryPoint.Instance;
  156. if (instance == null)
  157. {
  158. throw new InvalidOperationException(unavilableMessage);
  159. }
  160. var pages = instance.PluginConfigurationPages;
  161. if (pages == null)
  162. {
  163. throw new InvalidOperationException(unavilableMessage);
  164. }
  165. if (request.PageType.HasValue)
  166. {
  167. pages = pages.Where(p => p.ConfigurationPageType == request.PageType.Value);
  168. }
  169. // Don't allow a failing plugin to fail them all
  170. var configPages = pages.Select(p =>
  171. {
  172. try
  173. {
  174. return new ConfigurationPageInfo(p);
  175. }
  176. catch (Exception ex)
  177. {
  178. Logger.ErrorException("Error getting plugin information from {0}", ex, p.GetType().Name);
  179. return null;
  180. }
  181. })
  182. .Where(i => i != null)
  183. .ToList();
  184. return ResultFactory.GetOptimizedResult(Request, configPages);
  185. }
  186. /// <summary>
  187. /// Gets the specified request.
  188. /// </summary>
  189. /// <param name="request">The request.</param>
  190. /// <returns>System.Object.</returns>
  191. public object Get(GetDashboardResource request)
  192. {
  193. var path = request.ResourceName;
  194. var contentType = MimeTypes.GetMimeType(path);
  195. var isHtml = IsHtml(path);
  196. var localizationCulture = GetLocalizationCulture();
  197. // Don't cache if not configured to do so
  198. // But always cache images to simulate production
  199. if (!_serverConfigurationManager.Configuration.EnableDashboardResponseCaching &&
  200. !contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) &&
  201. !contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  202. {
  203. return ResultFactory.GetResult(GetResourceStream(path, isHtml, localizationCulture).Result, contentType);
  204. }
  205. TimeSpan? cacheDuration = null;
  206. // Cache images unconditionally - updates to image files will require new filename
  207. // If there's a version number in the query string we can cache this unconditionally
  208. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase) || !string.IsNullOrEmpty(request.V))
  209. {
  210. cacheDuration = TimeSpan.FromDays(365);
  211. }
  212. var assembly = GetType().Assembly.GetName();
  213. var cacheKey = (assembly.Version + (localizationCulture ?? string.Empty) + path).GetMD5();
  214. return ResultFactory.GetStaticResult(Request, cacheKey, null, cacheDuration, contentType, () => GetResourceStream(path, isHtml, localizationCulture));
  215. }
  216. private string GetLocalizationCulture()
  217. {
  218. return _serverConfigurationManager.Configuration.UICulture;
  219. }
  220. /// <summary>
  221. /// Gets the resource stream.
  222. /// </summary>
  223. /// <param name="path">The path.</param>
  224. /// <param name="isHtml">if set to <c>true</c> [is HTML].</param>
  225. /// <param name="localizationCulture">The localization culture.</param>
  226. /// <returns>Task{Stream}.</returns>
  227. private async Task<Stream> GetResourceStream(string path, bool isHtml, string localizationCulture)
  228. {
  229. Stream resourceStream;
  230. if (path.Equals("scripts/all.js", StringComparison.OrdinalIgnoreCase))
  231. {
  232. resourceStream = await GetAllJavascript().ConfigureAwait(false);
  233. }
  234. else if (path.Equals("css/all.css", StringComparison.OrdinalIgnoreCase))
  235. {
  236. resourceStream = await GetAllCss().ConfigureAwait(false);
  237. }
  238. else
  239. {
  240. resourceStream = GetRawResourceStream(path);
  241. }
  242. if (resourceStream != null)
  243. {
  244. // Don't apply any caching for html pages
  245. // jQuery ajax doesn't seem to handle if-modified-since correctly
  246. if (isHtml)
  247. {
  248. resourceStream = await ModifyHtml(resourceStream, localizationCulture).ConfigureAwait(false);
  249. }
  250. }
  251. return resourceStream;
  252. }
  253. /// <summary>
  254. /// Gets the raw resource stream.
  255. /// </summary>
  256. /// <param name="path">The path.</param>
  257. /// <returns>Task{Stream}.</returns>
  258. private Stream GetRawResourceStream(string path)
  259. {
  260. return _fileSystem.GetFileStream(GetDashboardResourcePath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  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. /// <param name="userId">The user identifier.</param>
  276. /// <param name="localizationCulture">The localization culture.</param>
  277. /// <returns>Task{Stream}.</returns>
  278. private async Task<Stream> ModifyHtml(Stream sourceStream, string localizationCulture)
  279. {
  280. using (sourceStream)
  281. {
  282. string html;
  283. using (var memoryStream = new MemoryStream())
  284. {
  285. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  286. html = Encoding.UTF8.GetString(memoryStream.ToArray());
  287. if (!string.IsNullOrWhiteSpace(localizationCulture))
  288. {
  289. var lang = localizationCulture.Split('-').FirstOrDefault();
  290. html = _localization.LocalizeDocument(html, localizationCulture, GetLocalizationToken);
  291. html = html.Replace("<html>", "<html lang=\"" + lang + "\">");
  292. }
  293. //try
  294. //{
  295. // var minifier = new HtmlMinifier(new HtmlMinificationSettings(true));
  296. // html = minifier.Minify(html).MinifiedContent;
  297. //}
  298. //catch (Exception ex)
  299. //{
  300. // Logger.ErrorException("Error minifying html", ex);
  301. //}
  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. return new MemoryStream(bytes);
  307. }
  308. }
  309. private string GetLocalizationToken(string phrase)
  310. {
  311. return "${" + phrase + "}";
  312. }
  313. /// <summary>
  314. /// Gets the meta tags.
  315. /// </summary>
  316. /// <returns>System.String.</returns>
  317. private static string GetMetaTags()
  318. {
  319. var sb = new StringBuilder();
  320. sb.Append("<meta http-equiv=\"X-UA-Compatibility\" content=\"IE=Edge\">");
  321. sb.Append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">");
  322. sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  323. sb.Append("<meta name=\"mobile-web-app-capable\" content=\"yes\">");
  324. sb.Append("<meta name=\"application-name\" content=\"Media Browser\">");
  325. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  326. sb.Append("<link rel=\"icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\" />");
  327. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  328. sb.Append("<link rel=\"apple-touch-icon\" href=\"css/images/touchicon.png\" />");
  329. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"css/images/touchicon72.png\" />");
  330. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\" />");
  331. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\" />");
  332. sb.Append("<link rel=\"shortcut icon\" href=\"css/images/favicon.ico\" />");
  333. return sb.ToString();
  334. }
  335. /// <summary>
  336. /// Gets the common CSS.
  337. /// </summary>
  338. /// <param name="version">The version.</param>
  339. /// <returns>System.String.</returns>
  340. private static string GetCommonCss(Version version)
  341. {
  342. var versionString = "?v=" + version;
  343. var files = new[]
  344. {
  345. "thirdparty/jquerymobile-1.4.3/jquery.mobile-1.4.3.min.css",
  346. "css/all.css" + versionString
  347. };
  348. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" />", s)).ToArray();
  349. return string.Join(string.Empty, tags);
  350. }
  351. /// <summary>
  352. /// Gets the common javascript.
  353. /// </summary>
  354. /// <param name="version">The version.</param>
  355. /// <returns>System.String.</returns>
  356. private static string GetCommonJavascript(Version version)
  357. {
  358. var builder = new StringBuilder();
  359. var versionString = "?v=" + version;
  360. var files = new[]
  361. {
  362. "scripts/all.js" + versionString,
  363. "thirdparty/jstree1.0/jquery.jstree.min.js"
  364. };
  365. var tags = files.Select(s => string.Format("<script src=\"{0}\"></script>", s)).ToArray();
  366. builder.Append(string.Join(string.Empty, tags));
  367. return builder.ToString();
  368. }
  369. /// <summary>
  370. /// Gets a stream containing all concatenated javascript
  371. /// </summary>
  372. /// <returns>Task{Stream}.</returns>
  373. private async Task<Stream> GetAllJavascript()
  374. {
  375. var memoryStream = new MemoryStream();
  376. var newLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
  377. // jQuery + jQuery mobile
  378. await AppendResource(memoryStream, "thirdparty/jquery-2.0.3.min.js", newLineBytes).ConfigureAwait(false);
  379. await AppendResource(memoryStream, "thirdparty/jquerymobile-1.4.3/jquery.mobile-1.4.3.min.js", newLineBytes).ConfigureAwait(false);
  380. await AppendResource(memoryStream, "thirdparty/jquery.unveil-custom.js", newLineBytes).ConfigureAwait(false);
  381. await AppendResource(memoryStream, "thirdparty/cast_sender.js", newLineBytes).ConfigureAwait(false);
  382. await AppendLocalization(memoryStream).ConfigureAwait(false);
  383. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  384. // Write the version string for the dashboard comparison function
  385. var versionString = string.Format("window.dashboardVersion='{0}';", _appHost.ApplicationVersion);
  386. var versionBytes = Encoding.UTF8.GetBytes(versionString);
  387. await memoryStream.WriteAsync(versionBytes, 0, versionBytes.Length).ConfigureAwait(false);
  388. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  389. var builder = new StringBuilder();
  390. using (var fs = _fileSystem.GetFileStream(GetDashboardResourcePath("thirdparty/mediabrowser.apiclient.js"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  391. {
  392. using (var streamReader = new StreamReader(fs))
  393. {
  394. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  395. builder.Append(text);
  396. builder.Append(Environment.NewLine);
  397. }
  398. }
  399. foreach (var file in GetScriptFiles())
  400. {
  401. var path = GetDashboardResourcePath("scripts/" + file);
  402. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  403. {
  404. using (var streamReader = new StreamReader(fs))
  405. {
  406. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  407. builder.Append(text);
  408. builder.Append(Environment.NewLine);
  409. }
  410. }
  411. }
  412. var js = builder.ToString();
  413. try
  414. {
  415. var result = new CrockfordJsMinifier().Minify(js, false, Encoding.UTF8);
  416. js = result.MinifiedContent;
  417. }
  418. catch (Exception ex)
  419. {
  420. Logger.ErrorException("Error minifying javascript", ex);
  421. }
  422. var bytes = Encoding.UTF8.GetBytes(js);
  423. await memoryStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  424. memoryStream.Position = 0;
  425. return memoryStream;
  426. }
  427. private IEnumerable<string> GetScriptFiles()
  428. {
  429. return new[]
  430. {
  431. "extensions.js",
  432. "site.js",
  433. "librarybrowser.js",
  434. "librarylist.js",
  435. "editorsidebar.js",
  436. "librarymenu.js",
  437. "mediacontroller.js",
  438. "chromecast.js",
  439. "backdrops.js",
  440. "mediaplayer.js",
  441. "mediaplayer-video.js",
  442. "nowplayingbar.js",
  443. "nowplayingpage.js",
  444. "ratingdialog.js",
  445. "aboutpage.js",
  446. "alphapicker.js",
  447. "addpluginpage.js",
  448. "advancedconfigurationpage.js",
  449. "advancedpaths.js",
  450. "advancedserversettings.js",
  451. "metadataadvanced.js",
  452. "appsplayback.js",
  453. "autoorganizetv.js",
  454. "autoorganizelog.js",
  455. "channels.js",
  456. "channelslatest.js",
  457. "channelitems.js",
  458. "channelsettings.js",
  459. "dashboardgeneral.js",
  460. "dashboardpage.js",
  461. "directorybrowser.js",
  462. "dlnaprofile.js",
  463. "dlnaprofiles.js",
  464. "dlnasettings.js",
  465. "dlnaserversettings.js",
  466. "editcollectionitems.js",
  467. "edititemmetadata.js",
  468. "edititemimages.js",
  469. "edititemsubtitles.js",
  470. "encodingsettings.js",
  471. "favorites.js",
  472. "gamesrecommendedpage.js",
  473. "gamesystemspage.js",
  474. "gamespage.js",
  475. "gamegenrepage.js",
  476. "gamestudiospage.js",
  477. "homelatest.js",
  478. "indexpage.js",
  479. "itembynamedetailpage.js",
  480. "itemdetailpage.js",
  481. "itemgallery.js",
  482. "itemlistpage.js",
  483. "librarypathmapping.js",
  484. "reports.js",
  485. "librarysettings.js",
  486. "livetvchannel.js",
  487. "livetvchannels.js",
  488. "livetvguide.js",
  489. "livetvnewrecording.js",
  490. "livetvprogram.js",
  491. "livetvrecording.js",
  492. "livetvrecordinglist.js",
  493. "livetvrecordings.js",
  494. "livetvtimer.js",
  495. "livetvseriestimer.js",
  496. "livetvseriestimers.js",
  497. "livetvsettings.js",
  498. "livetvsuggested.js",
  499. "livetvstatus.js",
  500. "livetvtimers.js",
  501. "loginpage.js",
  502. "logpage.js",
  503. "medialibrarypage.js",
  504. "metadataconfigurationpage.js",
  505. "metadataimagespage.js",
  506. "metadatasubtitles.js",
  507. "metadatachapters.js",
  508. "metadataxbmc.js",
  509. "moviegenres.js",
  510. "moviecollections.js",
  511. "movies.js",
  512. "movieslatest.js",
  513. "moviepeople.js",
  514. "moviesrecommended.js",
  515. "moviestudios.js",
  516. "movietrailers.js",
  517. "musicalbums.js",
  518. "musicalbumartists.js",
  519. "musicartists.js",
  520. "musicgenres.js",
  521. "musicrecommended.js",
  522. "musicvideos.js",
  523. "mypreferencesdisplay.js",
  524. "mypreferenceslanguages.js",
  525. "mypreferenceswebclient.js",
  526. "notifications.js",
  527. "notificationlist.js",
  528. "notificationsetting.js",
  529. "notificationsettings.js",
  530. "playlist.js",
  531. "plugincatalogpage.js",
  532. "pluginspage.js",
  533. "remotecontrol.js",
  534. "scheduledtaskpage.js",
  535. "scheduledtaskspage.js",
  536. "search.js",
  537. "serversecurity.js",
  538. "songs.js",
  539. "supporterkeypage.js",
  540. "supporterpage.js",
  541. "episodes.js",
  542. "thememediaplayer.js",
  543. "tvgenres.js",
  544. "tvlatest.js",
  545. "tvpeople.js",
  546. "tvrecommended.js",
  547. "tvshows.js",
  548. "tvstudios.js",
  549. "tvupcoming.js",
  550. "useredit.js",
  551. "userpassword.js",
  552. "userimagepage.js",
  553. "userprofilespage.js",
  554. "userparentalcontrol.js",
  555. "wizardfinishpage.js",
  556. "wizardservice.js",
  557. "wizardstartpage.js",
  558. "wizardsettings.js",
  559. "wizarduserpage.js"
  560. };
  561. }
  562. private async Task AppendLocalization(Stream stream)
  563. {
  564. var js = "window.localizationGlossary=" + _jsonSerializer.SerializeToString(_localization.GetJavaScriptLocalizationDictionary(GetLocalizationCulture()));
  565. var bytes = Encoding.UTF8.GetBytes(js);
  566. await stream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  567. }
  568. /// <summary>
  569. /// Gets all CSS.
  570. /// </summary>
  571. /// <returns>Task{Stream}.</returns>
  572. private async Task<Stream> GetAllCss()
  573. {
  574. var files = new[]
  575. {
  576. "site.css",
  577. "chromecast.css",
  578. "mediaplayer.css",
  579. "mediaplayer-video.css",
  580. "librarymenu.css",
  581. "librarybrowser.css",
  582. "detailtable.css",
  583. "posteritem.css",
  584. "tileitem.css",
  585. "metadataeditor.css",
  586. "notifications.css",
  587. "search.css",
  588. "pluginupdates.css",
  589. "remotecontrol.css",
  590. "userimage.css",
  591. "livetv.css",
  592. "nowplaying.css",
  593. "icons.css"
  594. };
  595. var builder = new StringBuilder();
  596. foreach (var file in files)
  597. {
  598. var path = GetDashboardResourcePath("css/" + file);
  599. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  600. {
  601. using (var streamReader = new StreamReader(fs))
  602. {
  603. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  604. builder.Append(text);
  605. builder.Append(Environment.NewLine);
  606. }
  607. }
  608. }
  609. var css = builder.ToString();
  610. //try
  611. //{
  612. // var result = new KristensenCssMinifier().Minify(builder.ToString(), false, Encoding.UTF8);
  613. // css = result.MinifiedContent;
  614. //}
  615. //catch (Exception ex)
  616. //{
  617. // Logger.ErrorException("Error minifying css", ex);
  618. //}
  619. var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(css));
  620. memoryStream.Position = 0;
  621. return memoryStream;
  622. }
  623. /// <summary>
  624. /// Appends the resource.
  625. /// </summary>
  626. /// <param name="outputStream">The output stream.</param>
  627. /// <param name="path">The path.</param>
  628. /// <param name="newLineBytes">The new line bytes.</param>
  629. /// <returns>Task.</returns>
  630. private async Task AppendResource(Stream outputStream, string path, byte[] newLineBytes)
  631. {
  632. path = GetDashboardResourcePath(path);
  633. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  634. {
  635. using (var streamReader = new StreamReader(fs))
  636. {
  637. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  638. var bytes = Encoding.UTF8.GetBytes(text);
  639. await outputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  640. }
  641. }
  642. await outputStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  643. }
  644. }
  645. }