import java.net.URI;
import java.net.http.*;
import java.time.Duration;
import java.util.regex.*;
import com.fasterxml.jackson.databind.*;
public class TempInbox {
private static final String BASE = "https://tempinbox.dev";
private static final HttpClient http = HttpClient.newHttpClient();
private static final ObjectMapper json = new ObjectMapper();
public record Inbox(String address, String jwt) {}
public record Mail(String uuid, String subject, String raw) {}
public static Inbox createInbox() throws Exception {
var req = HttpRequest.newBuilder(URI.create(BASE + "/api/new_address"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{}"))
.build();
var node = json.readTree(http.send(req, HttpResponse.BodyHandlers.ofString()).body());
return new Inbox(node.get("address").asText(), node.get("jwt").asText());
}
public static Mail waitForMail(String jwt, Duration timeout) throws Exception {
long deadline = System.nanoTime() + timeout.toNanos();
while (System.nanoTime() < deadline) {
var list = json.readTree(get("/api/mails?limit=1&offset=0", jwt));
if (list.get("results").size() > 0) {
String uuid = list.get("results").get(0).get("uuid").asText();
var full = json.readTree(get("/api/mail/" + uuid, jwt));
var meta = json.readTree(full.get("metadata").asText(""));
return new Mail(uuid,
meta.path("subject").asText(""),
full.path("raw").asText(""));
}
Thread.sleep(2500);
}
throw new IllegalStateException("No email received within " + timeout);
}
public static String extractOtp(String raw) {
Matcher m = Pattern.compile("\\b\\d{6}\\b").matcher(raw);
if (!m.find()) throw new IllegalStateException("No 6-digit OTP found");
return m.group();
}
private static String get(String path, String jwt) throws Exception {
var req = HttpRequest.newBuilder(URI.create(BASE + path))
.header("Authorization", "Bearer " + jwt)
.GET().build();
return http.send(req, HttpResponse.BodyHandlers.ofString()).body();
}
}