PackageCreator.cs 33 KB

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