Repository navigation
Expand file tree
/
Copy pathaction - Super Bookmarker - Script.js
More file actions
145 lines (123 loc) · 4.46 KB
/
Copy pathaction - Super Bookmarker - Script.js
File metadata and controls
145 lines (123 loc) · 4.46 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
/*
* @title: Push file to GitHub
* @author: thechelsuk
* @version: 1.6.0
* @notes: Creates a new file in a GitHub repo using the GitHub API.
* The draft content is used as the file content, and the draft title is used as the filename.
* The GitHub API requires a personal access token with repo permissions.
* 1.6.0: Refuses to post empty drafts or drafts without a usable title.
*
*/
// Configuration
const PATH = "_bookmarks";
const GITHUB_TOKEN_LABEL = "bm_gh_pat";
const GITHUB_REPO_LABEL = "bm_gh_repo";
const GITHUB_OWNER_LABEL = "bm_gh_owner";
// Wrapped in a function so we can return early:
// context.cancel() marks the action cancelled but does not stop the script.
function run() {
// Get credentials from credential store
let credential = Credential.create("Bookmarker GH", "PAT and Repo Details");
credential.addPasswordField(GITHUB_TOKEN_LABEL, "GitHub Personal Access Token");
credential.addTextField(GITHUB_OWNER_LABEL, "GitHub Repository Owner");
credential.addTextField(GITHUB_REPO_LABEL, "GitHub Repository Name");
// Prompt for credentials if needed
if (!credential.authorize()) {
app.displayErrorMessage("GitHub credentials not configured");
context.cancel();
return;
}
// FIX: Use the correct label constants to retrieve stored values
let token = credential.getValue(GITHUB_TOKEN_LABEL);
let owner = credential.getValue(GITHUB_OWNER_LABEL);
let repo = credential.getValue(GITHUB_REPO_LABEL);
let draftText = draft.content;
// Guard: never post an empty draft
if (!draftText || draftText.trim() === "") {
app.displayErrorMessage("Draft is empty — nothing posted.");
context.cancel();
return;
}
let lines = draftText.split("\n");
// Extract title (first line)
let title = lines[0].trim();
let sourceUrl = "";
for (let i = 0; i < lines.length; i++) {
if (lines[i].trim().toLowerCase().startsWith("link:")) {
sourceUrl = lines[i].replace(/^link:\s*/i, "").trim();
break;
}
}
let bodyLines = [];
for (let i = 1; i < lines.length; i++) {
let trimmedLine = lines[i].trim().toLowerCase();
if (
!trimmedLine.startsWith("source:") &&
!trimmedLine.startsWith("link:")
) {
bodyLines.push(lines[i]);
}
}
let body = bodyLines.join("\n").trim();
// Generate slug from title
function generateSlug(title) {
return title
.toLowerCase()
.trim()
.replace(/[^\w\s-]/g, "") // Remove special characters
.replace(/\s+/g, "-") // Replace spaces with hyphens
.replace(/-+/g, "-") // Replace multiple hyphens with single hyphen
.replace(/^-+|-+$/g, ""); // Remove leading/trailing hyphens
}
let slug = generateSlug(title);
// Guard: need a usable title for the filename
if (!title || !slug) {
app.displayErrorMessage("Draft has no usable title on the first line — nothing posted.");
context.cancel();
return;
}
// Get today's date in YYYY-MM-DD format
let today = new Date();
let dateString = today.toISOString().split("T")[0];
// Generate filename
let filename = `${dateString}-${slug}.md`;
// Create Jekyll front matter
let frontMatter = `---
title: "${title}"
date: ${dateString}
i_url: "${sourceUrl}"
i_type: u-bookmark-of
type: bookmark
layout: bookmark
---
`;
let fileContent = frontMatter + body;
let base64Content = Base64.encode(fileContent);
let apiUrl = `https://api.github.com/repos/${owner}/${repo}/contents/${PATH}/${filename}`;
let http = HTTP.create();
let response = http.request({
url: apiUrl,
method: "PUT",
headers: {
Authorization: `token ${token}`,
"Content-Type": "application/json",
Accept: "application/vnd.github.v3+json",
"User-Agent": "Drafts-GitHub-Action",
},
data: {
message: `Add new post: ${title}`,
content: base64Content,
branch: "main",
},
});
if (response.success) {
app.displaySuccessMessage(`✓ Published: ${filename}`);
} else {
let errorMsg = `Failed to publish post.\nStatus: ${response.statusCode}`;
if (response.responseText) {
errorMsg += `\nResponse: ${response.responseText}`;
}
app.displayErrorMessage(errorMsg);
}
}
run();