summaryrefslogtreecommitdiffstats
path: root/packages/gitbook/src/output/modifiers/fetchRemoteImages.js
diff options
context:
space:
mode:
Diffstat (limited to 'packages/gitbook/src/output/modifiers/fetchRemoteImages.js')
-rw-r--r--packages/gitbook/src/output/modifiers/fetchRemoteImages.js44
1 files changed, 44 insertions, 0 deletions
diff --git a/packages/gitbook/src/output/modifiers/fetchRemoteImages.js b/packages/gitbook/src/output/modifiers/fetchRemoteImages.js
new file mode 100644
index 0000000..f022093
--- /dev/null
+++ b/packages/gitbook/src/output/modifiers/fetchRemoteImages.js
@@ -0,0 +1,44 @@
+const path = require('path');
+const crc = require('crc');
+
+const editHTMLElement = require('./editHTMLElement');
+const fs = require('../../utils/fs');
+const LocationUtils = require('../../utils/location');
+
+/**
+ * Fetch all remote images
+ *
+ * @param {String} rootFolder
+ * @param {String} currentFile
+ * @param {HTMLDom} $
+ * @return {Promise}
+ */
+function fetchRemoteImages(rootFolder, currentFile, $) {
+ const currentDirectory = path.dirname(currentFile);
+
+ return editHTMLElement($, 'img', function($img) {
+ let src = $img.attr('src');
+ const extension = path.extname(src);
+
+ if (!LocationUtils.isExternal(src)) {
+ return;
+ }
+
+ // We avoid generating twice the same PNG
+ const hash = crc.crc32(src).toString(16);
+ const fileName = hash + extension;
+ const filePath = path.join(rootFolder, fileName);
+
+ return fs.assertFile(filePath, function() {
+ return fs.download(src, filePath);
+ })
+ .then(function() {
+ // Convert to relative
+ src = LocationUtils.relative(currentDirectory, fileName);
+
+ $img.replaceWith('<img src="' + src + '" />');
+ });
+ });
+}
+
+module.exports = fetchRemoteImages;