PackageCreator.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  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.Minifiers;
  13. using WebMarkupMin.Core.Settings;
  14. namespace MediaBrowser.WebDashboard.Api
  15. {
  16. public class PackageCreator
  17. {
  18. private readonly IFileSystem _fileSystem;
  19. private readonly ILocalizationManager _localization;
  20. private readonly ILogger _logger;
  21. private readonly IServerConfigurationManager _config;
  22. private readonly IJsonSerializer _jsonSerializer;
  23. public PackageCreator(IFileSystem fileSystem, ILocalizationManager localization, ILogger logger, IServerConfigurationManager config, IJsonSerializer jsonSerializer)
  24. {
  25. _fileSystem = fileSystem;
  26. _localization = localization;
  27. _logger = logger;
  28. _config = config;
  29. _jsonSerializer = jsonSerializer;
  30. }
  31. public async Task<Stream> GetResource(string path,
  32. string localizationCulture,
  33. string appVersion, bool enableMinification)
  34. {
  35. var isHtml = IsHtml(path);
  36. Stream resourceStream;
  37. if (path.Equals("scripts/all.js", StringComparison.OrdinalIgnoreCase))
  38. {
  39. resourceStream = await GetAllJavascript(localizationCulture, appVersion, enableMinification).ConfigureAwait(false);
  40. }
  41. else if (path.Equals("css/all.css", StringComparison.OrdinalIgnoreCase))
  42. {
  43. resourceStream = await GetAllCss(enableMinification).ConfigureAwait(false);
  44. }
  45. else
  46. {
  47. resourceStream = GetRawResourceStream(path);
  48. }
  49. if (resourceStream != null)
  50. {
  51. // Don't apply any caching for html pages
  52. // jQuery ajax doesn't seem to handle if-modified-since correctly
  53. if (isHtml)
  54. {
  55. resourceStream = await ModifyHtml(resourceStream, localizationCulture, enableMinification).ConfigureAwait(false);
  56. }
  57. }
  58. return resourceStream;
  59. }
  60. /// <summary>
  61. /// Determines whether the specified path is HTML.
  62. /// </summary>
  63. /// <param name="path">The path.</param>
  64. /// <returns><c>true</c> if the specified path is HTML; otherwise, <c>false</c>.</returns>
  65. private bool IsHtml(string path)
  66. {
  67. return Path.GetExtension(path).EndsWith("html", StringComparison.OrdinalIgnoreCase);
  68. }
  69. /// <summary>
  70. /// Gets the dashboard UI path.
  71. /// </summary>
  72. /// <value>The dashboard UI path.</value>
  73. public string DashboardUIPath
  74. {
  75. get
  76. {
  77. if (!string.IsNullOrEmpty(_config.Configuration.DashboardSourcePath))
  78. {
  79. return _config.Configuration.DashboardSourcePath;
  80. }
  81. return Path.Combine(_config.ApplicationPaths.ApplicationResourcesPath, "dashboard-ui");
  82. }
  83. }
  84. /// <summary>
  85. /// Gets the dashboard resource path.
  86. /// </summary>
  87. /// <param name="virtualPath">The virtual path.</param>
  88. /// <returns>System.String.</returns>
  89. private string GetDashboardResourcePath(string virtualPath)
  90. {
  91. return Path.Combine(DashboardUIPath, virtualPath.Replace('/', Path.DirectorySeparatorChar));
  92. }
  93. /// <summary>
  94. /// Modifies the HTML by adding common meta tags, css and js.
  95. /// </summary>
  96. /// <param name="sourceStream">The source stream.</param>
  97. /// <param name="localizationCulture">The localization culture.</param>
  98. /// <param name="enableMinification">if set to <c>true</c> [enable minification].</param>
  99. /// <returns>Task{Stream}.</returns>
  100. public async Task<Stream> ModifyHtml(Stream sourceStream, string localizationCulture, bool enableMinification)
  101. {
  102. using (sourceStream)
  103. {
  104. string html;
  105. using (var memoryStream = new MemoryStream())
  106. {
  107. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  108. html = Encoding.UTF8.GetString(memoryStream.ToArray());
  109. if (!string.IsNullOrWhiteSpace(localizationCulture))
  110. {
  111. var lang = localizationCulture.Split('-').FirstOrDefault();
  112. html = _localization.LocalizeDocument(html, localizationCulture, GetLocalizationToken);
  113. html = html.Replace("<html>", "<html lang=\"" + lang + "\">");
  114. }
  115. if (enableMinification)
  116. {
  117. try
  118. {
  119. var minifier = new HtmlMinifier(new HtmlMinificationSettings());
  120. var result = minifier.Minify(html, false);
  121. if (result.Errors.Count > 0)
  122. {
  123. _logger.Error("Error minifying html: " + result.Errors[0].Message);
  124. }
  125. else
  126. {
  127. html = result.MinifiedContent;
  128. }
  129. }
  130. catch (Exception ex)
  131. {
  132. _logger.ErrorException("Error minifying html", ex);
  133. }
  134. }
  135. }
  136. var version = GetType().Assembly.GetName().Version;
  137. html = html.Replace("<head>", "<head>" + GetMetaTags() + GetCommonCss(version) + GetCommonJavascript(version));
  138. var bytes = Encoding.UTF8.GetBytes(html);
  139. return new MemoryStream(bytes);
  140. }
  141. }
  142. private string GetLocalizationToken(string phrase)
  143. {
  144. return "${" + phrase + "}";
  145. }
  146. /// <summary>
  147. /// Gets the meta tags.
  148. /// </summary>
  149. /// <returns>System.String.</returns>
  150. private static string GetMetaTags()
  151. {
  152. var sb = new StringBuilder();
  153. sb.Append("<meta http-equiv=\"X-UA-Compatibility\" content=\"IE=Edge\">");
  154. sb.Append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">");
  155. //sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  156. sb.Append("<meta name=\"mobile-web-app-capable\" content=\"yes\">");
  157. sb.Append("<meta name=\"application-name\" content=\"Media Browser\">");
  158. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  159. sb.Append("<meta name=\"application-name\" content=\"Media Browser\">");
  160. sb.Append("<meta name=\"robots\" content=\"noindex, nofollow, noarchive\" />");
  161. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  162. sb.Append("<link rel=\"apple-touch-icon\" href=\"css/images/touchicon.png\" />");
  163. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"css/images/touchicon72.png\" />");
  164. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\" />");
  165. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\" />");
  166. sb.Append("<link rel=\"shortcut icon\" href=\"css/images/favicon.ico\" />");
  167. return sb.ToString();
  168. }
  169. /// <summary>
  170. /// Gets the common CSS.
  171. /// </summary>
  172. /// <param name="version">The version.</param>
  173. /// <returns>System.String.</returns>
  174. private string GetCommonCss(Version version)
  175. {
  176. var versionString = "?v=" + version;
  177. var files = new[]
  178. {
  179. "thirdparty/jquerymobile-1.4.5/jquery.mobile-1.4.5.min.css",
  180. "thirdparty/swipebox-master/css/swipebox.min.css" + versionString,
  181. "thirdparty/fontawesome/css/font-awesome.min.css" + versionString,
  182. "thirdparty/jstree3.0.8/themes/default/style.min.css",
  183. "css/all.css" + versionString
  184. };
  185. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" />", s)).ToArray();
  186. return string.Join(string.Empty, tags);
  187. }
  188. /// <summary>
  189. /// Gets the common javascript.
  190. /// </summary>
  191. /// <param name="version">The version.</param>
  192. /// <returns>System.String.</returns>
  193. private string GetCommonJavascript(Version version)
  194. {
  195. var builder = new StringBuilder();
  196. var versionString = "?v=" + version;
  197. var files = new[]
  198. {
  199. "scripts/all.js" + versionString,
  200. "thirdparty/swipebox-master/js/jquery.swipebox.min.js" + versionString
  201. };
  202. var tags = files.Select(s => string.Format("<script src=\"{0}\"></script>", s)).ToArray();
  203. builder.Append(string.Join(string.Empty, tags));
  204. return builder.ToString();
  205. }
  206. /// <summary>
  207. /// Gets a stream containing all concatenated javascript
  208. /// </summary>
  209. /// <returns>Task{Stream}.</returns>
  210. private async Task<Stream> GetAllJavascript(string culture, string version, bool enableMinification)
  211. {
  212. var memoryStream = new MemoryStream();
  213. var newLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
  214. // jQuery + jQuery mobile
  215. await AppendResource(memoryStream, "thirdparty/jquery-2.1.1.min.js", newLineBytes).ConfigureAwait(false);
  216. await AppendResource(memoryStream, "thirdparty/jquerymobile-1.4.5/jquery.mobile-1.4.5.min.js", newLineBytes).ConfigureAwait(false);
  217. await AppendResource(memoryStream, "thirdparty/jquery.unveil-custom.js", newLineBytes).ConfigureAwait(false);
  218. await AppendResource(memoryStream, "thirdparty/cast_sender.js", newLineBytes).ConfigureAwait(false);
  219. await AppendResource(memoryStream, "thirdparty/browser.js", newLineBytes).ConfigureAwait(false);
  220. await AppendResource(memoryStream, "thirdparty/jstree3.0.8/jstree.js", newLineBytes).ConfigureAwait(false);
  221. await AppendLocalization(memoryStream, culture).ConfigureAwait(false);
  222. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  223. // Write the version string for the dashboard comparison function
  224. var versionString = string.Format("window.dashboardVersion='{0}';", version);
  225. var versionBytes = Encoding.UTF8.GetBytes(versionString);
  226. await memoryStream.WriteAsync(versionBytes, 0, versionBytes.Length).ConfigureAwait(false);
  227. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  228. var builder = new StringBuilder();
  229. foreach (var file in new[]
  230. {
  231. "thirdparty/apiclient/logger.js",
  232. "thirdparty/apiclient/md5.js",
  233. "thirdparty/apiclient/sha1.js",
  234. "thirdparty/apiclient/store.js",
  235. "thirdparty/apiclient/network.js",
  236. "thirdparty/apiclient/device.js",
  237. "thirdparty/apiclient/credentials.js",
  238. "thirdparty/apiclient/mediabrowser.apiclient.js",
  239. "thirdparty/apiclient/connectservice.js",
  240. "thirdparty/apiclient/connectionmanager.js"
  241. })
  242. {
  243. using (var fs = _fileSystem.GetFileStream(GetDashboardResourcePath(file), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  244. {
  245. using (var streamReader = new StreamReader(fs))
  246. {
  247. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  248. builder.Append(text);
  249. builder.Append(Environment.NewLine);
  250. }
  251. }
  252. }
  253. foreach (var file in GetScriptFiles())
  254. {
  255. var path = GetDashboardResourcePath("scripts/" + file);
  256. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  257. {
  258. using (var streamReader = new StreamReader(fs))
  259. {
  260. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  261. builder.Append(text);
  262. builder.Append(Environment.NewLine);
  263. }
  264. }
  265. }
  266. var js = builder.ToString();
  267. if (enableMinification)
  268. {
  269. try
  270. {
  271. var result = new CrockfordJsMinifier().Minify(js, false, Encoding.UTF8);
  272. if (result.Errors.Count > 0)
  273. {
  274. _logger.Error("Error minifying javascript: " + result.Errors[0].Message);
  275. }
  276. else
  277. {
  278. js = result.MinifiedContent;
  279. }
  280. }
  281. catch (Exception ex)
  282. {
  283. _logger.ErrorException("Error minifying javascript", ex);
  284. }
  285. }
  286. var bytes = Encoding.UTF8.GetBytes(js);
  287. await memoryStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  288. memoryStream.Position = 0;
  289. return memoryStream;
  290. }
  291. private IEnumerable<string> GetScriptFiles()
  292. {
  293. return new[]
  294. {
  295. "extensions.js",
  296. "site.js",
  297. "librarybrowser.js",
  298. "librarylist.js",
  299. "editorsidebar.js",
  300. "librarymenu.js",
  301. "mediacontroller.js",
  302. "chromecast.js",
  303. "backdrops.js",
  304. "sync.js",
  305. "syncjob.js",
  306. "playlistmanager.js",
  307. "mediaplayer.js",
  308. "mediaplayer-video.js",
  309. "nowplayingbar.js",
  310. "nowplayingpage.js",
  311. "taskbutton.js",
  312. "ratingdialog.js",
  313. "aboutpage.js",
  314. "alphapicker.js",
  315. "addpluginpage.js",
  316. "advancedconfigurationpage.js",
  317. "metadataadvanced.js",
  318. "autoorganizetv.js",
  319. "autoorganizelog.js",
  320. "channels.js",
  321. "channelslatest.js",
  322. "channelitems.js",
  323. "channelsettings.js",
  324. "connectlogin.js",
  325. "dashboardgeneral.js",
  326. "dashboardhosting.js",
  327. "dashboardpage.js",
  328. "device.js",
  329. "devices.js",
  330. "devicesupload.js",
  331. "directorybrowser.js",
  332. "dlnaprofile.js",
  333. "dlnaprofiles.js",
  334. "dlnasettings.js",
  335. "dlnaserversettings.js",
  336. "editcollectionitems.js",
  337. "edititemmetadata.js",
  338. "edititemimages.js",
  339. "edititemsubtitles.js",
  340. "playbackconfiguration.js",
  341. "cinemamodeconfiguration.js",
  342. "encodingsettings.js",
  343. "externalplayer.js",
  344. "favorites.js",
  345. "forgotpassword.js",
  346. "forgotpasswordpin.js",
  347. "gamesrecommendedpage.js",
  348. "gamesystemspage.js",
  349. "gamespage.js",
  350. "gamegenrepage.js",
  351. "gamestudiospage.js",
  352. "homelatest.js",
  353. "indexpage.js",
  354. "itembynamedetailpage.js",
  355. "itemdetailpage.js",
  356. "itemgallery.js",
  357. "itemlistpage.js",
  358. "librarypathmapping.js",
  359. "reports.js",
  360. "librarysettings.js",
  361. "livetvchannel.js",
  362. "livetvchannels.js",
  363. "livetvguide.js",
  364. "livetvnewrecording.js",
  365. "livetvprogram.js",
  366. "livetvrecording.js",
  367. "livetvrecordinglist.js",
  368. "livetvrecordings.js",
  369. "livetvtimer.js",
  370. "livetvseriestimer.js",
  371. "livetvseriestimers.js",
  372. "livetvsettings.js",
  373. "livetvsuggested.js",
  374. "livetvstatus.js",
  375. "livetvtimers.js",
  376. "loginpage.js",
  377. "logpage.js",
  378. "medialibrarypage.js",
  379. "metadataconfigurationpage.js",
  380. "metadataimagespage.js",
  381. "metadatasubtitles.js",
  382. "metadatanfo.js",
  383. "moviegenres.js",
  384. "moviecollections.js",
  385. "movies.js",
  386. "movieslatest.js",
  387. "moviepeople.js",
  388. "moviesrecommended.js",
  389. "moviestudios.js",
  390. "movietrailers.js",
  391. "musicalbums.js",
  392. "musicalbumartists.js",
  393. "musicartists.js",
  394. "musicgenres.js",
  395. "musicrecommended.js",
  396. "musicvideos.js",
  397. "mypreferencesdisplay.js",
  398. "mypreferenceslanguages.js",
  399. "mypreferenceswebclient.js",
  400. "notifications.js",
  401. "notificationlist.js",
  402. "notificationsetting.js",
  403. "notificationsettings.js",
  404. "playlist.js",
  405. "playlists.js",
  406. "playlistedit.js",
  407. "plugincatalogpage.js",
  408. "pluginspage.js",
  409. "remotecontrol.js",
  410. "scheduledtaskpage.js",
  411. "scheduledtaskspage.js",
  412. "search.js",
  413. "selectserver.js",
  414. "serversecurity.js",
  415. "songs.js",
  416. "supporterkeypage.js",
  417. "supporterpage.js",
  418. "syncactivity.js",
  419. "syncsettings.js",
  420. "episodes.js",
  421. "thememediaplayer.js",
  422. "tvgenres.js",
  423. "tvlatest.js",
  424. "tvpeople.js",
  425. "tvrecommended.js",
  426. "tvshows.js",
  427. "tvstudios.js",
  428. "tvupcoming.js",
  429. "useredit.js",
  430. "usernew.js",
  431. "myprofile.js",
  432. "userpassword.js",
  433. "userprofilespage.js",
  434. "userparentalcontrol.js",
  435. "userlibraryaccess.js",
  436. "wizardagreement.js",
  437. "wizardfinishpage.js",
  438. "wizardservice.js",
  439. "wizardstartpage.js",
  440. "wizardsettings.js",
  441. "wizarduserpage.js"
  442. };
  443. }
  444. private async Task AppendLocalization(Stream stream, string culture)
  445. {
  446. var js = "window.localizationGlossary=" + _jsonSerializer.SerializeToString(_localization.GetJavaScriptLocalizationDictionary(culture));
  447. var bytes = Encoding.UTF8.GetBytes(js);
  448. await stream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  449. }
  450. /// <summary>
  451. /// Appends the resource.
  452. /// </summary>
  453. /// <param name="outputStream">The output stream.</param>
  454. /// <param name="path">The path.</param>
  455. /// <param name="newLineBytes">The new line bytes.</param>
  456. /// <returns>Task.</returns>
  457. private async Task AppendResource(Stream outputStream, string path, byte[] newLineBytes)
  458. {
  459. path = GetDashboardResourcePath(path);
  460. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  461. {
  462. using (var streamReader = new StreamReader(fs))
  463. {
  464. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  465. var bytes = Encoding.UTF8.GetBytes(text);
  466. await outputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  467. }
  468. }
  469. await outputStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  470. }
  471. /// <summary>
  472. /// Gets all CSS.
  473. /// </summary>
  474. /// <returns>Task{Stream}.</returns>
  475. private async Task<Stream> GetAllCss(bool enableMinification)
  476. {
  477. var files = new[]
  478. {
  479. "site.css",
  480. "chromecast.css",
  481. "mediaplayer.css",
  482. "mediaplayer-video.css",
  483. "librarymenu.css",
  484. "librarybrowser.css",
  485. "detailtable.css",
  486. "card.css",
  487. "tileitem.css",
  488. "metadataeditor.css",
  489. "notifications.css",
  490. "search.css",
  491. "pluginupdates.css",
  492. "remotecontrol.css",
  493. "userimage.css",
  494. "livetv.css",
  495. "nowplaying.css",
  496. "icons.css",
  497. "materialize.css"
  498. };
  499. var builder = new StringBuilder();
  500. foreach (var file in files)
  501. {
  502. var path = GetDashboardResourcePath("css/" + file);
  503. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  504. {
  505. using (var streamReader = new StreamReader(fs))
  506. {
  507. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  508. builder.Append(text);
  509. builder.Append(Environment.NewLine);
  510. }
  511. }
  512. }
  513. var css = builder.ToString();
  514. if (enableMinification)
  515. {
  516. try
  517. {
  518. var result = new KristensenCssMinifier().Minify(builder.ToString(), false, Encoding.UTF8);
  519. if (result.Errors.Count > 0)
  520. {
  521. _logger.Error("Error minifying css: " + result.Errors[0].Message);
  522. }
  523. else
  524. {
  525. css = result.MinifiedContent;
  526. }
  527. }
  528. catch (Exception ex)
  529. {
  530. _logger.ErrorException("Error minifying css", ex);
  531. }
  532. }
  533. var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(css));
  534. memoryStream.Position = 0;
  535. return memoryStream;
  536. }
  537. /// <summary>
  538. /// Gets the raw resource stream.
  539. /// </summary>
  540. /// <param name="path">The path.</param>
  541. /// <returns>Task{Stream}.</returns>
  542. private Stream GetRawResourceStream(string path)
  543. {
  544. return _fileSystem.GetFileStream(GetDashboardResourcePath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  545. }
  546. }
  547. }