PackageCreator.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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("<link rel=\"icon\" sizes=\"114x114\" href=\"css/images/touchicon114.png\" />");
  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.4/jquery.mobile-1.4.4.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.4/jquery.mobile-1.4.4.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/connectionmanager.js"
  224. })
  225. {
  226. using (var fs = _fileSystem.GetFileStream(GetDashboardResourcePath(file), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  227. {
  228. using (var streamReader = new StreamReader(fs))
  229. {
  230. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  231. builder.Append(text);
  232. builder.Append(Environment.NewLine);
  233. }
  234. }
  235. }
  236. foreach (var file in GetScriptFiles())
  237. {
  238. var path = GetDashboardResourcePath("scripts/" + file);
  239. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  240. {
  241. using (var streamReader = new StreamReader(fs))
  242. {
  243. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  244. builder.Append(text);
  245. builder.Append(Environment.NewLine);
  246. }
  247. }
  248. }
  249. var js = builder.ToString();
  250. try
  251. {
  252. var result = new CrockfordJsMinifier().Minify(js, false, Encoding.UTF8);
  253. js = result.MinifiedContent;
  254. }
  255. catch (Exception ex)
  256. {
  257. _logger.ErrorException("Error minifying javascript", ex);
  258. }
  259. var bytes = Encoding.UTF8.GetBytes(js);
  260. await memoryStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  261. memoryStream.Position = 0;
  262. return memoryStream;
  263. }
  264. private IEnumerable<string> GetScriptFiles()
  265. {
  266. return new[]
  267. {
  268. "extensions.js",
  269. "site.js",
  270. "librarybrowser.js",
  271. "librarylist.js",
  272. "editorsidebar.js",
  273. "librarymenu.js",
  274. "mediacontroller.js",
  275. "chromecast.js",
  276. "backdrops.js",
  277. "sync.js",
  278. "playlistmanager.js",
  279. "mediaplayer.js",
  280. "mediaplayer-video.js",
  281. "nowplayingbar.js",
  282. "nowplayingpage.js",
  283. "ratingdialog.js",
  284. "aboutpage.js",
  285. "alphapicker.js",
  286. "addpluginpage.js",
  287. "advancedconfigurationpage.js",
  288. "metadataadvanced.js",
  289. "autoorganizetv.js",
  290. "autoorganizelog.js",
  291. "channels.js",
  292. "channelslatest.js",
  293. "channelitems.js",
  294. "channelsettings.js",
  295. "connectlogin.js",
  296. "dashboardgeneral.js",
  297. "dashboardpage.js",
  298. "dashboardsync.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. "gamesrecommendedpage.js",
  317. "gamesystemspage.js",
  318. "gamespage.js",
  319. "gamegenrepage.js",
  320. "gamestudiospage.js",
  321. "homelatest.js",
  322. "indexpage.js",
  323. "itembynamedetailpage.js",
  324. "itemdetailpage.js",
  325. "itemgallery.js",
  326. "itemlistpage.js",
  327. "librarypathmapping.js",
  328. "reports.js",
  329. "librarysettings.js",
  330. "livetvchannel.js",
  331. "livetvchannels.js",
  332. "livetvguide.js",
  333. "livetvnewrecording.js",
  334. "livetvprogram.js",
  335. "livetvrecording.js",
  336. "livetvrecordinglist.js",
  337. "livetvrecordings.js",
  338. "livetvtimer.js",
  339. "livetvseriestimer.js",
  340. "livetvseriestimers.js",
  341. "livetvsettings.js",
  342. "livetvsuggested.js",
  343. "livetvstatus.js",
  344. "livetvtimers.js",
  345. "loginpage.js",
  346. "logpage.js",
  347. "medialibrarypage.js",
  348. "metadataconfigurationpage.js",
  349. "metadataimagespage.js",
  350. "metadatasubtitles.js",
  351. "metadatakodi.js",
  352. "moviegenres.js",
  353. "moviecollections.js",
  354. "movies.js",
  355. "movieslatest.js",
  356. "moviepeople.js",
  357. "moviesrecommended.js",
  358. "moviestudios.js",
  359. "movietrailers.js",
  360. "musicalbums.js",
  361. "musicalbumartists.js",
  362. "musicartists.js",
  363. "musicgenres.js",
  364. "musicrecommended.js",
  365. "musicvideos.js",
  366. "mypreferencesdisplay.js",
  367. "mypreferenceslanguages.js",
  368. "mypreferenceswebclient.js",
  369. "notifications.js",
  370. "notificationlist.js",
  371. "notificationsetting.js",
  372. "notificationsettings.js",
  373. "playlist.js",
  374. "playlists.js",
  375. "playlistedit.js",
  376. "plugincatalogpage.js",
  377. "pluginspage.js",
  378. "remotecontrol.js",
  379. "scheduledtaskpage.js",
  380. "scheduledtaskspage.js",
  381. "search.js",
  382. "selectserver.js",
  383. "serversecurity.js",
  384. "songs.js",
  385. "supporterkeypage.js",
  386. "supporterpage.js",
  387. "episodes.js",
  388. "thememediaplayer.js",
  389. "tvgenres.js",
  390. "tvlatest.js",
  391. "tvpeople.js",
  392. "tvrecommended.js",
  393. "tvshows.js",
  394. "tvstudios.js",
  395. "tvupcoming.js",
  396. "useredit.js",
  397. "myprofile.js",
  398. "userprofilespage.js",
  399. "userparentalcontrol.js",
  400. "userlibraryaccess.js",
  401. "wizardfinishpage.js",
  402. "wizardservice.js",
  403. "wizardstartpage.js",
  404. "wizardsettings.js",
  405. "wizarduserpage.js"
  406. };
  407. }
  408. private async Task AppendLocalization(Stream stream, string culture)
  409. {
  410. var js = "window.localizationGlossary=" + _jsonSerializer.SerializeToString(_localization.GetJavaScriptLocalizationDictionary(culture));
  411. var bytes = Encoding.UTF8.GetBytes(js);
  412. await stream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  413. }
  414. /// <summary>
  415. /// Appends the resource.
  416. /// </summary>
  417. /// <param name="outputStream">The output stream.</param>
  418. /// <param name="path">The path.</param>
  419. /// <param name="newLineBytes">The new line bytes.</param>
  420. /// <returns>Task.</returns>
  421. private async Task AppendResource(Stream outputStream, string path, byte[] newLineBytes)
  422. {
  423. path = GetDashboardResourcePath(path);
  424. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  425. {
  426. using (var streamReader = new StreamReader(fs))
  427. {
  428. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  429. var bytes = Encoding.UTF8.GetBytes(text);
  430. await outputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  431. }
  432. }
  433. await outputStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  434. }
  435. /// <summary>
  436. /// Gets all CSS.
  437. /// </summary>
  438. /// <returns>Task{Stream}.</returns>
  439. private async Task<Stream> GetAllCss()
  440. {
  441. var files = new[]
  442. {
  443. "site.css",
  444. "chromecast.css",
  445. "mediaplayer.css",
  446. "mediaplayer-video.css",
  447. "librarymenu.css",
  448. "librarybrowser.css",
  449. "detailtable.css",
  450. "card.css",
  451. "tileitem.css",
  452. "metadataeditor.css",
  453. "notifications.css",
  454. "search.css",
  455. "pluginupdates.css",
  456. "remotecontrol.css",
  457. "userimage.css",
  458. "livetv.css",
  459. "nowplaying.css",
  460. "icons.css"
  461. };
  462. var builder = new StringBuilder();
  463. foreach (var file in files)
  464. {
  465. var path = GetDashboardResourcePath("css/" + file);
  466. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  467. {
  468. using (var streamReader = new StreamReader(fs))
  469. {
  470. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  471. builder.Append(text);
  472. builder.Append(Environment.NewLine);
  473. }
  474. }
  475. }
  476. var css = builder.ToString();
  477. //try
  478. //{
  479. // var result = new KristensenCssMinifier().Minify(builder.ToString(), false, Encoding.UTF8);
  480. // css = result.MinifiedContent;
  481. //}
  482. //catch (Exception ex)
  483. //{
  484. // Logger.ErrorException("Error minifying css", ex);
  485. //}
  486. var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(css));
  487. memoryStream.Position = 0;
  488. return memoryStream;
  489. }
  490. /// <summary>
  491. /// Gets the raw resource stream.
  492. /// </summary>
  493. /// <param name="path">The path.</param>
  494. /// <returns>Task{Stream}.</returns>
  495. private Stream GetRawResourceStream(string path)
  496. {
  497. return _fileSystem.GetFileStream(GetDashboardResourcePath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  498. }
  499. }
  500. }