feat: whatsapp admin api in mobile-api
- /api/admin/whatsapp: conversations, thread, send, read, assign, start, templates and sync, media, unread count, assignees. - Caller context from the token: company through AdminCompanyScope (fail closed), admin for BO_WHATSAPP_ADMIN or super admin. - Exactly-one validation for send, assign and start; path ids must look like uuids before they reach the service. - Service reason codes come back with their status and a message; an unreachable service is 502. - Owner and assignee names filled from the system service. - Audit: send (conversation and template name, never text), assign (owner before and after), start, sync; read markers skipped. - Media streams with nosniff and a sandbox CSP; anything but image, audio or video downloads. - Disabling a user or changing their roles tells the service to free their chats (best effort). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
0d5c3f351a
commit
13b692748c
8 files changed
+1030
-1
No files matched your search
+1
@@ -7,6 +7,7 @@ public class RestApiSystemServiceConstants {
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_USERNAME = "/user/findByUsername/{username}";
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_ID = "/user/findById/{id}";
|
||||
public static final String API_REST_SYSTEM_USER_ACTIVE_ADMIN_OF = "/user/{id}/activeAdminOf/{companyId}";
|
||||
public static final String API_REST_SYSTEM_USER_ACTIVE_WITH_MODULE = "/user/activeWithModule?companyId={companyId}&module={module}";
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL = "/user/findByEmail/{email}";
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_ID_NOT = "/user/findByEmailAndIdNot/{email}/{id}";
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_EMAIL_AND_COMPANY = "/user/findByEmailAndCompanyId/{email}";
|
||||
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package com.solvway.mobile.api.controller.admin;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.mobile.api.dto.whatsapp.AssignRequest;
|
||||
import com.solvway.mobile.api.dto.whatsapp.ConversationPage;
|
||||
import com.solvway.mobile.api.dto.whatsapp.ConversationView;
|
||||
import com.solvway.mobile.api.dto.whatsapp.MessageView;
|
||||
import com.solvway.mobile.api.dto.whatsapp.SendMessageRequest;
|
||||
import com.solvway.mobile.api.dto.whatsapp.StartChatRequest;
|
||||
import com.solvway.mobile.api.dto.whatsapp.TemplateView;
|
||||
import com.solvway.mobile.api.dto.whatsapp.ThreadView;
|
||||
import com.solvway.mobile.api.dto.whatsapp.UnreadCount;
|
||||
import com.solvway.mobile.api.service.AdminWhatsAppService;
|
||||
import com.solvway.mobile.api.useraccess.AdminModule;
|
||||
import com.solvway.mobile.api.useraccess.Audited;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
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;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The WhatsApp inbox (design decision 9). Staff with BO_WHATSAPP see their own chats; BO_WHATSAPP_ADMIN sees the
|
||||
* company's. companyId is honoured for a super admin only (AdminCompanyScope). Must stay under {@code controller..}.
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/whatsapp")
|
||||
@RequiredArgsConstructor
|
||||
@AdminModule({AdminWhatsAppService.MODULE, AdminWhatsAppService.MODULE_ADMIN})
|
||||
public class AdminWhatsAppController {
|
||||
private final AdminWhatsAppService whatsapp;
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/conversations")
|
||||
public ResponseEntity<ConversationPage> list(@RequestParam(defaultValue = "mine") String tab, @RequestParam(required = false) String q,
|
||||
@RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "30") int size,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.list(companyId, tab, q, page, size));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/conversations/{uuid}")
|
||||
public ResponseEntity<ThreadView> thread(@PathVariable String uuid, @RequestParam(required = false) String before,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.thread(uuid, companyId, before));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@Audited(action = "WHATSAPP_SEND")
|
||||
@PostMapping("/conversations/{uuid}/messages")
|
||||
public ResponseEntity<MessageView> send(@PathVariable String uuid, @RequestBody SendMessageRequest request,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.send(uuid, companyId, request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@Audited(skip = true)
|
||||
@PostMapping("/conversations/{uuid}/read")
|
||||
public ResponseEntity<Void> read(@PathVariable String uuid, @RequestParam(required = false) Long companyId) {
|
||||
whatsapp.read(uuid, companyId);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule(AdminWhatsAppService.MODULE_ADMIN)
|
||||
@Audited(action = "WHATSAPP_ASSIGN")
|
||||
@PostMapping("/conversations/{uuid}/assign")
|
||||
public ResponseEntity<ConversationView> assign(@PathVariable String uuid, @RequestBody AssignRequest request,
|
||||
@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.assign(uuid, companyId, request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@Audited(action = "WHATSAPP_START")
|
||||
@PostMapping("/start")
|
||||
public ResponseEntity<ConversationView> start(@RequestBody StartChatRequest request, @RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.start(companyId, request));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/templates")
|
||||
public ResponseEntity<List<TemplateView>> templates(@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.templates(companyId));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule(AdminWhatsAppService.MODULE_ADMIN)
|
||||
@Audited(action = "WHATSAPP_TEMPLATE_SYNC")
|
||||
@PostMapping("/templates/sync")
|
||||
public ResponseEntity<List<TemplateView>> syncTemplates(@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.syncTemplates(companyId));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/media/{messageUuid}")
|
||||
public void media(@PathVariable String messageUuid, @RequestParam(required = false) Long companyId, HttpServletResponse response) {
|
||||
whatsapp.media(messageUuid, companyId, (type, length) -> {
|
||||
response.setContentType(type);
|
||||
if (length >= 0) response.setContentLengthLong(length);
|
||||
response.setHeader("Cache-Control", "private, no-store");
|
||||
// The type is whatever the sender declared: never let it run as a page on this origin.
|
||||
response.setHeader("X-Content-Type-Options", "nosniff");
|
||||
response.setHeader("Content-Security-Policy", "sandbox");
|
||||
if (!type.startsWith("image/") && !type.startsWith("audio/") && !type.startsWith("video/")) {
|
||||
response.setHeader("Content-Disposition", "attachment");
|
||||
}
|
||||
return response.getOutputStream();
|
||||
});
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@GetMapping("/unread-count")
|
||||
public ResponseEntity<UnreadCount> unreadCount(@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.unreadCount(companyId));
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@AdminModule(AdminWhatsAppService.MODULE_ADMIN)
|
||||
@GetMapping("/assignees")
|
||||
public ResponseEntity<List<Map<String, Object>>> assignees(@RequestParam(required = false) Long companyId) {
|
||||
return ResponseEntity.ok(whatsapp.assignees(companyId));
|
||||
}
|
||||
}
|
||||
@@ -178,6 +178,10 @@ public class AdminUserService {
|
||||
List<String> rolesAfter = sortedRoleNames(user.get("roles"));
|
||||
if (r.roles() != null && !rolesBefore.equals(rolesAfter)) AuditChanges.put("roles", rolesBefore, rolesAfter);
|
||||
if (r.enabled() != null && !r.enabled().equals(enabledBefore)) AuditChanges.put("enabled", enabledBefore, r.enabled());
|
||||
if (Boolean.FALSE.equals(r.enabled()) && !Boolean.FALSE.equals(enabledBefore)
|
||||
|| r.roles() != null && !rolesBefore.equals(rolesAfter)) {
|
||||
AdminWhatsAppService.userChanged(restTemplateUtil, id); // they may have lost WhatsApp: free their chats
|
||||
}
|
||||
return present(clean(saved));
|
||||
}
|
||||
|
||||
|
||||
+308
@@ -0,0 +1,308 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.constant.api.RestApiWhatsappServiceConstants;
|
||||
import com.solvway.mobile.api.dto.whatsapp.AssignRequest;
|
||||
import com.solvway.mobile.api.dto.whatsapp.ConversationPage;
|
||||
import com.solvway.mobile.api.dto.whatsapp.ConversationView;
|
||||
import com.solvway.mobile.api.dto.whatsapp.MessageView;
|
||||
import com.solvway.mobile.api.dto.whatsapp.SendMessageRequest;
|
||||
import com.solvway.mobile.api.dto.whatsapp.StartChatRequest;
|
||||
import com.solvway.mobile.api.dto.whatsapp.TemplateView;
|
||||
import com.solvway.mobile.api.dto.whatsapp.ThreadView;
|
||||
import com.solvway.mobile.api.dto.whatsapp.UnreadCount;
|
||||
import com.solvway.mobile.api.dto.whatsapp.UserChangedRequest;
|
||||
import com.solvway.mobile.api.errorhandler.CodedResponseStatusException;
|
||||
import com.solvway.mobile.api.useraccess.AdminCompanyScope;
|
||||
import com.solvway.mobile.api.useraccess.AdminModuleAccess;
|
||||
import com.solvway.mobile.api.useraccess.AuditChanges;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.HttpStatusCode;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
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.io.UncheckedIOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* The WhatsApp inbox for the admin portal. Resolves the caller's context (company, user, admin) from the token and
|
||||
* passes it to the WhatsApp service, which enforces who may see what (RestApiWhatsappServiceConstants).
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class AdminWhatsAppService {
|
||||
public static final String MODULE = "BO_WHATSAPP";
|
||||
public static final String MODULE_ADMIN = "BO_WHATSAPP_ADMIN";
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final java.util.regex.Pattern UUID_LIKE = java.util.regex.Pattern.compile("[A-Za-z0-9-]{1,64}");
|
||||
private static final ParameterizedTypeReference<List<Long>> IDS = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<List<TemplateView>> TEMPLATES = new ParameterizedTypeReference<>() {};
|
||||
private static final ParameterizedTypeReference<Map<String, Object>> MAP = new ParameterizedTypeReference<>() {};
|
||||
/** Messages the portal shows for the service's reason codes; anything else keeps the code. */
|
||||
private static final Map<String, String> MESSAGES = Map.of(
|
||||
"WINDOW_CLOSED", "The 24-hour window has closed. Send a template.",
|
||||
"TEMPLATE_PARAMS", "Fill in every template parameter.",
|
||||
"MEDIA_EXPIRED", "Media expired",
|
||||
"WHATSAPP_NOT_CONFIGURED", "WhatsApp is not configured",
|
||||
"ASSIGNEE_NOT_ALLOWED", "This user cannot take WhatsApp chats.",
|
||||
"LEAD_NOT_FOUND", "This lead has no mobile number.",
|
||||
"USERS_UNAVAILABLE", "Users could not be loaded. Try again.");
|
||||
|
||||
private final RestTemplateCustomUtil rest;
|
||||
private final RestTemplate restTemplate;
|
||||
private final AdminAuthenticationService adminAuthenticationService;
|
||||
// a field initializer: the scope holds no state
|
||||
private final AdminCompanyScope scope = new AdminCompanyScope();
|
||||
|
||||
public AdminWhatsAppService(RestTemplateCustomUtil rest, RestTemplate restTemplate,
|
||||
AdminAuthenticationService adminAuthenticationService) {
|
||||
this.rest = rest;
|
||||
this.restTemplate = restTemplate;
|
||||
this.adminAuthenticationService = adminAuthenticationService;
|
||||
}
|
||||
|
||||
/** Who is asking: the company they may see (null = super admin, all companies), their id, and admin rights. */
|
||||
record Context(Long companyId, long userId, boolean admin) {}
|
||||
|
||||
Context context(Long requestedCompanyId) {
|
||||
User caller = adminAuthenticationService.loadUserByToken(HttpReqRespUtils.getJwtToken());
|
||||
if (caller == null || caller.getId() == null) throw coded(HttpStatus.UNAUTHORIZED, "Not signed in", "UNAUTHORIZED");
|
||||
Long company = scope.scope(caller, requestedCompanyId); // staff without a company: 403, fail closed
|
||||
boolean admin = AdminCompanyScope.isSuper(caller) || AdminModuleAccess.holds(rest, caller, MODULE_ADMIN);
|
||||
return new Context(company, caller.getId(), admin);
|
||||
}
|
||||
|
||||
public ConversationPage list(Long companyId, String tab, String q, int page, int size) {
|
||||
Context c = context(companyId);
|
||||
ConversationPage p = call(() -> rest.getForEntity(
|
||||
url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATIONS, null, c)
|
||||
+ "&tab={tab}&q={q}&page={page}&size={size}",
|
||||
ConversationPage.class, tab, q == null ? "" : q.trim(), page, size).getBody());
|
||||
Function<Long, String> names = names();
|
||||
return new ConversationPage(p.items().stream().map(v -> named(v, names)).toList(), p.total(), p.page(), p.size());
|
||||
}
|
||||
|
||||
public ThreadView thread(String uuid, Long companyId, String before) {
|
||||
Context c = context(companyId);
|
||||
String u = url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION, uuid, c);
|
||||
ThreadView t = call(() -> before == null
|
||||
? rest.getForEntity(u, ThreadView.class).getBody()
|
||||
: rest.getForEntity(u + "&before={before}", ThreadView.class, before).getBody());
|
||||
return new ThreadView(named(t.conversation(), names()), t.messages(), t.hasOlder());
|
||||
}
|
||||
|
||||
public MessageView send(String uuid, Long companyId, SendMessageRequest r) {
|
||||
boolean text = r != null && StringUtils.hasText(r.text());
|
||||
boolean template = r != null && StringUtils.hasText(r.template());
|
||||
if (text == template) throw coded(HttpStatus.BAD_REQUEST, "Send a text or a template.", "INVALID_PAYLOAD");
|
||||
Context c = context(companyId);
|
||||
// the template name only: never the message text or the filled-in parameters
|
||||
AuditChanges.put("conversation", null, uuid);
|
||||
if (template) AuditChanges.put("template", null, r.template());
|
||||
return call(() -> rest.postForEntity(url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION_SEND, uuid, c),
|
||||
MessageView.class, r).getBody());
|
||||
}
|
||||
|
||||
public void read(String uuid, Long companyId) {
|
||||
Context c = context(companyId);
|
||||
call(() -> rest.postForEntity(url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION_READ, uuid, c),
|
||||
Void.class, null));
|
||||
}
|
||||
|
||||
public ConversationView assign(String uuid, Long companyId, AssignRequest r) {
|
||||
boolean manual = r != null && r.userId() != null;
|
||||
boolean automatic = r != null && Boolean.TRUE.equals(r.automatic());
|
||||
if (manual == automatic) throw coded(HttpStatus.BAD_REQUEST, "Choose a user or automatic.", "INVALID_PAYLOAD");
|
||||
Context c = context(companyId);
|
||||
if (!c.admin()) throw coded(HttpStatus.FORBIDDEN, "WhatsApp Admin only", "FORBIDDEN");
|
||||
// ponytail: reads the thread for the owner before the change (audit); a light conversation GET if it shows up in latency.
|
||||
ConversationView before = call(() -> rest.getForEntity(
|
||||
url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION, uuid, c), ThreadView.class).getBody()).conversation();
|
||||
ConversationView after = call(() -> rest.postForEntity(
|
||||
url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION_ASSIGN, uuid, c),
|
||||
ConversationView.class, r).getBody());
|
||||
AuditChanges.put("ownerUserId", before.ownerUserId(), after.ownerUserId());
|
||||
AuditChanges.put("ownerManual", before.ownerManual(), after.ownerManual());
|
||||
return named(after, names());
|
||||
}
|
||||
|
||||
public ConversationView start(Long companyId, StartChatRequest r) {
|
||||
if (r == null || (r.leadUuid() == null) == (r.eventLeadUuid() == null)) {
|
||||
throw coded(HttpStatus.BAD_REQUEST, "Choose a lead or an event lead.", "INVALID_PAYLOAD");
|
||||
}
|
||||
Context c = context(companyId);
|
||||
ConversationView v = call(() -> rest.postForEntity(
|
||||
url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_CONVERSATION_START, null, c), ConversationView.class, r).getBody());
|
||||
AuditChanges.put("conversation", null, v.uuid());
|
||||
return named(v, names());
|
||||
}
|
||||
|
||||
public List<TemplateView> templates(Long companyId) {
|
||||
Context c = context(companyId);
|
||||
List<TemplateView> t = call(() -> rest.getForEntity(
|
||||
rest.getURLforApiService(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_TEMPLATES) + "?companyId={companyId}",
|
||||
TEMPLATES, c.companyId() == null ? "" : c.companyId()).getBody());
|
||||
return t == null ? List.of() : t;
|
||||
}
|
||||
|
||||
public List<TemplateView> syncTemplates(Long companyId) {
|
||||
Context c = context(companyId);
|
||||
if (!c.admin()) throw coded(HttpStatus.FORBIDDEN, "WhatsApp Admin only", "FORBIDDEN");
|
||||
AuditChanges.put("companyId", null, c.companyId());
|
||||
List<TemplateView> t = call(() -> rest.postForEntity(
|
||||
rest.getURLforApiService(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_TEMPLATES_SYNC)
|
||||
+ "?companyId=" + (c.companyId() == null ? "" : c.companyId()) + "&admin=true",
|
||||
TEMPLATES, null).getBody());
|
||||
return t == null ? List.of() : t;
|
||||
}
|
||||
|
||||
public UnreadCount unreadCount(Long companyId) {
|
||||
Context c = context(companyId);
|
||||
return call(() -> rest.getForEntity(url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_UNREAD_COUNT, null, c),
|
||||
UnreadCount.class).getBody());
|
||||
}
|
||||
|
||||
/** Active users of the company who hold BO_WHATSAPP: the people a WhatsApp Admin may assign a chat to. */
|
||||
public List<Map<String, Object>> assignees(Long companyId) {
|
||||
Context c = context(companyId);
|
||||
if (!c.admin()) throw coded(HttpStatus.FORBIDDEN, "WhatsApp Admin only", "FORBIDDEN");
|
||||
if (c.companyId() == null) throw coded(HttpStatus.BAD_REQUEST, "Choose a company.", "COMPANY_REQUIRED");
|
||||
List<Long> ids = call(() -> rest.getForEntity(rest.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_ACTIVE_WITH_MODULE),
|
||||
IDS, c.companyId(), MODULE).getBody());
|
||||
Function<Long, String> names = names();
|
||||
List<Map<String, Object>> out = new ArrayList<>();
|
||||
for (Long id : ids == null ? List.<Long>of() : ids) {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("id", id);
|
||||
row.put("name", names.apply(id));
|
||||
out.add(row);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Where the media bytes go: called once with the type and length, before any byte is written. */
|
||||
public interface MediaOutput {
|
||||
OutputStream open(String contentType, long contentLength) throws IOException;
|
||||
}
|
||||
|
||||
/** Streams an incoming image or document through; 404 without access, 410 when Meta no longer holds it. */
|
||||
public void media(String messageUuid, Long companyId, MediaOutput out) {
|
||||
Context c = context(companyId);
|
||||
String url = url(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_MEDIA, messageUuid, c);
|
||||
call(() -> restTemplate.execute(url, HttpMethod.GET,
|
||||
req -> req.getHeaders().addAll(rest.getCommonHeaders()),
|
||||
resp -> {
|
||||
HttpHeaders h = resp.getHeaders();
|
||||
String type = h.getContentType() == null ? "application/octet-stream" : h.getContentType().toString();
|
||||
try (InputStream in = resp.getBody(); OutputStream o = out.open(type, h.getContentLength())) {
|
||||
in.transferTo(o);
|
||||
}
|
||||
return null;
|
||||
}));
|
||||
}
|
||||
|
||||
/** Best effort after a user is disabled or their roles change: the service unassigns chats they may no longer own. */
|
||||
public static void userChanged(RestTemplateCustomUtil rest, Long userId) {
|
||||
try {
|
||||
rest.postForEntity(rest.getURLforApiService(RestApiWhatsappServiceConstants.API_REST_WHATSAPP_OWNERSHIP_USER_CHANGED),
|
||||
Void.class, new UserChangedRequest(userId));
|
||||
} catch (RuntimeException e) { // the nightly job repairs a missed call
|
||||
log.warn("WhatsApp ownership update for user {} failed: {}", userId, e.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
|
||||
/** The service URL with the path id filled in and the caller context as query params. Ids are uuids only, so nothing else reaches the path. */
|
||||
private String url(String api, String id, Context c) {
|
||||
String path = api;
|
||||
if (id != null) {
|
||||
if (!UUID_LIKE.matcher(id).matches()) throw coded(HttpStatus.NOT_FOUND, "Not found", "CONVERSATION_NOT_FOUND");
|
||||
path = api.replaceFirst("\\{[^}]+}", id);
|
||||
}
|
||||
return rest.getURLforApiService(path) + "?companyId=" + (c.companyId() == null ? "" : c.companyId())
|
||||
+ "&userId=" + c.userId() + "&admin=" + c.admin();
|
||||
}
|
||||
|
||||
/** User names by id, one lookup per distinct id per request. */
|
||||
// ponytail: N lookups for N distinct owners on a page (usually a handful); add a system findByIds if pages grow.
|
||||
private Function<Long, String> names() {
|
||||
Map<Long, String> cache = new HashMap<>();
|
||||
return id -> id == null ? null : cache.computeIfAbsent(id, k -> {
|
||||
try {
|
||||
ResponseEntity<Map<String, Object>> found = rest.getForEntity(
|
||||
rest.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_ID), MAP, k);
|
||||
Map<String, Object> u = found == null ? null : found.getBody();
|
||||
if (u == null) return null;
|
||||
String name = (String.valueOf(u.getOrDefault("name", "")) + " "
|
||||
+ (u.get("surname") == null ? "" : u.get("surname"))).trim();
|
||||
return name.isEmpty() ? String.valueOf(u.get("username")) : name;
|
||||
} catch (RestClientException e) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static ConversationView named(ConversationView v, Function<Long, String> names) {
|
||||
if (v == null) return null;
|
||||
return new ConversationView(v.uuid(), v.companyId(), v.contactWaId(), v.contactName(), v.leadUuid(), v.leadName(),
|
||||
v.ownerUserId(), names.apply(v.ownerUserId()), v.ownerManual(), v.lastInboundAt(), v.lastMessageAt(),
|
||||
v.lastMessagePreview(), v.windowOpen(), v.unreadCount());
|
||||
}
|
||||
|
||||
/** Runs a service call; a 4xx from the service becomes the same status with its reason code and a message. */
|
||||
private static <T> T call(java.util.function.Supplier<T> s) {
|
||||
try {
|
||||
return s.get();
|
||||
} catch (HttpStatusCodeException e) {
|
||||
HttpStatusCode status = e.getStatusCode();
|
||||
if (!status.is4xxClientError()) throw coded(HttpStatus.BAD_GATEWAY, "WhatsApp is unavailable. Try again.", "WHATSAPP_UNAVAILABLE");
|
||||
String code = detail(e);
|
||||
return throwCoded(status, MESSAGES.getOrDefault(code, code), code);
|
||||
} catch (RestClientException | UncheckedIOException e) {
|
||||
throw coded(HttpStatus.BAD_GATEWAY, "WhatsApp is unavailable. Try again.", "WHATSAPP_UNAVAILABLE");
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> T throwCoded(HttpStatusCode status, String message, String code) {
|
||||
CodedResponseStatusException ex = new CodedResponseStatusException(status, message, code);
|
||||
ex.getBody().setProperty("message", message);
|
||||
throw ex;
|
||||
}
|
||||
|
||||
private static String detail(HttpStatusCodeException e) {
|
||||
try {
|
||||
JsonNode body = JSON.readTree(e.getResponseBodyAsString());
|
||||
String d = body == null ? "" : body.path("detail").asText("");
|
||||
return d.isEmpty() ? "NOT_FOUND" : d;
|
||||
} catch (IOException ex) {
|
||||
return "NOT_FOUND";
|
||||
}
|
||||
}
|
||||
|
||||
private static CodedResponseStatusException coded(HttpStatusCode status, String message, String code) {
|
||||
CodedResponseStatusException ex = new CodedResponseStatusException(status, message, code);
|
||||
ex.getBody().setProperty("message", message);
|
||||
return ex;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user