Action

Open from Bear Blog

Posted by @otaviocc@social.lol, Last update 3 days 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 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.`;
    
        const byLabel = {};
        posts.forEach(post => {
          const base = label(post);
          let text = base, n = 2;
          while (byLabel[text]) text = `${base} (${n++})`; // button labels must be unique
          byLabel[text] = post;
          p.addButton(text);
        });
        if (data.next_page) p.addButton(OLDER);
        if (page > 1) p.addButton(NEWER);
        Object.keys(FILTERS).forEach(b => { if (FILTERS[b][0] !== filter) p.addButton(b); });
        if (!p.show()) return context.cancel();
    
        const b = p.buttonPressed;
        if (b === OLDER) page = typeof data.next_page === "number" ? data.next_page : page + 1;
        else if (b === NEWER) page -= 1;
        else if (FILTERS[b]) { [filter, query] = FILTERS[b]; page = 1; }
        else picked = byLabel[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 = {};
      try { map = fm.readJSON(MAP_PATH) || {}; } catch (e) {}
      const linkedId = Object.keys(map).find(k =>
        (typeof map[k] === "string" ? map[k] : map[k] && map[k].uid) === post.uid);
      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();
    
      map[d.uuid] = {
        uid: post.uid,
        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");
        const date = post.published_date ? new Date(post.published_date) : null;
        const day = date ? date.toISOString().slice(0, 10) : "";
        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.responseHeaders || {};
        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.