-
Notifications
You must be signed in to change notification settings - Fork 1
/
drafts
76 lines (66 loc) · 2.61 KB
/
drafts
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
// Create a GitHub credential
let githubCredential = Credential.create("GitHub", "Enter your GitHub details for posting to your repository.");
githubCredential.addTextField("username", "Username");
githubCredential.addPasswordField("token", "Personal Access Token");
githubCredential.addTextField("repoName", "Repository Name");
githubCredential.addTextField("email", "Email Address");
// Prompt the user for credentials if not already saved
if (!githubCredential.authorize()) {
console.log("Authorization failed or was cancelled by the user.");
context.fail();
}
// Extract details from the credentials
const username = githubCredential.getValue("username");
const token = githubCredential.getValue("token");
const repoName = githubCredential.getValue("repoName");
const email = githubCredential.getValue("email");
// Prepare your post content with front matter
const title = draft.content.split("\n")[0].replace('# ', ''); // Assuming the first line of the draft is the title
const date = new Date().toISOString().split('T')[0];
const slug = title.toLowerCase().replace(/\s+/g, '-').replace(/[^\w\-]+/g, '').replace(/\-\-+/g, '-').trim('-');
const fileName = `${date}-${slug}.md`;
// Dynamically generate categories from Drafts tags
const categories = draft.tags.join(', ');
// Construct front matter
const frontMatter = `---
layout: post
title: "${title}"
date: ${date}
categories: [${categories}] // Dynamically generated categories from Drafts tags
---
`;
const fullContent = frontMatter + draft.content.split("\n").slice(1).join("\n"); // Append the rest of the draft content excluding the title
const encodedContent = Base64.encode(fullContent);
// Setup for the GitHub API request
const path = `_posts/${fileName}`;
const apiUrl = `https://api.github.com/repos/${username}/${repoName}/contents/${path}`;
const data = {
owner: `${username}`,
repo: `${repoName}`,
path: `${path}`,
message: 'Sent from Drafts',
committer: {
name: `${username}`,
email: `${email}`
},
content: encodedContent
};
// Create the HTTP request
let http = HTTP.create();
let response = http.request({
"url": apiUrl,
"method": "PUT",
"headers": {
"Authorization": `Bearer ${token}`,
"User-Agent": "DraftsApp",
"Content-Type": "application/json",
'X-GitHub-Api-Version': '2022-11-28'
},
"data": JSON.stringify(data)
});
// Process the response
if (response.statusCode === 200 || response.statusCode === 201) {
console.log("Successfully created/updated the file on GitHub.");
} else {
console.log("Failed to post to GitHub. Status code: " + response.statusCode + " Response: " + response.responseText);
}