-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.js
More file actions
497 lines (432 loc) · 15.9 KB
/
extension.js
File metadata and controls
497 lines (432 loc) · 15.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
const vscode = require('vscode');
const jwt = require('jsonwebtoken');
const axios = require('axios');
const marked = require('marked');
const matter = require('gray-matter');
const turndown = require('turndown');
const turndownService = new turndown(
{
headingStyle: 'atx'
}
);
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const secretKey = vscode.workspace.getConfiguration().get('code2ghost.secretKey');
const iv = crypto.randomBytes(16);
const ERR_NO_EDITOR = 'No active editor found.';
const ERR_404 = 'Post not found. Do the post exist?';
/**
* @param {vscode.ExtensionContext} context
*/
function activate(context) {
const set_config = vscode.commands.registerCommand('code2ghost.setConfig', async function () {
vscode.window.showInformationMessage('Setting Config...');
const url = await vscode.window.showInputBox({ prompt: 'Enter API URL' });
const key = await vscode.window.showInputBox({ prompt: 'Enter Admin API key' });
setConfig(context, url, key);
});
const get_config = vscode.commands.registerCommand('code2ghost.getConfig', function () {
const { bareUrl, key } = getConfig(context);
vscode.window.showInformationMessage(`URL: ${bareUrl}, Key: ${key}`);
});
const create_post_current_editor_draft = vscode.commands.registerCommand('code2ghost.createPostCurrentEditorDraft', async function () {
// vscode.window.showInformationMessage('Creating Post...');
createPost(context, 0);
});
const create_post_current_editor_publish = vscode.commands.registerCommand('code2ghost.createPostCurrentEditorPublish', async function () {
// vscode.window.showInformationMessage('Creating Post...');
createPost(context, 1);
});
const get_post = vscode.commands.registerCommand('code2ghost.getPost', function () {
getPost(context);
});
const update_post_current_editor = vscode.commands.registerCommand('code2ghost.updatePostCurrentEditor', async function () {
updatePost(context);
});
const sync_post_current_editor = vscode.commands.registerCommand('code2ghost.syncPostCurrentEditor', async function () {
syncPost(context);
});
context.subscriptions.push(set_config);
context.subscriptions.push(get_config);
context.subscriptions.push(create_post_current_editor_draft);
context.subscriptions.push(create_post_current_editor_publish);
context.subscriptions.push(get_post);
context.subscriptions.push(update_post_current_editor);
context.subscriptions.push(sync_post_current_editor);
}
function deactivate() {}
function setConfig(context, url, key) {
context.globalState.update('ghostUrl', url);
context.globalState.update('ghostAdminKey', encrypt(key));
}
function getConfig(context) {
const bareUrl = context.globalState.get('ghostUrl');
const key = decrypt(context.globalState.get('ghostAdminKey'));
return { bareUrl, key };
}
function encrypt(text) {
let cipher = crypto.createCipheriv(algorithm, Buffer.from(secretKey), iv);
let encrypted = cipher.update(text, 'utf-8', 'hex');
encrypted += cipher.final('hex');
return iv.toString('hex') + ':' + encrypted;
}
function decrypt(text) {
let textParts = text.split(':');
let iv = Buffer.from(textParts.shift(), 'hex');
let encryptedText = textParts.join(':');
let decipher = crypto.createDecipheriv(algorithm, Buffer.from(secretKey), iv);
let decrypted = decipher.update(encryptedText, 'hex', 'utf-8');
decrypted += decipher.final('utf-8');
return decrypted;
}
function getAuthToken(context) {
const { key } = getConfig(context);
// Split the key into ID and SECRET
const [id, secret] = key.split(':');
// Create the token (including decoding secret)
const authToken = jwt.sign({}, Buffer.from(secret, 'hex'), {
keyid: id,
algorithm: 'HS256',
expiresIn: '5m',
audience: `/admin/`
});
return authToken;
};
async function createPost(context, publish) {
vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: 'Creating Post...',
cancellable: false
},
async (progress, token) => {
const authToken = getAuthToken(context);
const { bareUrl } = getConfig(context);
const { h1, html, FMtitle, FMauthors, FMtags } = await getEditor(bareUrl, authToken);
// if title is provided in the front matter, title of the post won't be asked.
var postTitle = null
if (FMtitle) {
postTitle = FMtitle;
} else {
postTitle = await vscode.window.showInputBox({ prompt: 'Enter Post Title', value: h1 });
if (!postTitle) {
vscode.window.showInformationMessage('Post creation cancelled.');
return;
}
}
// Make an authenticated request to create a post
const url = bareUrl + '/ghost/api/admin/posts/?source=html';
const headers = { Authorization: `Ghost ${authToken}` };
// const payload = {
// posts: [{
// title: postTitle,
// html: html,
// authors: Array.isArray(FMauthors) ? FMauthors : [FMauthors],
// tags: Array.isArray(FMtags) ? FMtags : [FMtags]
// }]
// };
const postData = {
title: postTitle,
html: html
};
if (FMauthors && Array.isArray(FMauthors) && FMauthors.length > 0) {
postData.authors = FMauthors;
}
if (FMtags && Array.isArray(FMtags) && FMtags.length > 0) {
postData.tags = FMtags;
}
if (publish) {
postData.status = "published";
}
const payload = { posts: [postData] };
let res;
try {
res = await axios.post(url, payload, { headers });
} catch (error) {
console.error(error);
vscode.window.showErrorMessage('Failed to create post.');
return;
}
// Update front-matter
// updateFM(res.data.posts[0]);
// Update FM only causes updating image everytime. Sync the post, the front-matter, URL of image will be updated.
syncPost(context);
vscode.window.showInformationMessage('Created Post successful at ' + `[${bareUrl}/ghost/#/editor/post/${res.data.posts[0].id}](${bareUrl}/ghost/#/editor/post/${res.data.posts[0].id})`);
// vscode.commands.executeCommand('workbench.action.closeActiveEditor');
}
);
}
async function updatePost(context) {
vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: 'Updating Post...',
cancellable: false
},
async (progress, token) => {
const authToken = getAuthToken(context);
const { bareUrl } = getConfig(context);
const { html, FMtitle, FMauthors, FMtags, FMid, FMupdated_at, FMstatus } = await getEditor(bareUrl, authToken);
const postTitle = FMtitle
// Make an authenticated request to create a post
const url = bareUrl + '/ghost/api/admin/posts/' + FMid + '/?source=html';
const headers = { Authorization: `Ghost ${authToken}` };
const postData = {
title: postTitle,
html: html,
status: FMstatus,
updated_at: FMupdated_at
};
if (FMauthors && Array.isArray(FMauthors) && FMauthors.length > 0) {
postData.authors = FMauthors;
}
if (FMtags && Array.isArray(FMtags) && FMtags.length > 0) {
postData.tags = FMtags;
}
const payload = { posts: [postData] };
let res;
try {
res = await axios.put(url, payload, { headers });
} catch (error) {
console.error(error);
if (error.response.status == 404) {
vscode.window.showErrorMessage(ERR_404);
return;
}
if (res.status == 409) {
vscode.window.showErrorMessage('Post has been updated since you last get it, please get the post again and modify from the newer version.');
return;
}
vscode.window.showErrorMessage('Failed to update post.');
return;
}
// Update front-matter
// updateFM(res.data.posts[0]);
// Update FM only causes updating image everytime. Sync the post, the front-matter, URL of image will be updated.
syncPost(context);
vscode.window.showInformationMessage('Updated Post successful at ' + `[${bareUrl}/ghost/#/editor/post/${res.data.posts[0].id}](${bareUrl}/ghost/#/editor/post/${res.data.posts[0].id})`);
// vscode.commands.executeCommand('workbench.action.closeActiveEditor');
}
);
}
async function syncPost(context) {
vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: 'Syncing Post...',
cancellable: false
},
async (progress, token) => {
const FMid = getPostFM().id;
const post = await getPostById(context, FMid);
if (post) {
if (post.updated_at == getPostFM().updated_at) {
vscode.window.showInformationMessage('The post is already up-to-date.');
return;
}
const editor = vscode.window.activeTextEditor;
if (editor) {
const newContent = parseFM(post) + '\n' + turndownService.turndown(post.html);
editor.edit(editBuilder => {
const document = editor.document;
const lastLine = document.lineAt(document.lineCount - 1);
const range = new vscode.Range(new vscode.Position(0, 0), lastLine.range.end);
editBuilder.delete(range);
editBuilder.insert(new vscode.Position(0, 0), newContent);
});
} else {
vscode.window.showInformationMessage(ERR_NO_EDITOR);
return;
}
} else {
return;
}
vscode.window.showInformationMessage('Post synced.');
}
);
}
async function uploadImage(filePath, imageUrl, authToken, bareUrl) {
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const FormData = require('form-data');
try {
const imagePath = path.resolve(filePath, imageUrl);
const image = fs.createReadStream(imagePath);
// Prepare FormData
const form = new FormData();
form.append('file', image);
form.append('ref', imageUrl);
const uploadUrl = `${bareUrl}/ghost/api/admin/images/upload/`;
const headers = {
...form.getHeaders(),
Authorization: `Ghost ${authToken}`,
'Accept-Version': 'v3',
};
const response = await axios.post(uploadUrl, form, { headers });
return response.data;
} catch (error) {
console.error('Image upload failed:', error);
throw new Error('Failed to upload image');
}
}
function addFMcomment(FM) {
const comment = `# This front-matter is generated by Code2Ghost.\n# Under any circumstances, please do not modify the \`url\` \`id\` \`updated_at\` fields (It will be readed when updating the post).\n# If you modify other parts, the changes will overwrite the original settings of the post, not merged.\n`;
const commentPublish = `\n# If you set \`status\` to \`published\`, the post will be published.\n`
var frontMatterString
if (FM.status == `published`) {
frontMatterString = matter.stringify('', FM).replace(/---\s*$/, comment + '---');
} else {
frontMatterString = matter.stringify('', FM).replace(/---\s*$/, comment + commentPublish + '---');
}
frontMatterString += `\n`;
return frontMatterString
}
function parseFM(FMdata) {
const showComment = vscode.workspace.getConfiguration().get('code2ghost.showFrontMatterComment');
const FM = {
id: FMdata.id,
url: FMdata.url,
updated_at: FMdata.updated_at,
status: FMdata.status,
title: FMdata.title,
tags: FMdata.tags.map(tag => tag.name),
authors: FMdata.authors.map(author => author.email)
};
if (showComment) {
return addFMcomment(FM);
} else {
return matter.stringify('', FM);
}
}
function updateFM(FMdata) {
const editor = vscode.window.activeTextEditor;
if (editor) {
const fileContent = editor.document.getText();
const { data, content } = matter(fileContent);
let newContent = parseFM(FMdata);
if (!content.startsWith('\n')) {
newContent += '\n';
}
newContent += content;
editor.edit(editBuilder => {
const document = editor.document;
const lastLine = document.lineAt(document.lineCount - 1);
const range = new vscode.Range(new vscode.Position(0, 0), lastLine.range.end);
editBuilder.delete(range);
editBuilder.insert(new vscode.Position(0, 0), newContent);
});
} else {
vscode.window.showInformationMessage(ERR_NO_EDITOR);
}
}
function getPostFM() {
const editor = vscode.window.activeTextEditor;
if (editor) {
const fileContent = editor.document.getText();
const { data } = matter(fileContent);
return data;
} else {
vscode.window.showInformationMessage(ERR_NO_EDITOR);
}
}
async function getEditor(bareUrl, authToken) {
const editor = vscode.window.activeTextEditor;
if (editor) {
const filePath = editor.document.fileName.replace(/[^/\\]*$/, '');
const fileContent = editor.document.getText();
const { data, content } = matter(fileContent);
const html = marked.parse(content);
var resolvedHtml = await html;
// Get all images
// const imageMatches = [...fileContent.matchAll(/!\[([^\]]*)\]\(([^)]+)\)/g)].map(match => match[2]);
const imageMatches = [...resolvedHtml.matchAll(/<img[^>]*src=["'](.*?)["'][^>]*>/g)]
.map(match => match[1])
.filter(imageUrl => !imageUrl.startsWith('http') && !imageUrl.startsWith('https'));
const uploadedImages = {};
for (let imageUrl of imageMatches) {
try {
const uploadedData = await uploadImage(filePath, imageUrl, authToken, bareUrl);
const ghostImageUrl = uploadedData.images[0].url; // Get URL in Ghost
uploadedImages[imageUrl] = ghostImageUrl;
// Replace html
resolvedHtml = resolvedHtml.replace(imageUrl, ghostImageUrl);
} catch (error) {
console.error(`Failed to upload image: ${imageUrl}`);
}
}
// TODO: Use a more efficiency way to identifiy title
const h1Match = resolvedHtml.match(/<h1.*?>(.*?)<\/h1>/);
const h1 = h1Match ? h1Match[1] : 'Untitled';
const resolvedHtmlWithoutTitle = resolvedHtml.replace(/<h1.*?>(.*?)<\/h1>/, '');
const FMtitle = data.title || null;
const FMauthors = data.authors || null;
const FMtags = data.tags || null;
// Post id will be readed when updating post.
const FMid = data.id || null;
// updated_at is necessary.
const FMupdated_at = data.updated_at || null;
// Post status is set by different command when creating post, and read by front-matter when updating post.
const FMstatus = data.status || null;
return { h1, html: resolvedHtmlWithoutTitle, FMtitle, FMauthors, FMtags, FMid, FMupdated_at, FMstatus };
} else {
vscode.window.showInformationMessage(ERR_NO_EDITOR);
}
}
async function getPosts(context) {
const authToken = getAuthToken(context);
const { bareUrl } = getConfig(context);
const url = bareUrl + '/ghost/api/admin/posts/?formats=html';
const headers = { Authorization: `Ghost ${authToken}` };
let res;
try {
res = await axios.get(url, { headers });
} catch (error) {
console.error(error);
vscode.window.showErrorMessage('Failed to get posts.');
return;
}
// console.log(res.data.posts);
return res.data.posts;
}
async function getPost(context) {
const posts = await getPosts(context);
if (posts) {
const postTitles = posts.map(post => post.title);
const selectedPostTitle = await vscode.window.showQuickPick(postTitles, { placeHolder: 'Select a post to open' });
if (selectedPostTitle) {
const selectedPost = posts.find(post => post.title === selectedPostTitle);
// const { bareUrl } = getConfig(context);
// vscode.env.openExternal(vscode.Uri.parse(`${bareUrl}/ghost/#/editor/post/${selectedPost.id}`));
const PostMD = turndownService.turndown(selectedPost.html);
const content = parseFM(selectedPost)+ '\n' + PostMD;
const document = await vscode.workspace.openTextDocument({ content: content, language: 'markdown' });
await vscode.window.showTextDocument(document);
}
}
}
async function getPostById(context, id) {
const authToken = getAuthToken(context);
const { bareUrl } = getConfig(context);
const url = bareUrl + '/ghost/api/admin/posts/' + id + '?formats=html';
const headers = {
Authorization: `Ghost ${authToken}`
};
let res;
try {
res = await axios.get(url, { headers });
} catch (error) {
if (error.response.status == 404) {
vscode.window.showErrorMessage(ERR_404);
return;
}
console.error(error);
vscode.window.showErrorMessage('Failed to sync posts.');
return;
}
return res.data.posts[0];
}
module.exports = {
activate,
deactivate
}