DashboardService.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  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. path = path.Replace("scripts/jquery.mobile-1.4.3.min.map", "thirdparty/jquerymobile-1.4.3/jquery.mobile-1.4.3.min.map", StringComparison.OrdinalIgnoreCase);
  205. var localizationCulture = GetLocalizationCulture();
  206. // Don't cache if not configured to do so
  207. // But always cache images to simulate production
  208. if (!_serverConfigurationManager.Configuration.EnableDashboardResponseCaching &&
  209. !contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) &&
  210. !contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase))
  211. {
  212. return ResultFactory.GetResult(GetResourceStream(path, isHtml, localizationCulture).Result, contentType);
  213. }
  214. TimeSpan? cacheDuration = null;
  215. // Cache images unconditionally - updates to image files will require new filename
  216. // If there's a version number in the query string we can cache this unconditionally
  217. if (contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("font/", StringComparison.OrdinalIgnoreCase) || !string.IsNullOrEmpty(request.V))
  218. {
  219. cacheDuration = TimeSpan.FromDays(365);
  220. }
  221. var assembly = GetType().Assembly.GetName();
  222. var cacheKey = (assembly.Version + (localizationCulture ?? string.Empty) + path).GetMD5();
  223. return ResultFactory.GetStaticResult(Request, cacheKey, null, cacheDuration, contentType, () => GetResourceStream(path, isHtml, localizationCulture));
  224. }
  225. private string GetLocalizationCulture()
  226. {
  227. return _serverConfigurationManager.Configuration.UICulture;
  228. }
  229. /// <summary>
  230. /// Gets the resource stream.
  231. /// </summary>
  232. /// <param name="path">The path.</param>
  233. /// <param name="isHtml">if set to <c>true</c> [is HTML].</param>
  234. /// <param name="localizationCulture">The localization culture.</param>
  235. /// <returns>Task{Stream}.</returns>
  236. private async Task<Stream> GetResourceStream(string path, bool isHtml, string localizationCulture)
  237. {
  238. Stream resourceStream;
  239. if (path.Equals("scripts/all.js", StringComparison.OrdinalIgnoreCase))
  240. {
  241. resourceStream = await GetAllJavascript().ConfigureAwait(false);
  242. }
  243. else if (path.Equals("css/all.css", StringComparison.OrdinalIgnoreCase))
  244. {
  245. resourceStream = await GetAllCss().ConfigureAwait(false);
  246. }
  247. else
  248. {
  249. resourceStream = GetRawResourceStream(path);
  250. }
  251. if (resourceStream != null)
  252. {
  253. // Don't apply any caching for html pages
  254. // jQuery ajax doesn't seem to handle if-modified-since correctly
  255. if (isHtml)
  256. {
  257. resourceStream = await ModifyHtml(resourceStream, localizationCulture).ConfigureAwait(false);
  258. }
  259. }
  260. return resourceStream;
  261. }
  262. /// <summary>
  263. /// Gets the raw resource stream.
  264. /// </summary>
  265. /// <param name="path">The path.</param>
  266. /// <returns>Task{Stream}.</returns>
  267. private Stream GetRawResourceStream(string path)
  268. {
  269. return _fileSystem.GetFileStream(GetDashboardResourcePath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  270. }
  271. /// <summary>
  272. /// Determines whether the specified path is HTML.
  273. /// </summary>
  274. /// <param name="path">The path.</param>
  275. /// <returns><c>true</c> if the specified path is HTML; otherwise, <c>false</c>.</returns>
  276. private bool IsHtml(string path)
  277. {
  278. return Path.GetExtension(path).EndsWith("html", StringComparison.OrdinalIgnoreCase);
  279. }
  280. /// <summary>
  281. /// Modifies the HTML by adding common meta tags, css and js.
  282. /// </summary>
  283. /// <param name="sourceStream">The source stream.</param>
  284. /// <param name="userId">The user identifier.</param>
  285. /// <param name="localizationCulture">The localization culture.</param>
  286. /// <returns>Task{Stream}.</returns>
  287. private async Task<Stream> ModifyHtml(Stream sourceStream, string localizationCulture)
  288. {
  289. using (sourceStream)
  290. {
  291. string html;
  292. using (var memoryStream = new MemoryStream())
  293. {
  294. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  295. html = Encoding.UTF8.GetString(memoryStream.ToArray());
  296. if (!string.IsNullOrWhiteSpace(localizationCulture))
  297. {
  298. var lang = localizationCulture.Split('-').FirstOrDefault();
  299. html = _localization.LocalizeDocument(html, localizationCulture, GetLocalizationToken);
  300. html = html.Replace("<html>", "<html lang=\"" + lang + "\">");
  301. }
  302. //try
  303. //{
  304. // var minifier = new HtmlMinifier(new HtmlMinificationSettings(true));
  305. // html = minifier.Minify(html).MinifiedContent;
  306. //}
  307. //catch (Exception ex)
  308. //{
  309. // Logger.ErrorException("Error minifying html", ex);
  310. //}
  311. }
  312. var version = GetType().Assembly.GetName().Version;
  313. html = html.Replace("<head>", "<head>" + GetMetaTags() + GetCommonCss(version) + GetCommonJavascript(version));
  314. var bytes = Encoding.UTF8.GetBytes(html);
  315. return new MemoryStream(bytes);
  316. }
  317. }
  318. private string GetLocalizationToken(string phrase)
  319. {
  320. return "${" + phrase + "}";
  321. }
  322. /// <summary>
  323. /// Gets the meta tags.
  324. /// </summary>
  325. /// <returns>System.String.</returns>
  326. private static string GetMetaTags()
  327. {
  328. var sb = new StringBuilder();
  329. sb.Append("<meta http-equiv=\"X-UA-Compatibility\" content=\"IE=Edge\">");
  330. sb.Append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">");
  331. //sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  332. sb.Append("<meta name=\"mobile-web-app-capable\" content=\"yes\">");
  333. sb.Append("<meta name=\"application-name\" content=\"Media Browser\">");
  334. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  335. sb.Append("<link rel=\"icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\" />");
  336. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  337. sb.Append("<link rel=\"apple-touch-icon\" href=\"css/images/touchicon.png\" />");
  338. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"css/images/touchicon72.png\" />");
  339. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\" />");
  340. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\" />");
  341. sb.Append("<link rel=\"shortcut icon\" href=\"css/images/favicon.ico\" />");
  342. return sb.ToString();
  343. }
  344. /// <summary>
  345. /// Gets the common CSS.
  346. /// </summary>
  347. /// <param name="version">The version.</param>
  348. /// <returns>System.String.</returns>
  349. private static string GetCommonCss(Version version)
  350. {
  351. var versionString = "?v=" + version;
  352. var files = new[]
  353. {
  354. "thirdparty/jquerymobile-1.4.3/jquery.mobile-1.4.3.min.css",
  355. "css/all.css" + versionString
  356. };
  357. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" />", s)).ToArray();
  358. return string.Join(string.Empty, tags);
  359. }
  360. /// <summary>
  361. /// Gets the common javascript.
  362. /// </summary>
  363. /// <param name="version">The version.</param>
  364. /// <returns>System.String.</returns>
  365. private static string GetCommonJavascript(Version version)
  366. {
  367. var builder = new StringBuilder();
  368. var versionString = "?v=" + version;
  369. var files = new[]
  370. {
  371. "scripts/all.js" + versionString,
  372. "thirdparty/jstree1.0/jquery.jstree.min.js"
  373. };
  374. var tags = files.Select(s => string.Format("<script src=\"{0}\"></script>", s)).ToArray();
  375. builder.Append(string.Join(string.Empty, tags));
  376. return builder.ToString();
  377. }
  378. /// <summary>
  379. /// Gets a stream containing all concatenated javascript
  380. /// </summary>
  381. /// <returns>Task{Stream}.</returns>
  382. private async Task<Stream> GetAllJavascript()
  383. {
  384. var memoryStream = new MemoryStream();
  385. var newLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
  386. // jQuery + jQuery mobile
  387. await AppendResource(memoryStream, "thirdparty/jquery-2.1.1.min.js", newLineBytes).ConfigureAwait(false);
  388. await AppendResource(memoryStream, "thirdparty/jquerymobile-1.4.3/jquery.mobile-1.4.3.min.js", newLineBytes).ConfigureAwait(false);
  389. await AppendResource(memoryStream, "thirdparty/jquery.unveil-custom.js", newLineBytes).ConfigureAwait(false);
  390. // This script produces errors in older versions of safari
  391. if ((Request.UserAgent ?? string.Empty).IndexOf("chrome/", StringComparison.OrdinalIgnoreCase) != -1)
  392. {
  393. await AppendResource(memoryStream, "thirdparty/cast_sender.js", newLineBytes).ConfigureAwait(false);
  394. }
  395. await AppendLocalization(memoryStream).ConfigureAwait(false);
  396. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  397. // Write the version string for the dashboard comparison function
  398. var versionString = string.Format("window.dashboardVersion='{0}';", _appHost.ApplicationVersion);
  399. var versionBytes = Encoding.UTF8.GetBytes(versionString);
  400. await memoryStream.WriteAsync(versionBytes, 0, versionBytes.Length).ConfigureAwait(false);
  401. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  402. var builder = new StringBuilder();
  403. using (var fs = _fileSystem.GetFileStream(GetDashboardResourcePath("thirdparty/mediabrowser.apiclient.js"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  404. {
  405. using (var streamReader = new StreamReader(fs))
  406. {
  407. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  408. builder.Append(text);
  409. builder.Append(Environment.NewLine);
  410. }
  411. }
  412. foreach (var file in GetScriptFiles())
  413. {
  414. var path = GetDashboardResourcePath("scripts/" + file);
  415. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  416. {
  417. using (var streamReader = new StreamReader(fs))
  418. {
  419. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  420. builder.Append(text);
  421. builder.Append(Environment.NewLine);
  422. }
  423. }
  424. }
  425. var js = builder.ToString();
  426. try
  427. {
  428. var result = new CrockfordJsMinifier().Minify(js, false, Encoding.UTF8);
  429. js = result.MinifiedContent;
  430. }
  431. catch (Exception ex)
  432. {
  433. Logger.ErrorException("Error minifying javascript", ex);
  434. }
  435. var bytes = Encoding.UTF8.GetBytes(js);
  436. await memoryStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  437. memoryStream.Position = 0;
  438. return memoryStream;
  439. }
  440. private IEnumerable<string> GetScriptFiles()
  441. {
  442. return new[]
  443. {
  444. "extensions.js",
  445. "site.js",
  446. "librarybrowser.js",
  447. "librarylist.js",
  448. "editorsidebar.js",
  449. "librarymenu.js",
  450. "mediacontroller.js",
  451. "chromecast.js",
  452. "backdrops.js",
  453. "sync.js",
  454. "playlistmanager.js",
  455. "mediaplayer.js",
  456. "mediaplayer-video.js",
  457. "nowplayingbar.js",
  458. "nowplayingpage.js",
  459. "ratingdialog.js",
  460. "aboutpage.js",
  461. "alphapicker.js",
  462. "addpluginpage.js",
  463. "advancedconfigurationpage.js",
  464. "metadataadvanced.js",
  465. "autoorganizetv.js",
  466. "autoorganizelog.js",
  467. "channels.js",
  468. "channelslatest.js",
  469. "channelitems.js",
  470. "channelsettings.js",
  471. "dashboardgeneral.js",
  472. "dashboardpage.js",
  473. "dashboardsync.js",
  474. "directorybrowser.js",
  475. "dlnaprofile.js",
  476. "dlnaprofiles.js",
  477. "dlnasettings.js",
  478. "dlnaserversettings.js",
  479. "editcollectionitems.js",
  480. "edititemmetadata.js",
  481. "edititemimages.js",
  482. "edititemsubtitles.js",
  483. "encodingsettings.js",
  484. "favorites.js",
  485. "gamesrecommendedpage.js",
  486. "gamesystemspage.js",
  487. "gamespage.js",
  488. "gamegenrepage.js",
  489. "gamestudiospage.js",
  490. "homelatest.js",
  491. "indexpage.js",
  492. "itembynamedetailpage.js",
  493. "itemdetailpage.js",
  494. "itemgallery.js",
  495. "itemlistpage.js",
  496. "librarypathmapping.js",
  497. "reports.js",
  498. "librarysettings.js",
  499. "livetvchannel.js",
  500. "livetvchannels.js",
  501. "livetvguide.js",
  502. "livetvnewrecording.js",
  503. "livetvprogram.js",
  504. "livetvrecording.js",
  505. "livetvrecordinglist.js",
  506. "livetvrecordings.js",
  507. "livetvtimer.js",
  508. "livetvseriestimer.js",
  509. "livetvseriestimers.js",
  510. "livetvsettings.js",
  511. "livetvsuggested.js",
  512. "livetvstatus.js",
  513. "livetvtimers.js",
  514. "loginpage.js",
  515. "logpage.js",
  516. "medialibrarypage.js",
  517. "metadataconfigurationpage.js",
  518. "metadataimagespage.js",
  519. "metadatasubtitles.js",
  520. "metadataxbmc.js",
  521. "moviegenres.js",
  522. "moviecollections.js",
  523. "movies.js",
  524. "movieslatest.js",
  525. "moviepeople.js",
  526. "moviesrecommended.js",
  527. "moviestudios.js",
  528. "movietrailers.js",
  529. "musicalbums.js",
  530. "musicalbumartists.js",
  531. "musicartists.js",
  532. "musicgenres.js",
  533. "musicrecommended.js",
  534. "musicvideos.js",
  535. "mypreferencesdisplay.js",
  536. "mypreferenceslanguages.js",
  537. "mypreferenceswebclient.js",
  538. "notifications.js",
  539. "notificationlist.js",
  540. "notificationsetting.js",
  541. "notificationsettings.js",
  542. "playlist.js",
  543. "playlists.js",
  544. "playlistedit.js",
  545. "plugincatalogpage.js",
  546. "pluginspage.js",
  547. "remotecontrol.js",
  548. "scheduledtaskpage.js",
  549. "scheduledtaskspage.js",
  550. "search.js",
  551. "serversecurity.js",
  552. "songs.js",
  553. "supporterkeypage.js",
  554. "supporterpage.js",
  555. "episodes.js",
  556. "thememediaplayer.js",
  557. "tvgenres.js",
  558. "tvlatest.js",
  559. "tvpeople.js",
  560. "tvrecommended.js",
  561. "tvshows.js",
  562. "tvstudios.js",
  563. "tvupcoming.js",
  564. "useredit.js",
  565. "userpassword.js",
  566. "userimagepage.js",
  567. "userprofilespage.js",
  568. "userparentalcontrol.js",
  569. "wizardfinishpage.js",
  570. "wizardservice.js",
  571. "wizardstartpage.js",
  572. "wizardsettings.js",
  573. "wizarduserpage.js"
  574. };
  575. }
  576. private async Task AppendLocalization(Stream stream)
  577. {
  578. var js = "window.localizationGlossary=" + _jsonSerializer.SerializeToString(_localization.GetJavaScriptLocalizationDictionary(GetLocalizationCulture()));
  579. var bytes = Encoding.UTF8.GetBytes(js);
  580. await stream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  581. }
  582. /// <summary>
  583. /// Gets all CSS.
  584. /// </summary>
  585. /// <returns>Task{Stream}.</returns>
  586. private async Task<Stream> GetAllCss()
  587. {
  588. var files = new[]
  589. {
  590. "site.css",
  591. "chromecast.css",
  592. "mediaplayer.css",
  593. "mediaplayer-video.css",
  594. "librarymenu.css",
  595. "librarybrowser.css",
  596. "detailtable.css",
  597. "card.css",
  598. "tileitem.css",
  599. "metadataeditor.css",
  600. "notifications.css",
  601. "search.css",
  602. "pluginupdates.css",
  603. "remotecontrol.css",
  604. "userimage.css",
  605. "livetv.css",
  606. "nowplaying.css",
  607. "icons.css"
  608. };
  609. var builder = new StringBuilder();
  610. foreach (var file in files)
  611. {
  612. var path = GetDashboardResourcePath("css/" + file);
  613. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  614. {
  615. using (var streamReader = new StreamReader(fs))
  616. {
  617. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  618. builder.Append(text);
  619. builder.Append(Environment.NewLine);
  620. }
  621. }
  622. }
  623. var css = builder.ToString();
  624. //try
  625. //{
  626. // var result = new KristensenCssMinifier().Minify(builder.ToString(), false, Encoding.UTF8);
  627. // css = result.MinifiedContent;
  628. //}
  629. //catch (Exception ex)
  630. //{
  631. // Logger.ErrorException("Error minifying css", ex);
  632. //}
  633. var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(css));
  634. memoryStream.Position = 0;
  635. return memoryStream;
  636. }
  637. /// <summary>
  638. /// Appends the resource.
  639. /// </summary>
  640. /// <param name="outputStream">The output stream.</param>
  641. /// <param name="path">The path.</param>
  642. /// <param name="newLineBytes">The new line bytes.</param>
  643. /// <returns>Task.</returns>
  644. private async Task AppendResource(Stream outputStream, string path, byte[] newLineBytes)
  645. {
  646. path = GetDashboardResourcePath(path);
  647. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  648. {
  649. using (var streamReader = new StreamReader(fs))
  650. {
  651. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  652. var bytes = Encoding.UTF8.GetBytes(text);
  653. await outputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  654. }
  655. }
  656. await outputStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  657. }
  658. }
  659. }