Image uplaod and replace works.

This commit is contained in:
Laur Ivan 2022-06-30 13:43:49 +02:00
parent 8cf8c12d54
commit be2467d2c8
5 changed files with 69 additions and 30 deletions

2
.gitignore vendored
View File

@ -1,4 +1,4 @@
.idea .idea
node_modules node_modules
dist dist
temp

View File

@ -12,12 +12,18 @@ const api = new GhostAdminAPI({
version: "v4.0", version: "v4.0",
}); });
let convertor = new Convertor("./src/data/markdown-it-example.md"); let convertor = new Convertor("./src/data/markdown-it-example.md");
convertor.processImages(api, "./"); convertor
.processImages(api, "./temp")
.then(() => {
console.log("ok");
})
.catch((r) => {
console.log(r);
});
let mdoc: string = ""; //convertor.process(); let mdoc: string = ""; //convertor.process();
let creation = false; let creation = false;
let imageUpload = true;
if (creation) { if (creation) {
api.posts api.posts

View File

@ -11,6 +11,10 @@ interface Stack {
meta: any; meta: any;
token: Token; token: Token;
} }
interface StackedImage {
path: string;
url: string;
}
const renderer: any = Renderer; const renderer: any = Renderer;
@ -21,6 +25,7 @@ const headerAsMarkdown = true;
export class Convertor { export class Convertor {
markups: Record<string, any> = {}; markups: Record<string, any> = {};
markers: Record<string, any> = {}; markers: Record<string, any> = {};
images: Record<string, StackedImage> = {};
sections: any[] = []; sections: any[] = [];
builder: any = new PostNodeBuilder(); builder: any = new PostNodeBuilder();
@ -209,28 +214,50 @@ export class Convertor {
* *
* @returns this * @returns this
*/ */
public processImages(api: any, basepath: string): Convertor { public async processImages(api: any, basepath: string) {
// collect images in an array // collect images in an array
const imageRegex = /!\[[^\]]*\]\((.*?)\s*("(?:.*[^"])")?\s*\)/g; const imageRegex = /!\[[^\]]*\]\((.*?)\s*("(?:.*[^"])")?\s*\)/g;
let images: string[] = []; //let images: string[] = [];
let m: any; //let m: any;
while ((m = imageRegex.exec(this.content))) { [...this.content.matchAll(imageRegex)].forEach(async (item) => {
if (images.indexOf(m[1]) < 0) images.push(m[1]); console.log(JSON.stringify(item));
} if (item[1] in this.images) {
console.log("Images: ", JSON.stringify(images)); console.log("Skip cached image for URL: ", item[1]);
} else {
let url = item[1];
// Add the image to the cache of processed images
this.images[url] = {
path: url,
url: url,
};
// download image locally if in an url // Download images locally if not already
images.forEach(async (url) => {
let localpath = url;
if (url.toLowerCase().startsWith("http")) { if (url.toLowerCase().startsWith("http")) {
// Download the image locally // Download the image locally
let localPath = path.join(basepath, path.basename(url)); let localpath = path.join(basepath, path.basename(url));
await downloadImagefromURL(url, localPath); await downloadImagefromURL(url, localpath);
// Upload the image to ghost
if (api) { if (api) {
await uploadToGhost(api, localPath); let reference = await uploadToGhost(api, localpath);
this.images[url].url = reference.url;
} }
} }
// replace the image string with the new URL
console.log(
"replace",
this.images[url].path,
" with ",
this.images[url].url
);
this.content = this.content.replaceAll(
this.images[url].path,
this.images[url].url
);
}
console.log(this.content);
}); });
return this;
} }
} }

View File

@ -2,9 +2,9 @@ import fs from "fs";
import http from "http"; import http from "http";
import https from "https"; import https from "https";
import path from "path"; import path from "path";
import { Blob } from "buffer";
import stream from "stream"; import stream from "stream";
import { Z_FIXED } from "zlib";
const Stream = stream.Transform; const Stream = stream.Transform;
@ -35,18 +35,26 @@ export async function downloadImagefromURL(url: string, filename: string) {
} }
interface Image { interface Image {
file: Blob | File | undefined; file: Blob | File | string;
purpose: "image" | "profile_image" | "icon"; purpose: "image" | "profile_image" | "icon";
ref?: string; ref?: string;
} }
export async function uploadToGhost(api: any, filename: string) { export interface GhostReference {
const data: Buffer = fs.readFileSync(filename); url: string;
ref: string;
}
export async function uploadToGhost(
api: any,
filename: string
): Promise<GhostReference> {
//const data: Buffer = fs.readFileSync(filename);
let image: Image = { let image: Image = {
ref: path.basename(filename), ref: path.basename(filename),
file: new Blob([data]), file: filename,
purpose: "image", purpose: "image",
}; };
let result = api.images.upload(image); let result = api.images.upload(image);
console.log(JSON.stringify(result)); return result;
} }

View File

@ -9,7 +9,7 @@
"forceConsistentCasingInFileNames": true, "forceConsistentCasingInFileNames": true,
"module": "CommonJS", "module": "CommonJS",
"moduleResolution": "Node", "moduleResolution": "Node",
"target": "ES2015", "target": "ES2021",
"outDir": "./dist", "outDir": "./dist",
"declaration": true, "declaration": true,
"declarationDir": "./dist/__types__", "declarationDir": "./dist/__types__",
@ -31,7 +31,5 @@
"strictNullChecks": true, "strictNullChecks": true,
"strictPropertyInitialization": true "strictPropertyInitialization": true
}, },
"include": [ "include": ["./src"]
"./src"
]
} }