DashboardService.cs 31 KB

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