PackageCreator.cs 24 KB

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