DashboardService.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  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(), null, 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=\"application-name\" content=\"Media Browser\">");
  321. //sb.Append("<meta name=\"msapplication-config\" content=\"config.xml\">");
  322. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  323. sb.Append("<link rel=\"icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\" />");
  324. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  325. sb.Append("<link rel=\"apple-touch-icon\" href=\"css/images/touchicon.png\" />");
  326. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"css/images/touchicon72.png\" />");
  327. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\" />");
  328. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\" />");
  329. sb.Append("<link rel=\"shortcut icon\" href=\"css/images/favicon.ico\" />");
  330. return sb.ToString();
  331. }
  332. /// <summary>
  333. /// Gets the common CSS.
  334. /// </summary>
  335. /// <param name="version">The version.</param>
  336. /// <returns>System.String.</returns>
  337. private static string GetCommonCss(Version version)
  338. {
  339. var versionString = "?v=" + version;
  340. var files = new[]
  341. {
  342. "thirdparty/jquerymobile-1.4.2/jquery.mobile-1.4.2.min.css",
  343. "css/all.css" + versionString
  344. };
  345. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" />", s)).ToArray();
  346. return string.Join(string.Empty, tags);
  347. }
  348. /// <summary>
  349. /// Gets the common javascript.
  350. /// </summary>
  351. /// <param name="version">The version.</param>
  352. /// <returns>System.String.</returns>
  353. private static string GetCommonJavascript(Version version)
  354. {
  355. var builder = new StringBuilder();
  356. var versionString = "?v=" + version;
  357. var files = new[]
  358. {
  359. "scripts/all.js" + versionString,
  360. "thirdparty/jstree1.0/jquery.jstree.min.js",
  361. "thirdparty/jquery.unveil-custom.js",
  362. "https://www.gstatic.com/cv/js/sender/v1/cast_sender.js"
  363. };
  364. var tags = files.Select(s => string.Format("<script src=\"{0}\"></script>", s)).ToArray();
  365. builder.Append(string.Join(string.Empty, tags));
  366. return builder.ToString();
  367. }
  368. /// <summary>
  369. /// Gets a stream containing all concatenated javascript
  370. /// </summary>
  371. /// <returns>Task{Stream}.</returns>
  372. private async Task<Stream> GetAllJavascript()
  373. {
  374. var memoryStream = new MemoryStream();
  375. var newLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
  376. // jQuery + jQuery mobile
  377. await AppendResource(memoryStream, "thirdparty/jquery-2.0.3.min.js", newLineBytes).ConfigureAwait(false);
  378. await AppendResource(memoryStream, "thirdparty/jquerymobile-1.4.2/jquery.mobile-1.4.2.min.js", newLineBytes).ConfigureAwait(false);
  379. await AppendLocalization(memoryStream).ConfigureAwait(false);
  380. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  381. // Write the version string for the dashboard comparison function
  382. var versionString = string.Format("window.dashboardVersion='{0}';", _appHost.ApplicationVersion);
  383. var versionBytes = Encoding.UTF8.GetBytes(versionString);
  384. await memoryStream.WriteAsync(versionBytes, 0, versionBytes.Length).ConfigureAwait(false);
  385. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  386. var builder = new StringBuilder();
  387. using (var fs = _fileSystem.GetFileStream(GetDashboardResourcePath("thirdparty/mediabrowser.apiclient.js"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  388. {
  389. using (var streamReader = new StreamReader(fs))
  390. {
  391. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  392. builder.Append(text);
  393. builder.Append(Environment.NewLine);
  394. }
  395. }
  396. foreach (var file in GetScriptFiles())
  397. {
  398. var path = GetDashboardResourcePath("scripts/" + file);
  399. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  400. {
  401. using (var streamReader = new StreamReader(fs))
  402. {
  403. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  404. builder.Append(text);
  405. builder.Append(Environment.NewLine);
  406. }
  407. }
  408. }
  409. var js = builder.ToString();
  410. try
  411. {
  412. var result = new CrockfordJsMinifier().Minify(js, false, Encoding.UTF8);
  413. js = result.MinifiedContent;
  414. }
  415. catch (Exception ex)
  416. {
  417. Logger.ErrorException("Error minifying javascript", ex);
  418. }
  419. var bytes = Encoding.UTF8.GetBytes(js);
  420. await memoryStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  421. memoryStream.Position = 0;
  422. return memoryStream;
  423. }
  424. private IEnumerable<string> GetScriptFiles()
  425. {
  426. return new[]
  427. {
  428. "extensions.js",
  429. "site.js",
  430. "librarybrowser.js",
  431. "librarylist.js",
  432. "editorsidebar.js",
  433. "librarymenu.js",
  434. "mediacontroller.js",
  435. "chromecast.js",
  436. "backdrops.js",
  437. "mediaplayer.js",
  438. "mediaplayer-video.js",
  439. "nowplayingbar.js",
  440. "nowplayingpage.js",
  441. "ratingdialog.js",
  442. "aboutpage.js",
  443. "allusersettings.js",
  444. "alphapicker.js",
  445. "addpluginpage.js",
  446. "advancedconfigurationpage.js",
  447. "advancedpaths.js",
  448. "advancedserversettings.js",
  449. "metadataadvanced.js",
  450. "appsplayback.js",
  451. "appsweather.js",
  452. "autoorganizetv.js",
  453. "autoorganizelog.js",
  454. "channels.js",
  455. "channelitems.js",
  456. "dashboardgeneral.js",
  457. "dashboardinfo.js",
  458. "dashboardpage.js",
  459. "directorybrowser.js",
  460. "dlnaprofile.js",
  461. "dlnaprofiles.js",
  462. "dlnasettings.js",
  463. "dlnaserversettings.js",
  464. "editcollectionitems.js",
  465. "edititemmetadata.js",
  466. "edititemimages.js",
  467. "edititemsubtitles.js",
  468. "encodingsettings.js",
  469. "gamesrecommendedpage.js",
  470. "gamesystemspage.js",
  471. "gamespage.js",
  472. "gamegenrepage.js",
  473. "gamestudiospage.js",
  474. "indexpage.js",
  475. "itembynamedetailpage.js",
  476. "itemdetailpage.js",
  477. "itemgallery.js",
  478. "itemlistpage.js",
  479. "librarypathmapping.js",
  480. "reports.js",
  481. "librarysettings.js",
  482. "livetvchannel.js",
  483. "livetvchannels.js",
  484. "livetvguide.js",
  485. "livetvnewrecording.js",
  486. "livetvprogram.js",
  487. "livetvrecording.js",
  488. "livetvrecordinglist.js",
  489. "livetvrecordings.js",
  490. "livetvtimer.js",
  491. "livetvseriestimer.js",
  492. "livetvseriestimers.js",
  493. "livetvsettings.js",
  494. "livetvsuggested.js",
  495. "livetvstatus.js",
  496. "livetvtimers.js",
  497. "localsettings.js",
  498. "loginpage.js",
  499. "logpage.js",
  500. "medialibrarypage.js",
  501. "metadataconfigurationpage.js",
  502. "metadataimagespage.js",
  503. "metadatasubtitles.js",
  504. "moviegenres.js",
  505. "moviecollections.js",
  506. "movies.js",
  507. "movieslatest.js",
  508. "moviepeople.js",
  509. "moviesrecommended.js",
  510. "moviestudios.js",
  511. "movietrailers.js",
  512. "musicalbums.js",
  513. "musicalbumartists.js",
  514. "musicartists.js",
  515. "musicgenres.js",
  516. "musicrecommended.js",
  517. "musicvideos.js",
  518. "mypreferencesdisplay.js",
  519. "mypreferenceslanguages.js",
  520. "mypreferenceswebclient.js",
  521. "notifications.js",
  522. "notificationlist.js",
  523. "notificationsetting.js",
  524. "notificationsettings.js",
  525. "playlist.js",
  526. "plugincatalogpage.js",
  527. "pluginspage.js",
  528. "remotecontrol.js",
  529. "scheduledtaskpage.js",
  530. "scheduledtaskspage.js",
  531. "search.js",
  532. "songs.js",
  533. "supporterkeypage.js",
  534. "supporterpage.js",
  535. "episodes.js",
  536. "thememediaplayer.js",
  537. "tvgenres.js",
  538. "tvlatest.js",
  539. "tvpeople.js",
  540. "tvrecommended.js",
  541. "tvshows.js",
  542. "tvstudios.js",
  543. "tvupcoming.js",
  544. "useredit.js",
  545. "userpassword.js",
  546. "userimagepage.js",
  547. "userprofilespage.js",
  548. "userparentalcontrol.js",
  549. "wizardfinishpage.js",
  550. "wizardimagesettings.js",
  551. "wizardservice.js",
  552. "wizardstartpage.js",
  553. "wizardsettings.js",
  554. "wizarduserpage.js"
  555. };
  556. }
  557. private async Task AppendLocalization(Stream stream)
  558. {
  559. var js = "window.localizationGlossary=" + _jsonSerializer.SerializeToString(_localization.GetJavaScriptLocalizationDictionary(GetLocalizationCulture()));
  560. var bytes = Encoding.UTF8.GetBytes(js);
  561. await stream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  562. }
  563. /// <summary>
  564. /// Gets all CSS.
  565. /// </summary>
  566. /// <returns>Task{Stream}.</returns>
  567. private async Task<Stream> GetAllCss()
  568. {
  569. var files = new[]
  570. {
  571. "site.css",
  572. "chromecast.css",
  573. "contextmenu.css",
  574. "mediaplayer.css",
  575. "mediaplayer-video.css",
  576. "librarymenu.css",
  577. "librarybrowser.css",
  578. "detailtable.css",
  579. "posteritem.css",
  580. "tileitem.css",
  581. "metadataeditor.css",
  582. "notifications.css",
  583. "search.css",
  584. "pluginupdates.css",
  585. "remotecontrol.css",
  586. "userimage.css",
  587. "livetv.css",
  588. "nowplaying.css",
  589. "icons.css"
  590. };
  591. var builder = new StringBuilder();
  592. foreach (var file in files)
  593. {
  594. var path = GetDashboardResourcePath("css/" + file);
  595. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  596. {
  597. using (var streamReader = new StreamReader(fs))
  598. {
  599. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  600. builder.Append(text);
  601. builder.Append(Environment.NewLine);
  602. }
  603. }
  604. }
  605. var css = builder.ToString();
  606. //try
  607. //{
  608. // var result = new KristensenCssMinifier().Minify(builder.ToString(), false, Encoding.UTF8);
  609. // css = result.MinifiedContent;
  610. //}
  611. //catch (Exception ex)
  612. //{
  613. // Logger.ErrorException("Error minifying css", ex);
  614. //}
  615. var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(css));
  616. memoryStream.Position = 0;
  617. return memoryStream;
  618. }
  619. /// <summary>
  620. /// Appends the resource.
  621. /// </summary>
  622. /// <param name="outputStream">The output stream.</param>
  623. /// <param name="path">The path.</param>
  624. /// <param name="newLineBytes">The new line bytes.</param>
  625. /// <returns>Task.</returns>
  626. private async Task AppendResource(Stream outputStream, string path, byte[] newLineBytes)
  627. {
  628. path = GetDashboardResourcePath(path);
  629. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  630. {
  631. using (var streamReader = new StreamReader(fs))
  632. {
  633. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  634. var bytes = Encoding.UTF8.GetBytes(text);
  635. await outputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  636. }
  637. }
  638. await outputStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  639. }
  640. }
  641. }