Action

Open from Wordwrap

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

Shows your Wordwrap entries, newest first and drafts included, and opens the one you pick as a draft, ready to edit.

The draft is linked to the entry, so running “Send to Wordwrap” on it updates the original instead of creating a new entry. If the entry is already linked to a draft, you can open that draft or replace its text with the current version from Wordwrap.

Uses the same omg.lol address and API key as the status.lol action.

Steps

  • script

    // Open from Wordwrap — Drafts action script
    // Shows your Wordwrap entries (newest first, drafts included) and opens the one you pick as a draft.
    // Edit it, then run "Send to Wordwrap" to update the original entry.
    
    const MAP_PATH = "/Library/Scripts/wordwrap-entries.json"; // shared with "Send to Wordwrap"
    const PAGE_SIZE = 25;
    const OLDER = "Older →";
    const NEWER = "← Newer";
    
    // Must match the setting in "Send to Wordwrap".
    const USE_WORDWRAP_KEY = false;
    
    (() => {
      // --- Credentials (same store as "Send to Wordwrap") ---
      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();
    
      // --- Fetch all entries (with the key, drafts are included) ---
      const r = call("GET", base);
      if (!r.ok) return fail(describeError(r));
      const entries = (r.result.response && r.result.response.entries) || [];
      if (!entries.length) {
        app.displayInfoMessage(`There are no Wordwrap entries for ${address} yet.`);
        return context.cancel();
      }
    
      // --- Pick an entry, PAGE_SIZE at a time ---
      const pages = Math.ceil(entries.length / PAGE_SIZE);
      let page = 0;
      let picked = null;
      while (!picked) {
        const slice = entries.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);
        const p = Prompt.create();
        p.title = "Open Wordwrap Entry";
        p.message = `${entries.length} entr${entries.length === 1 ? "y" : "ies"} for ${address}` +
          (pages > 1 ? ` · page ${page + 1} of ${pages}` : "");
    
        const byLabel = {};
        slice.forEach(e => {
          const base = label(e);
          let text = base, n = 2;
          while (byLabel[text]) text = `${base} (${n++})`; // button labels must be unique
          byLabel[text] = e;
          p.addButton(text);
        });
        if (page < pages - 1) p.addButton(OLDER);
        if (page > 0) p.addButton(NEWER);
        if (!p.show()) return context.cancel();
    
        if (p.buttonPressed === OLDER) page += 1;
        else if (p.buttonPressed === NEWER) page -= 1;
        else picked = byLabel[p.buttonPressed];
      }
    
      // --- Is this entry 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 => map[k] && map[k].entry === picked.entry);
      const linked = linkedId ? Draft.find(linkedId) : null;
    
      let d;
      if (linked && !linked.isTrashed) {
        const q = Prompt.create();
        q.title = "Already in Drafts";
        q.message = `“${excerpt(picked.text, 60)}” is already linked to a draft. Open it as is, or replace its text with the version on Wordwrap? (The current text stays in the draft's version history.)`;
        q.addButton("Open Draft");
        q.addButton("Replace with Wordwrap's Version");
        if (!q.show()) return context.cancel();
        if (q.buttonPressed === "Open Draft") {
          editor.load(linked);
          return;
        }
        d = linked;
      } else {
        d = Draft.create();
      }
    
      // --- Fill the draft ---
      d.content = (picked.text || "").trim() + "\n";
      d.update();
    
      map[d.uuid] = { entry: picked.entry };
      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 entry. Sending it will create a new entry instead of updating this one.");
      } else {
        app.displaySuccessMessage("Entry opened. Run Send to Wordwrap when you're done editing.");
      }
    
      // --- Helpers ---
      // e.g. "Hello from the Wordwrap API! · 2026-11-26", "Half-finished thought · Draft"
      function label(e) {
        const parts = [excerpt(e.text, 50) || "(empty)"];
        if (!e.published) parts.push("Draft");
        else if (e.created) parts.push(e.created.slice(0, 10)); // the entry's own local date
        if (e.reply_to) parts.push("Reply");
        return parts.join(" · ");
      }
    
      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 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 || `Something went wrong (HTTP ${r.code}).`;
      }
    
      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.