SmsMessageController.java 2.78 KB
package com.diligrp.assistant.sms.controller;

import com.diligrp.assistant.shared.domain.Message;
import com.diligrp.assistant.shared.util.AssertUtils;
import com.diligrp.assistant.sms.Constants;
import com.diligrp.assistant.sms.SmsProperties;
import com.diligrp.assistant.sms.domain.SmsAccessToken;
import com.diligrp.assistant.sms.domain.SmsMessageDTO;
import com.diligrp.assistant.sms.service.SmsMessageService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/sms/message")
public class SmsMessageController {
    @Resource
    private SmsProperties smsProperties;

    @Resource
    private SmsMessageService smsMessageService;

    @RequestMapping(value = "/send.do")
    public Message<?> send(@RequestBody SmsMessageDTO request, @RequestHeader(Constants.HEADER_AUTHORIZATION) String authorization) {
        SmsAccessToken.of(authorization, smsProperties.getPublicKey());
        AssertUtils.notEmpty(request.getTemplateId(), "templateId missed");
        AssertUtils.notEmpty(request.getTelephone(), "telephone missed");
        AssertUtils.notEmpty(request.getSignature(), "signature missed");

        List<String> telephones = Collections.singletonList(request.getTelephone());
        if (!request.isAsync()) {
            smsMessageService.sendSmsMessage(request.getTemplateId(), telephones, request.getParams(), request.getSignature());
        } else {
            smsMessageService.asyncSendSmsMessage(request.getTemplateId(), telephones, request.getParams(), request.getSignature());
        }
        return Message.success();
    }

    @RequestMapping(value = "/batchSend.do")
    public Message<?> batchSend(@RequestBody SmsMessageDTO request, @RequestHeader(Constants.HEADER_AUTHORIZATION) String authorization) {
        SmsAccessToken.of(authorization, smsProperties.getPublicKey());
        AssertUtils.notEmpty(request.getTemplateId(), "templateId missed");
        AssertUtils.notEmpty(request.getTelephones(), "telephones missed");
        AssertUtils.isTrue(request.getTelephones().size() <= 1000, "Exceed max batch limit");
        AssertUtils.notEmpty(request.getSignature(), "signature missed");

        if (!request.isAsync()) {
            smsMessageService.sendSmsMessage(request.getTemplateId(), request.getTelephones(), request.getParams(), request.getSignature());
        } else {
            smsMessageService.asyncSendSmsMessage(request.getTemplateId(), request.getTelephones(), request.getParams(), request.getSignature());
        }
        return Message.success();
    }
}