PackageCreator.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Localization;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Serialization;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using WebMarkupMin.Core;
  13. using WebMarkupMin.Core.Minifiers;
  14. using WebMarkupMin.Core.Settings;
  15. namespace MediaBrowser.WebDashboard.Api
  16. {
  17. public class PackageCreator
  18. {
  19. private readonly IFileSystem _fileSystem;
  20. private readonly ILocalizationManager _localization;
  21. private readonly ILogger _logger;
  22. private readonly IServerConfigurationManager _config;
  23. private readonly IJsonSerializer _jsonSerializer;
  24. public PackageCreator(IFileSystem fileSystem, ILocalizationManager localization, ILogger logger, IServerConfigurationManager config, IJsonSerializer jsonSerializer)
  25. {
  26. _fileSystem = fileSystem;
  27. _localization = localization;
  28. _logger = logger;
  29. _config = config;
  30. _jsonSerializer = jsonSerializer;
  31. }
  32. public async Task<Stream> GetResource(string path,
  33. string mode,
  34. string localizationCulture,
  35. string appVersion,
  36. bool enableMinification)
  37. {
  38. var isHtml = IsHtml(path);
  39. Stream resourceStream;
  40. if (path.Equals("scripts/all.js", StringComparison.OrdinalIgnoreCase))
  41. {
  42. resourceStream = await GetAllJavascript(mode, localizationCulture, appVersion, enableMinification).ConfigureAwait(false);
  43. }
  44. else if (path.Equals("css/all.css", StringComparison.OrdinalIgnoreCase))
  45. {
  46. resourceStream = await GetAllCss(enableMinification).ConfigureAwait(false);
  47. }
  48. else
  49. {
  50. resourceStream = GetRawResourceStream(path);
  51. }
  52. if (resourceStream != null)
  53. {
  54. // Don't apply any caching for html pages
  55. // jQuery ajax doesn't seem to handle if-modified-since correctly
  56. if (isHtml && path.IndexOf("cordovaindex.html", StringComparison.OrdinalIgnoreCase) == -1)
  57. {
  58. resourceStream = await ModifyHtml(resourceStream, mode, localizationCulture, enableMinification).ConfigureAwait(false);
  59. }
  60. }
  61. return resourceStream;
  62. }
  63. /// <summary>
  64. /// Determines whether the specified path is HTML.
  65. /// </summary>
  66. /// <param name="path">The path.</param>
  67. /// <returns><c>true</c> if the specified path is HTML; otherwise, <c>false</c>.</returns>
  68. private bool IsHtml(string path)
  69. {
  70. return Path.GetExtension(path).EndsWith("html", StringComparison.OrdinalIgnoreCase);
  71. }
  72. /// <summary>
  73. /// Gets the dashboard UI path.
  74. /// </summary>
  75. /// <value>The dashboard UI path.</value>
  76. public string DashboardUIPath
  77. {
  78. get
  79. {
  80. if (!string.IsNullOrEmpty(_config.Configuration.DashboardSourcePath))
  81. {
  82. return _config.Configuration.DashboardSourcePath;
  83. }
  84. return Path.Combine(_config.ApplicationPaths.ApplicationResourcesPath, "dashboard-ui");
  85. }
  86. }
  87. /// <summary>
  88. /// Gets the dashboard resource path.
  89. /// </summary>
  90. /// <param name="virtualPath">The virtual path.</param>
  91. /// <returns>System.String.</returns>
  92. private string GetDashboardResourcePath(string virtualPath)
  93. {
  94. var rootPath = DashboardUIPath;
  95. var fullPath = Path.Combine(rootPath, virtualPath.Replace('/', Path.DirectorySeparatorChar));
  96. // Don't allow file system access outside of the source folder
  97. if (!_fileSystem.ContainsSubPath(rootPath, fullPath))
  98. {
  99. throw new UnauthorizedAccessException();
  100. }
  101. return fullPath;
  102. }
  103. /// <summary>
  104. /// Modifies the HTML by adding common meta tags, css and js.
  105. /// </summary>
  106. /// <param name="sourceStream">The source stream.</param>
  107. /// <param name="mode">The mode.</param>
  108. /// <param name="localizationCulture">The localization culture.</param>
  109. /// <param name="enableMinification">if set to <c>true</c> [enable minification].</param>
  110. /// <returns>Task{Stream}.</returns>
  111. public async Task<Stream> ModifyHtml(Stream sourceStream, string mode, string localizationCulture, bool enableMinification)
  112. {
  113. using (sourceStream)
  114. {
  115. string html;
  116. using (var memoryStream = new MemoryStream())
  117. {
  118. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  119. html = Encoding.UTF8.GetString(memoryStream.ToArray());
  120. if (!string.IsNullOrWhiteSpace(localizationCulture))
  121. {
  122. var lang = localizationCulture.Split('-').FirstOrDefault();
  123. html = _localization.LocalizeDocument(html, localizationCulture, GetLocalizationToken);
  124. html = html.Replace("<html>", "<html lang=\"" + lang + "\">");
  125. }
  126. if (enableMinification)
  127. {
  128. try
  129. {
  130. var minifier = new HtmlMinifier(new HtmlMinificationSettings
  131. {
  132. AttributeQuotesRemovalMode = HtmlAttributeQuotesRemovalMode.KeepQuotes,
  133. RemoveOptionalEndTags = false,
  134. RemoveTagsWithoutContent = false
  135. });
  136. var result = minifier.Minify(html, false);
  137. if (result.Errors.Count > 0)
  138. {
  139. _logger.Error("Error minifying html: " + result.Errors[0].Message);
  140. }
  141. else
  142. {
  143. html = result.MinifiedContent;
  144. }
  145. }
  146. catch (Exception ex)
  147. {
  148. _logger.ErrorException("Error minifying html", ex);
  149. }
  150. }
  151. }
  152. var version = GetType().Assembly.GetName().Version;
  153. html = html.Replace("<head>", "<head>" + GetMetaTags(mode) + GetCommonCss(mode, version) + GetCommonJavascript(mode, version));
  154. var bytes = Encoding.UTF8.GetBytes(html);
  155. return new MemoryStream(bytes);
  156. }
  157. }
  158. private string GetLocalizationToken(string phrase)
  159. {
  160. return "${" + phrase + "}";
  161. }
  162. /// <summary>
  163. /// Gets the meta tags.
  164. /// </summary>
  165. /// <returns>System.String.</returns>
  166. private static string GetMetaTags(string mode)
  167. {
  168. var sb = new StringBuilder();
  169. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  170. {
  171. sb.Append("<meta http-equiv=\"Content-Security-Policy\" content=\"default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'\">");
  172. }
  173. sb.Append("<meta http-equiv=\"X-UA-Compatibility\" content=\"IE=Edge\">");
  174. sb.Append("<meta name=\"format-detection\" content=\"telephone=no\">");
  175. sb.Append("<meta name=\"msapplication-tap-highlight\" content=\"no\">");
  176. sb.Append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no\">");
  177. sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  178. sb.Append("<meta name=\"mobile-web-app-capable\" content=\"yes\">");
  179. sb.Append("<meta name=\"application-name\" content=\"Emby\">");
  180. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  181. sb.Append("<meta name=\"robots\" content=\"noindex, nofollow, noarchive\" />");
  182. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  183. sb.Append("<link rel=\"apple-touch-icon\" href=\"css/images/touchicon.png\" />");
  184. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"css/images/touchicon72.png\" />");
  185. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\" />");
  186. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\" />");
  187. sb.Append("<link rel=\"shortcut icon\" href=\"css/images/favicon.ico\" />");
  188. sb.Append("<meta name=\"msapplication-TileImage\" content=\"css/images/touchicon144.png\">");
  189. sb.Append("<meta name=\"msapplication-TileColor\" content=\"#23456B\">");
  190. return sb.ToString();
  191. }
  192. /// <summary>
  193. /// Gets the common CSS.
  194. /// </summary>
  195. /// <param name="mode">The mode.</param>
  196. /// <param name="version">The version.</param>
  197. /// <returns>System.String.</returns>
  198. private string GetCommonCss(string mode, Version version)
  199. {
  200. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  201. var files = new[]
  202. {
  203. "thirdparty/jquerymobile-1.4.5/jquery.mobile-1.4.5.min.css",
  204. "thirdparty/fontawesome/css/font-awesome.min.css" + versionString,
  205. "css/all.css" + versionString
  206. };
  207. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" />", s)).ToArray();
  208. return string.Join(string.Empty, tags);
  209. }
  210. /// <summary>
  211. /// Gets the common javascript.
  212. /// </summary>
  213. /// <param name="mode">The mode.</param>
  214. /// <param name="version">The version.</param>
  215. /// <returns>System.String.</returns>
  216. private string GetCommonJavascript(string mode, Version version)
  217. {
  218. var builder = new StringBuilder();
  219. var versionString = !string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase) ? "?v=" + version : string.Empty;
  220. var files = new List<string>
  221. {
  222. "scripts/all.js" + versionString
  223. };
  224. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  225. {
  226. files.Insert(0, "cordova.js");
  227. }
  228. var tags = files.Select(s => string.Format("<script src=\"{0}\"></script>", s)).ToArray();
  229. builder.Append(string.Join(string.Empty, tags));
  230. return builder.ToString();
  231. }
  232. /// <summary>
  233. /// Gets a stream containing all concatenated javascript
  234. /// </summary>
  235. /// <returns>Task{Stream}.</returns>
  236. private async Task<Stream> GetAllJavascript(string mode, string culture, string version, bool enableMinification)
  237. {
  238. var memoryStream = new MemoryStream();
  239. var newLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
  240. // jQuery + jQuery mobile
  241. await AppendResource(memoryStream, "thirdparty/jquery-2.1.1.min.js", newLineBytes).ConfigureAwait(false);
  242. await AppendResource(memoryStream, "thirdparty/jquerymobile-1.4.5/jquery.mobile-1.4.5.min.js", newLineBytes).ConfigureAwait(false);
  243. await AppendResource(memoryStream, "thirdparty/browser.js", newLineBytes).ConfigureAwait(false);
  244. await AppendResource(memoryStream, "thirdparty/require.js", newLineBytes).ConfigureAwait(false);
  245. await AppendResource(memoryStream, "thirdparty/jquery.unveil-custom.js", newLineBytes).ConfigureAwait(false);
  246. await AppendLocalization(memoryStream, culture).ConfigureAwait(false);
  247. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  248. if (!string.IsNullOrWhiteSpace(mode))
  249. {
  250. var appModeBytes = Encoding.UTF8.GetBytes(string.Format("window.appMode='{0}';", mode));
  251. await memoryStream.WriteAsync(appModeBytes, 0, appModeBytes.Length).ConfigureAwait(false);
  252. }
  253. // Write the version string for the dashboard comparison function
  254. var versionString = string.Format("window.dashboardVersion='{0}';", version);
  255. var versionBytes = Encoding.UTF8.GetBytes(versionString);
  256. await memoryStream.WriteAsync(versionBytes, 0, versionBytes.Length).ConfigureAwait(false);
  257. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  258. var builder = new StringBuilder();
  259. var apiClientFiles = new[]
  260. {
  261. "thirdparty/apiclient/logger.js",
  262. "thirdparty/apiclient/md5.js",
  263. "thirdparty/apiclient/sha1.js",
  264. "thirdparty/apiclient/store.js",
  265. "thirdparty/apiclient/network.js",
  266. "thirdparty/apiclient/device.js",
  267. "thirdparty/apiclient/credentials.js",
  268. "thirdparty/apiclient/ajax.js",
  269. "thirdparty/apiclient/events.js",
  270. "thirdparty/apiclient/deferred.js",
  271. "thirdparty/apiclient/apiclient.js",
  272. "thirdparty/apiclient/connectservice.js"
  273. }.ToList();
  274. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  275. {
  276. apiClientFiles.Add("thirdparty/cordova/serverdiscovery.js");
  277. }
  278. else
  279. {
  280. apiClientFiles.Add("thirdparty/apiclient/serverdiscovery.js");
  281. }
  282. apiClientFiles.Add("thirdparty/apiclient/connectionmanager.js");
  283. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  284. {
  285. apiClientFiles.Add("thirdparty/cordova/remotecontrols.js");
  286. }
  287. foreach (var file in apiClientFiles)
  288. {
  289. using (var fs = _fileSystem.GetFileStream(GetDashboardResourcePath(file), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  290. {
  291. using (var streamReader = new StreamReader(fs))
  292. {
  293. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  294. builder.Append(text);
  295. builder.Append(Environment.NewLine);
  296. }
  297. }
  298. }
  299. foreach (var file in GetScriptFiles())
  300. {
  301. var path = GetDashboardResourcePath("scripts/" + file);
  302. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  303. {
  304. using (var streamReader = new StreamReader(fs))
  305. {
  306. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  307. builder.Append(text);
  308. builder.Append(Environment.NewLine);
  309. }
  310. }
  311. }
  312. var js = builder.ToString();
  313. if (enableMinification)
  314. {
  315. try
  316. {
  317. var result = new CrockfordJsMinifier().Minify(js, false, Encoding.UTF8);
  318. if (result.Errors.Count > 0)
  319. {
  320. _logger.Error("Error minifying javascript: " + result.Errors[0].Message);
  321. }
  322. else
  323. {
  324. js = result.MinifiedContent;
  325. }
  326. }
  327. catch (Exception ex)
  328. {
  329. _logger.ErrorException("Error minifying javascript", ex);
  330. }
  331. }
  332. var bytes = Encoding.UTF8.GetBytes(js);
  333. await memoryStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  334. memoryStream.Position = 0;
  335. return memoryStream;
  336. }
  337. private IEnumerable<string> GetScriptFiles()
  338. {
  339. return new[]
  340. {
  341. "extensions.js",
  342. "site.js",
  343. "librarybrowser.js",
  344. "librarylist.js",
  345. "editorsidebar.js",
  346. "librarymenu.js",
  347. "mediacontroller.js",
  348. "chromecast.js",
  349. "backdrops.js",
  350. "sync.js",
  351. "syncjob.js",
  352. "appservices.js",
  353. "playlistmanager.js",
  354. "mediaplayer.js",
  355. "mediaplayer-video.js",
  356. "nowplayingbar.js",
  357. "nowplayingpage.js",
  358. "taskbutton.js",
  359. "ratingdialog.js",
  360. "aboutpage.js",
  361. "alphapicker.js",
  362. "addpluginpage.js",
  363. "advancedconfigurationpage.js",
  364. "metadataadvanced.js",
  365. "autoorganizetv.js",
  366. "autoorganizelog.js",
  367. "channels.js",
  368. "channelslatest.js",
  369. "channelitems.js",
  370. "channelsettings.js",
  371. "connectlogin.js",
  372. "dashboardgeneral.js",
  373. "dashboardhosting.js",
  374. "dashboardpage.js",
  375. "device.js",
  376. "devices.js",
  377. "devicesupload.js",
  378. "directorybrowser.js",
  379. "dlnaprofile.js",
  380. "dlnaprofiles.js",
  381. "dlnasettings.js",
  382. "dlnaserversettings.js",
  383. "editcollectionitems.js",
  384. "edititemmetadata.js",
  385. "edititemimages.js",
  386. "edititemsubtitles.js",
  387. "playbackconfiguration.js",
  388. "cinemamodeconfiguration.js",
  389. "encodingsettings.js",
  390. "externalplayer.js",
  391. "favorites.js",
  392. "forgotpassword.js",
  393. "forgotpasswordpin.js",
  394. "gamesrecommendedpage.js",
  395. "gamesystemspage.js",
  396. "gamespage.js",
  397. "gamegenrepage.js",
  398. "gamestudiospage.js",
  399. "homelatest.js",
  400. "indexpage.js",
  401. "itembynamedetailpage.js",
  402. "itemdetailpage.js",
  403. "itemlistpage.js",
  404. "kids.js",
  405. "librarypathmapping.js",
  406. "reports.js",
  407. "librarysettings.js",
  408. "livetvchannel.js",
  409. "livetvchannels.js",
  410. "livetvguide.js",
  411. "livetvitems.js",
  412. "livetvnewrecording.js",
  413. "livetvprogram.js",
  414. "livetvrecording.js",
  415. "livetvrecordinglist.js",
  416. "livetvrecordings.js",
  417. "livetvtimer.js",
  418. "livetvseriestimer.js",
  419. "livetvseriestimers.js",
  420. "livetvsettings.js",
  421. "livetvsuggested.js",
  422. "livetvstatus.js",
  423. "livetvtimers.js",
  424. "loginpage.js",
  425. "logpage.js",
  426. "medialibrarypage.js",
  427. "metadataconfigurationpage.js",
  428. "metadataimagespage.js",
  429. "metadatasubtitles.js",
  430. "metadatanfo.js",
  431. "moviegenres.js",
  432. "moviecollections.js",
  433. "movies.js",
  434. "moviepeople.js",
  435. "moviesrecommended.js",
  436. "moviestudios.js",
  437. "movietrailers.js",
  438. "musicalbums.js",
  439. "musicalbumartists.js",
  440. "musicartists.js",
  441. "musicgenres.js",
  442. "musicrecommended.js",
  443. "musicvideos.js",
  444. "mypreferencesdisplay.js",
  445. "mypreferenceslanguages.js",
  446. "mypreferenceswebclient.js",
  447. "notifications.js",
  448. "notificationlist.js",
  449. "notificationsetting.js",
  450. "notificationsettings.js",
  451. "photos.js",
  452. "playlists.js",
  453. "playlistedit.js",
  454. "plugincatalogpage.js",
  455. "pluginspage.js",
  456. "remotecontrol.js",
  457. "scheduledtaskpage.js",
  458. "scheduledtaskspage.js",
  459. "search.js",
  460. "selectserver.js",
  461. "serversecurity.js",
  462. "songs.js",
  463. "streamingsettings.js",
  464. "supporterkeypage.js",
  465. "supporterpage.js",
  466. "syncactivity.js",
  467. "syncsettings.js",
  468. "episodes.js",
  469. "thememediaplayer.js",
  470. "tvgenres.js",
  471. "tvlatest.js",
  472. "tvpeople.js",
  473. "tvrecommended.js",
  474. "tvshows.js",
  475. "tvstudios.js",
  476. "tvupcoming.js",
  477. "useredit.js",
  478. "usernew.js",
  479. "myprofile.js",
  480. "userpassword.js",
  481. "userprofilespage.js",
  482. "userparentalcontrol.js",
  483. "userlibraryaccess.js",
  484. "wizardagreement.js",
  485. "wizardfinishpage.js",
  486. "wizardservice.js",
  487. "wizardstartpage.js",
  488. "wizardsettings.js",
  489. "wizarduserpage.js"
  490. };
  491. }
  492. private async Task AppendLocalization(Stream stream, string culture)
  493. {
  494. var js = "window.localizationGlossary=" + _jsonSerializer.SerializeToString(_localization.GetJavaScriptLocalizationDictionary(culture));
  495. var bytes = Encoding.UTF8.GetBytes(js);
  496. await stream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  497. }
  498. /// <summary>
  499. /// Appends the resource.
  500. /// </summary>
  501. /// <param name="outputStream">The output stream.</param>
  502. /// <param name="path">The path.</param>
  503. /// <param name="newLineBytes">The new line bytes.</param>
  504. /// <returns>Task.</returns>
  505. private async Task AppendResource(Stream outputStream, string path, byte[] newLineBytes)
  506. {
  507. path = GetDashboardResourcePath(path);
  508. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  509. {
  510. using (var streamReader = new StreamReader(fs))
  511. {
  512. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  513. var bytes = Encoding.UTF8.GetBytes(text);
  514. await outputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  515. }
  516. }
  517. await outputStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  518. }
  519. /// <summary>
  520. /// Gets all CSS.
  521. /// </summary>
  522. /// <returns>Task{Stream}.</returns>
  523. private async Task<Stream> GetAllCss(bool enableMinification)
  524. {
  525. var files = new[]
  526. {
  527. "site.css",
  528. "chromecast.css",
  529. "mediaplayer.css",
  530. "mediaplayer-video.css",
  531. "librarymenu.css",
  532. "librarybrowser.css",
  533. "detailtable.css",
  534. "card.css",
  535. "tileitem.css",
  536. "metadataeditor.css",
  537. "notifications.css",
  538. "search.css",
  539. "pluginupdates.css",
  540. "remotecontrol.css",
  541. "userimage.css",
  542. "livetv.css",
  543. "nowplaying.css",
  544. "icons.css",
  545. "materialize.css"
  546. };
  547. var builder = new StringBuilder();
  548. foreach (var file in files)
  549. {
  550. var path = GetDashboardResourcePath("css/" + file);
  551. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  552. {
  553. using (var streamReader = new StreamReader(fs))
  554. {
  555. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  556. builder.Append(text);
  557. builder.Append(Environment.NewLine);
  558. }
  559. }
  560. }
  561. var css = builder.ToString();
  562. if (enableMinification)
  563. {
  564. try
  565. {
  566. var result = new KristensenCssMinifier().Minify(builder.ToString(), false, Encoding.UTF8);
  567. if (result.Errors.Count > 0)
  568. {
  569. _logger.Error("Error minifying css: " + result.Errors[0].Message);
  570. }
  571. else
  572. {
  573. css = result.MinifiedContent;
  574. }
  575. }
  576. catch (Exception ex)
  577. {
  578. _logger.ErrorException("Error minifying css", ex);
  579. }
  580. }
  581. var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(css));
  582. memoryStream.Position = 0;
  583. return memoryStream;
  584. }
  585. /// <summary>
  586. /// Gets the raw resource stream.
  587. /// </summary>
  588. /// <param name="path">The path.</param>
  589. /// <returns>Task{Stream}.</returns>
  590. private Stream GetRawResourceStream(string path)
  591. {
  592. return _fileSystem.GetFileStream(GetDashboardResourcePath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  593. }
  594. }
  595. }