Action

Open from Bear Blog

Posted by @otaviocc@social.lol, Last update about 14 hours ago

Shows the posts and pages on your Bear Blog, newest first, and opens the one you pick as a draft, ready to edit.

Steps

  • script

    // Open from Bear Blog — Drafts action script
    // Shows your Bear Blog posts (newest first) and opens the one you pick as a draft.
    // Edit it, then run "Send to Bear Blog" to update the original post.
    
    const MAP_PATH = "/Library/Scripts/bearblog-posts.json"; // shared with "Send to Bear Blog"
    const OLDER = "Older →";
    const NEWER = "← Newer";
    const FILTERS = {                       // button label -> [filter, query string]
        "Show Everything": ["all", ""],
        "Show Posts Only": ["posts", "&is_page=false"],
        "Show Pages Only": ["pages", "&is_page=true"],
    };
    
    (() => {
        // --- Credentials (same store as "Send to Bear Blog") ---
        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();
        const get = url => http.request({ url, method: "GET", headers });
    
        // --- Browse the list, 20 at a time, filtered to posts, pages or both ---
        let page = 1;
        let filter = "all";
        let query = "";
        let picked = null;
        while (!picked) {
            const res = get(`${base}?page=${page}${query}`);
            if (!res.success) return fail(describeError(res, true));
            const data = json(res) || {};
            const posts = data.posts || [];
            if (!posts.length && filter === "all") {
                app.displayInfoMessage(`There's nothing on ${subdomain}.bearblog.dev yet.`);
                return context.cancel();
            }
    
            const total = data.count || posts.length;
            const pages = Math.max(1, Math.ceil(total / (data.page_size || 20)));
            const noun = filter === "pages" ? "page" : filter === "posts" ? "post" : "item";
            const p = Prompt.create();
            p.title = filter === "pages" ? "Open Bear Blog Page" : "Open Bear Blog Post";
            p.message = posts.length
                ? `${total} ${noun}${total === 1 ? "" : "s"} on ${subdomain}.bearblog.dev` +
                (pages > 1 ? ` · page ${page} of ${pages}` : "")
                : `No ${noun}s on ${subdomain}.bearblog.dev.`;
    
            // Every button gets its own value, so a post titled like a control button can't be mistaken for it.
            const byValue = new Map();
            const used = new Set();
            posts.forEach(post => {
                const name = label(post);
                let text = name, n = 2;
                while (used.has(text)) text = `${name} (${n++})`; // keep labels distinguishable
                used.add(text);
                const value = `post:${post.uid}`;
                byValue.set(value, post);
                p.addButton(text, value);
            });
            if (data.next_page) p.addButton(OLDER, "nav:older");
            if (page > 1) p.addButton(NEWER, "nav:newer");
            Object.keys(FILTERS).forEach(b => { if (FILTERS[b][0] !== filter) p.addButton(b, `filter:${b}`); });
            if (!p.show()) return context.cancel();
    
            const b = String(p.buttonPressed);
            if (b === "nav:older") page = typeof data.next_page === "number" ? data.next_page : page + 1;
            else if (b === "nav:newer") page -= 1;
            else if (b.startsWith("filter:")) { [filter, query] = FILTERS[b.slice(7)]; page = 1; }
            else picked = byValue.get(b);
        }
    
        // --- Fetch the full post (lists don't include content) ---
        const res = get(`${base}${picked.uid}/`);
        if (!res.success) return fail(describeError(res, false));
        const post = json(res);
        if (!post || !post.uid) return fail("Bear Blog sent back a post this action couldn't read.");
    
        // --- Is this post already linked to a draft? ---
        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 opened. Give iCloud a moment to sync and try again.");
            }
        }
        // A link counts only if it's for this blog. (Entries without a blog are older; assume this one.)
        const linkedId = Object.keys(map).find(k => {
            const e = map[k];
            if (typeof e === "string") return e === post.uid; // older map format
            return !!e && e.uid === post.uid && (!e.blog || String(e.blog).toLowerCase() === blog);
        });
        const linked = linkedId ? Draft.find(linkedId) : null;
    
        let d;
        if (linked && !linked.isTrashed) {
            const q = Prompt.create();
            q.title = "Already in Drafts";
            q.message = `“${post.title}” is already linked to a draft. Open it as is, or replace its text with the version on Bear Blog? (The current text stays in the draft's version history.)`;
            q.addButton("Open Draft");
            q.addButton("Replace with Bear's Version");
            if (!q.show()) return context.cancel();
            if (q.buttonPressed === "Open Draft") {
                editor.load(linked);
                return;
            }
            d = linked;
            d.tags.forEach(t => d.removeTag(t)); // draft tags = post tags, so start clean
        } else {
            d = Draft.create();
        }
    
        // --- Fill the draft in the format "Send to Bear Blog" expects ---
        d.content = `# ${post.title}\n\n${(post.content || "").trim()}\n`;
        (post.tags || []).forEach(t => d.addTag(String(t)));
        d.update();
    
        // Merge onto the existing entry so fields this script doesn't know about survive.
        const prev = map[d.uuid] && typeof map[d.uuid] === "object" ? map[d.uuid] : {};
        map[d.uuid] = Object.assign({}, prev, {
            uid: post.uid,
            blog,
            published: !!post.publish,
            discoverable: !!post.discoverable,
            is_page: !!post.is_page,
        });
        const saved = fm.writeJSON(MAP_PATH, map);
    
        editor.load(d);
        editor.activate();
    
        if (!saved) {
            app.displayWarningMessage("Opened, but the draft couldn't be linked to the post. Sending it will create a new post instead of updating this one.");
        } else {
            app.displaySuccessMessage(`Opened “${post.title}”. Run Send to Bear Blog when you're done editing.`);
        }
    
        // --- Helpers ---
        // e.g. "Hello World · 2026-09-11", "About · Page", "Now · Page · Draft"
        function label(post) {
            const parts = [post.title || "Untitled"];
            if (post.is_page && filter !== "pages") parts.push("Page");
            // Bear sends dates in UTC; show the local calendar day, and skip dates that don't parse.
            const parsed = post.published_date ? new Date(post.published_date) : null;
            const date = parsed && !isNaN(parsed.getTime()) ? parsed : null;
            const pad = n => String(n).padStart(2, "0");
            const day = date ? `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}` : "";
            if (!post.publish) parts.push("Draft");
            else if (date && date > new Date()) parts.push(`Scheduled ${day}`);
            else if (date && !post.is_page) parts.push(day);
            return parts.join(" · ");
        }
    
        function json(res) {
            if (res.responseData && typeof res.responseData === "object") return res.responseData;
            try { return JSON.parse(res.responseText); } catch (e) { return null; }
        }
    
        function describeError(res, listing) {
            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 && listing) {
                cred.forget();
                return `Couldn't find a blog at ${subdomain}.bearblog.dev. Run the action again to re-enter your subdomain.`;
            }
            if (code === 404) return "That post no longer exists on Bear Blog.";
            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 returned an error: ${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.