auto-upload-images.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. /**
  2. * Image Auto Upload script for Hexo static site generator.
  3. *
  4. * Automatically detects linked external images on each post, downloads them
  5. * into the corresponding folder for the post and puts new image urls in the
  6. * post body.
  7. *
  8. * IMPORTANT!!
  9. * To work properly set `post_asset_folder` to `true` in _config.yml
  10. * And install hexo-asset-link plugin:
  11. * npm i -s hexo-asset-link
  12. *
  13. * To use:
  14. * - create a folder called `scripts` on Hexo root and put this inside.
  15. * - then run `hexo generate`
  16. * - after the script finishes, delete it or move outside of scripts folder.
  17. */
  18. const fs = require('fs');
  19. const path = require('path');
  20. const config = hexo.config;
  21. const http = require('http');
  22. const https = require('https');
  23. /**
  24. * Terminal colors.
  25. *
  26. * Usage:
  27. * console.log(`${g('I')} love ${r('Italy')}`);
  28. * console.log(g(`This is your name: ${name}`));
  29. * console.log(r(`Red `), g(`Red `), b(`Red `));
  30. *
  31. * Hint: r,g,b,w,c,m,y,k stands for Red, Green, Blue, White, Cyan, Magenta,
  32. * Yellow and Blac(k).
  33. *
  34. * @source https://stackoverflow.com/a/46705010
  35. */
  36. const { r, g, b, w, c, m, y, k } = [
  37. ['r', 1], ['g', 2], ['b', 4], ['w', 7],
  38. ['c', 6], ['m', 5], ['y', 3], ['k', 0],
  39. ].reduce((cols, col) => ({
  40. ...cols, [col[0]]: f => `\x1b[3${col[1]}m${f}\x1b[0m`
  41. }), {});
  42. /**
  43. * Replaces with multiple string pairs in one go.
  44. *
  45. * @source https://stackoverflow.com/a/16577007
  46. */
  47. String.prototype.allReplace = function(obj) {
  48. var retStr = this;
  49. for (var x in obj) {
  50. retStr = retStr.replace(new RegExp(x, 'g'), obj[x]);
  51. }
  52. return retStr;
  53. };
  54. /**
  55. * Makes the string safe (escape) for running regex with it.
  56. *
  57. * @source https://esdiscuss.org/topic/regexp-escape#content-10
  58. *
  59. * @param thestring str The string to make it safe for regex.
  60. * @return str
  61. */
  62. function regex_safe_string(thestring) {
  63. return thestring.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
  64. }
  65. /**
  66. * Downloads a bunch of urls in an array and returns array to replace them
  67. * in content.
  68. *
  69. * @param urlList array An array holding all the image urls to be downloaded.
  70. * @param destDirectory str Destination directory where all images will be
  71. * downloaded to.
  72. * @param relatedFile str (optional) But required if you want to get relative
  73. * url to the images in the return array.
  74. * @return array
  75. */
  76. async function downloadFiles(urlList, destDirectory, relatedFile='', regexSafe=true) {
  77. return new Promise(async (resolve) => {
  78. var replaceUrlList=[];
  79. var requestClient = http;
  80. for (const url of urlList) {
  81. var destFile = destDirectory + path.sep + path.basename(url);
  82. if (relatedFile) {
  83. var destFileReplace = path.relative(relatedFile, destFile);
  84. // Gets rid of the prepending '../' that gets returned by
  85. // path.relative() function.
  86. destFileReplace = destFileReplace.replace('../', '');
  87. } else {
  88. var destFileReplace = destFile;
  89. }
  90. // Deletes files from previous failed attempts (files that got
  91. // created but could not complete download).
  92. // Please note that it works most of the times but not 100% of the
  93. // times. So it is recommended that the process is not inturrupted
  94. // (e.g. with Ctrl+C).
  95. if (fs.existsSync(destFile)) {
  96. if (fs.statSync(destFile)['size'] == 0) {
  97. try {
  98. fs.unlinkSync(destFile);
  99. } catch(err) {
  100. console.error(r(err));
  101. }
  102. }
  103. }
  104. if (!fs.existsSync(destFile)) {
  105. try {
  106. var file = fs.createWriteStream(destFile);
  107. requestClient=(url.startsWith("https:")) ? https : http;
  108. var prom = await new Promise((resolve, reject) => {
  109. var request = requestClient.get(url, function(response) {
  110. response.pipe(file);
  111. console.log(g('-- Downloaded: '+url));
  112. resolve();
  113. });
  114. // Handles request failure
  115. request.on('error', err => {
  116. fs.unlink(destFile, () => reject(err));
  117. });
  118. // Handles file system failure
  119. file.on('error', err => {
  120. fs.unlink(destFile, () => reject(err));
  121. });
  122. });
  123. if (regexSafe==true) {
  124. replaceUrlList[regex_safe_string(url)] = destFileReplace;
  125. } else {
  126. replaceUrlList[url] = destFileReplace;
  127. }
  128. //replaceUrlList[url] = '{% asset_img "'+path.basename(destFile)+'" "some title" %}';
  129. } catch (e) {
  130. // Push existing url, since we failed to download it
  131. if (regexSafe==true) {
  132. replaceUrlList[regex_safe_string(url)] = url;
  133. } else {
  134. replaceUrlList[url] = url;
  135. }
  136. console.error(r('[Error]: ') + destFile + '\n' + e.message);
  137. }
  138. } else {
  139. if (regexSafe==true) {
  140. replaceUrlList[regex_safe_string(url)] = destFileReplace;
  141. } else {
  142. replaceUrlList[url] = destFileReplace;
  143. }
  144. //replaceUrlList[url] = '{% asset_img "'+path.basename(destFile)+'" "some title" %}';
  145. }
  146. };
  147. resolve(replaceUrlList);
  148. });
  149. }
  150. async function process(file) {
  151. // look into only .md files and ignore others
  152. if (!fs.existsSync(file) || !file.match(/\.md/)) {
  153. return;
  154. }
  155. return new Promise(async (resolve) => {
  156. // Gets directory to put downloaded images into
  157. var imageDir = file.match(/(.*)\.md/)[1];
  158. console.log(c(`== Processing file: ${file}`));
  159. if (fs.existsSync(imageDir)) {
  160. console.log(g("-- Image directory "+imageDir+" found"));
  161. } else {
  162. fs.mkdirSync(imageDir);
  163. console.log(y("-- Image directory not found. Created directory "+imageDir));
  164. }
  165. try {
  166. var encoding = 'utf-8';
  167. var content = fs.readFileSync(file, encoding);
  168. var imageUrls = content.matchAll(/\!\[.*\]\((https?:.*.(?:jpg|gif|png)).*\)/g);
  169. imageUrls = Array.from(imageUrls, m => m[1]);
  170. if (imageUrls) {
  171. var replaces = await downloadFiles(imageUrls, imageDir, file);
  172. if (Object.keys(replaces).length > 0) {
  173. content = await content.allReplace(replaces);
  174. fs.writeFileSync(file, content, encoding);
  175. console.log(c("-- Replaced "+Object.keys(replaces).length+" image urls"));
  176. } else {
  177. console.log(g("-- No replacements were needed for image urls"));
  178. }
  179. } else {
  180. console.log(c("-- No image URLs found"));
  181. }
  182. } catch (e) {
  183. console.error(r('[Error]: ') + file + '\n' + e.message);
  184. }
  185. resolve();
  186. });
  187. }
  188. async function walk(dir) {
  189. if (!fs.existsSync(dir)) {
  190. return;
  191. }
  192. var files = fs.readdirSync(dir);
  193. for (const fileName of files) {
  194. var curPath = path.join(dir, fileName);
  195. var stats = fs.statSync(curPath);
  196. if (stats.isFile()) {
  197. await process(curPath);
  198. } else {
  199. await walk(curPath);
  200. }
  201. };
  202. }
  203. async function run(locals, render, callback) {
  204. // Check for the requirements
  205. if (!config.post_asset_folder) {
  206. console.error(r('[Error]: ')+'Setting `post_asset_folder: true` in `_config.yml` is only currently supported');
  207. return;
  208. }
  209. try {
  210. require.resolve("hexo-asset-link");
  211. } catch(e) {
  212. console.error(r("[Error]: ")+"hexo-asset-link package is not found. Please install with `npm i -s hexo-asset-link`");
  213. return;
  214. }
  215. console.log(y("WARNING! The auto image upload process has started. Do not inturrupt the process (e.g. by pressing Ctrl+C). Doing this may result in empty image files."));
  216. console.log("-------------------------------------------------------------");
  217. // Run the download and replace...
  218. await walk(source_dir);
  219. console.log("-------------------------------------------------------------");
  220. console.log(y("== IMPORTANT!! The replacement procedure was completed. To not run it everytime you run `hexo generate`, delete "+__filename+" or move this file elsewhere out of the scripts folder."));
  221. if (callback) { callback(); }
  222. locals.posts.map(function(post){
  223. //console.log(post);
  224. });
  225. }
  226. // Since we are running this from `scripts`, we would go up one directory
  227. var public_dir = path.resolve(__dirname, '../')+path.sep+config.public_dir;
  228. var source_dir = path.resolve(__dirname, '../')+path.sep+config.source_dir;
  229. (async() => {
  230. var generator = hexo.extend.generator;
  231. if (generator.register.length === 1) {
  232. generator.register(run);
  233. } else {
  234. generator.register('autouploadimages', run);
  235. }
  236. })();