From 9f1b8de04da2f2155cd1e8a02ac988c2b65577ce Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 09:19:55 +0800 Subject: [PATCH] feat: whatsapp send, templates and media proxy - MetaClient: text and template sends, approved templates with bounded paging, streamed media with a 100 MB cap. - Send endpoint: 24-hour window, template params and supported checks before Meta; pending then sent or failed with Meta's code and title. - Template sync per company and nightly at 03:30 KL; a failed fetch keeps existing rows. - Media proxy: 404 without access, 410 when Meta no longer holds the file. - Mock: Graph send, templates, media and bearer checks; /simulate/inbound and /simulate/status sign with the company secret. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- local/docker-compose.yml | 11 + local/whatsapp-mock/server.js | 128 +++++++- .../services/whatsapp/inbox/InboxService.java | 4 +- .../whatsapp/inbox/OutboundController.java | 68 ++++ .../whatsapp/inbox/OutboundService.java | 185 +++++++++++ .../whatsapp/inbox/TemplateService.java | 187 +++++++++++ .../services/whatsapp/meta/MetaClient.java | 210 ++++++++++++ .../repository/WaConversationRepository.java | 8 + .../repository/WaTemplateRepository.java | 17 +- .../whatsapp/service/CompanyDirectory.java | 15 + .../services/whatsapp/inbox/OutboundTest.java | 310 ++++++++++++++++++ .../whatsapp/inbox/TemplateServiceTest.java | 175 ++++++++++ .../whatsapp/meta/MetaClientTest.java | 263 +++++++++++++++ 13 files changed, 1570 insertions(+), 11 deletions(-) create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/OutboundController.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/OutboundService.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/TemplateService.java create mode 100644 solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/meta/MetaClient.java create mode 100644 solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/OutboundTest.java create mode 100644 solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/TemplateServiceTest.java create mode 100644 solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/meta/MetaClientTest.java diff --git a/local/docker-compose.yml b/local/docker-compose.yml index 276e4f3..1afc8ac 100644 --- a/local/docker-compose.yml +++ b/local/docker-compose.yml @@ -121,5 +121,16 @@ services: mysql: {condition: service_healthy} whatsapp-mock: build: ./whatsapp-mock + environment: + WEBHOOK_URL: http://mobile-api/api/public/whatsapp/webhook + WHATSAPP_COMPANIES: ${WHATSAPP_COMPANIES} + WHATSAPP_INS_PHONE_NUMBER_ID: ${WHATSAPP_INS_PHONE_NUMBER_ID} + WHATSAPP_INS_WABA_ID: ${WHATSAPP_INS_WABA_ID} + WHATSAPP_INS_ACCESS_TOKEN: ${WHATSAPP_INS_ACCESS_TOKEN} + WHATSAPP_INS_APP_SECRET: ${WHATSAPP_INS_APP_SECRET} + WHATSAPP_CV_PHONE_NUMBER_ID: ${WHATSAPP_CV_PHONE_NUMBER_ID} + WHATSAPP_CV_WABA_ID: ${WHATSAPP_CV_WABA_ID} + WHATSAPP_CV_ACCESS_TOKEN: ${WHATSAPP_CV_ACCESS_TOKEN} + WHATSAPP_CV_APP_SECRET: ${WHATSAPP_CV_APP_SECRET} volumes: mysql-data: diff --git a/local/whatsapp-mock/server.js b/local/whatsapp-mock/server.js index fa93adf..3ccf27e 100644 --- a/local/whatsapp-mock/server.js +++ b/local/whatsapp-mock/server.js @@ -1,11 +1,123 @@ -// Local stand-in for the WhatsApp Cloud (Graph) API. Later tasks add Graph endpoints and signed webhooks. +// Local stand-in for the WhatsApp Cloud (Graph) API and for Meta's signed webhook. Never part of release packaging. +// Env: PORT (8080), WEBHOOK_URL, WHATSAPP_COMPANIES=INS,CV and per company WHATSAPP__PHONE_NUMBER_ID / _WABA_ID / _ACCESS_TOKEN / _APP_SECRET. const http = require('node:http'); +const crypto = require('node:crypto'); -http.createServer((req, res) => { - if (req.method === 'GET' && req.url === '/health') { - res.writeHead(200, { 'Content-Type': 'application/json' }); - return res.end('{"status":"UP"}'); +const env = process.env; +const companies = (env.WHATSAPP_COMPANIES || '').split(',').map((s) => s.trim()).filter(Boolean).map((code) => ({ + code, + phoneNumberId: env[`WHATSAPP_${code}_PHONE_NUMBER_ID`], + wabaId: env[`WHATSAPP_${code}_WABA_ID`], + token: env[`WHATSAPP_${code}_ACCESS_TOKEN`], + secret: env[`WHATSAPP_${code}_APP_SECRET`], +})); +const tokens = new Set(companies.map((c) => c.token).filter(Boolean)); + +const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', 'base64'); +const PDF = Buffer.from('%PDF-1.1\n1 0 obj<>endobj\n2 0 obj<>endobj\n' + + '3 0 obj<>endobj\ntrailer<>\n%%EOF\n'); + +let counter = 0; + +function send(res, status, body, type = 'application/json') { + res.writeHead(status, { 'Content-Type': type }); + res.end(Buffer.isBuffer(body) || typeof body === 'string' ? body : JSON.stringify(body)); +} + +function readBody(req) { + return new Promise((resolve) => { + const chunks = []; + req.on('data', (c) => chunks.push(c)); + req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); + }); +} + +function templates(wabaId, host, page) { + const expo = { name: 'expo_followup', language: 'en', category: 'MARKETING', status: 'APPROVED', + components: [{ type: 'BODY', text: 'Hi {{1}}, thanks for visiting us at {{2}}.' }] }; + const promo = { name: 'promo_header', language: 'en', category: 'MARKETING', status: 'APPROVED', + components: [{ type: 'HEADER', format: 'IMAGE' }, { type: 'BODY', text: 'Big sale this weekend.' }] }; + return page === 'p2' + ? { data: [promo], paging: {} } + : { data: [expo], paging: { next: `http://${host}/${wabaId}/message_templates?status=APPROVED&limit=200&after=p2` } }; +} + +// Delivers a signed webhook the way Meta does: HMAC-SHA256 over the exact bytes, header "sha256=". +async function deliver(company, payload) { + const body = JSON.stringify(payload); + const signature = 'sha256=' + crypto.createHmac('sha256', company.secret).update(body).digest('hex'); + const r = await fetch(env.WEBHOOK_URL, { method: 'POST', body, headers: { 'Content-Type': 'application/json', 'X-Hub-Signature-256': signature } }); + return r.status; +} + +function envelope(company, value) { + return { object: 'whatsapp_business_account', entry: [{ id: company.wabaId, changes: [{ field: 'messages', + value: { messaging_product: 'whatsapp', metadata: { display_phone_number: '15550000000', phone_number_id: company.phoneNumberId }, ...value } }] }] }; +} + +async function simulate(path, req, res) { + let input; + try { + input = JSON.parse(await readBody(req)); + } catch (e) { + return send(res, 400, { error: 'invalid json' }); } - res.writeHead(404, { 'Content-Type': 'application/json' }); - res.end('{"error":"not found"}'); -}).listen(8080); + const company = companies.find((c) => c.code === input.companyCode); + if (!company || !env.WEBHOOK_URL) return send(res, 400, { error: 'unknown companyCode or WEBHOOK_URL not set' }); + const now = Math.floor(Date.now() / 1000); + let payload; + if (path === '/simulate/status') { + payload = envelope(company, { statuses: [{ id: input.wamid, status: input.status, timestamp: String(now), recipient_id: input.from || '60100000000' }] }); + } else { + const type = input.type || 'text'; + const message = { from: input.from, id: `wamid.MOCKIN${++counter}`, timestamp: String(now), type }; + if (type === 'text') message.text = { body: input.text || 'hello' }; + else if (type === 'location') message.location = { latitude: 3.139, longitude: 101.6869, name: 'Mock Location' }; + else if (type === 'document') message.document = { id: input.mediaId, mime_type: 'application/pdf', filename: 'quote.pdf' }; + else message[type] = { id: input.mediaId, mime_type: 'image/png' }; + payload = envelope(company, { contacts: [{ profile: { name: 'Mock Contact' }, wa_id: input.from }], messages: [message] }); + } + try { + send(res, await deliver(company, payload), { delivered: true }); + } catch (e) { + send(res, 502, { error: 'webhook unreachable' }); + } +} + +http.createServer(async (req, res) => { + const url = new URL(req.url, 'http://mock'); + const path = url.pathname.replace(/^\/v\d+\.\d+/, ''); // the client may add a Graph version prefix + if (req.method === 'GET' && path === '/health') return send(res, 200, { status: 'UP' }); + if (req.method === 'POST' && (path === '/simulate/inbound' || path === '/simulate/status')) return simulate(path, req, res); + + const auth = /^Bearer (.+)$/.exec(req.headers.authorization || ''); + if (!auth || !tokens.has(auth[1])) return send(res, 401, { error: { code: 190, title: 'Invalid OAuth access token' } }); + + // media bytes: Meta wants the bearer token on the download too + const bytes = path.match(/^\/media-bytes\/([^/]+)$/); + if (req.method === 'GET' && bytes) { + const id = bytes[1]; + if (id.startsWith('expired')) return send(res, 404, { error: { code: 100, title: 'Media expired' } }); + return id.startsWith('doc') ? send(res, 200, PDF, 'application/pdf') : send(res, 200, PNG, 'image/png'); + } + + const parts = path.split('/').filter(Boolean); + if (req.method === 'POST' && parts.length === 2 && parts[1] === 'messages') { + let input; + try { + input = JSON.parse(await readBody(req)); + } catch (e) { + return send(res, 400, { error: { code: 100, title: 'Invalid parameter' } }); + } + if (String(input.to || '').endsWith('0000')) return send(res, 400, { error: { code: 131026, title: 'Message undeliverable' } }); + return send(res, 200, { messaging_product: 'whatsapp', messages: [{ id: `wamid.MOCK${++counter}` }] }); + } + if (req.method === 'GET' && parts.length === 2 && parts[1] === 'message_templates') { + return send(res, 200, templates(parts[0], req.headers.host, url.searchParams.get('after'))); + } + if (req.method === 'GET' && parts.length === 1) { // media lookup + const id = parts[0]; + return send(res, 200, { id, url: `http://whatsapp-mock:8080/media-bytes/${id}`, mime_type: id.startsWith('doc') ? 'application/pdf' : 'image/png' }); + } + send(res, 404, { error: { code: 100, title: 'Unknown path' } }); +}).listen(Number(env.PORT || 8080)); diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxService.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxService.java index 163e967..31a64ba 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxService.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/InboxService.java @@ -217,7 +217,7 @@ public class InboxService { return companyId == null && !admin; } - private WaConversation visible(String uuid, Long companyId, Long userId, boolean admin) { + WaConversation visible(String uuid, Long companyId, Long userId, boolean admin) { if (failClosed(companyId, admin)) { throw notFound(); } @@ -258,7 +258,7 @@ public class InboxService { c.ownerManual, c.lastInboundAt, c.lastMessageAt, withPreview ? c.lastMessagePreview : null, open, unread); } - private static MessageView message(WaMessage m) { + static MessageView message(WaMessage m) { return new MessageView(m.uuid, m.direction, m.type, m.body, m.templateName, m.mediaMime, m.mediaFilename, m.locationLat, m.locationLng, m.locationName, m.status, m.errorCode, m.errorTitle, m.sentByUserId, m.createdAt, m.statusAt); } diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/OutboundController.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/OutboundController.java new file mode 100644 index 0000000..1f746e7 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/OutboundController.java @@ -0,0 +1,68 @@ +package com.solvway.services.whatsapp.inbox; + +import com.solvway.services.whatsapp.dto.MessageView; +import com.solvway.services.whatsapp.dto.SendMessageRequest; +import com.solvway.services.whatsapp.dto.TemplateView; +import jakarta.servlet.http.HttpServletResponse; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** Sending, templates and media. Caller context arrives as trusted query params from mobile-api, like {@link InboxController}. */ +@RestController +@RequestMapping("/whatsapp") +public class OutboundController { + + private final OutboundService service; + private final TemplateService templates; + + public OutboundController(OutboundService service, TemplateService templates) { + this.service = service; + this.templates = templates; + } + + @PostMapping("/conversations/{uuid}/messages") + public MessageView send(@PathVariable String uuid, @RequestParam(required = false) Long companyId, @RequestParam Long userId, + @RequestParam boolean admin, @RequestBody SendMessageRequest request) { + return service.send(uuid, companyId, userId, admin, request); + } + + @GetMapping("/templates") + public List templates(@RequestParam(required = false) Long companyId) { + return templates.list(companyId); + } + + @PostMapping("/templates/sync") + public List sync(@RequestParam(required = false) Long companyId, @RequestParam boolean admin) { + return templates.sync(companyId, admin); + } + + /** Streams straight from Meta into the response; errors are decided before the first byte so they still get a ProblemDetail. */ + @GetMapping("/media/{messageUuid}") + public void media(@PathVariable String messageUuid, @RequestParam(required = false) Long companyId, @RequestParam Long userId, + @RequestParam boolean admin, HttpServletResponse response) { + service.media(messageUuid, companyId, userId, admin, (mime, disposition, length) -> { + MediaType type; + try { + type = mime == null ? MediaType.APPLICATION_OCTET_STREAM : MediaType.parseMediaType(mime); + } catch (IllegalArgumentException e) { + type = MediaType.APPLICATION_OCTET_STREAM; + } + response.setContentType(type.toString()); + response.setHeader(HttpHeaders.CONTENT_DISPOSITION, disposition); + response.setHeader("X-Content-Type-Options", "nosniff"); + if (length >= 0) { + response.setContentLengthLong(length); + } + return response.getOutputStream(); + }); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/OutboundService.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/OutboundService.java new file mode 100644 index 0000000..e45ef99 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/OutboundService.java @@ -0,0 +1,185 @@ +package com.solvway.services.whatsapp.inbox; + +import com.solvway.services.whatsapp.config.WhatsAppSettings.CompanyConfig; +import com.solvway.services.whatsapp.dto.MessageView; +import com.solvway.services.whatsapp.dto.SendMessageRequest; +import com.solvway.services.whatsapp.meta.MetaClient; +import com.solvway.services.whatsapp.model.WaConversation; +import com.solvway.services.whatsapp.model.WaMessage; +import com.solvway.services.whatsapp.model.WaTemplate; +import com.solvway.services.whatsapp.repository.WaConversationRepository; +import com.solvway.services.whatsapp.repository.WaMessageRepository; +import com.solvway.services.whatsapp.repository.WaTemplateRepository; +import com.solvway.services.whatsapp.service.CompanyDirectory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ContentDisposition; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; + +import java.time.Clock; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Sends text (inside the 24-hour window) and templates, and proxies media. The Meta call runs outside any transaction. + * Never logs numbers, message text or tokens. + * ponytail: a delivery webhook that arrives before the wamid is saved is ignored (rare); the message then stays "sent". + */ +@Service +public class OutboundService { + + private static final int TEXT_MAX = 4096; + private static final int PREVIEW_MAX = 80; + private static final Pattern PARAM = Pattern.compile("\\{\\{(\\d+)}}"); + private static final Set MEDIA_TYPES = Set.of("image", "sticker", "document", "audio", "video"); + private static final Set INLINE_MIMES = Set.of("image/jpeg", "image/png", "image/webp", "image/gif"); + + /** Where the proxied bytes go: called once with the final headers, before any byte is written. */ + @FunctionalInterface + public interface MediaOutput { + java.io.OutputStream open(String mime, String disposition, long length) throws java.io.IOException; + } + + private final InboxService inbox; + private final WaConversationRepository conversations; + private final WaMessageRepository messages; + private final WaTemplateRepository templates; + private final CompanyDirectory companies; + private final MetaClient meta; + private final Clock clock; + + @Autowired + public OutboundService(InboxService inbox, WaConversationRepository conversations, WaMessageRepository messages, + WaTemplateRepository templates, CompanyDirectory companies, MetaClient meta) { + this(inbox, conversations, messages, templates, companies, meta, Clock.systemDefaultZone()); + } + + OutboundService(InboxService inbox, WaConversationRepository conversations, WaMessageRepository messages, + WaTemplateRepository templates, CompanyDirectory companies, MetaClient meta, Clock clock) { + this.inbox = inbox; + this.conversations = conversations; + this.messages = messages; + this.templates = templates; + this.companies = companies; + this.meta = meta; + this.clock = clock; + } + + public MessageView send(String uuid, Long companyId, Long userId, boolean admin, SendMessageRequest request) { + WaConversation c = inbox.visible(uuid, companyId, userId, admin); + boolean isText = request != null && request.text() != null; + boolean isTemplate = request != null && request.template() != null; + if (isText == isTemplate || (isText && (request.text().isBlank() || request.text().length() > TEXT_MAX)) + || (isTemplate && (request.template().isBlank() || request.language() == null || request.language().isBlank()))) { + throw bad("INVALID_PAYLOAD"); + } + CompanyConfig cfg = companies.configOf(c.companyId) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.CONFLICT, "WHATSAPP_NOT_CONFIGURED")); + LocalDateTime now = LocalDateTime.now(clock); + + String type; + String body; + String templateName = null; + List params = null; + if (isText) { + if (c.lastInboundAt == null || !c.lastInboundAt.isAfter(now.minusHours(24))) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "WINDOW_CLOSED"); + } + type = "text"; + body = request.text(); + } else { + WaTemplate t = templates.findByCompanyIdAndNameAndLanguage(c.companyId, request.template(), request.language()) + .filter(x -> TemplateService.APPROVED.equals(x.status)).orElseThrow(() -> bad("TEMPLATE_PARAMS")); + params = request.params() == null ? List.of() : request.params(); + if (params.size() != t.paramCount || params.stream().anyMatch(p -> p == null || p.isBlank())) { + throw bad("TEMPLATE_PARAMS"); + } + type = "template"; + templateName = t.name; + body = fill(t.bodyText, params); + } + + WaMessage m = new WaMessage(); + m.uuid = UUID.randomUUID().toString(); + m.conversationId = c.id; + m.direction = "OUT"; + m.type = type; + m.body = body; + m.templateName = templateName; + m.status = "pending"; + m.sentByUserId = userId; + m.createdAt = now; + m = messages.save(m); + + MetaClient.SendResult r = isText ? meta.sendText(cfg, c.contactWaId, body) + : meta.sendTemplate(cfg, c.contactWaId, templateName, request.language(), params); + m.statusAt = LocalDateTime.now(clock); + if (r.failed()) { + m.status = "failed"; + m.errorCode = r.errorCode(); + m.errorTitle = r.errorTitle(); + } else { + m.status = "sent"; + m.wamid = r.wamid(); + } + m = messages.save(m); + conversations.recordOutbound(c.id, m.createdAt, preview(body)); + return InboxService.message(m); + } + + /** + * Streams a media message's bytes from Meta (404 when not visible or not media, 410 when Meta no longer has it). + * ponytail: Meta keeps media about 30 days and every view re-fetches it; upgrade by copying to object storage on receipt. + */ + public void media(String messageUuid, Long companyId, Long userId, boolean admin, MediaOutput output) { + WaMessage m = messages.findByUuid(messageUuid).orElseThrow(OutboundService::mediaNotFound); + WaConversation c = conversations.findById(m.conversationId).orElseThrow(OutboundService::mediaNotFound); + inbox.visible(c.uuid, companyId, userId, admin); + if (m.mediaId == null || !MEDIA_TYPES.contains(m.type)) { + throw mediaNotFound(); + } + CompanyConfig cfg = companies.configOf(c.companyId) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.CONFLICT, "WHATSAPP_NOT_CONFIGURED")); + try { + meta.media(cfg, m.mediaId, (upstreamMime, length) -> { + String mime = m.mediaMime != null ? m.mediaMime : upstreamMime; + // Only plain raster images render inline; anything else (SVG, HTML, PDF...) downloads, so media can never run script here. + boolean inline = ("image".equals(m.type) || "sticker".equals(m.type)) && mime != null && INLINE_MIMES.contains(mime.toLowerCase()); + String disposition = inline ? "inline" + : m.mediaFilename == null ? "attachment" : ContentDisposition.attachment().filename(m.mediaFilename).build().toString(); + return output.open(mime, disposition, length); + }); + } catch (MetaClient.MediaExpiredException e) { + throw new ResponseStatusException(HttpStatus.GONE, "MEDIA_EXPIRED"); + } catch (MetaClient.MetaException e) { + throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "META_UNAVAILABLE"); + } + } + + private static String fill(String template, List params) { + Matcher m = PARAM.matcher(template == null ? "" : template); + StringBuilder out = new StringBuilder(); + while (m.find()) { // one pass over the template, so a parameter that contains {{2}} is not substituted again + int i = Integer.parseInt(m.group(1)); + m.appendReplacement(out, Matcher.quoteReplacement(i >= 1 && i <= params.size() ? params.get(i - 1) : m.group())); + } + return m.appendTail(out).toString(); + } + + private static String preview(String text) { + return text.codePointCount(0, text.length()) <= PREVIEW_MAX ? text : text.substring(0, text.offsetByCodePoints(0, PREVIEW_MAX)); + } + + private static ResponseStatusException bad(String reason) { + return new ResponseStatusException(HttpStatus.BAD_REQUEST, reason); + } + + private static ResponseStatusException mediaNotFound() { + return new ResponseStatusException(HttpStatus.NOT_FOUND, "CONVERSATION_NOT_FOUND"); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/TemplateService.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/TemplateService.java new file mode 100644 index 0000000..6eb2360 --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/inbox/TemplateService.java @@ -0,0 +1,187 @@ +package com.solvway.services.whatsapp.inbox; + +import com.fasterxml.jackson.databind.JsonNode; +import com.solvway.services.whatsapp.config.WhatsAppSettings.CompanyConfig; +import com.solvway.services.whatsapp.dto.TemplateView; +import com.solvway.services.whatsapp.meta.MetaClient; +import com.solvway.services.whatsapp.model.WaTemplate; +import com.solvway.services.whatsapp.repository.WaTemplateRepository; +import com.solvway.services.whatsapp.service.CompanyDirectory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.web.server.ResponseStatusException; + +import java.time.Clock; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Template list and sync from Meta. A template this app cannot fill in (media or parameterised header, parameterised or + * copy-code buttons, named parameters) is stored with status UNSUPPORTED so it shows but cannot be sent; supported ones + * keep status APPROVED (the sync only asks Meta for approved templates). + */ +@Service +public class TemplateService { + + private static final Logger log = LoggerFactory.getLogger(TemplateService.class); + private static final Pattern PARAM = Pattern.compile("\\{\\{(\\d+)}}"); + private static final Set BUTTONS_OK = Set.of("QUICK_REPLY", "PHONE_NUMBER", "URL"); + + static final String APPROVED = "APPROVED"; + static final String UNSUPPORTED = "UNSUPPORTED"; + + private final WaTemplateRepository templates; + private final CompanyDirectory companies; + private final MetaClient meta; + private final TransactionTemplate tx; + private final Clock clock; + + @Autowired + public TemplateService(WaTemplateRepository templates, CompanyDirectory companies, MetaClient meta, TransactionTemplate tx) { + this(templates, companies, meta, tx, Clock.systemDefaultZone()); + } + + TemplateService(WaTemplateRepository templates, CompanyDirectory companies, MetaClient meta, TransactionTemplate tx, Clock clock) { + this.templates = templates; + this.companies = companies; + this.meta = meta; + this.tx = tx; + this.clock = clock; + } + + /** ponytail: no company means no list (a super admin picks a company); upgrade to a merged list if needed. */ + public List list(Long companyId) { + if (companyId == null) { + return List.of(); + } + return templates.findByCompanyIdOrderByNameAsc(companyId).stream().map(TemplateService::view).toList(); + } + + /** Admin only (404 otherwise). A super admin without a company syncs every configured company; one failure does not stop the rest. */ + public List sync(Long companyId, boolean admin) { + if (!admin) { + throw new ResponseStatusException(HttpStatus.NOT_FOUND, "NOT_FOUND"); + } + if (companyId == null) { + syncAll(); + return List.of(); + } + CompanyConfig cfg = companies.configOf(companyId) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.CONFLICT, "WHATSAPP_NOT_CONFIGURED")); + return syncOne(companyId, cfg).stream().map(TemplateService::view).toList(); + } + + @Scheduled(cron = "${whatsapp.templates.cron:0 30 3 * * *}", zone = "Asia/Kuala_Lumpur") + public void nightly() { + syncAll(); + } + + private void syncAll() { + for (Map.Entry e : companies.configured().entrySet()) { + try { + syncOne(e.getKey(), e.getValue()); + } catch (RuntimeException ex) { // per company: log the id and exception type only + log.warn("WhatsApp template sync failed for company {}: {}", e.getKey(), ex.getClass().getSimpleName()); + } + } + } + + /** Fetch first, so a Meta failure leaves the existing rows alone; then replace them atomically. */ + private List syncOne(long companyId, CompanyConfig cfg) { + List fetched; + try { + fetched = meta.templates(cfg); + } catch (MetaClient.MetaException e) { + throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "META_UNAVAILABLE"); + } + LocalDateTime now = LocalDateTime.now(clock); + List rows = new ArrayList<>(); + Set seen = new HashSet<>(); + for (JsonNode t : fetched) { + String name = t.path("name").asText(""); + String language = t.path("language").asText(""); + if (name.isEmpty() || language.isEmpty() || !seen.add(name + "\0" + language)) { + continue; + } + String body = bodyText(t); + WaTemplate row = new WaTemplate(); + row.companyId = companyId; + row.name = name; + row.language = language; + row.category = t.path("category").asText(null); + row.status = supported(t) ? APPROVED : UNSUPPORTED; + row.bodyText = body; + row.paramCount = paramCount(body); + row.syncedAt = now; + rows.add(row); + } + tx.executeWithoutResult(s -> { + templates.deleteByCompanyId(companyId); + templates.saveAll(rows); + }); + return rows; + } + + /** The one place that decides whether this app can fill a template in: body-only parameters, plain header and buttons. */ + static boolean supported(JsonNode template) { + if ("NAMED".equals(template.path("parameter_format").asText())) { + return false; + } + for (JsonNode c : template.path("components")) { + switch (c.path("type").asText()) { + case "BODY", "FOOTER" -> { } + case "HEADER" -> { + if (!"TEXT".equals(c.path("format").asText()) || c.path("text").asText("").contains("{{")) { + return false; + } + } + case "BUTTONS" -> { + for (JsonNode b : c.path("buttons")) { + if (!BUTTONS_OK.contains(b.path("type").asText()) || b.path("url").asText("").contains("{{")) { + return false; + } + } + } + default -> { + return false; + } + } + } + return true; + } + + private static String bodyText(JsonNode template) { + for (JsonNode c : template.path("components")) { + if ("BODY".equals(c.path("type").asText())) { + return c.path("text").asText(null); + } + } + return null; + } + + static int paramCount(String body) { + Set distinct = new HashSet<>(); + if (body != null) { + Matcher m = PARAM.matcher(body); + while (m.find()) { + distinct.add(m.group(1)); + } + } + return distinct.size(); + } + + private static TemplateView view(WaTemplate t) { + return new TemplateView(t.name, t.language, t.category, t.bodyText, t.paramCount, APPROVED.equals(t.status)); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/meta/MetaClient.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/meta/MetaClient.java new file mode 100644 index 0000000..26b880e --- /dev/null +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/meta/MetaClient.java @@ -0,0 +1,210 @@ +package com.solvway.services.whatsapp.meta; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.solvway.services.whatsapp.config.WhatsAppSettings; +import com.solvway.services.whatsapp.config.WhatsAppSettings.CompanyConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.HttpStatusCode; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +/** + * Meta WhatsApp Cloud (Graph) API client. Never logs tokens, URLs, message text or numbers; failures surface as codes only. + * ponytail: the media and paging URLs Meta returns get the bearer token as returned; no host allow-list. + */ +@Component +public class MetaClient { + + /** wamid on success; otherwise Meta's error code and title (code NETWORK when Meta was not reached). */ + public record SendResult(String wamid, String errorCode, String errorTitle) { + public boolean failed() { + return wamid == null; + } + } + + /** Receives the upstream's mime type and length (-1 unknown) once, before the first byte, and returns where to write. */ + @FunctionalInterface + public interface MediaSink { + OutputStream open(String mime, long length) throws IOException; + } + + public static class MediaExpiredException extends RuntimeException { + public MediaExpiredException() { + super("MEDIA_EXPIRED"); + } + } + + /** A Graph call that failed; the message is only the error code, never a body. */ + public static class MetaException extends RuntimeException { + public MetaException(String code) { + super(code); + } + } + + private static final JsonNodeFactory JSON = JsonNodeFactory.instance; + private static final int MAX_PAGES = 50; + /** ponytail: fixed 100 MB ceiling on one proxied media file (WhatsApp's own limit is 100 MB for documents); make it a setting if that changes. */ + static final long MAX_MEDIA_BYTES = 100L * 1024 * 1024; + + long maxMediaBytes = MAX_MEDIA_BYTES; // not final so a test can use a small cap + + private final WhatsAppSettings settings; + private final RestTemplate rest; + + @Autowired + public MetaClient(WhatsAppSettings settings, RestTemplateBuilder builder) { + this(settings, builder.setConnectTimeout(Duration.ofSeconds(10)).setReadTimeout(Duration.ofSeconds(10)).build()); + } + + MetaClient(WhatsAppSettings settings, RestTemplate rest) { + this.settings = settings; + this.rest = rest; + } + + public SendResult sendText(CompanyConfig cfg, String to, String body) { + ObjectNode payload = payload(to, "text"); + payload.putObject("text").put("body", body); + return send(cfg, payload); + } + + public SendResult sendTemplate(CompanyConfig cfg, String to, String name, String language, List params) { + ObjectNode payload = payload(to, "template"); + ObjectNode template = payload.putObject("template"); + template.put("name", name); + template.putObject("language").put("code", language); + if (!params.isEmpty()) { + ArrayNode parameters = template.putArray("components").addObject().put("type", "body").putArray("parameters"); + params.forEach(p -> parameters.addObject().put("type", "text").put("text", p)); + } + return send(cfg, payload); + } + + /** Every approved template of the business account, following paging.next. Throws MetaException. */ + public List templates(CompanyConfig cfg) { + List all = new ArrayList<>(); + URI next = URI.create(settings.graphBaseUrl() + "/" + cfg.wabaId() + "/message_templates?status=APPROVED&limit=200"); + for (int pages = 0; next != null; pages++) { + if (pages == MAX_PAGES) { // fail rather than return a truncated list: sync would delete the missing templates + throw new MetaException("PAGING"); + } + JsonNode page = get(cfg, next, JsonNode.class); + JsonNode data = page.path("data"); + data.forEach(all::add); + String link = page.path("paging").path("next").asText(""); + // a repeated link or an empty page means Meta is not advancing: stop instead of looping + next = link.isEmpty() || data.isEmpty() || link.equals(next.toString()) ? null : URI.create(link); + } + return all; + } + + /** + * Short-lived URL lookup, then streams the bytes into the sink (never held whole in memory). The sink opens only after + * Meta answered with success and a length within the cap, so 404/410 and refusals happen before anything is written. + * Throws MediaExpiredException (Meta 404/410) or MetaException. + */ + public void media(CompanyConfig cfg, String mediaId, MediaSink sink) { + try { + JsonNode info = rest.exchange(settings.graphBaseUrl() + "/{id}", HttpMethod.GET, auth(cfg), JsonNode.class, mediaId).getBody(); + if (info == null || !info.hasNonNull("url")) { + throw new MetaException("NO_URL"); + } + String mime = info.path("mime_type").asText(null); + rest.execute(URI.create(info.get("url").asText()), HttpMethod.GET, request -> request.getHeaders().setBearerAuth(cfg.accessToken()), response -> { + long length = response.getHeaders().getContentLength(); + if (length > maxMediaBytes) { + throw new MetaException("TOO_LARGE"); + } + try (InputStream in = response.getBody(); OutputStream out = sink.open(mime, length)) { + byte[] buffer = new byte[8192]; + long total = 0; + for (int n; (n = in.read(buffer)) != -1; ) { + total += n; + if (total > maxMediaBytes) { + throw new MetaException("TOO_LARGE"); + } + out.write(buffer, 0, n); + } + } + return null; + }); + } catch (HttpStatusCodeException e) { + HttpStatusCode code = e.getStatusCode(); + if (code.isSameCodeAs(HttpStatus.NOT_FOUND) || code.isSameCodeAs(HttpStatus.GONE)) { + throw new MediaExpiredException(); + } + throw new MetaException(String.valueOf(code.value())); + } catch (RestClientException e) { + throw new MetaException("NETWORK"); + } + } + + private SendResult send(CompanyConfig cfg, ObjectNode payload) { + HttpHeaders headers = new HttpHeaders(); + headers.setBearerAuth(cfg.accessToken()); + try { + JsonNode r = rest.exchange(settings.graphBaseUrl() + "/{id}/messages", HttpMethod.POST, new HttpEntity<>(payload, headers), + JsonNode.class, cfg.phoneNumberId()).getBody(); + String wamid = r == null ? "" : r.path("messages").path(0).path("id").asText(""); + return wamid.isEmpty() ? new SendResult(null, "NO_WAMID", null) : new SendResult(wamid, null, null); + } catch (HttpStatusCodeException e) { + JsonNode error = parse(e); + String title = error.path("title").asText(error.path("message").asText("")); + return new SendResult(null, cut(error.path("code").asText(String.valueOf(e.getStatusCode().value())), 32), + title.isEmpty() ? null : cut(title, 255)); + } catch (RestClientException e) { + return new SendResult(null, "NETWORK", null); + } + } + + private T get(CompanyConfig cfg, URI uri, Class type) { + try { + return rest.exchange(uri, HttpMethod.GET, auth(cfg), type).getBody(); + } catch (HttpStatusCodeException e) { + throw new MetaException(cut(parse(e).path("code").asText(String.valueOf(e.getStatusCode().value())), 32)); + } catch (RestClientException e) { + throw new MetaException("NETWORK"); + } + } + + private static JsonNode parse(HttpStatusCodeException e) { + try { + return new com.fasterxml.jackson.databind.ObjectMapper().readTree(e.getResponseBodyAsString()).path("error"); + } catch (Exception ignored) { // not JSON: fall back to the HTTP status + return JSON.missingNode(); + } + } + + private static ObjectNode payload(String to, String type) { + ObjectNode payload = JSON.objectNode(); + payload.put("messaging_product", "whatsapp").put("to", to).put("type", type); + return payload; + } + + private static HttpEntity auth(CompanyConfig cfg) { + HttpHeaders headers = new HttpHeaders(); + headers.setBearerAuth(cfg.accessToken()); + return new HttpEntity<>(headers); + } + + private static String cut(String s, int max) { + return s.length() <= max ? s : s.substring(0, max); + } +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java index 3283aac..fc728f0 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaConversationRepository.java @@ -31,6 +31,14 @@ public interface WaConversationRepository extends JpaRepository= last_message_at THEN :preview ELSE last_message_preview END, " + + "last_message_at = GREATEST(COALESCE(last_message_at, :at), :at) WHERE id = :id", nativeQuery = true) + int recordOutbound(@Param("id") Long id, @Param("at") LocalDateTime at, @Param("preview") String preview); + Optional findByUuid(String uuid); /** Inbox list: null companyId = all companies, null owner = any owner; q and digits are ready-made LIKE patterns. */ diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaTemplateRepository.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaTemplateRepository.java index 090b3f4..61977d3 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaTemplateRepository.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/repository/WaTemplateRepository.java @@ -2,5 +2,20 @@ package com.solvway.services.whatsapp.repository; import com.solvway.services.whatsapp.model.WaTemplate; import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; -public interface WaTemplateRepository extends JpaRepository {} +import java.util.List; +import java.util.Optional; + +public interface WaTemplateRepository extends JpaRepository { + List findByCompanyIdOrderByNameAsc(Long companyId); + + Optional findByCompanyIdAndNameAndLanguage(Long companyId, String name, String language); + + /** Bulk delete (runs at once, so re-inserting the same name+language in the same transaction does not collide). */ + @Modifying + @Query("delete from WaTemplate t where t.companyId = :companyId") + void deleteByCompanyId(@Param("companyId") Long companyId); +} diff --git a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java index 6d2630f..443cd67 100644 --- a/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java +++ b/solvway-services-whatsapp/src/main/java/com/solvway/services/whatsapp/service/CompanyDirectory.java @@ -14,6 +14,7 @@ import org.springframework.web.client.RestTemplate; import java.time.Clock; import java.time.Duration; import java.time.Instant; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import java.util.Set; @@ -72,6 +73,20 @@ public class CompanyDirectory { return byPhoneNumberId.entrySet().stream().filter(e -> e.getValue().id() == companyId).map(Map.Entry::getKey).findFirst(); } + /** The company's WhatsApp settings; empty when WhatsApp is not configured for it. */ + public Optional configOf(long companyId) { + return phoneNumberIdOf(companyId).flatMap(settings::findByPhoneNumberId); + } + + /** Every configured and resolved company id with its settings. */ + public Map configured() { + Map all = new LinkedHashMap<>(); + for (WhatsAppSettings.CompanyConfig c : settings.companies()) { + byPhoneNumberId(c.phoneNumberId()).ifPresent(company -> all.put(company.id(), c)); + } + return all; + } + private boolean coolingDown() { Instant failed = lastFailure; return failed != null && clock.instant().isBefore(failed.plus(RETRY_COOLDOWN)); diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/OutboundTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/OutboundTest.java new file mode 100644 index 0000000..2e1fa20 --- /dev/null +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/OutboundTest.java @@ -0,0 +1,310 @@ +package com.solvway.services.whatsapp.inbox; + +import com.solvway.services.whatsapp.config.WhatsAppSettings.CompanyConfig; +import com.solvway.services.whatsapp.controller.ErrorHandler; +import com.solvway.services.whatsapp.dto.MessageView; +import com.solvway.services.whatsapp.dto.SendMessageRequest; +import com.solvway.services.whatsapp.meta.MetaClient; +import com.solvway.services.whatsapp.model.WaConversation; +import com.solvway.services.whatsapp.model.WaMessage; +import com.solvway.services.whatsapp.model.WaTemplate; +import com.solvway.services.whatsapp.ownership.OwnershipService; +import com.solvway.services.whatsapp.repository.WaConversationRepository; +import com.solvway.services.whatsapp.repository.WaMessageRepository; +import com.solvway.services.whatsapp.repository.WaReadRepository; +import com.solvway.services.whatsapp.repository.WaTemplateRepository; +import com.solvway.services.whatsapp.service.CompanyDirectory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpStatus; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.server.ResponseStatusException; + +import java.time.Clock; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +class OutboundTest { + + private static final LocalDateTime NOW = LocalDateTime.of(2026, 12, 2, 12, 0); + private static final long STAFF = 10L; + private static final CompanyConfig CFG = new CompanyConfig("INS", "111", "222", "t", "s"); + + private WaConversationRepository conversations; + private WaMessageRepository messages; + private WaTemplateRepository templates; + private CompanyDirectory directory; + private MetaClient meta; + private OutboundService service; + private MockMvc mvc; + private final List statuses = new ArrayList<>(); + private WaConversation conv; + + @BeforeEach + void setUp() { + conversations = mock(WaConversationRepository.class); + messages = mock(WaMessageRepository.class); + templates = mock(WaTemplateRepository.class); + directory = mock(CompanyDirectory.class); + meta = mock(MetaClient.class); + Clock clock = Clock.fixed(NOW.toInstant(ZoneOffset.UTC), ZoneOffset.UTC); + InboxService inbox = new InboxService(conversations, messages, mock(WaReadRepository.class), mock(OwnershipService.class), directory, + mock(RestTemplate.class), clock); + service = new OutboundService(inbox, conversations, messages, templates, directory, meta, clock); + mvc = MockMvcBuilders.standaloneSetup(new OutboundController(service, mock(TemplateService.class))).setControllerAdvice(new ErrorHandler()).build(); + conv = new WaConversation(); + conv.id = 5L; + conv.uuid = "c-5"; + conv.companyId = 1L; + conv.contactWaId = "60123"; + conv.ownerUserId = STAFF; + conv.lastInboundAt = NOW.minusHours(1); + when(conversations.findByUuid("c-5")).thenReturn(Optional.of(conv)); + when(conversations.findById(5L)).thenReturn(Optional.of(conv)); + when(directory.configOf(1L)).thenReturn(Optional.of(CFG)); + when(messages.save(any(WaMessage.class))).thenAnswer(i -> { + WaMessage m = i.getArgument(0); + if (m.id == null) { + m.id = 77L; + } + statuses.add(m.status); + return m; + }); + } + + private void template(String status, int params) { + WaTemplate t = new WaTemplate(); + t.companyId = 1L; + t.name = "expo_followup"; + t.language = "en"; + t.status = status; + t.paramCount = params; + t.bodyText = "Hi {{1}}, thanks for visiting us at {{2}}."; + when(templates.findByCompanyIdAndNameAndLanguage(1L, "expo_followup", "en")).thenReturn(Optional.of(t)); + } + + private static void assertStatus(Runnable call, HttpStatus status, String reason) { + assertThatThrownBy(call::run).isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(status); + assertThat(e.getReason()).isEqualTo(reason); + }); + } + + private MessageView sendText(String text) { + return service.send("c-5", 1L, STAFF, false, new SendMessageRequest(text, null, null, null)); + } + + private MessageView sendTemplate(String... params) { + return service.send("c-5", 1L, STAFF, false, new SendMessageRequest(null, "expo_followup", "en", List.of(params))); + } + + // ---- sending + + @Test + void windowClosedRefusesTextAndSendsNothing() { + conv.lastInboundAt = NOW.minusHours(25); + assertStatus(() -> sendText("hi"), HttpStatus.CONFLICT, "WINDOW_CLOSED"); + conv.lastInboundAt = NOW.minusHours(24); + assertStatus(() -> sendText("hi"), HttpStatus.CONFLICT, "WINDOW_CLOSED"); + conv.lastInboundAt = null; + assertStatus(() -> sendText("hi"), HttpStatus.CONFLICT, "WINDOW_CLOSED"); + verifyNoInteractions(meta); + verify(messages, never()).save(any()); + } + + @Test + void openWindowTextIsPendingThenSentWithWamid() { + when(meta.sendText(CFG, "60123", "hi")).thenReturn(new MetaClient.SendResult("wamid.A", null, null)); + + MessageView view = sendText("hi"); + + assertThat(statuses).containsExactly("pending", "sent"); + assertThat(view.status()).isEqualTo("sent"); + assertThat(view.direction()).isEqualTo("OUT"); + assertThat(view.type()).isEqualTo("text"); + assertThat(view.body()).isEqualTo("hi"); + assertThat(view.sentByUserId()).isEqualTo(STAFF); + assertThat(view.statusAt()).isEqualTo(NOW); + verify(messages, never()).findByWamidAndDirection(anyString(), anyString()); + verify(conversations).recordOutbound(5L, NOW, "hi"); + verify(conversations, never()).updateOwnership(any(), any(), any(Boolean.class), any()); + } + + @Test + void metaErrorStoresFailedWithCodeAndTitle() { + when(meta.sendText(CFG, "60123", "hi")).thenReturn(new MetaClient.SendResult(null, "131026", "Message undeliverable")); + + MessageView view = sendText("hi"); + + assertThat(statuses).containsExactly("pending", "failed"); + assertThat(view.status()).isEqualTo("failed"); + assertThat(view.errorCode()).isEqualTo("131026"); + assertThat(view.errorTitle()).isEqualTo("Message undeliverable"); + } + + @Test + void templateSendSubstitutesBodyAndWorksOutsideWindow() { + conv.lastInboundAt = null; + template("APPROVED", 2); + when(meta.sendTemplate(CFG, "60123", "expo_followup", "en", List.of("Ann", "Expo"))) + .thenReturn(new MetaClient.SendResult("wamid.T", null, null)); + + MessageView view = sendTemplate("Ann", "Expo"); + + assertThat(view.type()).isEqualTo("template"); + assertThat(view.templateName()).isEqualTo("expo_followup"); + assertThat(view.body()).isEqualTo("Hi Ann, thanks for visiting us at Expo."); + assertThat(view.status()).isEqualTo("sent"); + } + + @Test + void templateParamProblemsAreRefusedBeforeMeta() { + template("APPROVED", 2); + assertStatus(() -> sendTemplate("Ann", " "), HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS"); + assertStatus(() -> sendTemplate("Ann"), HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS"); + assertStatus(() -> sendTemplate("a", "b", "c"), HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS"); + assertStatus(() -> service.send("c-5", 1L, STAFF, false, new SendMessageRequest(null, "expo_followup", "en", null)), + HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS"); + verifyNoInteractions(meta); + verify(messages, never()).save(any()); + } + + @Test + void unknownOrUnsupportedTemplateIsRefused() { + assertStatus(() -> sendTemplate("a", "b"), HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS"); + template("UNSUPPORTED", 0); + assertStatus(() -> sendTemplate(), HttpStatus.BAD_REQUEST, "TEMPLATE_PARAMS"); + verifyNoInteractions(meta); + } + + @Test + void notConfiguredIs409() { + when(directory.configOf(1L)).thenReturn(Optional.empty()); + assertStatus(() -> sendText("hi"), HttpStatus.CONFLICT, "WHATSAPP_NOT_CONFIGURED"); + verifyNoInteractions(meta); + } + + @Test + void staffOnAnotherUsersChatOrCompanyGets404() { + conv.ownerUserId = 99L; + assertStatus(() -> sendText("hi"), HttpStatus.NOT_FOUND, "CONVERSATION_NOT_FOUND"); + conv.ownerUserId = STAFF; + assertStatus(() -> service.send("c-5", 2L, STAFF, false, new SendMessageRequest("hi", null, null, null)), + HttpStatus.NOT_FOUND, "CONVERSATION_NOT_FOUND"); + assertStatus(() -> service.send("c-5", null, STAFF, false, new SendMessageRequest("hi", null, null, null)), + HttpStatus.NOT_FOUND, "CONVERSATION_NOT_FOUND"); + verifyNoInteractions(meta); + } + + @Test + void emptyOrBothBodiesAreInvalid() { + assertStatus(() -> sendText(" "), HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD"); + assertStatus(() -> service.send("c-5", 1L, STAFF, false, new SendMessageRequest("x", "expo_followup", "en", List.of())), + HttpStatus.BAD_REQUEST, "INVALID_PAYLOAD"); + verifyNoInteractions(meta); + } + + // ---- media + + private WaMessage media(String type, String mime, String filename) { + WaMessage m = new WaMessage(); + m.id = 3L; + m.uuid = "m-3"; + m.conversationId = 5L; + m.direction = "IN"; + m.type = type; + m.mediaId = "media-1"; + m.mediaMime = mime; + m.mediaFilename = filename; + when(messages.findByUuid("m-3")).thenReturn(Optional.of(m)); + return m; + } + + /** Meta stand-in: announces the mime to the sink, then writes the bytes. */ + private void streams(String mime, byte[] bytes) throws Exception { + doAnswer(inv -> { + try (java.io.OutputStream out = inv.getArgument(2).open(mime, bytes.length)) { + out.write(bytes); + } + return null; + }).when(meta).media(eq(CFG), eq("media-1"), any()); + } + + @Test + void mediaImageIsInlineWithMime() throws Exception { + media("image", "image/jpeg", null); + streams("image/jpeg", new byte[] {1, 2}); + + mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isOk()).andExpect(header().string("Content-Type", "image/jpeg")) + .andExpect(header().string("Content-Disposition", "inline")).andExpect(content().bytes(new byte[] {1, 2})); + } + + @Test + void mediaDocumentIsAttachmentWithFilename() throws Exception { + media("document", "application/pdf", "Quote 1.pdf"); + streams("application/pdf", new byte[] {1}); + + mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isOk()).andExpect(header().string("Content-Type", "application/pdf")) + .andExpect(header().string("Content-Disposition", org.hamcrest.Matchers.startsWith("attachment; filename=\"Quote 1.pdf\""))); + } + + @Test + void mediaActiveContentIsNeverInline() throws Exception { + media("image", "image/svg+xml", null); + streams("image/svg+xml", new byte[] {1}); + + mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(header().string("Content-Disposition", org.hamcrest.Matchers.startsWith("attachment"))) + .andExpect(header().string("X-Content-Type-Options", "nosniff")); + } + + @Test + void mediaExpiredIs410() throws Exception { + media("image", "image/jpeg", null); + doThrow(new MetaClient.MediaExpiredException()).when(meta).media(eq(CFG), eq("media-1"), any()); + + mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isGone()).andExpect(jsonPath("$.detail").value("MEDIA_EXPIRED")); + } + + @Test + void mediaNotVisibleOrNotMediaIs404() throws Exception { + WaMessage m = media("image", "image/jpeg", null); + conv.ownerUserId = 99L; + mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isNotFound()).andExpect(jsonPath("$.detail").value("CONVERSATION_NOT_FOUND")); + conv.ownerUserId = STAFF; + m.mediaId = null; + m.type = "text"; + mvc.perform(get("/whatsapp/media/m-3").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isNotFound()); + mvc.perform(get("/whatsapp/media/nope").param("companyId", "1").param("userId", "10").param("admin", "false")) + .andExpect(status().isNotFound()).andExpect(jsonPath("$.detail").value("CONVERSATION_NOT_FOUND")); + verifyNoInteractions(meta); + } +} diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/TemplateServiceTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/TemplateServiceTest.java new file mode 100644 index 0000000..ee1542f --- /dev/null +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/inbox/TemplateServiceTest.java @@ -0,0 +1,175 @@ +package com.solvway.services.whatsapp.inbox; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.solvway.services.whatsapp.config.WhatsAppSettings.CompanyConfig; +import com.solvway.services.whatsapp.dto.TemplateView; +import com.solvway.services.whatsapp.meta.MetaClient; +import com.solvway.services.whatsapp.model.WaTemplate; +import com.solvway.services.whatsapp.repository.WaTemplateRepository; +import com.solvway.services.whatsapp.service.CompanyDirectory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.http.HttpStatus; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.web.server.ResponseStatusException; + +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class TemplateServiceTest { + + private static final ObjectMapper JSON = new ObjectMapper(); + private static final CompanyConfig INS = new CompanyConfig("INS", "111", "222", "t", "s"); + private static final CompanyConfig CV = new CompanyConfig("CV", "112", "223", "t", "s"); + + private WaTemplateRepository repo; + private CompanyDirectory directory; + private MetaClient meta; + private TemplateService service; + + @BeforeEach + void setUp() { + repo = mock(WaTemplateRepository.class); + directory = mock(CompanyDirectory.class); + meta = mock(MetaClient.class); + when(directory.configOf(1L)).thenReturn(Optional.of(INS)); + when(directory.configOf(2L)).thenReturn(Optional.of(CV)); + service = new TemplateService(repo, directory, meta, new TransactionTemplate(mock(PlatformTransactionManager.class)), + Clock.fixed(Instant.parse("2026-12-02T04:00:00Z"), ZoneOffset.UTC)); + } + + private static JsonNode json(String s) { + try { + return JSON.readTree(s); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + + private static final String EXPO = "{\"name\":\"expo_followup\",\"language\":\"en\",\"category\":\"MARKETING\",\"status\":\"APPROVED\"," + + "\"components\":[{\"type\":\"BODY\",\"text\":\"Hi {{1}}, thanks for visiting us at {{2}}. {{1}} again.\"}]}"; + private static final String PROMO = "{\"name\":\"promo_header\",\"language\":\"en\",\"category\":\"MARKETING\",\"status\":\"APPROVED\"," + + "\"components\":[{\"type\":\"HEADER\",\"format\":\"IMAGE\"},{\"type\":\"BODY\",\"text\":\"Big sale\"}]}"; + + @SuppressWarnings("unchecked") + private List savedRows() { + ArgumentCaptor> captor = ArgumentCaptor.forClass(List.class); + verify(repo).saveAll(captor.capture()); + return captor.getValue(); + } + + @Test + void syncReplacesRowsWithBodyTextParamCountAndUnsupported() { + when(meta.templates(INS)).thenReturn(List.of(json(EXPO), json(PROMO))); + + service.sync(1L, true); + + verify(repo).deleteByCompanyId(1L); + List rows = savedRows(); + assertThat(rows).hasSize(2); + WaTemplate expo = rows.get(0); + assertThat(expo.companyId).isEqualTo(1L); + assertThat(expo.name).isEqualTo("expo_followup"); + assertThat(expo.language).isEqualTo("en"); + assertThat(expo.category).isEqualTo("MARKETING"); + assertThat(expo.status).isEqualTo("APPROVED"); + assertThat(expo.paramCount).isEqualTo(2); // {{1}} twice counts once + assertThat(expo.bodyText).startsWith("Hi {{1}}"); + assertThat(rows.get(1).status).isEqualTo("UNSUPPORTED"); + } + + @Test + void metaFailureKeepsExistingRows() { + when(meta.templates(INS)).thenThrow(new MetaClient.MetaException("NETWORK")); + + assertThatThrownBy(() -> service.sync(1L, true)).isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.BAD_GATEWAY)); + verify(repo, never()).deleteByCompanyId(any(Long.class)); + } + + @Test + void staffCannotSyncAndUnconfiguredCompanyIs409() { + assertThatThrownBy(() -> service.sync(1L, false)).isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND)); + assertThatThrownBy(() -> service.sync(9L, true)).isInstanceOfSatisfying(ResponseStatusException.class, e -> { + assertThat(e.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(e.getReason()).isEqualTo("WHATSAPP_NOT_CONFIGURED"); + }); + verify(meta, never()).templates(any()); + } + + @Test + void superAdminWithoutCompanySyncsEveryConfiguredCompanyAndSurvivesOneFailure() { + LinkedHashMap all = new LinkedHashMap<>(); + all.put(1L, INS); + all.put(2L, CV); + when(directory.configured()).thenReturn(all); + when(meta.templates(INS)).thenThrow(new MetaClient.MetaException("190")); + when(meta.templates(CV)).thenReturn(List.of(json(EXPO))); + + service.sync(null, true); + + verify(repo).deleteByCompanyId(2L); + verify(repo, never()).deleteByCompanyId(1L); + } + + @Test + void nightlySyncsEveryCompany() { + LinkedHashMap all = new LinkedHashMap<>(); + all.put(1L, INS); + when(directory.configured()).thenReturn(all); + when(meta.templates(INS)).thenReturn(List.of(json(EXPO))); + + service.nightly(); + + verify(repo).deleteByCompanyId(1L); + } + + @Test + void listShowsSupportedFlagFromStatus() { + WaTemplate ok = row("a", "APPROVED"); + WaTemplate bad = row("b", "UNSUPPORTED"); + when(repo.findByCompanyIdOrderByNameAsc(1L)).thenReturn(List.of(ok, bad)); + + List views = service.list(1L); + + assertThat(views).extracting(TemplateView::name).containsExactly("a", "b"); + assertThat(views).extracting(TemplateView::supported).containsExactly(true, false); + assertThat(service.list(null)).isEmpty(); + } + + private static WaTemplate row(String name, String status) { + WaTemplate t = new WaTemplate(); + t.name = name; + t.language = "en"; + t.status = status; + return t; + } + + @Test + void supportedRule() { + assertThat(TemplateService.supported(json(EXPO))).isTrue(); + assertThat(TemplateService.supported(json(PROMO))).isFalse(); + assertThat(TemplateService.supported(json("{\"components\":[{\"type\":\"HEADER\",\"format\":\"TEXT\",\"text\":\"Hello\"},{\"type\":\"BODY\",\"text\":\"x\"}]}"))).isTrue(); + assertThat(TemplateService.supported(json("{\"components\":[{\"type\":\"HEADER\",\"format\":\"TEXT\",\"text\":\"Hello {{1}}\"}]}"))).isFalse(); + assertThat(TemplateService.supported(json("{\"components\":[{\"type\":\"BODY\",\"text\":\"x\"},{\"type\":\"BUTTONS\",\"buttons\":[{\"type\":\"QUICK_REPLY\"},{\"type\":\"URL\",\"url\":\"https://a.com\"}]}]}"))).isTrue(); + assertThat(TemplateService.supported(json("{\"components\":[{\"type\":\"BODY\",\"text\":\"x\"},{\"type\":\"BUTTONS\",\"buttons\":[{\"type\":\"URL\",\"url\":\"https://a.com/{{1}}\"}]}]}"))).isFalse(); + assertThat(TemplateService.supported(json("{\"components\":[{\"type\":\"BODY\",\"text\":\"x\"},{\"type\":\"BUTTONS\",\"buttons\":[{\"type\":\"COPY_CODE\"}]}]}"))).isFalse(); + assertThat(TemplateService.supported(json("{\"parameter_format\":\"NAMED\",\"components\":[{\"type\":\"BODY\",\"text\":\"Hi {{name}}\"}]}"))).isFalse(); + } +} diff --git a/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/meta/MetaClientTest.java b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/meta/MetaClientTest.java new file mode 100644 index 0000000..331ee10 --- /dev/null +++ b/solvway-services-whatsapp/src/test/java/com/solvway/services/whatsapp/meta/MetaClientTest.java @@ -0,0 +1,263 @@ +package com.solvway.services.whatsapp.meta; + +import com.fasterxml.jackson.databind.JsonNode; +import com.solvway.services.whatsapp.config.WhatsAppSettings; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.mock.env.MockEnvironment; +import org.springframework.test.web.client.ExpectedCount; +import org.springframework.test.web.client.MockRestServiceServer; +import org.springframework.web.client.RestTemplate; + +import java.io.IOException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.header; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.jsonPath; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; +import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess; +import static org.springframework.test.web.client.response.MockRestResponseCreators.withException; + +class MetaClientTest { + + private WhatsAppSettings.CompanyConfig cfg; + private MockRestServiceServer server; + private MetaClient client; + + @BeforeEach + void setUp() { + MockEnvironment env = new MockEnvironment().withProperty("WHATSAPP_COMPANIES", "INS") + .withProperty("WHATSAPP_INS_PHONE_NUMBER_ID", "111").withProperty("WHATSAPP_INS_WABA_ID", "222") + .withProperty("WHATSAPP_INS_ACCESS_TOKEN", "tok").withProperty("WHATSAPP_INS_APP_SECRET", "s") + .withProperty("WHATSAPP_GRAPH_BASE_URL", "http://graph.test/v1"); + WhatsAppSettings settings = new WhatsAppSettings(env); + cfg = settings.companies().get(0); + RestTemplate rest = new RestTemplate(); + server = MockRestServiceServer.bindTo(rest).build(); + client = new MetaClient(settings, rest); + } + + @Test + void sendsTextWithBearerAndReturnsWamid() { + server.expect(requestTo("http://graph.test/v1/111/messages")).andExpect(method(HttpMethod.POST)) + .andExpect(header("Authorization", "Bearer tok")) + .andExpect(jsonPath("$.messaging_product").value("whatsapp")).andExpect(jsonPath("$.to").value("60123")) + .andExpect(jsonPath("$.type").value("text")).andExpect(jsonPath("$.text.body").value("hello")) + .andRespond(withSuccess("{\"messages\":[{\"id\":\"wamid.X\"}]}", MediaType.APPLICATION_JSON)); + + MetaClient.SendResult r = client.sendText(cfg, "60123", "hello"); + + assertThat(r.wamid()).isEqualTo("wamid.X"); + assertThat(r.failed()).isFalse(); + server.verify(); + } + + @Test + void sendsTemplateWithBodyParametersAndOmitsComponentsWithoutParams() { + server.expect(requestTo("http://graph.test/v1/111/messages")).andExpect(jsonPath("$.type").value("template")) + .andExpect(jsonPath("$.template.name").value("expo_followup")).andExpect(jsonPath("$.template.language.code").value("en")) + .andExpect(jsonPath("$.template.components[0].type").value("body")) + .andExpect(jsonPath("$.template.components[0].parameters[1].text").value("Expo")) + .andRespond(withSuccess("{\"messages\":[{\"id\":\"wamid.T\"}]}", MediaType.APPLICATION_JSON)); + server.expect(requestTo("http://graph.test/v1/111/messages")).andExpect(jsonPath("$.template.components").doesNotExist()) + .andRespond(withSuccess("{\"messages\":[{\"id\":\"wamid.U\"}]}", MediaType.APPLICATION_JSON)); + + assertThat(client.sendTemplate(cfg, "60123", "expo_followup", "en", List.of("Ann", "Expo")).wamid()).isEqualTo("wamid.T"); + assertThat(client.sendTemplate(cfg, "60123", "plain", "en", List.of()).wamid()).isEqualTo("wamid.U"); + } + + @Test + void metaErrorGivesCodeAndTitleOrMessage() { + server.expect(requestTo("http://graph.test/v1/111/messages")).andRespond(withStatus(HttpStatus.BAD_REQUEST) + .contentType(MediaType.APPLICATION_JSON).body("{\"error\":{\"code\":131026,\"title\":\"Message undeliverable\",\"message\":\"m\"}}")); + server.expect(requestTo("http://graph.test/v1/111/messages")).andRespond(withStatus(HttpStatus.UNAUTHORIZED) + .contentType(MediaType.APPLICATION_JSON).body("{\"error\":{\"code\":190,\"message\":\"Invalid token\"}}")); + + MetaClient.SendResult first = client.sendText(cfg, "60123", "x"); + MetaClient.SendResult second = client.sendText(cfg, "60123", "x"); + + assertThat(first.failed()).isTrue(); + assertThat(first.errorCode()).isEqualTo("131026"); + assertThat(first.errorTitle()).isEqualTo("Message undeliverable"); + assertThat(second.errorCode()).isEqualTo("190"); + assertThat(second.errorTitle()).isEqualTo("Invalid token"); + } + + @Test + void networkErrorGivesNetworkCode() { + server.expect(requestTo("http://graph.test/v1/111/messages")).andRespond(withException(new IOException("down"))); + + MetaClient.SendResult r = client.sendText(cfg, "60123", "x"); + + assertThat(r.failed()).isTrue(); + assertThat(r.errorCode()).isEqualTo("NETWORK"); + } + + @Test + void templatesFollowPagingNext() { + server.expect(requestTo("http://graph.test/v1/222/message_templates?status=APPROVED&limit=200")) + .andExpect(header("Authorization", "Bearer tok")) + .andRespond(withSuccess("{\"data\":[{\"name\":\"a\"}],\"paging\":{\"next\":\"http://graph.test/v1/222/message_templates?after=X\"}}", + MediaType.APPLICATION_JSON)); + server.expect(requestTo("http://graph.test/v1/222/message_templates?after=X")) + .andExpect(header("Authorization", "Bearer tok")) + .andRespond(withSuccess("{\"data\":[{\"name\":\"b\"}],\"paging\":{}}", MediaType.APPLICATION_JSON)); + + List all = client.templates(cfg); + + assertThat(all).extracting(n -> n.get("name").asText()).containsExactly("a", "b"); + server.verify(); + } + + @Test + void templatePagingStopsWhenNextRepeatsTheRequestedUrl() { + server.expect(requestTo("http://graph.test/v1/222/message_templates?status=APPROVED&limit=200")) + .andRespond(withSuccess("{\"data\":[{\"name\":\"a\"}],\"paging\":{\"next\":\"http://graph.test/v1/222/message_templates?after=X\"}}", + MediaType.APPLICATION_JSON)); + server.expect(requestTo("http://graph.test/v1/222/message_templates?after=X")) + .andRespond(withSuccess("{\"data\":[{\"name\":\"b\"}],\"paging\":{\"next\":\"http://graph.test/v1/222/message_templates?after=X\"}}", + MediaType.APPLICATION_JSON)); + + assertThat(client.templates(cfg)).hasSize(2); + server.verify(); + } + + @Test + void templatePagingStopsOnAnEmptyPage() { + server.expect(requestTo("http://graph.test/v1/222/message_templates?status=APPROVED&limit=200")) + .andRespond(withSuccess("{\"data\":[],\"paging\":{\"next\":\"http://graph.test/v1/222/message_templates?after=Y\"}}", + MediaType.APPLICATION_JSON)); + + assertThat(client.templates(cfg)).isEmpty(); + server.verify(); + } + + @Test + void templatePagingIsCappedAtFiftyPages() { + int[] n = {0}; + server.expect(ExpectedCount.manyTimes(), requestTo(org.hamcrest.Matchers.startsWith("http://graph.test/v1/222/message_templates"))) + .andRespond(request -> withSuccess("{\"data\":[{\"name\":\"t\"}],\"paging\":{\"next\":\"http://graph.test/v1/222/message_templates?after=p" + + (++n[0]) + "\"}}", MediaType.APPLICATION_JSON).createResponse(request)); + + assertThatThrownBy(() -> client.templates(cfg)).isInstanceOf(MetaClient.MetaException.class); + assertThat(n[0]).isEqualTo(50); + } + + /** Sink that records what was announced and written, and how much of the upstream had been read at the first write. */ + private static class Sink implements MetaClient.MediaSink { + String mime; + long length = -2; + boolean opened; + final java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(); + long upstreamReadAtFirstWrite = -1; + java.util.function.LongSupplier upstreamRead = () -> -1; + + @Override + public java.io.OutputStream open(String mime, long length) { + this.mime = mime; + this.length = length; + opened = true; + return new java.io.OutputStream() { + @Override + public void write(int b) { + write(new byte[] {(byte) b}, 0, 1); + } + + @Override + public void write(byte[] b, int off, int len) { + if (upstreamReadAtFirstWrite < 0) { + upstreamReadAtFirstWrite = upstreamRead.getAsLong(); + } + out.write(b, off, len); + } + }; + } + } + + private void expectMediaLookup(String url) { + server.expect(requestTo("http://graph.test/v1/m1")).andExpect(header("Authorization", "Bearer tok")) + .andRespond(withSuccess("{\"url\":\"" + url + "\",\"mime_type\":\"image/png\"}", MediaType.APPLICATION_JSON)); + } + + @Test + void mediaFetchesUrlThenStreamsBytes() { + expectMediaLookup("http://cdn.test/file"); + server.expect(requestTo("http://cdn.test/file")).andExpect(header("Authorization", "Bearer tok")) + .andRespond(withSuccess(new byte[] {1, 2, 3}, MediaType.APPLICATION_OCTET_STREAM)); + Sink sink = new Sink(); + + client.media(cfg, "m1", sink); + + assertThat(sink.out.toByteArray()).containsExactly(1, 2, 3); + assertThat(sink.mime).isEqualTo("image/png"); + } + + @Test + void mediaIsPassedThroughNotBufferedWhole() { + expectMediaLookup("http://cdn.test/big"); + byte[] data = new byte[64 * 1024]; + long[] read = {0}; + java.io.InputStream upstream = new java.io.ByteArrayInputStream(data) { + @Override + public synchronized int read(byte[] b, int off, int len) { + int n = super.read(b, off, len); + if (n > 0) { + read[0] += n; + } + return n; + } + }; + server.expect(requestTo("http://cdn.test/big")).andRespond(request -> + new org.springframework.mock.http.client.MockClientHttpResponse(upstream, HttpStatus.OK)); + Sink sink = new Sink(); + sink.upstreamRead = () -> read[0]; + + client.media(cfg, "m1", sink); + + assertThat(sink.out.size()).isEqualTo(data.length); + assertThat(sink.upstreamReadAtFirstWrite).isGreaterThan(0).isLessThan(data.length); + } + + @Test + void mediaOverTheCapIsRefusedByContentLengthBeforeAnyByte() { + expectMediaLookup("http://cdn.test/huge"); + server.expect(requestTo("http://cdn.test/huge")).andRespond(withSuccess(new byte[] {1}, MediaType.APPLICATION_OCTET_STREAM) + .header("Content-Length", String.valueOf(MetaClient.MAX_MEDIA_BYTES + 1))); + Sink sink = new Sink(); + + assertThatThrownBy(() -> client.media(cfg, "m1", sink)).isInstanceOf(MetaClient.MetaException.class); + assertThat(sink.opened).isFalse(); + } + + @Test + void mediaCopyStopsAtTheCapWhenLengthIsUnknown() { + expectMediaLookup("http://cdn.test/chunked"); + server.expect(requestTo("http://cdn.test/chunked")).andRespond(withSuccess(new byte[100], MediaType.APPLICATION_OCTET_STREAM)); + client.maxMediaBytes = 10; + Sink sink = new Sink(); + + assertThatThrownBy(() -> client.media(cfg, "m1", sink)).isInstanceOf(MetaClient.MetaException.class); + assertThat(sink.out.size()).isLessThanOrEqualTo(10); + } + + @Test + void mediaGoneIsExpiredAndNothingIsOpened() { + server.expect(requestTo("http://graph.test/v1/m1")).andRespond(withStatus(HttpStatus.NOT_FOUND)); + server.expect(requestTo("http://graph.test/v1/m2")) + .andRespond(withSuccess("{\"url\":\"http://cdn.test/f\",\"mime_type\":\"image/png\"}", MediaType.APPLICATION_JSON)); + server.expect(requestTo("http://cdn.test/f")).andRespond(withStatus(HttpStatus.GONE)); + Sink sink = new Sink(); + + assertThatThrownBy(() -> client.media(cfg, "m1", sink)).isInstanceOf(MetaClient.MediaExpiredException.class); + assertThatThrownBy(() -> client.media(cfg, "m2", sink)).isInstanceOf(MetaClient.MediaExpiredException.class); + assertThat(sink.opened).isFalse(); + } +}