PackageCreator.cs 31 KB

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