2
0

DashboardService.cs 29 KB

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