Action

Send to Bear Blog

Posted by @otaviocc@social.lol, Last update 3 days 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, 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 base = `https://bearblog.dev/${subdomain}/api/v1/post/`;
      const headers = { "Authorization": `Bearer ${cred.getValue("apiKey").trim()}` };
    
      // --- 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.");
      const title = lines[start].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 = {};
      try { map = fm.readJSON(MAP_PATH) || {}; } catch (e) {}
      let entry = map[draft.uuid];
      if (typeof entry === "string") entry = { uid: entry }; // older map format
      const isUpdate = !!(entry && entry.uid);
      const isLive = isUpdate && entry.published === true;
    
      // --- 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");
      p.addSwitch("discoverable", "Show in Bear's discovery feed", !!(entry && entry.discoverable));
      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 body = { title, content, tags: draft.tags, discoverable: p.fieldValues["discoverable"] };
      if (button === "Publish" || button === "Save & Publish") body.publish = true;
    
      // --- Send it ---
      const http = HTTP.create();
      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) {      // post was deleted on Bear; recreate it
        recreated = true;
        if (isLive) body.publish = true;             // keep it live if it was live
        if (entry.is_page) body.is_page = true;      // and 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);
      let saved = true;
      if (post.uid) {
        map[draft.uuid] = {
          uid: post.uid,
          published: nowLive,
          discoverable: body.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 = "The original post was deleted on Bear Blog, so a new one was created.";
      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.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.