PackageCreator.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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.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. "dashboardsync.js",
  300. "device.js",
  301. "devices.js",
  302. "devicesupload.js",
  303. "directorybrowser.js",
  304. "dlnaprofile.js",
  305. "dlnaprofiles.js",
  306. "dlnasettings.js",
  307. "dlnaserversettings.js",
  308. "editcollectionitems.js",
  309. "edititemmetadata.js",
  310. "edititemimages.js",
  311. "edititemsubtitles.js",
  312. "playbackconfiguration.js",
  313. "cinemamodeconfiguration.js",
  314. "encodingsettings.js",
  315. "externalplayer.js",
  316. "favorites.js",
  317. "forgotpassword.js",
  318. "forgotpasswordpin.js",
  319. "gamesrecommendedpage.js",
  320. "gamesystemspage.js",
  321. "gamespage.js",
  322. "gamegenrepage.js",
  323. "gamestudiospage.js",
  324. "homelatest.js",
  325. "indexpage.js",
  326. "itembynamedetailpage.js",
  327. "itemdetailpage.js",
  328. "itemgallery.js",
  329. "itemlistpage.js",
  330. "librarypathmapping.js",
  331. "reports.js",
  332. "librarysettings.js",
  333. "livetvchannel.js",
  334. "livetvchannels.js",
  335. "livetvguide.js",
  336. "livetvnewrecording.js",
  337. "livetvprogram.js",
  338. "livetvrecording.js",
  339. "livetvrecordinglist.js",
  340. "livetvrecordings.js",
  341. "livetvtimer.js",
  342. "livetvseriestimer.js",
  343. "livetvseriestimers.js",
  344. "livetvsettings.js",
  345. "livetvsuggested.js",
  346. "livetvstatus.js",
  347. "livetvtimers.js",
  348. "loginpage.js",
  349. "logpage.js",
  350. "medialibrarypage.js",
  351. "metadataconfigurationpage.js",
  352. "metadataimagespage.js",
  353. "metadatasubtitles.js",
  354. "metadatakodi.js",
  355. "moviegenres.js",
  356. "moviecollections.js",
  357. "movies.js",
  358. "movieslatest.js",
  359. "moviepeople.js",
  360. "moviesrecommended.js",
  361. "moviestudios.js",
  362. "movietrailers.js",
  363. "musicalbums.js",
  364. "musicalbumartists.js",
  365. "musicartists.js",
  366. "musicgenres.js",
  367. "musicrecommended.js",
  368. "musicvideos.js",
  369. "mypreferencesdisplay.js",
  370. "mypreferenceslanguages.js",
  371. "mypreferenceswebclient.js",
  372. "notifications.js",
  373. "notificationlist.js",
  374. "notificationsetting.js",
  375. "notificationsettings.js",
  376. "playlist.js",
  377. "playlists.js",
  378. "playlistedit.js",
  379. "plugincatalogpage.js",
  380. "pluginspage.js",
  381. "remotecontrol.js",
  382. "scheduledtaskpage.js",
  383. "scheduledtaskspage.js",
  384. "search.js",
  385. "selectserver.js",
  386. "serversecurity.js",
  387. "songs.js",
  388. "supporterkeypage.js",
  389. "supporterpage.js",
  390. "episodes.js",
  391. "thememediaplayer.js",
  392. "tvgenres.js",
  393. "tvlatest.js",
  394. "tvpeople.js",
  395. "tvrecommended.js",
  396. "tvshows.js",
  397. "tvstudios.js",
  398. "tvupcoming.js",
  399. "useredit.js",
  400. "usernew.js",
  401. "myprofile.js",
  402. "userpassword.js",
  403. "userprofilespage.js",
  404. "userparentalcontrol.js",
  405. "userlibraryaccess.js",
  406. "wizardfinishpage.js",
  407. "wizardservice.js",
  408. "wizardstartpage.js",
  409. "wizardsettings.js",
  410. "wizarduserpage.js"
  411. };
  412. }
  413. private async Task AppendLocalization(Stream stream, string culture)
  414. {
  415. var js = "window.localizationGlossary=" + _jsonSerializer.SerializeToString(_localization.GetJavaScriptLocalizationDictionary(culture));
  416. var bytes = Encoding.UTF8.GetBytes(js);
  417. await stream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  418. }
  419. /// <summary>
  420. /// Appends the resource.
  421. /// </summary>
  422. /// <param name="outputStream">The output stream.</param>
  423. /// <param name="path">The path.</param>
  424. /// <param name="newLineBytes">The new line bytes.</param>
  425. /// <returns>Task.</returns>
  426. private async Task AppendResource(Stream outputStream, string path, byte[] newLineBytes)
  427. {
  428. path = GetDashboardResourcePath(path);
  429. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  430. {
  431. using (var streamReader = new StreamReader(fs))
  432. {
  433. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  434. var bytes = Encoding.UTF8.GetBytes(text);
  435. await outputStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
  436. }
  437. }
  438. await outputStream.WriteAsync(newLineBytes, 0, newLineBytes.Length).ConfigureAwait(false);
  439. }
  440. /// <summary>
  441. /// Gets all CSS.
  442. /// </summary>
  443. /// <returns>Task{Stream}.</returns>
  444. private async Task<Stream> GetAllCss()
  445. {
  446. var files = new[]
  447. {
  448. "site.css",
  449. "chromecast.css",
  450. "mediaplayer.css",
  451. "mediaplayer-video.css",
  452. "librarymenu.css",
  453. "librarybrowser.css",
  454. "detailtable.css",
  455. "card.css",
  456. "tileitem.css",
  457. "metadataeditor.css",
  458. "notifications.css",
  459. "search.css",
  460. "pluginupdates.css",
  461. "remotecontrol.css",
  462. "userimage.css",
  463. "livetv.css",
  464. "nowplaying.css",
  465. "icons.css"
  466. };
  467. var builder = new StringBuilder();
  468. foreach (var file in files)
  469. {
  470. var path = GetDashboardResourcePath("css/" + file);
  471. using (var fs = _fileSystem.GetFileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true))
  472. {
  473. using (var streamReader = new StreamReader(fs))
  474. {
  475. var text = await streamReader.ReadToEndAsync().ConfigureAwait(false);
  476. builder.Append(text);
  477. builder.Append(Environment.NewLine);
  478. }
  479. }
  480. }
  481. var css = builder.ToString();
  482. //try
  483. //{
  484. // var result = new KristensenCssMinifier().Minify(builder.ToString(), false, Encoding.UTF8);
  485. // css = result.MinifiedContent;
  486. //}
  487. //catch (Exception ex)
  488. //{
  489. // Logger.ErrorException("Error minifying css", ex);
  490. //}
  491. var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(css));
  492. memoryStream.Position = 0;
  493. return memoryStream;
  494. }
  495. /// <summary>
  496. /// Gets the raw resource stream.
  497. /// </summary>
  498. /// <param name="path">The path.</param>
  499. /// <returns>Task{Stream}.</returns>
  500. private Stream GetRawResourceStream(string path)
  501. {
  502. return _fileSystem.GetFileStream(GetDashboardResourcePath(path), FileMode.Open, FileAccess.Read, FileShare.ReadWrite, true);
  503. }
  504. }
  505. }