PackageCreator.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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. sb.Append("<meta name=\"msapplication-TileImage\" content=\"css/images/touchicon144.png\">");
  168. sb.Append("<meta name=\"msapplication-TileColor\" content=\"#23456B\">");
  169. return sb.ToString();
  170. }
  171. /// <summary>
  172. /// Gets the common CSS.
  173. /// </summary>
  174. /// <param name="version">The version.</param>
  175. /// <returns>System.String.</returns>
  176. private string GetCommonCss(Version version)
  177. {
  178. var versionString = "?v=" + version;
  179. var files = new[]
  180. {
  181. "thirdparty/jquerymobile-1.4.5/jquery.mobile-1.4.5.min.css",
  182. "thirdparty/swipebox-master/css/swipebox.min.css" + versionString,
  183. "thirdparty/fontawesome/css/font-awesome.min.css" + versionString,
  184. "thirdparty/jstree3.0.8/themes/default/style.min.css",
  185. "css/all.css" + versionString
  186. };
  187. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" />", s)).ToArray();
  188. return string.Join(string.Empty, tags);
  189. }
  190. /// <summary>
  191. /// Gets the common javascript.
  192. /// </summary>
  193. /// <param name="version">The version.</param>
  194. /// <returns>System.String.</returns>
  195. private string GetCommonJavascript(Version version)
  196. {
  197. var builder = new StringBuilder();
  198. var versionString = "?v=" + version;
  199. var files = new[]
  200. {
  201. "scripts/all.js" + versionString,
  202. "thirdparty/swipebox-master/js/jquery.swipebox.min.js" + versionString
  203. };
  204. var tags = files.Select(s => string.Format("<script src=\"{0}\"></script>", s)).ToArray();
  205. builder.Append(string.Join(string.Empty, tags));
  206. return builder.ToString();
  207. }
  208. /// <summary>
  209. /// Gets a stream containing all concatenated javascript
  210. /// </summary>
  211. /// <returns>Task{Stream}.</returns>
  212. private async Task<Stream> GetAllJavascript(string culture, string version, bool enableMinification)
  213. {
  214. var memoryStream = new MemoryStream();
  215. var newLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
  216. // jQuery + jQuery mobile
  217. await AppendResource(memoryStream, "thirdparty/jquery-2.1.1.min.js", newLineBytes).ConfigureAwait(false);
  218. await AppendResource(memoryStream, "thirdparty/jquerymobile-1.4.5/jquery.mobile-1.4.5.min.js", newLineBytes).ConfigureAwait(false);
  219. await AppendResource(memoryStream, "thirdparty/jquery.unveil-custom.js", newLineBytes).ConfigureAwait(false);
  220. await AppendResource(memoryStream, "thirdparty/cast_sender.js", newLineBytes).ConfigureAwait(false);
  221. await AppendResource(memoryStream, "thirdparty/browser.js", newLineBytes).ConfigureAwait(false);
  222. await AppendResource(memoryStream, "thirdparty/jstree3.0.8/jstree.js", newLineBytes).ConfigureAwait(false);
  223. await AppendLocalization(memoryStream, culture).ConfigureAwait(false);
  224. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  225. // Write the version string for the dashboard comparison function
  226. var versionString = string.Format("window.dashboardVersion='{0}';", version);
  227. var versionBytes = Encoding.UTF8.GetBytes(versionString);
  228. await memoryStream.WriteAsync(versionBytes, 0, versionBytes.Length).ConfigureAwait(false);
  229. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  230. var builder = new StringBuilder();
  231. foreach (var file in new[]
  232. {
  233. "thirdparty/apiclient/logger.js",
  234. "thirdparty/apiclient/md5.js",
  235. "thirdparty/apiclient/sha1.js",
  236. "thirdparty/apiclient/store.js",
  237. "thirdparty/apiclient/network.js",
  238. "thirdparty/apiclient/device.js",
  239. "thirdparty/apiclient/credentials.js",
  240. "thirdparty/apiclient/ajax.js",
  241. "thirdparty/apiclient/events.js",
  242. "thirdparty/apiclient/deferred.js",
  243. "thirdparty/apiclient/mediabrowser.apiclient.js",
  244. "thirdparty/apiclient/connectservice.js",
  245. "thirdparty/apiclient/serverdiscovery.js",
  246. "thirdparty/apiclient/connectionmanager.js"
  247. })
  248. {
  249. using (var fs = _fileSystem.GetFileStream(GetDashboardResourcePath(file), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  250. {
  251. using (var streamReader = new StreamReader(fs))
  252. {
  253. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  254. builder.Append(text);
  255. builder.Append(Environment.NewLine);
  256. }
  257. }
  258. }
  259. foreach (var file in GetScriptFiles())
  260. {
  261. var path = GetDashboardResourcePath("scripts/" + file);
  262. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  263. {
  264. using (var streamReader = new StreamReader(fs))
  265. {
  266. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  267. builder.Append(text);
  268. builder.Append(Environment.NewLine);
  269. }
  270. }
  271. }
  272. var js = builder.ToString();
  273. if (enableMinification)
  274. {
  275. try
  276. {
  277. var result = new CrockfordJsMinifier().Minify(js, false, Encoding.UTF8);
  278. if (result.Errors.Count > 0)
  279. {
  280. _logger.Error("Error minifying javascript: " + result.Errors[0].Message);
  281. }
  282. else
  283. {
  284. js = result.MinifiedContent;
  285. }
  286. }
  287. catch (Exception ex)
  288. {
  289. _logger.ErrorException("Error minifying javascript", ex);
  290. }
  291. }
  292. var bytes = Encoding.UTF8.GetBytes(js);
  293. await memoryStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  294. memoryStream.Position = 0;
  295. return memoryStream;
  296. }
  297. private IEnumerable<string> GetScriptFiles()
  298. {
  299. return new[]
  300. {
  301. "extensions.js",
  302. "site.js",
  303. "librarybrowser.js",
  304. "librarylist.js",
  305. "editorsidebar.js",
  306. "librarymenu.js",
  307. "mediacontroller.js",
  308. "chromecast.js",
  309. "backdrops.js",
  310. "sync.js",
  311. "syncjob.js",
  312. "playlistmanager.js",
  313. "mediaplayer.js",
  314. "mediaplayer-video.js",
  315. "nowplayingbar.js",
  316. "nowplayingpage.js",
  317. "taskbutton.js",
  318. "ratingdialog.js",
  319. "aboutpage.js",
  320. "alphapicker.js",
  321. "addpluginpage.js",
  322. "advancedconfigurationpage.js",
  323. "metadataadvanced.js",
  324. "autoorganizetv.js",
  325. "autoorganizelog.js",
  326. "channels.js",
  327. "channelslatest.js",
  328. "channelitems.js",
  329. "channelsettings.js",
  330. "connectlogin.js",
  331. "dashboardgeneral.js",
  332. "dashboardhosting.js",
  333. "dashboardpage.js",
  334. "device.js",
  335. "devices.js",
  336. "devicesupload.js",
  337. "directorybrowser.js",
  338. "dlnaprofile.js",
  339. "dlnaprofiles.js",
  340. "dlnasettings.js",
  341. "dlnaserversettings.js",
  342. "editcollectionitems.js",
  343. "edititemmetadata.js",
  344. "edititemimages.js",
  345. "edititemsubtitles.js",
  346. "playbackconfiguration.js",
  347. "cinemamodeconfiguration.js",
  348. "encodingsettings.js",
  349. "externalplayer.js",
  350. "favorites.js",
  351. "forgotpassword.js",
  352. "forgotpasswordpin.js",
  353. "gamesrecommendedpage.js",
  354. "gamesystemspage.js",
  355. "gamespage.js",
  356. "gamegenrepage.js",
  357. "gamestudiospage.js",
  358. "homelatest.js",
  359. "indexpage.js",
  360. "itembynamedetailpage.js",
  361. "itemdetailpage.js",
  362. "itemlistpage.js",
  363. "librarypathmapping.js",
  364. "reports.js",
  365. "librarysettings.js",
  366. "livetvchannel.js",
  367. "livetvchannels.js",
  368. "livetvguide.js",
  369. "livetvnewrecording.js",
  370. "livetvprogram.js",
  371. "livetvrecording.js",
  372. "livetvrecordinglist.js",
  373. "livetvrecordings.js",
  374. "livetvtimer.js",
  375. "livetvseriestimer.js",
  376. "livetvseriestimers.js",
  377. "livetvsettings.js",
  378. "livetvsuggested.js",
  379. "livetvstatus.js",
  380. "livetvtimers.js",
  381. "loginpage.js",
  382. "logpage.js",
  383. "medialibrarypage.js",
  384. "metadataconfigurationpage.js",
  385. "metadataimagespage.js",
  386. "metadatasubtitles.js",
  387. "metadatanfo.js",
  388. "moviegenres.js",
  389. "moviecollections.js",
  390. "movies.js",
  391. "movieslatest.js",
  392. "moviepeople.js",
  393. "moviesrecommended.js",
  394. "moviestudios.js",
  395. "movietrailers.js",
  396. "musicalbums.js",
  397. "musicalbumartists.js",
  398. "musicartists.js",
  399. "musicgenres.js",
  400. "musicrecommended.js",
  401. "musicvideos.js",
  402. "mypreferencesdisplay.js",
  403. "mypreferenceslanguages.js",
  404. "mypreferenceswebclient.js",
  405. "notifications.js",
  406. "notificationlist.js",
  407. "notificationsetting.js",
  408. "notificationsettings.js",
  409. "playlist.js",
  410. "playlists.js",
  411. "playlistedit.js",
  412. "plugincatalogpage.js",
  413. "pluginspage.js",
  414. "remotecontrol.js",
  415. "scheduledtaskpage.js",
  416. "scheduledtaskspage.js",
  417. "search.js",
  418. "selectserver.js",
  419. "serversecurity.js",
  420. "songs.js",
  421. "supporterkeypage.js",
  422. "supporterpage.js",
  423. "syncactivity.js",
  424. "syncsettings.js",
  425. "episodes.js",
  426. "thememediaplayer.js",
  427. "tvgenres.js",
  428. "tvlatest.js",
  429. "tvpeople.js",
  430. "tvrecommended.js",
  431. "tvshows.js",
  432. "tvstudios.js",
  433. "tvupcoming.js",
  434. "useredit.js",
  435. "usernew.js",
  436. "myprofile.js",
  437. "userpassword.js",
  438. "userprofilespage.js",
  439. "userparentalcontrol.js",
  440. "userlibraryaccess.js",
  441. "wizardagreement.js",
  442. "wizardfinishpage.js",
  443. "wizardservice.js",
  444. "wizardstartpage.js",
  445. "wizardsettings.js",
  446. "wizarduserpage.js"
  447. };
  448. }
  449. private async Task AppendLocalization(Stream stream, string culture)
  450. {
  451. var js = "window.localizationGlossary=" + _jsonSerializer.SerializeToString(_localization.GetJavaScriptLocalizationDictionary(culture));
  452. var bytes = Encoding.UTF8.GetBytes(js);
  453. await stream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  454. }
  455. /// <summary>
  456. /// Appends the resource.
  457. /// </summary>
  458. /// <param name="outputStream">The output stream.</param>
  459. /// <param name="path">The path.</param>
  460. /// <param name="newLineBytes">The new line bytes.</param>
  461. /// <returns>Task.</returns>
  462. private async Task AppendResource(Stream outputStream, string path, byte[] newLineBytes)
  463. {
  464. path = GetDashboardResourcePath(path);
  465. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  466. {
  467. using (var streamReader = new StreamReader(fs))
  468. {
  469. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  470. var bytes = Encoding.UTF8.GetBytes(text);
  471. await outputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  472. }
  473. }
  474. await outputStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  475. }
  476. /// <summary>
  477. /// Gets all CSS.
  478. /// </summary>
  479. /// <returns>Task{Stream}.</returns>
  480. private async Task<Stream> GetAllCss(bool enableMinification)
  481. {
  482. var files = new[]
  483. {
  484. "site.css",
  485. "chromecast.css",
  486. "mediaplayer.css",
  487. "mediaplayer-video.css",
  488. "librarymenu.css",
  489. "librarybrowser.css",
  490. "detailtable.css",
  491. "card.css",
  492. "tileitem.css",
  493. "metadataeditor.css",
  494. "notifications.css",
  495. "search.css",
  496. "pluginupdates.css",
  497. "remotecontrol.css",
  498. "userimage.css",
  499. "livetv.css",
  500. "nowplaying.css",
  501. "icons.css",
  502. "materialize.css"
  503. };
  504. var builder = new StringBuilder();
  505. foreach (var file in files)
  506. {
  507. var path = GetDashboardResourcePath("css/" + file);
  508. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  509. {
  510. using (var streamReader = new StreamReader(fs))
  511. {
  512. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  513. builder.Append(text);
  514. builder.Append(Environment.NewLine);
  515. }
  516. }
  517. }
  518. var css = builder.ToString();
  519. if (enableMinification)
  520. {
  521. try
  522. {
  523. var result = new KristensenCssMinifier().Minify(builder.ToString(), false, Encoding.UTF8);
  524. if (result.Errors.Count > 0)
  525. {
  526. _logger.Error("Error minifying css: " + result.Errors[0].Message);
  527. }
  528. else
  529. {
  530. css = result.MinifiedContent;
  531. }
  532. }
  533. catch (Exception ex)
  534. {
  535. _logger.ErrorException("Error minifying css", ex);
  536. }
  537. }
  538. var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(css));
  539. memoryStream.Position = 0;
  540. return memoryStream;
  541. }
  542. /// <summary>
  543. /// Gets the raw resource stream.
  544. /// </summary>
  545. /// <param name="path">The path.</param>
  546. /// <returns>Task{Stream}.</returns>
  547. private Stream GetRawResourceStream(string path)
  548. {
  549. return _fileSystem.GetFileStream(GetDashboardResourcePath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  550. }
  551. }
  552. }