PackageCreator.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. using System.Text.RegularExpressions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Localization;
  5. using MediaBrowser.Model.Logging;
  6. using MediaBrowser.Model.Serialization;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading.Tasks;
  13. using WebMarkupMin.Core;
  14. using WebMarkupMin.Core.Minifiers;
  15. using WebMarkupMin.Core.Settings;
  16. namespace MediaBrowser.WebDashboard.Api
  17. {
  18. public class PackageCreator
  19. {
  20. private readonly IFileSystem _fileSystem;
  21. private readonly ILocalizationManager _localization;
  22. private readonly ILogger _logger;
  23. private readonly IServerConfigurationManager _config;
  24. private readonly IJsonSerializer _jsonSerializer;
  25. public PackageCreator(IFileSystem fileSystem, ILocalizationManager localization, ILogger logger, IServerConfigurationManager config, IJsonSerializer jsonSerializer)
  26. {
  27. _fileSystem = fileSystem;
  28. _localization = localization;
  29. _logger = logger;
  30. _config = config;
  31. _jsonSerializer = jsonSerializer;
  32. }
  33. public async Task<Stream> GetResource(string path,
  34. string mode,
  35. string localizationCulture,
  36. string appVersion,
  37. bool enableMinification)
  38. {
  39. Stream resourceStream;
  40. if (path.Equals("scripts/all.js", StringComparison.OrdinalIgnoreCase))
  41. {
  42. resourceStream = await GetAllJavascript(mode, localizationCulture, appVersion, enableMinification).ConfigureAwait(false);
  43. enableMinification = false;
  44. }
  45. else if (path.Equals("css/all.css", StringComparison.OrdinalIgnoreCase))
  46. {
  47. resourceStream = await GetAllCss(enableMinification).ConfigureAwait(false);
  48. enableMinification = false;
  49. }
  50. else
  51. {
  52. resourceStream = GetRawResourceStream(path);
  53. }
  54. if (resourceStream != null)
  55. {
  56. // Don't apply any caching for html pages
  57. // jQuery ajax doesn't seem to handle if-modified-since correctly
  58. if (IsFormat(path, "html"))
  59. {
  60. if (path.IndexOf("cordovaindex.html", StringComparison.OrdinalIgnoreCase) == -1)
  61. {
  62. resourceStream = await ModifyHtml(resourceStream, mode, localizationCulture, enableMinification).ConfigureAwait(false);
  63. }
  64. }
  65. else if (IsFormat(path, "js"))
  66. {
  67. if (path.IndexOf("thirdparty", StringComparison.OrdinalIgnoreCase) == -1)
  68. {
  69. resourceStream = await ModifyJs(resourceStream, enableMinification).ConfigureAwait(false);
  70. }
  71. }
  72. else if (IsFormat(path, "css"))
  73. {
  74. if (path.IndexOf("thirdparty", StringComparison.OrdinalIgnoreCase) == -1)
  75. {
  76. resourceStream = await ModifyCss(resourceStream, enableMinification).ConfigureAwait(false);
  77. }
  78. }
  79. }
  80. return resourceStream;
  81. }
  82. /// <summary>
  83. /// Determines whether the specified path is HTML.
  84. /// </summary>
  85. /// <param name="path">The path.</param>
  86. /// <param name="format">The format.</param>
  87. /// <returns><c>true</c> if the specified path is HTML; otherwise, <c>false</c>.</returns>
  88. private bool IsFormat(string path, string format)
  89. {
  90. return Path.GetExtension(path).EndsWith(format, StringComparison.OrdinalIgnoreCase);
  91. }
  92. /// <summary>
  93. /// Gets the dashboard UI path.
  94. /// </summary>
  95. /// <value>The dashboard UI path.</value>
  96. public string DashboardUIPath
  97. {
  98. get
  99. {
  100. if (!string.IsNullOrEmpty(_config.Configuration.DashboardSourcePath))
  101. {
  102. return _config.Configuration.DashboardSourcePath;
  103. }
  104. return Path.Combine(_config.ApplicationPaths.ApplicationResourcesPath, "dashboard-ui");
  105. }
  106. }
  107. /// <summary>
  108. /// Gets the dashboard resource path.
  109. /// </summary>
  110. /// <param name="virtualPath">The virtual path.</param>
  111. /// <returns>System.String.</returns>
  112. private string GetDashboardResourcePath(string virtualPath)
  113. {
  114. var rootPath = DashboardUIPath;
  115. var fullPath = Path.Combine(rootPath, virtualPath.Replace('/', Path.DirectorySeparatorChar));
  116. // Don't allow file system access outside of the source folder
  117. if (!_fileSystem.ContainsSubPath(rootPath, fullPath))
  118. {
  119. throw new UnauthorizedAccessException();
  120. }
  121. return fullPath;
  122. }
  123. public async Task<Stream> ModifyCss(Stream sourceStream, bool enableMinification)
  124. {
  125. using (sourceStream)
  126. {
  127. string content;
  128. using (var memoryStream = new MemoryStream())
  129. {
  130. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  131. content = Encoding.UTF8.GetString(memoryStream.ToArray());
  132. if (enableMinification)
  133. {
  134. try
  135. {
  136. var result = new KristensenCssMinifier().Minify(content, false, Encoding.UTF8);
  137. if (result.Errors.Count > 0)
  138. {
  139. _logger.Error("Error minifying css: " + result.Errors[0].Message);
  140. }
  141. else
  142. {
  143. content = result.MinifiedContent;
  144. }
  145. }
  146. catch (Exception ex)
  147. {
  148. _logger.ErrorException("Error minifying css", ex);
  149. }
  150. }
  151. }
  152. var bytes = Encoding.UTF8.GetBytes(content);
  153. return new MemoryStream(bytes);
  154. }
  155. }
  156. public async Task<Stream> ModifyJs(Stream sourceStream, bool enableMinification)
  157. {
  158. using (sourceStream)
  159. {
  160. string content;
  161. using (var memoryStream = new MemoryStream())
  162. {
  163. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  164. content = Encoding.UTF8.GetString(memoryStream.ToArray());
  165. if (enableMinification)
  166. {
  167. try
  168. {
  169. var result = new CrockfordJsMinifier().Minify(content, false, Encoding.UTF8);
  170. if (result.Errors.Count > 0)
  171. {
  172. _logger.Error("Error minifying javascript: " + result.Errors[0].Message);
  173. }
  174. else
  175. {
  176. content = result.MinifiedContent;
  177. }
  178. }
  179. catch (Exception ex)
  180. {
  181. _logger.ErrorException("Error minifying javascript", ex);
  182. }
  183. }
  184. }
  185. var bytes = Encoding.UTF8.GetBytes(content);
  186. return new MemoryStream(bytes);
  187. }
  188. }
  189. /// <summary>
  190. /// Modifies the HTML by adding common meta tags, css and js.
  191. /// </summary>
  192. /// <param name="sourceStream">The source stream.</param>
  193. /// <param name="mode">The mode.</param>
  194. /// <param name="localizationCulture">The localization culture.</param>
  195. /// <param name="enableMinification">if set to <c>true</c> [enable minification].</param>
  196. /// <returns>Task{Stream}.</returns>
  197. public async Task<Stream> ModifyHtml(Stream sourceStream, string mode, string localizationCulture, bool enableMinification)
  198. {
  199. using (sourceStream)
  200. {
  201. string html;
  202. using (var memoryStream = new MemoryStream())
  203. {
  204. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  205. html = Encoding.UTF8.GetString(memoryStream.ToArray());
  206. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  207. {
  208. html = ModifyForCordova(html);
  209. }
  210. if (!string.IsNullOrWhiteSpace(localizationCulture))
  211. {
  212. var lang = localizationCulture.Split('-').FirstOrDefault();
  213. html = _localization.LocalizeDocument(html, localizationCulture, GetLocalizationToken);
  214. html = html.Replace("<html>", "<html lang=\"" + lang + "\">");
  215. }
  216. if (enableMinification)
  217. {
  218. try
  219. {
  220. var minifier = new HtmlMinifier(new HtmlMinificationSettings
  221. {
  222. AttributeQuotesRemovalMode = HtmlAttributeQuotesRemovalMode.KeepQuotes,
  223. RemoveOptionalEndTags = false,
  224. RemoveTagsWithoutContent = false
  225. });
  226. var result = minifier.Minify(html, false);
  227. if (result.Errors.Count > 0)
  228. {
  229. _logger.Error("Error minifying html: " + result.Errors[0].Message);
  230. }
  231. else
  232. {
  233. html = result.MinifiedContent;
  234. }
  235. }
  236. catch (Exception ex)
  237. {
  238. _logger.ErrorException("Error minifying html", ex);
  239. }
  240. }
  241. }
  242. var version = GetType().Assembly.GetName().Version;
  243. html = html.Replace("<head>", "<head>" + GetMetaTags(mode) + GetCommonCss(mode, version) + GetCommonJavascript(mode, version));
  244. var bytes = Encoding.UTF8.GetBytes(html);
  245. return new MemoryStream(bytes);
  246. }
  247. }
  248. private string ModifyForCordova(string html)
  249. {
  250. // Strip everything between CORDOVA_EXCLUDE_START and CORDOVA_EXCLUDE_END
  251. html = ReplaceBetween(html, "<!--CORDOVA_EXCLUDE_START-->", "<!--CORDOVA_EXCLUDE_END-->", string.Empty);
  252. // Replace CORDOVA_REPLACE_SUPPORTER_SUBMIT_START
  253. html = ReplaceBetween(html, "<!--CORDOVA_REPLACE_SUPPORTER_SUBMIT_START-->", "<!--CORDOVA_REPLACE_SUPPORTER_SUBMIT_END-->", "<i class=\"fa fa-check\"></i><span>${ButtonDonate}</span>");
  254. return html;
  255. }
  256. private string ReplaceBetween(string html, string startToken, string endToken, string newHtml)
  257. {
  258. var start = html.IndexOf(startToken, StringComparison.OrdinalIgnoreCase);
  259. var end = html.IndexOf(endToken, StringComparison.OrdinalIgnoreCase);
  260. if (start == -1 || end == -1)
  261. {
  262. return html;
  263. }
  264. string result = html.Substring(start + 1, end - start - 1);
  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. if (string.Equals(mode, "cordova", StringComparison.OrdinalIgnoreCase))
  399. {
  400. apiClientFiles.Add("thirdparty/cordova/remotecontrols.js");
  401. }
  402. foreach (var file in apiClientFiles)
  403. {
  404. using (var fs = _fileSystem.GetFileStream(GetDashboardResourcePath(file), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  405. {
  406. using (var streamReader = new StreamReader(fs))
  407. {
  408. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  409. builder.Append(text);
  410. builder.Append(Environment.NewLine);
  411. }
  412. }
  413. }
  414. foreach (var file in GetScriptFiles())
  415. {
  416. var path = GetDashboardResourcePath("scripts/" + file);
  417. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  418. {
  419. using (var streamReader = new StreamReader(fs))
  420. {
  421. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  422. builder.Append(text);
  423. builder.Append(Environment.NewLine);
  424. }
  425. }
  426. }
  427. var js = builder.ToString();
  428. if (enableMinification)
  429. {
  430. try
  431. {
  432. var result = new CrockfordJsMinifier().Minify(js, false, Encoding.UTF8);
  433. if (result.Errors.Count > 0)
  434. {
  435. _logger.Error("Error minifying javascript: " + result.Errors[0].Message);
  436. }
  437. else
  438. {
  439. js = result.MinifiedContent;
  440. }
  441. }
  442. catch (Exception ex)
  443. {
  444. _logger.ErrorException("Error minifying javascript", ex);
  445. }
  446. }
  447. var bytes = Encoding.UTF8.GetBytes(js);
  448. await memoryStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  449. memoryStream.Position = 0;
  450. return memoryStream;
  451. }
  452. private IEnumerable<string> GetScriptFiles()
  453. {
  454. return new[]
  455. {
  456. "extensions.js",
  457. "site.js",
  458. "librarybrowser.js",
  459. "librarylist.js",
  460. "editorsidebar.js",
  461. "librarymenu.js",
  462. "mediacontroller.js",
  463. "chromecast.js",
  464. "backdrops.js",
  465. "sync.js",
  466. "syncjob.js",
  467. "appservices.js",
  468. "playlistmanager.js",
  469. "mediaplayer.js",
  470. "mediaplayer-video.js",
  471. "nowplayingbar.js",
  472. "nowplayingpage.js",
  473. "taskbutton.js",
  474. "ratingdialog.js",
  475. "alphapicker.js",
  476. "addpluginpage.js",
  477. "metadataadvanced.js",
  478. "autoorganizetv.js",
  479. "autoorganizelog.js",
  480. "channelslatest.js",
  481. "channelitems.js",
  482. "channelsettings.js",
  483. "connectlogin.js",
  484. "dashboardgeneral.js",
  485. "dashboardpage.js",
  486. "devicesupload.js",
  487. "directorybrowser.js",
  488. "dlnaprofile.js",
  489. "dlnaprofiles.js",
  490. "dlnasettings.js",
  491. "dlnaserversettings.js",
  492. "editcollectionitems.js",
  493. "edititemmetadata.js",
  494. "edititemimages.js",
  495. "edititemsubtitles.js",
  496. "playbackconfiguration.js",
  497. "cinemamodeconfiguration.js",
  498. "encodingsettings.js",
  499. "externalplayer.js",
  500. "favorites.js",
  501. "forgotpassword.js",
  502. "forgotpasswordpin.js",
  503. "homelatest.js",
  504. "indexpage.js",
  505. "itembynamedetailpage.js",
  506. "itemdetailpage.js",
  507. "kids.js",
  508. "librarypathmapping.js",
  509. "reports.js",
  510. "librarysettings.js",
  511. "livetvchannel.js",
  512. "livetvguide.js",
  513. "livetvnewrecording.js",
  514. "livetvprogram.js",
  515. "livetvrecording.js",
  516. "livetvrecordinglist.js",
  517. "livetvtimer.js",
  518. "livetvseriestimer.js",
  519. "livetvsettings.js",
  520. "livetvstatus.js",
  521. "loginpage.js",
  522. "medialibrarypage.js",
  523. "metadataconfigurationpage.js",
  524. "metadataimagespage.js",
  525. "metadatasubtitles.js",
  526. "metadatanfo.js",
  527. "moviecollections.js",
  528. "mypreferencesdisplay.js",
  529. "mypreferenceslanguages.js",
  530. "mypreferenceswebclient.js",
  531. "notifications.js",
  532. "notificationlist.js",
  533. "notificationsetting.js",
  534. "notificationsettings.js",
  535. "playlists.js",
  536. "playlistedit.js",
  537. "plugincatalogpage.js",
  538. "pluginspage.js",
  539. "remotecontrol.js",
  540. "scheduledtaskpage.js",
  541. "scheduledtaskspage.js",
  542. "search.js",
  543. "selectserver.js",
  544. "supporterkeypage.js",
  545. "syncactivity.js",
  546. "syncsettings.js",
  547. "thememediaplayer.js",
  548. "useredit.js",
  549. "myprofile.js",
  550. "userpassword.js",
  551. "userprofilespage.js",
  552. "userparentalcontrol.js",
  553. "userlibraryaccess.js",
  554. "wizardagreement.js",
  555. "wizardfinishpage.js",
  556. "wizardservice.js",
  557. "wizardstartpage.js",
  558. "wizardsettings.js",
  559. "wizarduserpage.js"
  560. };
  561. }
  562. private async Task AppendLocalization(Stream stream, string culture, List<string> excludePhrases)
  563. {
  564. var dictionary = _localization.GetJavaScriptLocalizationDictionary(culture);
  565. if (excludePhrases.Count > 0)
  566. {
  567. var removes = new List<string>();
  568. foreach (var pair in dictionary)
  569. {
  570. if (excludePhrases.Any(i => pair.Key.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1 || pair.Value.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1))
  571. {
  572. removes.Add(pair.Key);
  573. }
  574. }
  575. foreach (var remove in removes)
  576. {
  577. dictionary.Remove(remove);
  578. }
  579. }
  580. var js = "window.localizationGlossary=" + _jsonSerializer.SerializeToString(dictionary);
  581. var bytes = Encoding.UTF8.GetBytes(js);
  582. await stream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  583. }
  584. /// <summary>
  585. /// Appends the resource.
  586. /// </summary>
  587. /// <param name="outputStream">The output stream.</param>
  588. /// <param name="path">The path.</param>
  589. /// <param name="newLineBytes">The new line bytes.</param>
  590. /// <returns>Task.</returns>
  591. private async Task AppendResource(Stream outputStream, string path, byte[] newLineBytes)
  592. {
  593. path = GetDashboardResourcePath(path);
  594. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  595. {
  596. using (var streamReader = new StreamReader(fs))
  597. {
  598. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  599. var bytes = Encoding.UTF8.GetBytes(text);
  600. await outputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  601. }
  602. }
  603. await outputStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  604. }
  605. /// <summary>
  606. /// Gets all CSS.
  607. /// </summary>
  608. /// <returns>Task{Stream}.</returns>
  609. private async Task<Stream> GetAllCss(bool enableMinification)
  610. {
  611. var files = new[]
  612. {
  613. "site.css",
  614. "chromecast.css",
  615. "mediaplayer.css",
  616. "mediaplayer-video.css",
  617. "librarymenu.css",
  618. "librarybrowser.css",
  619. "detailtable.css",
  620. "card.css",
  621. "tileitem.css",
  622. "metadataeditor.css",
  623. "notifications.css",
  624. "search.css",
  625. "pluginupdates.css",
  626. "remotecontrol.css",
  627. "userimage.css",
  628. "livetv.css",
  629. "nowplaying.css",
  630. "icons.css",
  631. "materialize.css"
  632. };
  633. var builder = new StringBuilder();
  634. foreach (var file in files)
  635. {
  636. var path = GetDashboardResourcePath("css/" + file);
  637. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  638. {
  639. using (var streamReader = new StreamReader(fs))
  640. {
  641. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  642. builder.Append(text);
  643. builder.Append(Environment.NewLine);
  644. }
  645. }
  646. }
  647. var css = builder.ToString();
  648. if (enableMinification)
  649. {
  650. try
  651. {
  652. var result = new KristensenCssMinifier().Minify(builder.ToString(), false, Encoding.UTF8);
  653. if (result.Errors.Count > 0)
  654. {
  655. _logger.Error("Error minifying css: " + result.Errors[0].Message);
  656. }
  657. else
  658. {
  659. css = result.MinifiedContent;
  660. }
  661. }
  662. catch (Exception ex)
  663. {
  664. _logger.ErrorException("Error minifying css", ex);
  665. }
  666. }
  667. var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(css));
  668. memoryStream.Position = 0;
  669. return memoryStream;
  670. }
  671. /// <summary>
  672. /// Gets the raw resource stream.
  673. /// </summary>
  674. /// <param name="path">The path.</param>
  675. /// <returns>Task{Stream}.</returns>
  676. private Stream GetRawResourceStream(string path)
  677. {
  678. return _fileSystem.GetFileStream(GetDashboardResourcePath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  679. }
  680. }
  681. }