PackageCreator.cs 25 KB

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