Action

Send to Wordwrap

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

Posts the current draft to your Wordwrap site, or updates the entry if this draft has been sent before.

The whole draft becomes the entry’s text. Before sending, you choose whether to publish or save it as a draft, and whether replies are allowed. Published entries can also be unpublished. When an entry is live, its link is copied to the clipboard.

When an entry is published for the first time, you also choose whether it’s posted to Mastodon. The switch starts off for drafts tagged “skip-mastodon”.

Uses the same omg.lol address and API key as the status.lol action. Each draft is linked to its entry in iCloud Drive → Drafts → Library/Scripts/wordwrap-entries.json.

Steps

  • script

    // Send to Wordwrap — Drafts action script
    // The whole draft is the entry's text.
    // Running it again on the same draft updates the existing entry.
    // When publishing, a switch asks whether to also post to Mastodon.
    // It starts off for drafts tagged "skip-mastodon", on otherwise.
    
    const MAP_PATH = "/Library/Scripts/wordwrap-entries.json"; // draft uuid -> { entry }
    
    // false: use your omg.lol API key (shared with the status.lol action).
    // true:  use a Wordwrap-only API key from your Wordwrap settings.
    const USE_WORDWRAP_KEY = false;
    
    (() => {
      // --- Credentials ---
      const cred = USE_WORDWRAP_KEY
        ? Credential.create("Wordwrap", "Your omg.lol address and the API key from your Wordwrap settings.")
        : Credential.create("status.lol", "Your omg.lol address and API key (from home.omg.lol/account).");
      cred.addTextField("address", "Address (e.g. foobar)");
      cred.addPasswordField("apiKey", "API Key");
      if (!cred.authorize()) return context.cancel();
    
      const address = (cred.getValue("address") || "").trim().replace(/^@/, "").replace(/\.omg\.lol.*$/, "");
      const apiKey = (cred.getValue("apiKey") || "").trim();
      if (!address || !apiKey) {
        cred.forget();
        return fail("Your omg.lol address or API key is missing. Run the action again to enter them.");
      }
      const base = USE_WORDWRAP_KEY
        ? `https://wordwrap.lol/_/api/address/${encodeURIComponent(address)}/entries`
        : `https://api.omg.lol/address/${encodeURIComponent(address)}/wordwrap/entries`;
      const http = HTTP.create();
    
      // --- The entry's text ---
      const text = (draft.content || "").trim();
      if (!text) return fail("This draft is empty. Write something to post.");
    
      // --- Has this draft been posted before? If so, get the entry's current state ---
      const fm = FileManager.createCloud();
      let map = {};
      try { map = fm.readJSON(MAP_PATH) || {}; } catch (e) {}
      const id = map[draft.uuid] && map[draft.uuid].entry;
    
      let current = null;
      let gone = false;
      if (id) {
        const r = call("GET", `${base}/${encodeURIComponent(id)}`);
        if (r.ok) current = r.result.response.entry;
        else if (r.code === 404) gone = true;        // deleted on Wordwrap; we'll create a new one
        else return fail(describeError(r));
      }
    
      // --- Ask what to do ---
      const p = Prompt.create();
      p.title = current ? "Update Wordwrap Entry" : "Post to Wordwrap";
      const notes = [excerpt(text, 80)];
      if (current) notes.push(current.published ? "Currently published." : "Currently a draft.");
      if (gone) notes.push("The original entry was deleted on Wordwrap, so this will create a new one.");
      p.message = notes.join("\n\n");
      p.addSwitch("allowReplies", "Allow replies", current ? current.allow_replies !== false : true);
      const firstPublish = !current || !current.published;   // only then does Mastodon apply
      if (firstPublish) {
        p.addSwitch("mastodon", "Also post to Mastodon (when publishing)", !draft.hasTag("skip-mastodon"));
      }
      if (!current) {
        p.addButton("Publish");
        p.addButton("Save as Draft");
      } else if (current.published) {
        p.addButton("Update Entry");
        p.addButton("Unpublish");
      } else {
        p.addButton("Save Changes");
        p.addButton("Save & Publish");
      }
      if (!p.show()) return context.cancel();
    
      const button = p.buttonPressed;
      const body = { text, allow_replies: p.fieldValues["allowReplies"] };
      if (button === "Publish" || button === "Save & Publish") body.published = true;
      if (button === "Unpublish") body.published = false;
      // Only decide about Mastodon when an entry goes live for the first time
      if (firstPublish && body.published === true) body.mastodon = !!p.fieldValues["mastodon"];
    
      // --- Send it ---
      const r = current
        ? call("PATCH", `${base}/${encodeURIComponent(current.entry)}`, body)
        : call("POST", base, body);
      if (!r.ok) return fail(describeError(r));
    
      // --- Remember the entry and report back ---
      const entry = (r.result.response && r.result.response.entry) || {};
      let saved = true;
      if (entry.entry) {
        map[draft.uuid] = { entry: entry.entry };
        saved = fm.writeJSON(MAP_PATH, map);
      }
    
      let copied = "";
      if (entry.url && entry.published) {
        app.setClipboard(entry.url);
        copied = " Link copied.";
      }
    
      if (!saved) {
        return app.displayWarningMessage("Posted, but this draft couldn't be linked to the entry. Running the action again will create a duplicate." + copied);
      }
    
      let msg;
      if (gone)                       msg = "The original entry was deleted on Wordwrap, so a new one was created.";
      else if (button === "Unpublish") msg = "Entry unpublished. It's a draft again.";
      else if (!current)              msg = entry.published ? "Published to Wordwrap." : "Saved to Wordwrap as a draft.";
      else if (current.published)     msg = "Entry updated.";
      else                            msg = entry.published ? "Published to Wordwrap." : "Changes saved.";
      app.displaySuccessMessage(msg + copied);
    
      // --- Helpers ---
      function call(method, url, data) {
        const options = { url, method, headers: { Authorization: `Bearer ${apiKey}` } };
        if (data) { options.data = data; options.encoding = "json"; }
        const res = http.request(options);
        let result = null;
        try { result = JSON.parse(res.responseText); } catch (e) {}
        const ok = res.success && !!result && !(result.request && result.request.success === false);
        return { res, result, ok, code: res.statusCode };
      }
    
      function describeError(r) {
        const server = r.result && r.result.response && r.result.response.message;
        if (!r.code) return "Couldn't reach omg.lol. Check your connection and try again.";
        if (r.code === 401) {
          cred.forget();
          return "omg.lol didn't accept your API key. Run the action again to enter a new one.";
        }
        if (r.code === 429) return "Too many requests. Wait a minute and try again.";
        if (r.code >= 500)  return `omg.lol is having trouble right now (HTTP ${r.code}). Try again in a bit.`;
        return server ? `Wordwrap didn't accept the entry: ${server}` : `Something went wrong (HTTP ${r.code}).`;
      }
    
      function excerpt(s, max) {
        const line = s.split("\n").find(l => l.trim()) || "";
        const clean = line.replace(/^#+\s*/, "").trim();
        return clean.length > max ? clean.slice(0, max - 1) + "…" : clean;
      }
    
      function fail(msg) {
        console.log(msg);
        app.displayErrorMessage(msg);
        context.fail(msg);
      }
    })();
    

Options

  • After Success Default , Tags: wordwrap
    Notification Info
    Log Level Error
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.