Action
Send to Bear Blog
Posted by @otaviocc@social.lol,
Last update
about 14 hours ago
Publish or update a draft as a Bear Blog post, with its title, Markdown content, tags and discovery-feed setting.
Steps
-
script
// Send to Bear Blog — Drafts action script // First non-blank line = post title (leading #s are stripped) // Everything below it = post content (Markdown) // Draft tags = post tags // Running it again on the same draft updates the existing post. const MAP_PATH = "/Library/Scripts/bearblog-posts.json"; // draft uuid -> { uid, blog, published, discoverable, is_page } (() => { // --- Credentials (asked once, stored in Drafts' credential store) --- const cred = Credential.create("Bear Blog", "Your subdomain is the part before .bearblog.dev (for jane.bearblog.dev, enter “jane”). " + "You'll find your API key in Dashboard → Settings → API."); cred.addTextField("subdomain", "Subdomain"); cred.addPasswordField("apiKey", "API key"); if (!cred.authorize()) return context.cancel(); const subdomain = cred.getValue("subdomain").trim() .replace(/^https?:\/\//, "").replace(/\.bearblog\.dev.*$/, "").replace(/\/+$/, ""); const blog = subdomain.toLowerCase(); const base = `https://bearblog.dev/${subdomain}/api/v1/post/`; const headers = { "Authorization": `Bearer ${cred.getValue("apiKey").trim()}` }; const http = HTTP.create(); // --- Split the draft into title and content --- const lines = draft.content.split("\n"); const start = lines.findIndex(l => l.trim() !== ""); if (start < 0) return fail("This draft is empty. Put the title on the first line and the post below it."); // Only real heading syntax ("# Title") is stripped; "#hashtag titles" keep their "#". const title = lines[start].trim().replace(/^#+(\s+|$)/, "").trim(); const content = lines.slice(start + 1).join("\n").trim(); if (!title) return fail("The first line has no text after the “#”. Add a title there."); if (title.length > 200) return fail(`Bear Blog titles can be up to 200 characters. Yours is ${title.length}, so shorten the first line and try again.`); // --- Has this draft been posted before? --- const fm = FileManager.createCloud(); let map = {}; if (fm.exists(MAP_PATH)) { // Never fall back to an empty list here: writing it back would erase every other link. try { map = fm.readJSON(MAP_PATH); } catch (e) { map = null; } if (!map || typeof map !== "object" || Array.isArray(map)) { return fail("Couldn't read the list of posts linked to your drafts, so nothing was sent. Give iCloud a moment to sync and try again."); } } let entry = map[draft.uuid]; if (typeof entry === "string") entry = { uid: entry }; // older map format if (!entry || typeof entry !== "object") entry = null; // A link made on another blog doesn't apply here. (Entries without a blog are older; assume this one.) let otherBlog = ""; if (entry && entry.blog && String(entry.blog).toLowerCase() !== blog) { otherBlog = String(entry.blog); entry = null; } const isUpdate = !!(entry && entry.uid); const isLive = isUpdate && entry.published === true; // --- What does Bear have for the discovery feed? --- // The link file usually knows. If it doesn't (older entry), ask Bear, so the switch below starts truthful. let shown = !!(entry && entry.discoverable); if (isUpdate && typeof entry.discoverable !== "boolean") { const cur = http.request({ url: `${base}${entry.uid}/`, method: "GET", headers }); let data = cur.responseData; if (!data || typeof data !== "object") { try { data = JSON.parse(cur.responseText); } catch (e) { data = null; } } if (cur.success && data && typeof data.discoverable === "boolean") shown = data.discoverable; } // --- Ask what to do --- const p = Prompt.create(); p.title = !isUpdate ? "Post to Bear Blog" : entry.is_page ? "Update Bear Blog Page" : "Update Bear Blog Post"; p.message = `“${title}”\n` + (draft.tags.length ? `Tags: ${draft.tags.join(", ")}` : "No tags"); if (otherBlog) { p.message += `\n\nThis draft is linked to a post on ${otherBlog}.bearblog.dev. ` + `Sending it to ${subdomain}.bearblog.dev creates a new post and links the draft to that one instead.`; } p.addSwitch("discoverable", "Show in Bear's discovery feed", shown); if (!isUpdate) { p.addButton("Publish"); p.addButton("Save as Draft"); } else if (isLive) { p.addButton("Update Post"); } else { p.addButton("Save Changes"); // leaves the draft/published status alone p.addButton("Save & Publish"); } if (!p.show()) return context.cancel(); const button = p.buttonPressed; const discoverable = !!p.fieldValues["discoverable"]; const body = { title, content, tags: draft.tags }; // An update changes only the fields it sends, so leave the feed setting alone unless the switch was flipped. if (!isUpdate || discoverable !== shown) body.discoverable = discoverable; if (button === "Publish" || button === "Save & Publish") body.publish = true; // --- Send it --- const send = (method, url) => http.request({ url, method, headers, data: body, encoding: "json" }); let recreated = false; let res = isUpdate ? send("PATCH", `${base}${entry.uid}/`) : send("POST", base); if (isUpdate && res.statusCode === 404) { // the linked post is gone; ask before making a new one const kind = entry.is_page ? "page" : "post"; const q = Prompt.create(); q.title = entry.is_page ? "Page Not Found" : "Post Not Found"; q.message = `The ${kind} this draft is linked to no longer exists on ${subdomain}.bearblog.dev. ` + `Create it again as a new ${kind}?`; q.addButton("Publish as New"); q.addButton("Save as New Draft"); if (!q.show()) return context.cancel(); recreated = true; if (q.buttonPressed === "Publish as New") body.publish = true; else delete body.publish; body.discoverable = discoverable; // a new post needs the setting spelled out if (entry.is_page) body.is_page = true; // keep it a page if it was one res = send("POST", base); } if (!res.success) return fail(describeError(res, !isUpdate || recreated)); // --- Remember the post and report back --- const post = res.responseData || {}; const nowLive = typeof post.publish === "boolean" ? post.publish : (!!body.publish || (isLive && !recreated)); let saved = true; if (post.uid) { // Merge onto the existing entry so fields this script doesn't know about survive. map[draft.uuid] = Object.assign({}, entry, { uid: post.uid, blog, published: nowLive, discoverable: typeof post.discoverable === "boolean" ? post.discoverable : discoverable, is_page: !!post.is_page || !!(entry && entry.is_page), }); saved = fm.writeJSON(MAP_PATH, map); } let copied = ""; if (post.url && !nowLive && post.token) { app.setClipboard(`${post.url}?token=${post.token}`); copied = " Preview link copied."; } else if (post.url) { app.setClipboard(post.url); copied = " Link copied."; } if (!saved) { return app.displayWarningMessage("Posted, but this draft couldn't be linked to the post. Running the action again will create a duplicate." + copied); } let msg; if (recreated) msg = body.publish ? "Published to Bear Blog as a new post." : "Saved to Bear Blog as a new draft."; else if (!isUpdate) msg = body.publish ? "Published to Bear Blog." : "Saved to Bear Blog as a draft."; else if (isLive) msg = "Post updated."; else msg = body.publish ? "Published to Bear Blog." : "Changes saved."; app.displaySuccessMessage(msg + copied); // --- Helpers --- function describeError(res, creating) { let server; try { server = JSON.parse(res.responseText).error; } catch (e) { } const code = res.statusCode; if (!code) return "Couldn't reach Bear Blog. Check your connection and try again."; if (code === 401) { cred.forget(); return "Bear Blog didn't accept your API key. Run the action again to enter a new one."; } if (code === 403) return server || "The Bear Blog API is only available on upgraded blogs."; if (code === 404 && creating) { cred.forget(); return `Couldn't find a blog at ${subdomain}.bearblog.dev. Run the action again to re-enter your subdomain.`; } if (code === 429) { const wait = retryAfter(res); return wait ? `Too many requests. Try again in ${wait} seconds.` : "Too many requests. Wait a minute and try again."; } if (code >= 500) return `Bear Blog is having trouble right now (HTTP ${code}). Try again in a bit.`; return server ? `Bear Blog didn't accept the post: ${server}` : `Something went wrong (HTTP ${code}).`; } function retryAfter(res) { const h = res.headers || {}; const k = Object.keys(h).find(k => k.toLowerCase() === "retry-after"); return k ? h[k] : null; } function fail(msg) { app.displayErrorMessage(msg); context.fail(msg); } })();
Options
-
After Success Default Notification Info Log Level Error
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.