DashboardService.cs 29 KB

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