PackageCreator.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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. var runningDirectory = Path.GetDirectoryName(_config.ApplicationPaths.ApplicationPath);
  81. return Path.Combine(runningDirectory, "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. /// <returns>Task{Stream}.</returns>
  99. public async Task<Stream> ModifyHtml(Stream sourceStream, string localizationCulture)
  100. {
  101. using (sourceStream)
  102. {
  103. string html;
  104. using (var memoryStream = new MemoryStream())
  105. {
  106. await sourceStream.CopyToAsync(memoryStream).ConfigureAwait(false);
  107. html = Encoding.UTF8.GetString(memoryStream.ToArray());
  108. if (!string.IsNullOrWhiteSpace(localizationCulture))
  109. {
  110. var lang = localizationCulture.Split('-').FirstOrDefault();
  111. html = _localization.LocalizeDocument(html, localizationCulture, GetLocalizationToken);
  112. html = html.Replace("<html>", "<html lang=\"" + lang + "\">");
  113. }
  114. //try
  115. //{
  116. // var minifier = new HtmlMinifier(new HtmlMinificationSettings(true));
  117. // html = minifier.Minify(html).MinifiedContent;
  118. //}
  119. //catch (Exception ex)
  120. //{
  121. // Logger.ErrorException("Error minifying html", ex);
  122. //}
  123. }
  124. var version = GetType().Assembly.GetName().Version;
  125. html = html.Replace("<head>", "<head>" + GetMetaTags() + GetCommonCss(version) + GetCommonJavascript(version));
  126. var bytes = Encoding.UTF8.GetBytes(html);
  127. return new MemoryStream(bytes);
  128. }
  129. }
  130. private string GetLocalizationToken(string phrase)
  131. {
  132. return "${" + phrase + "}";
  133. }
  134. /// <summary>
  135. /// Gets the meta tags.
  136. /// </summary>
  137. /// <returns>System.String.</returns>
  138. private static string GetMetaTags()
  139. {
  140. var sb = new StringBuilder();
  141. sb.Append("<meta http-equiv=\"X-UA-Compatibility\" content=\"IE=Edge\">");
  142. sb.Append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">");
  143. //sb.Append("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
  144. sb.Append("<meta name=\"mobile-web-app-capable\" content=\"yes\">");
  145. sb.Append("<meta name=\"application-name\" content=\"Media Browser\">");
  146. //sb.Append("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
  147. sb.Append("<meta name=\"application-name\" content=\"Media Browser\">");
  148. sb.Append("<meta name=\"robots\" content=\"noindex, nofollow, noarchive\" />");
  149. // http://developer.apple.com/library/ios/#DOCUMENTATION/AppleApplications/Reference/SafariWebContent/ConfiguringWebApplications/ConfiguringWebApplications.html
  150. sb.Append("<link rel=\"apple-touch-icon\" href=\"css/images/touchicon.png\" />");
  151. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"72x72\" href=\"css/images/touchicon72.png\" />");
  152. sb.Append("<link rel=\"apple-touch-icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\" />");
  153. sb.Append("<link rel=\"apple-touch-startup-image\" href=\"css/images/iossplash.png\" />");
  154. sb.Append("<link rel=\"shortcut icon\" href=\"css/images/favicon.ico\" />");
  155. return sb.ToString();
  156. }
  157. /// <summary>
  158. /// Gets the common CSS.
  159. /// </summary>
  160. /// <param name="version">The version.</param>
  161. /// <returns>System.String.</returns>
  162. private string GetCommonCss(Version version)
  163. {
  164. var versionString = "?v=" + version;
  165. var files = new[]
  166. {
  167. "thirdparty/jquerymobile-1.4.5/jquery.mobile-1.4.5.min.css",
  168. "thirdparty/swipebox-master/css/swipebox.min.css" + versionString,
  169. "css/all.css" + versionString
  170. };
  171. var tags = files.Select(s => string.Format("<link rel=\"stylesheet\" href=\"{0}\" />", s)).ToArray();
  172. return string.Join(string.Empty, tags);
  173. }
  174. /// <summary>
  175. /// Gets the common javascript.
  176. /// </summary>
  177. /// <param name="version">The version.</param>
  178. /// <returns>System.String.</returns>
  179. private string GetCommonJavascript(Version version)
  180. {
  181. var builder = new StringBuilder();
  182. var versionString = "?v=" + version;
  183. var files = new[]
  184. {
  185. "scripts/all.js" + versionString,
  186. "thirdparty/jstree1.0/jquery.jstree.min.js",
  187. "thirdparty/swipebox-master/js/jquery.swipebox.min.js" + versionString
  188. };
  189. var tags = files.Select(s => string.Format("<script src=\"{0}\"></script>", s)).ToArray();
  190. builder.Append(string.Join(string.Empty, tags));
  191. return builder.ToString();
  192. }
  193. /// <summary>
  194. /// Gets a stream containing all concatenated javascript
  195. /// </summary>
  196. /// <returns>Task{Stream}.</returns>
  197. private async Task<Stream> GetAllJavascript(string culture, string version)
  198. {
  199. var memoryStream = new MemoryStream();
  200. var newLineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
  201. // jQuery + jQuery mobile
  202. await AppendResource(memoryStream, "thirdparty/jquery-2.1.1.min.js", newLineBytes).ConfigureAwait(false);
  203. await AppendResource(memoryStream, "thirdparty/jquerymobile-1.4.5/jquery.mobile-1.4.5.min.js", newLineBytes).ConfigureAwait(false);
  204. await AppendResource(memoryStream, "thirdparty/jquery.unveil-custom.js", newLineBytes).ConfigureAwait(false);
  205. await AppendResource(memoryStream, "thirdparty/cast_sender.js", newLineBytes).ConfigureAwait(false);
  206. await AppendResource(memoryStream, "thirdparty/browser.js", newLineBytes).ConfigureAwait(false);
  207. await AppendLocalization(memoryStream, culture).ConfigureAwait(false);
  208. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  209. // Write the version string for the dashboard comparison function
  210. var versionString = string.Format("window.dashboardVersion='{0}';", version);
  211. var versionBytes = Encoding.UTF8.GetBytes(versionString);
  212. await memoryStream.WriteAsync(versionBytes, 0, versionBytes.Length).ConfigureAwait(false);
  213. await memoryStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  214. var builder = new StringBuilder();
  215. foreach (var file in new[]
  216. {
  217. "thirdparty/apiclient/md5.js",
  218. "thirdparty/apiclient/sha1.js",
  219. "thirdparty/apiclient/store.js",
  220. "thirdparty/apiclient/network.js",
  221. "thirdparty/apiclient/device.js",
  222. "thirdparty/apiclient/credentials.js",
  223. "thirdparty/apiclient/mediabrowser.apiclient.js",
  224. "thirdparty/apiclient/connectservice.js",
  225. "thirdparty/apiclient/connectionmanager.js"
  226. })
  227. {
  228. using (var fs = _fileSystem.GetFileStream(GetDashboardResourcePath(file), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  229. {
  230. using (var streamReader = new StreamReader(fs))
  231. {
  232. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  233. builder.Append(text);
  234. builder.Append(Environment.NewLine);
  235. }
  236. }
  237. }
  238. foreach (var file in GetScriptFiles())
  239. {
  240. var path = GetDashboardResourcePath("scripts/" + file);
  241. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  242. {
  243. using (var streamReader = new StreamReader(fs))
  244. {
  245. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  246. builder.Append(text);
  247. builder.Append(Environment.NewLine);
  248. }
  249. }
  250. }
  251. var js = builder.ToString();
  252. try
  253. {
  254. var result = new CrockfordJsMinifier().Minify(js, false, Encoding.UTF8);
  255. js = result.MinifiedContent;
  256. }
  257. catch (Exception ex)
  258. {
  259. _logger.ErrorException("Error minifying javascript", ex);
  260. }
  261. var bytes = Encoding.UTF8.GetBytes(js);
  262. await memoryStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  263. memoryStream.Position = 0;
  264. return memoryStream;
  265. }
  266. private IEnumerable<string> GetScriptFiles()
  267. {
  268. return new[]
  269. {
  270. "extensions.js",
  271. "site.js",
  272. "librarybrowser.js",
  273. "librarylist.js",
  274. "editorsidebar.js",
  275. "librarymenu.js",
  276. "mediacontroller.js",
  277. "chromecast.js",
  278. "backdrops.js",
  279. "sync.js",
  280. "playlistmanager.js",
  281. "mediaplayer.js",
  282. "mediaplayer-video.js",
  283. "nowplayingbar.js",
  284. "nowplayingpage.js",
  285. "ratingdialog.js",
  286. "aboutpage.js",
  287. "alphapicker.js",
  288. "addpluginpage.js",
  289. "advancedconfigurationpage.js",
  290. "metadataadvanced.js",
  291. "autoorganizetv.js",
  292. "autoorganizelog.js",
  293. "channels.js",
  294. "channelslatest.js",
  295. "channelitems.js",
  296. "channelsettings.js",
  297. "connectlogin.js",
  298. "dashboardgeneral.js",
  299. "dashboardpage.js",
  300. "dashboardsync.js",
  301. "device.js",
  302. "devices.js",
  303. "devicesupload.js",
  304. "directorybrowser.js",
  305. "dlnaprofile.js",
  306. "dlnaprofiles.js",
  307. "dlnasettings.js",
  308. "dlnaserversettings.js",
  309. "editcollectionitems.js",
  310. "edititemmetadata.js",
  311. "edititemimages.js",
  312. "edititemsubtitles.js",
  313. "playbackconfiguration.js",
  314. "cinemamodeconfiguration.js",
  315. "encodingsettings.js",
  316. "externalplayer.js",
  317. "favorites.js",
  318. "forgotpassword.js",
  319. "forgotpasswordpin.js",
  320. "gamesrecommendedpage.js",
  321. "gamesystemspage.js",
  322. "gamespage.js",
  323. "gamegenrepage.js",
  324. "gamestudiospage.js",
  325. "homelatest.js",
  326. "indexpage.js",
  327. "itembynamedetailpage.js",
  328. "itemdetailpage.js",
  329. "itemgallery.js",
  330. "itemlistpage.js",
  331. "librarypathmapping.js",
  332. "reports.js",
  333. "librarysettings.js",
  334. "livetvchannel.js",
  335. "livetvchannels.js",
  336. "livetvguide.js",
  337. "livetvnewrecording.js",
  338. "livetvprogram.js",
  339. "livetvrecording.js",
  340. "livetvrecordinglist.js",
  341. "livetvrecordings.js",
  342. "livetvtimer.js",
  343. "livetvseriestimer.js",
  344. "livetvseriestimers.js",
  345. "livetvsettings.js",
  346. "livetvsuggested.js",
  347. "livetvstatus.js",
  348. "livetvtimers.js",
  349. "loginpage.js",
  350. "logpage.js",
  351. "medialibrarypage.js",
  352. "metadataconfigurationpage.js",
  353. "metadataimagespage.js",
  354. "metadatasubtitles.js",
  355. "metadatakodi.js",
  356. "moviegenres.js",
  357. "moviecollections.js",
  358. "movies.js",
  359. "movieslatest.js",
  360. "moviepeople.js",
  361. "moviesrecommended.js",
  362. "moviestudios.js",
  363. "movietrailers.js",
  364. "musicalbums.js",
  365. "musicalbumartists.js",
  366. "musicartists.js",
  367. "musicgenres.js",
  368. "musicrecommended.js",
  369. "musicvideos.js",
  370. "mypreferencesdisplay.js",
  371. "mypreferenceslanguages.js",
  372. "mypreferenceswebclient.js",
  373. "notifications.js",
  374. "notificationlist.js",
  375. "notificationsetting.js",
  376. "notificationsettings.js",
  377. "playlist.js",
  378. "playlists.js",
  379. "playlistedit.js",
  380. "plugincatalogpage.js",
  381. "pluginspage.js",
  382. "remotecontrol.js",
  383. "scheduledtaskpage.js",
  384. "scheduledtaskspage.js",
  385. "search.js",
  386. "selectserver.js",
  387. "serversecurity.js",
  388. "songs.js",
  389. "supporterkeypage.js",
  390. "supporterpage.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. }