feat(device): 新增短信记录采集、对账与两端查询
- 设备侧上报短信元数据/全量快照,正文仅实时拉取不入库 - 软删除同步平板端已删除记录,家属端主动触发全量对账 - 家属端与设备调试页提供分页查询、正文获取与采集开关
This commit is contained in:
1 parent
8f47d702f9
commit
5381d2b631
28 files changed
+1386
-11
No files matched your search
@@ -0,0 +1,30 @@
|
||||
-- 设备短信元数据(不存短信正文,正文按需从设备实时拉取)
|
||||
CREATE TABLE IF NOT EXISTS `sys_sn_sms_log` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT,
|
||||
`serialno` VARCHAR(64) NOT NULL COMMENT '设备序列号',
|
||||
`source_id` BIGINT NOT NULL COMMENT '设备短信库 _ID',
|
||||
`direction` VARCHAR(8) NOT NULL COMMENT '收发方向:IN/OUT',
|
||||
`address` VARCHAR(32) NOT NULL COMMENT '对端号码',
|
||||
`contact_name` VARCHAR(64) DEFAULT NULL COMMENT '联系人名称(设备通讯录)',
|
||||
`sent_time` DATETIME NOT NULL COMMENT '短信收发时间',
|
||||
`sim_slot` TINYINT DEFAULT NULL COMMENT 'SIM 卡槽',
|
||||
`deleted_at` DATETIME DEFAULT NULL COMMENT '设备端已删除(对账时软删除)',
|
||||
`create_time` DATETIME DEFAULT NULL,
|
||||
`update_time` DATETIME DEFAULT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_sn_source` (`serialno`, `source_id`, `sent_time`),
|
||||
KEY `idx_sn_visible` (`serialno`, `deleted_at`, `sent_time`),
|
||||
KEY `idx_sn_time` (`serialno`, `sent_time`)
|
||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = '设备短信元数据';
|
||||
|
||||
-- 通话/短信记录采集开关
|
||||
CREATE TABLE IF NOT EXISTS `sys_sn_record_setting` (
|
||||
`id` BIGINT NOT NULL AUTO_INCREMENT,
|
||||
`serialno` VARCHAR(64) NOT NULL COMMENT '设备序列号',
|
||||
`call_log_enabled` TINYINT NOT NULL DEFAULT 1 COMMENT '是否采集通话记录',
|
||||
`sms_log_enabled` TINYINT NOT NULL DEFAULT 1 COMMENT '是否采集短信记录',
|
||||
`create_time` DATETIME DEFAULT NULL,
|
||||
`update_time` DATETIME DEFAULT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_serialno` (`serialno`)
|
||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = '设备记录采集开关';
|
||||
@@ -14,6 +14,7 @@ import com.youlai.boot.device.model.vo.ScreenshotVO;
|
||||
import com.youlai.boot.device.service.DeviceService;
|
||||
import com.youlai.boot.device.service.LocationService;
|
||||
import com.youlai.boot.device.service.ScreenshotService;
|
||||
import com.youlai.boot.device.service.SmsRecordService;
|
||||
import com.youlai.boot.framework.security.util.SecurityUtils;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
@@ -52,6 +53,7 @@ public class ClientDeviceOpsController {
|
||||
private final DeviceService deviceService;
|
||||
private final LocationService locationService;
|
||||
private final ScreenshotService screenshotService;
|
||||
private final SmsRecordService smsRecordService;
|
||||
|
||||
/**
|
||||
* 校验当前登录的 client 用户是否绑定了传入的设备 SN。
|
||||
@@ -459,16 +461,15 @@ public class ClientDeviceOpsController {
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "短信同步(家属端)")
|
||||
@Operation(summary = "短信对账(家属端)", description = "下发对账指令,返回 syncId 供轮询状态")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@PostMapping("/msg_sync")
|
||||
public Result<?> msgSync(
|
||||
public Result<String> msgSync(
|
||||
@Parameter(description = "设备序列号") @RequestParam("sn") String sn
|
||||
) {
|
||||
try {
|
||||
checkBound(sn);
|
||||
boolean result = deviceService.msgSync(sn);
|
||||
return Result.judge(result);
|
||||
return Result.success(smsRecordService.startSync(sn));
|
||||
} catch (BusinessException be) {
|
||||
return Result.failed(be.getMessage());
|
||||
} catch (Exception e) {
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
package com.youlai.boot.client.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.youlai.boot.client.model.entity.ClientUser;
|
||||
import com.youlai.boot.client.service.ClientUserService;
|
||||
import com.youlai.boot.common.exception.BusinessException;
|
||||
import com.youlai.boot.common.result.PageResult;
|
||||
import com.youlai.boot.common.result.Result;
|
||||
import com.youlai.boot.device.model.entity.SnDeviceInfo;
|
||||
import com.youlai.boot.device.model.query.SmsLogQuery;
|
||||
import com.youlai.boot.device.model.req.RecordSettingReq;
|
||||
import com.youlai.boot.device.model.vo.RecordSettingVO;
|
||||
import com.youlai.boot.device.model.vo.SmsContentVO;
|
||||
import com.youlai.boot.device.model.vo.SmsLogVO;
|
||||
import com.youlai.boot.device.model.vo.SmsSyncStatusVO;
|
||||
import com.youlai.boot.device.service.DeviceService;
|
||||
import com.youlai.boot.device.service.RecordSettingService;
|
||||
import com.youlai.boot.device.service.SmsContentRegistry;
|
||||
import com.youlai.boot.device.service.SmsRecordService;
|
||||
import com.youlai.boot.framework.security.util.SecurityUtils;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
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 org.springframework.web.context.request.async.DeferredResult;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 家属端短信记录
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Tag(name = "客户端-短信记录")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/client/sn/records")
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class ClientSmsController {
|
||||
|
||||
private static final long CONTENT_TIMEOUT_MILLIS = 12_000L;
|
||||
|
||||
private final ClientUserService clientUserService;
|
||||
private final DeviceService deviceService;
|
||||
private final SmsRecordService smsRecordService;
|
||||
private final RecordSettingService recordSettingService;
|
||||
private final SmsContentRegistry contentRegistry;
|
||||
|
||||
@Operation(summary = "短信记录分页")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@GetMapping("/sms")
|
||||
public PageResult<SmsLogVO> getSmsPage(SmsLogQuery query) {
|
||||
checkBound(query.getSn());
|
||||
IPage<SmsLogVO> page = smsRecordService.getPage(query);
|
||||
return PageResult.success(page);
|
||||
}
|
||||
|
||||
@Operation(summary = "获取短信正文(实时向设备拉取)")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@GetMapping("/sms/content")
|
||||
public DeferredResult<Result<SmsContentVO>> getSmsContent(
|
||||
@Parameter(description = "设备序列号") @RequestParam("sn") String sn,
|
||||
@Parameter(description = "设备短信 ID") @RequestParam("sourceId") Long sourceId) {
|
||||
checkBound(sn);
|
||||
String requestId = UUID.randomUUID().toString().replace("-", "");
|
||||
DeferredResult<Result<SmsContentVO>> deferred =
|
||||
contentRegistry.register(requestId, sn, sourceId, CONTENT_TIMEOUT_MILLIS);
|
||||
try {
|
||||
if (!smsRecordService.requestContent(sn, sourceId, requestId)) {
|
||||
contentRegistry.fail(requestId, "正文请求下发失败,设备可能离线");
|
||||
}
|
||||
} catch (BusinessException e) {
|
||||
contentRegistry.fail(requestId, e.getMessage());
|
||||
} catch (Exception e) {
|
||||
log.error("request sms content error, sn: {}, sourceId: {}", sn, sourceId, e);
|
||||
contentRegistry.fail(requestId, "获取短信正文失败");
|
||||
}
|
||||
return deferred;
|
||||
}
|
||||
|
||||
@Operation(summary = "短信对账状态")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@GetMapping("/sms/sync/status")
|
||||
public Result<SmsSyncStatusVO> getSyncStatus(
|
||||
@Parameter(description = "设备序列号") @RequestParam("sn") String sn,
|
||||
@Parameter(description = "同步任务 ID") @RequestParam("syncId") String syncId) {
|
||||
checkBound(sn);
|
||||
return Result.success(smsRecordService.getSyncStatus(sn, syncId));
|
||||
}
|
||||
|
||||
@Operation(summary = "通话/短信记录采集开关")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@GetMapping("/setting")
|
||||
public Result<RecordSettingVO> getSetting(
|
||||
@Parameter(description = "设备序列号") @RequestParam("sn") String sn) {
|
||||
checkBound(sn);
|
||||
return Result.success(recordSettingService.getBySn(sn));
|
||||
}
|
||||
|
||||
@Operation(summary = "设置通话/短信记录采集开关")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@PutMapping("/setting")
|
||||
public Result<Void> updateSetting(
|
||||
@Parameter(description = "设备序列号") @RequestParam("sn") String sn,
|
||||
@RequestBody RecordSettingReq req) {
|
||||
checkBound(sn);
|
||||
if (req == null || (req.getCallLogEnabled() == null && req.getSmsLogEnabled() == null)) {
|
||||
return Result.failed("开关参数不能为空");
|
||||
}
|
||||
if (!recordSettingService.updateBySn(sn, req)) {
|
||||
return Result.failed("保存采集开关失败");
|
||||
}
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
private SnDeviceInfo checkBound(String sn) {
|
||||
if (!StringUtils.hasText(sn)) {
|
||||
throw new BusinessException("设备序列号不能为空");
|
||||
}
|
||||
Long userId = SecurityUtils.getUserId();
|
||||
ClientUser clientUser = clientUserService.getById(userId);
|
||||
if (clientUser == null || !StringUtils.hasText(clientUser.getMobile())) {
|
||||
throw new BusinessException("当前用户未绑定手机号,无法校验设备");
|
||||
}
|
||||
SnDeviceInfo deviceInfo = deviceService.getOne(
|
||||
new LambdaQueryWrapper<SnDeviceInfo>().eq(SnDeviceInfo::getSerialno, sn)
|
||||
);
|
||||
if (deviceInfo == null) {
|
||||
throw new BusinessException("设备不存在");
|
||||
}
|
||||
if (!StringUtils.hasText(deviceInfo.getSnMobile())
|
||||
|| !deviceInfo.getSnMobile().equals(clientUser.getMobile())) {
|
||||
log.warn("client用户 {} 未绑定设备 sn: {}", userId, sn);
|
||||
throw new BusinessException("当前用户未绑定该设备");
|
||||
}
|
||||
return deviceInfo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.youlai.boot.device.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.youlai.boot.common.result.PageResult;
|
||||
import com.youlai.boot.common.result.Result;
|
||||
import com.youlai.boot.device.model.query.SmsLogQuery;
|
||||
import com.youlai.boot.device.model.vo.RecordSettingVO;
|
||||
import com.youlai.boot.device.model.vo.SmsLogVO;
|
||||
import com.youlai.boot.device.service.RecordSettingService;
|
||||
import com.youlai.boot.device.service.SmsRecordService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
/**
|
||||
* 管理端设备短信记录
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Tag(name = "设备管理-短信记录")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/device")
|
||||
@RequiredArgsConstructor
|
||||
public class DeviceSmsController {
|
||||
|
||||
private final SmsRecordService smsRecordService;
|
||||
private final RecordSettingService recordSettingService;
|
||||
|
||||
@Operation(summary = "设备短信记录分页")
|
||||
@GetMapping("/{sn}/sms_log/page")
|
||||
public PageResult<SmsLogVO> getSmsPage(
|
||||
@Parameter(description = "设备序列号") @PathVariable("sn") String sn,
|
||||
SmsLogQuery query) {
|
||||
query.setSn(sn);
|
||||
IPage<SmsLogVO> page = smsRecordService.getPage(query);
|
||||
return PageResult.success(page);
|
||||
}
|
||||
|
||||
@Operation(summary = "设备记录采集开关")
|
||||
@GetMapping("/{sn}/record_setting")
|
||||
public Result<RecordSettingVO> getRecordSetting(
|
||||
@Parameter(description = "设备序列号") @PathVariable("sn") String sn) {
|
||||
return Result.success(recordSettingService.getBySn(sn));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package com.youlai.boot.device.controller;
|
||||
|
||||
import com.youlai.boot.common.result.Result;
|
||||
import com.youlai.boot.device.model.req.SmsContentReq;
|
||||
import com.youlai.boot.device.model.req.SmsMetaUploadReq;
|
||||
import com.youlai.boot.device.model.req.SmsSnapshotReq;
|
||||
import com.youlai.boot.device.model.req.SmsSyncDoneReq;
|
||||
import com.youlai.boot.device.model.vo.RecordSettingVO;
|
||||
import com.youlai.boot.device.model.vo.SmsSnapshotResultVO;
|
||||
import com.youlai.boot.device.service.RecordSettingService;
|
||||
import com.youlai.boot.device.service.SmsRecordService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
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;
|
||||
|
||||
/**
|
||||
* 设备端短信记录接口(需设备签名)
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Tag(name = "设备端-短信记录")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/sn")
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class SmsDeviceController {
|
||||
|
||||
private final SmsRecordService smsRecordService;
|
||||
private final RecordSettingService recordSettingService;
|
||||
|
||||
@Operation(summary = "设备自主发起兜底对账")
|
||||
@PostMapping("/sms_sync_start")
|
||||
public Result<String> startSync(@RequestHeader("X-Device-SN") String sn) {
|
||||
return Result.success(smsRecordService.startSyncFromDevice(sn));
|
||||
}
|
||||
|
||||
@Operation(summary = "上传短信元数据")
|
||||
@PostMapping("/sms_meta")
|
||||
public Result<Integer> uploadMeta(
|
||||
@RequestHeader("X-Device-SN") String sn,
|
||||
@RequestBody SmsMetaUploadReq req) {
|
||||
return Result.success(smsRecordService.uploadMeta(sn, req));
|
||||
}
|
||||
|
||||
@Operation(summary = "上传本地短信 ID 快照(对账)")
|
||||
@PostMapping("/sms_snapshot")
|
||||
public Result<SmsSnapshotResultVO> snapshot(
|
||||
@RequestHeader("X-Device-SN") String sn,
|
||||
@RequestBody SmsSnapshotReq req) {
|
||||
return Result.success(smsRecordService.snapshot(sn, req));
|
||||
}
|
||||
|
||||
@Operation(summary = "对账结束回执")
|
||||
@PostMapping("/sms_sync_done")
|
||||
public Result<Void> syncDone(
|
||||
@RequestHeader("X-Device-SN") String sn,
|
||||
@RequestBody SmsSyncDoneReq req) {
|
||||
smsRecordService.finishSync(sn, req);
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@Operation(summary = "回传短信正文(不落库)")
|
||||
@PostMapping("/sms_content")
|
||||
public Result<Void> uploadContent(
|
||||
@RequestHeader("X-Device-SN") String sn,
|
||||
@RequestBody SmsContentReq req) {
|
||||
if (req == null || req.getRequestId() == null || req.getSourceId() == null) {
|
||||
return Result.failed("requestId 与 sourceId 不能为空");
|
||||
}
|
||||
if (!smsRecordService.completeContent(sn, req.getRequestId(), req.getSourceId(), req.getContent())) {
|
||||
return Result.failed("正文请求已过期");
|
||||
}
|
||||
return Result.success();
|
||||
}
|
||||
|
||||
@Operation(summary = "获取通话/短信记录采集开关")
|
||||
@GetMapping("/get_record_settings")
|
||||
public Result<RecordSettingVO> getRecordSettings(@RequestHeader("X-Device-SN") String sn) {
|
||||
return Result.success(recordSettingService.getBySn(sn));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.youlai.boot.device.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.youlai.boot.device.model.entity.SnRecordSetting;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
@Mapper
|
||||
public interface RecordSettingMapper extends BaseMapper<SnRecordSetting> {
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.youlai.boot.device.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.youlai.boot.device.model.entity.SnSmsLog;
|
||||
import org.apache.ibatis.annotations.Insert;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface SmsLogMapper extends BaseMapper<SnSmsLog> {
|
||||
|
||||
@Insert("""
|
||||
<script>
|
||||
INSERT INTO sys_sn_sms_log
|
||||
(serialno, source_id, direction, address, contact_name, sent_time, sim_slot,
|
||||
deleted_at, create_time, update_time)
|
||||
VALUES
|
||||
<foreach collection="list" item="i" separator=",">
|
||||
(#{i.serialno}, #{i.sourceId}, #{i.direction}, #{i.address}, #{i.contactName},
|
||||
#{i.sentTime}, #{i.simSlot}, NULL, NOW(), NOW())
|
||||
</foreach>
|
||||
ON DUPLICATE KEY UPDATE
|
||||
direction = VALUES(direction),
|
||||
address = VALUES(address),
|
||||
contact_name = VALUES(contact_name),
|
||||
sim_slot = VALUES(sim_slot),
|
||||
deleted_at = NULL,
|
||||
update_time = NOW()
|
||||
</script>
|
||||
""")
|
||||
int upsertBatch(@Param("list") List<SnSmsLog> list);
|
||||
|
||||
/** 包含已软删除的行,用于对账判断设备端还缺哪些短信 */
|
||||
@Select("SELECT source_id FROM sys_sn_sms_log WHERE serialno = #{sn}")
|
||||
List<Long> selectAllSourceIds(@Param("sn") String sn);
|
||||
|
||||
@Select("""
|
||||
SELECT id, source_id, sent_time
|
||||
FROM sys_sn_sms_log
|
||||
WHERE serialno = #{sn} AND deleted_at IS NULL
|
||||
""")
|
||||
List<SnSmsLog> selectVisibleForReconcile(@Param("sn") String sn);
|
||||
|
||||
@Update("""
|
||||
<script>
|
||||
UPDATE sys_sn_sms_log SET deleted_at = NOW(), update_time = NOW()
|
||||
WHERE id IN
|
||||
<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
|
||||
</script>
|
||||
""")
|
||||
int markDeleted(@Param("ids") List<Long> ids);
|
||||
|
||||
@Update("""
|
||||
<script>
|
||||
UPDATE sys_sn_sms_log SET deleted_at = NULL, update_time = NOW()
|
||||
WHERE serialno = #{sn} AND source_id IN
|
||||
<foreach collection="sourceIds" item="sid" open="(" separator="," close=")">#{sid}</foreach>
|
||||
</script>
|
||||
""")
|
||||
int reviveBySourceIds(@Param("sn") String sn, @Param("sourceIds") List<Long> sourceIds);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.youlai.boot.device.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.youlai.boot.common.base.BaseEntity;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 设备通话/短信记录采集开关
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@TableName("sys_sn_record_setting")
|
||||
public class SnRecordSetting extends BaseEntity {
|
||||
|
||||
private String serialno;
|
||||
|
||||
private Boolean callLogEnabled;
|
||||
|
||||
private Boolean smsLogEnabled;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.youlai.boot.device.model.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import com.youlai.boot.common.base.BaseEntity;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 设备短信元数据(不含正文)
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@TableName("sys_sn_sms_log")
|
||||
public class SnSmsLog extends BaseEntity {
|
||||
|
||||
private String serialno;
|
||||
|
||||
/** 设备短信库 _ID */
|
||||
private Long sourceId;
|
||||
|
||||
/** IN=接收,OUT=发送 */
|
||||
private String direction;
|
||||
|
||||
private String address;
|
||||
|
||||
private String contactName;
|
||||
|
||||
private LocalDateTime sentTime;
|
||||
|
||||
private Integer simSlot;
|
||||
|
||||
/** 对账时设备端已不存在该短信则写入删除时间 */
|
||||
private LocalDateTime deletedAt;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.youlai.boot.device.model.query;
|
||||
|
||||
import com.youlai.boot.common.base.BaseQuery;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 短信记录查询
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public class SmsLogQuery extends BaseQuery {
|
||||
|
||||
private String sn;
|
||||
|
||||
@Schema(description = "IN=接收,OUT=发送")
|
||||
private String direction;
|
||||
|
||||
@Schema(description = "号码或联系人关键字")
|
||||
private String keyword;
|
||||
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime startTime;
|
||||
|
||||
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime endTime;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.youlai.boot.device.model.req;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 通话/短信记录采集开关
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public class RecordSettingReq {
|
||||
|
||||
private Boolean callLogEnabled;
|
||||
|
||||
private Boolean smsLogEnabled;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.youlai.boot.device.model.req;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 设备回传短信正文(仅落内存,不入库、不落日志)
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public class SmsContentReq {
|
||||
|
||||
private String requestId;
|
||||
|
||||
private Long sourceId;
|
||||
|
||||
private String content;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.youlai.boot.device.model.req;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 单条短信元数据(设备上报)
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public class SmsMetaItem {
|
||||
|
||||
/** 设备短信库 _ID */
|
||||
private Long sourceId;
|
||||
|
||||
/** IN=接收,OUT=发送 */
|
||||
private String direction;
|
||||
|
||||
private String address;
|
||||
|
||||
private String contactName;
|
||||
|
||||
/** 收发时间,epoch millis */
|
||||
private Long sentTime;
|
||||
|
||||
private Integer simSlot;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.youlai.boot.device.model.req;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 设备上传短信元数据
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public class SmsMetaUploadReq {
|
||||
|
||||
/** SYNC=对账补缺,INCREMENT=常规增量,省略时按 INCREMENT 处理 */
|
||||
private String mode;
|
||||
|
||||
/** 对账同步任务 ID,mode=SYNC 时必填 */
|
||||
private String syncId;
|
||||
|
||||
/** 增量上传游标(设备本地最大 _ID),仅记录,不参与服务端过滤 */
|
||||
private Long cursor;
|
||||
|
||||
private List<SmsMetaItem> items;
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.youlai.boot.device.model.req;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 设备上传本地短信 ID 快照
|
||||
*
|
||||
* <p>分片上传,最后一片带 {@code final=true} 时由服务端完成差集计算。
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public class SmsSnapshotReq {
|
||||
|
||||
private String syncId;
|
||||
|
||||
private Integer batchIndex;
|
||||
|
||||
@JsonProperty("final")
|
||||
private Boolean finalBatch;
|
||||
|
||||
/** 快照基准时间 epoch millis,只删除该时间之前入库的短信 */
|
||||
private Long snapshotAt;
|
||||
|
||||
private List<Long> sourceIds;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.youlai.boot.device.model.req;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 设备对账结束(或失败)回执
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public class SmsSyncDoneReq {
|
||||
|
||||
private String syncId;
|
||||
|
||||
private Boolean ok;
|
||||
|
||||
private String message;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.youlai.boot.device.model.vo;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 通话/短信记录采集开关
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public class RecordSettingVO {
|
||||
|
||||
private Boolean callLogEnabled;
|
||||
|
||||
private Boolean smsLogEnabled;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.youlai.boot.device.model.vo;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 短信正文(实时透传,不落库)
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public class SmsContentVO {
|
||||
|
||||
private Long sourceId;
|
||||
|
||||
private String content;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.youlai.boot.device.model.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 短信记录(元数据)
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public class SmsLogVO {
|
||||
|
||||
private Long sourceId;
|
||||
|
||||
private String direction;
|
||||
|
||||
private String address;
|
||||
|
||||
private String contactName;
|
||||
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime sentTime;
|
||||
|
||||
private Integer simSlot;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.youlai.boot.device.model.vo;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 短信对账结果
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public class SmsSnapshotResultVO {
|
||||
|
||||
/** 服务端缺失、需要设备补传元数据的短信 ID */
|
||||
private List<Long> missingSourceIds;
|
||||
|
||||
/** 设备端已删除、服务端同步软删除的条数 */
|
||||
private int deleted;
|
||||
|
||||
/** 之前软删除但设备端又存在的条数 */
|
||||
private int revived;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.youlai.boot.device.model.vo;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 短信对账任务状态
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
public class SmsSyncStatusVO {
|
||||
|
||||
private String syncId;
|
||||
|
||||
private String sn;
|
||||
|
||||
/** RUNNING=已下发,SNAPSHOT_DONE=已对账,DONE=完成,FAILED=失败 */
|
||||
private String state;
|
||||
|
||||
private Integer serverCount;
|
||||
|
||||
private Integer missing;
|
||||
|
||||
private Integer deleted;
|
||||
|
||||
private String message;
|
||||
|
||||
private Long startedAt;
|
||||
|
||||
private Long finishedAt;
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import com.youlai.boot.device.model.vo.DeviceSecurityInfoVO;
|
||||
import com.youlai.boot.device.model.vo.DeviceSystemInfoVO;
|
||||
import com.youlai.boot.device.model.vo.DevicePageVO;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
public interface DeviceService extends IService<SnDeviceInfo> {
|
||||
|
||||
@@ -126,9 +128,16 @@ public interface DeviceService extends IService<SnDeviceInfo> {
|
||||
boolean fileTransfer(String sn);
|
||||
|
||||
/**
|
||||
* 短信同步(通知设备上传短信记录)
|
||||
* 向设备推送自定义 contentType 指令
|
||||
*
|
||||
* @param sn 设备序列号(JPush alias)
|
||||
* @param contentType 设备端 {@code PushExecutor} 对应的指令类型
|
||||
* @param title 推送标题
|
||||
* @param content 推送内容
|
||||
* @param extras 透传扩展字段,可为 null
|
||||
* @return 是否推送成功
|
||||
*/
|
||||
boolean msgSync(String sn);
|
||||
boolean pushCustom(String sn, String contentType, String title, String content, Map<String, Object> extras);
|
||||
|
||||
/**
|
||||
* 清理(通知设备清理缓存/垃圾文件)
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.youlai.boot.device.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.youlai.boot.device.model.entity.SnRecordSetting;
|
||||
import com.youlai.boot.device.model.req.RecordSettingReq;
|
||||
import com.youlai.boot.device.model.vo.RecordSettingVO;
|
||||
|
||||
public interface RecordSettingService extends IService<SnRecordSetting> {
|
||||
|
||||
/**
|
||||
* 查询设备记录采集开关,无记录时返回默认全开
|
||||
*/
|
||||
RecordSettingVO getBySn(String sn);
|
||||
|
||||
/**
|
||||
* 保存开关并下发到设备
|
||||
*/
|
||||
boolean updateBySn(String sn, RecordSettingReq req);
|
||||
|
||||
/**
|
||||
* 短信记录采集是否开启(无记录视为开启)
|
||||
*/
|
||||
boolean isSmsLogEnabled(String sn);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.youlai.boot.device.service;
|
||||
|
||||
import com.youlai.boot.common.result.Result;
|
||||
import com.youlai.boot.device.model.vo.SmsContentVO;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.async.DeferredResult;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 家属端短信正文请求的挂起登记表。
|
||||
*
|
||||
* <p>正文只经内存从设备透传给家属端,不落库、不落日志。
|
||||
*
|
||||
* @author TTSTD
|
||||
* @since 2026/11/21
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class SmsContentRegistry {
|
||||
|
||||
private record Pending(String sn, Long sourceId, DeferredResult<Result<SmsContentVO>> result) {
|
||||
}
|
||||
|
||||
private final Map<String, Pending> pending = new ConcurrentHashMap<>();
|
||||
|
||||
public DeferredResult<Result<SmsContentVO>> register(String requestId, String sn, Long sourceId,
|
||||
long timeoutMillis) {
|
||||
DeferredResult<Result<SmsContentVO>> deferred = new DeferredResult<>(timeoutMillis);
|
||||
pending.put(requestId, new Pending(sn, sourceId, deferred));
|
||||
deferred.onTimeout(() -> fail(requestId, "设备响应超时"));
|
||||
deferred.onCompletion(() -> pending.remove(requestId));
|
||||
return deferred;
|
||||
}
|
||||
|
||||
public boolean complete(String requestId, String sn, Long sourceId, String content) {
|
||||
Pending current = pending.remove(requestId);
|
||||
if (current == null) {
|
||||
return false;
|
||||
}
|
||||
if (!Objects.equals(current.sn(), sn) || !Objects.equals(current.sourceId(), sourceId)) {
|
||||
log.warn("sms content mismatch, requestId:{}, expect sn:{}, actual sn:{}", requestId,
|
||||
current.sn(), sn);
|
||||
return false;
|
||||
}
|
||||
SmsContentVO vo = new SmsContentVO();
|
||||
vo.setSourceId(sourceId);
|
||||
vo.setContent(content);
|
||||
current.result().setResult(Result.success(vo));
|
||||
return true;
|
||||
}
|
||||
|
||||
public void fail(String requestId, String message) {
|
||||
Pending current = pending.remove(requestId);
|
||||
if (current != null) {
|
||||
current.result().setResult(Result.failed(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.youlai.boot.device.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.youlai.boot.device.model.entity.SnSmsLog;
|
||||
import com.youlai.boot.device.model.query.SmsLogQuery;
|
||||
import com.youlai.boot.device.model.req.SmsMetaUploadReq;
|
||||
import com.youlai.boot.device.model.req.SmsSnapshotReq;
|
||||
import com.youlai.boot.device.model.req.SmsSyncDoneReq;
|
||||
import com.youlai.boot.device.model.vo.SmsLogVO;
|
||||
import com.youlai.boot.device.model.vo.SmsSnapshotResultVO;
|
||||
import com.youlai.boot.device.model.vo.SmsSyncStatusVO;
|
||||
|
||||
public interface SmsRecordService extends IService<SnSmsLog> {
|
||||
|
||||
/**
|
||||
* 设备上传短信元数据(增量或对账补缺)
|
||||
*
|
||||
* @return 写入条数
|
||||
*/
|
||||
int uploadMeta(String sn, SmsMetaUploadReq req);
|
||||
|
||||
/**
|
||||
* 设备上传本地短信 ID 快照;最后一片返回对账结果
|
||||
*/
|
||||
SmsSnapshotResultVO snapshot(String sn, SmsSnapshotReq req);
|
||||
|
||||
/**
|
||||
* 设备对账结束回执
|
||||
*/
|
||||
void finishSync(String sn, SmsSyncDoneReq req);
|
||||
|
||||
/**
|
||||
* 家属端发起对账,返回 syncId;5 分钟内重复触发返回同一任务
|
||||
*/
|
||||
String startSync(String sn);
|
||||
|
||||
/**
|
||||
* 设备端自主发起兜底对账,不向设备下发推送
|
||||
*/
|
||||
String startSyncFromDevice(String sn);
|
||||
|
||||
/**
|
||||
* 查询对账任务状态
|
||||
*/
|
||||
SmsSyncStatusVO getSyncStatus(String sn, String syncId);
|
||||
|
||||
/**
|
||||
* 请求设备回传短信正文
|
||||
*/
|
||||
boolean requestContent(String sn, Long sourceId, String requestId);
|
||||
|
||||
/**
|
||||
* 设备回传正文,唤醒挂起的家属端请求
|
||||
*
|
||||
* @return 是否存在匹配的挂起请求
|
||||
*/
|
||||
boolean completeContent(String sn, String requestId, Long sourceId, String content);
|
||||
|
||||
/**
|
||||
* 分页查询短信元数据
|
||||
*/
|
||||
IPage<SmsLogVO> getPage(SmsLogQuery query);
|
||||
}
|
||||
@@ -69,7 +69,6 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, SnDeviceInfo> i
|
||||
private static final String DEVICE_APP_STOP = "11";
|
||||
private static final String DEVICE_TAKE_PHOTO = "12";
|
||||
private static final String DEVICE_FILE_TRANSFER = "13";
|
||||
private static final String DEVICE_MSG_SYNC = "14";
|
||||
private static final String DEVICE_CLEAN = "15";
|
||||
private static final String DEVICE_MIRROR = "16";
|
||||
private static final String DEVICE_SCREEN_LOCK = "17";
|
||||
@@ -691,17 +690,19 @@ public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, SnDeviceInfo> i
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean msgSync(String sn) {
|
||||
PushSendParam pushSendParam = getSinglePushSendParam(sn, DEVICE_MSG_SYNC, "msgSync", "msgSync");
|
||||
public boolean pushCustom(String sn, String contentType, String title, String content,
|
||||
Map<String, Object> extras) {
|
||||
PushSendParam pushSendParam = getPushSendParam(sn, contentType, title, content, extras);
|
||||
try {
|
||||
PushSendResult result = pushApi.send(pushSendParam);
|
||||
log.info("msgSync send success:{}", result);
|
||||
log.info("pushCustom send success, sn:{}, contentType:{}, result:{}", sn, contentType, result);
|
||||
return true;
|
||||
} catch (ApiErrorException e) {
|
||||
int httpStatus = e.getStats();
|
||||
int errorCode = e.getApiError().getError().getCode();
|
||||
String errorMessage = e.getApiError().getError().getMessage();
|
||||
log.error("msgSync send error, httpStatus:{} code:{}, message:{}", httpStatus, errorCode, errorMessage);
|
||||
log.error("pushCustom send error, sn:{}, contentType:{}, httpStatus:{} code:{}, message:{}",
|
||||
sn, contentType, httpStatus, errorCode, errorMessage);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.youlai.boot.device.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.youlai.boot.device.mapper.RecordSettingMapper;
|
||||
import com.youlai.boot.device.model.entity.SnRecordSetting;
|
||||
import com.youlai.boot.device.model.req.RecordSettingReq;
|
||||
import com.youlai.boot.device.model.vo.RecordSettingVO;
|
||||
import com.youlai.boot.device.service.DeviceService;
|
||||
import com.youlai.boot.device.service.RecordSettingService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class RecordSettingServiceImpl extends ServiceImpl<RecordSettingMapper, SnRecordSetting>
|
||||
implements RecordSettingService {
|
||||
|
||||
/** 与设备端 PushExecutor 的 DEVICE_RECORD_SETTING 对应 */
|
||||
private static final String PUSH_RECORD_SETTING = "26";
|
||||
|
||||
private final DeviceService deviceService;
|
||||
|
||||
@Override
|
||||
public RecordSettingVO getBySn(String sn) {
|
||||
SnRecordSetting setting = getOne(new LambdaQueryWrapper<SnRecordSetting>()
|
||||
.eq(SnRecordSetting::getSerialno, sn));
|
||||
RecordSettingVO vo = new RecordSettingVO();
|
||||
vo.setCallLogEnabled(setting == null || !Boolean.FALSE.equals(setting.getCallLogEnabled()));
|
||||
vo.setSmsLogEnabled(setting == null || !Boolean.FALSE.equals(setting.getSmsLogEnabled()));
|
||||
return vo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean updateBySn(String sn, RecordSettingReq req) {
|
||||
SnRecordSetting setting = getOne(new LambdaQueryWrapper<SnRecordSetting>()
|
||||
.eq(SnRecordSetting::getSerialno, sn));
|
||||
if (setting == null) {
|
||||
setting = new SnRecordSetting();
|
||||
setting.setSerialno(sn);
|
||||
setting.setCallLogEnabled(true);
|
||||
setting.setSmsLogEnabled(true);
|
||||
}
|
||||
if (req.getCallLogEnabled() != null) {
|
||||
setting.setCallLogEnabled(req.getCallLogEnabled());
|
||||
}
|
||||
if (req.getSmsLogEnabled() != null) {
|
||||
setting.setSmsLogEnabled(req.getSmsLogEnabled());
|
||||
}
|
||||
boolean saved = saveOrUpdate(setting);
|
||||
if (saved) {
|
||||
Map<String, Object> extras = new HashMap<>();
|
||||
extras.put("callLogEnabled", setting.getCallLogEnabled());
|
||||
extras.put("smsLogEnabled", setting.getSmsLogEnabled());
|
||||
if (!deviceService.pushCustom(sn, PUSH_RECORD_SETTING, "recordSetting", "recordSetting", extras)) {
|
||||
log.warn("record setting push failed, sn:{}", sn);
|
||||
}
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSmsLogEnabled(String sn) {
|
||||
SnRecordSetting setting = getOne(new LambdaQueryWrapper<SnRecordSetting>()
|
||||
.eq(SnRecordSetting::getSerialno, sn));
|
||||
return setting == null || !Boolean.FALSE.equals(setting.getSmsLogEnabled());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
package com.youlai.boot.device.service.impl;
|
||||
|
||||
import cn.hutool.json.JSONUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.youlai.boot.common.exception.BusinessException;
|
||||
import com.youlai.boot.device.mapper.SmsLogMapper;
|
||||
import com.youlai.boot.device.model.entity.SnSmsLog;
|
||||
import com.youlai.boot.device.model.query.SmsLogQuery;
|
||||
import com.youlai.boot.device.model.req.SmsMetaItem;
|
||||
import com.youlai.boot.device.model.req.SmsMetaUploadReq;
|
||||
import com.youlai.boot.device.model.req.SmsSnapshotReq;
|
||||
import com.youlai.boot.device.model.req.SmsSyncDoneReq;
|
||||
import com.youlai.boot.device.model.vo.SmsLogVO;
|
||||
import com.youlai.boot.device.model.vo.SmsSnapshotResultVO;
|
||||
import com.youlai.boot.device.model.vo.SmsSyncStatusVO;
|
||||
import com.youlai.boot.device.service.DeviceService;
|
||||
import com.youlai.boot.device.service.RecordSettingService;
|
||||
import com.youlai.boot.device.service.SmsContentRegistry;
|
||||
import com.youlai.boot.device.service.SmsRecordService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class SmsRecordServiceImpl extends ServiceImpl<SmsLogMapper, SnSmsLog> implements SmsRecordService {
|
||||
|
||||
/** 与设备端 PushExecutor 的 DEVICE_MSG_SYNC 对应 */
|
||||
private static final String PUSH_SMS_SYNC = "14";
|
||||
/** 与设备端 PushExecutor 的 DEVICE_SMS_CONTENT 对应 */
|
||||
private static final String PUSH_SMS_CONTENT = "27";
|
||||
|
||||
private static final String KEY_CURRENT = "sms:sync:current:";
|
||||
private static final String KEY_STATE = "sms:sync:state:";
|
||||
private static final String KEY_SNAPSHOT = "sms:sync:snapshot:";
|
||||
|
||||
private static final Duration CURRENT_TTL = Duration.ofMinutes(5);
|
||||
private static final Duration STATE_TTL = Duration.ofMinutes(30);
|
||||
private static final Duration SNAPSHOT_TTL = Duration.ofHours(1);
|
||||
private static final int BATCH_SIZE = 500;
|
||||
|
||||
private static final String STATE_RUNNING = "RUNNING";
|
||||
private static final String STATE_SNAPSHOT_DONE = "SNAPSHOT_DONE";
|
||||
private static final String STATE_DONE = "DONE";
|
||||
private static final String STATE_FAILED = "FAILED";
|
||||
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
private final DeviceService deviceService;
|
||||
private final RecordSettingService recordSettingService;
|
||||
private final SmsContentRegistry contentRegistry;
|
||||
|
||||
@Override
|
||||
public int uploadMeta(String sn, SmsMetaUploadReq req) {
|
||||
if (!recordSettingService.isSmsLogEnabled(sn)) {
|
||||
throw new BusinessException("短信记录采集已关闭");
|
||||
}
|
||||
if (req == null || req.getItems() == null || req.getItems().isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
if (StringUtils.hasText(req.getSyncId()) && readState(req.getSyncId()) == null) {
|
||||
throw new BusinessException("同步任务已过期");
|
||||
}
|
||||
|
||||
List<SnSmsLog> rows = new ArrayList<>();
|
||||
for (SmsMetaItem item : req.getItems()) {
|
||||
if (item == null || item.getSourceId() == null || item.getSentTime() == null
|
||||
|| !StringUtils.hasText(item.getAddress())) {
|
||||
continue;
|
||||
}
|
||||
String direction = item.getDirection();
|
||||
if (!"IN".equals(direction) && !"OUT".equals(direction)) {
|
||||
continue;
|
||||
}
|
||||
SnSmsLog row = new SnSmsLog();
|
||||
row.setSerialno(sn);
|
||||
row.setSourceId(item.getSourceId());
|
||||
row.setDirection(direction);
|
||||
row.setAddress(item.getAddress());
|
||||
row.setContactName(item.getContactName());
|
||||
row.setSentTime(toLocalDateTime(item.getSentTime()));
|
||||
row.setSimSlot(item.getSimSlot());
|
||||
rows.add(row);
|
||||
}
|
||||
if (rows.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
for (int i = 0; i < rows.size(); i += BATCH_SIZE) {
|
||||
baseMapper.upsertBatch(rows.subList(i, Math.min(i + BATCH_SIZE, rows.size())));
|
||||
}
|
||||
return rows.size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public SmsSnapshotResultVO snapshot(String sn, SmsSnapshotReq req) {
|
||||
if (req == null || !StringUtils.hasText(req.getSyncId())) {
|
||||
throw new BusinessException("syncId 不能为空");
|
||||
}
|
||||
SmsSyncStatusVO status = readState(req.getSyncId());
|
||||
if (status == null || !sn.equals(status.getSn())) {
|
||||
throw new BusinessException("同步任务已过期");
|
||||
}
|
||||
if (STATE_DONE.equals(status.getState()) || STATE_FAILED.equals(status.getState())) {
|
||||
SmsSnapshotResultVO result = new SmsSnapshotResultVO();
|
||||
result.setMissingSourceIds(Collections.emptyList());
|
||||
return result;
|
||||
}
|
||||
|
||||
String snapshotKey = KEY_SNAPSHOT + req.getSyncId();
|
||||
if (req.getSourceIds() != null && !req.getSourceIds().isEmpty()) {
|
||||
String[] members = req.getSourceIds().stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(String::valueOf)
|
||||
.distinct()
|
||||
.toArray(String[]::new);
|
||||
if (members.length > 0) {
|
||||
redisTemplate.opsForSet().add(snapshotKey, members);
|
||||
redisTemplate.expire(snapshotKey, SNAPSHOT_TTL);
|
||||
}
|
||||
}
|
||||
|
||||
SmsSnapshotResultVO result = new SmsSnapshotResultVO();
|
||||
if (!Boolean.TRUE.equals(req.getFinalBatch())) {
|
||||
result.setMissingSourceIds(Collections.emptyList());
|
||||
return result;
|
||||
}
|
||||
|
||||
Set<String> deviceIdStrings = redisTemplate.opsForSet().members(snapshotKey);
|
||||
Set<Long> deviceIds = deviceIdStrings == null ? Collections.emptySet() : deviceIdStrings.stream()
|
||||
.map(this::parseLong)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
List<Long> allServerIds = baseMapper.selectAllSourceIds(sn);
|
||||
Set<Long> allServerIdSet = new HashSet<>(allServerIds);
|
||||
List<SnSmsLog> visibleRows = baseMapper.selectVisibleForReconcile(sn);
|
||||
Set<Long> visibleIds = visibleRows.stream()
|
||||
.map(SnSmsLog::getSourceId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
LocalDateTime snapshotAt = req.getSnapshotAt() == null
|
||||
? LocalDateTime.now()
|
||||
: toLocalDateTime(req.getSnapshotAt());
|
||||
|
||||
List<Long> deleteIds = visibleRows.stream()
|
||||
.filter(row -> !deviceIds.contains(row.getSourceId()))
|
||||
.filter(row -> row.getSentTime() == null || !row.getSentTime().isAfter(snapshotAt))
|
||||
.map(SnSmsLog::getId)
|
||||
.toList();
|
||||
int deleted = deleteIds.size();
|
||||
for (int i = 0; i < deleteIds.size(); i += BATCH_SIZE) {
|
||||
baseMapper.markDeleted(deleteIds.subList(i, Math.min(i + BATCH_SIZE, deleteIds.size())));
|
||||
}
|
||||
|
||||
List<Long> reviveIds = allServerIdSet.stream()
|
||||
.filter(deviceIds::contains)
|
||||
.filter(id -> !visibleIds.contains(id))
|
||||
.toList();
|
||||
for (int i = 0; i < reviveIds.size(); i += BATCH_SIZE) {
|
||||
baseMapper.reviveBySourceIds(sn, reviveIds.subList(i, Math.min(i + BATCH_SIZE, reviveIds.size())));
|
||||
}
|
||||
|
||||
List<Long> missing = deviceIds.stream()
|
||||
.filter(id -> !allServerIdSet.contains(id))
|
||||
.toList();
|
||||
redisTemplate.delete(snapshotKey);
|
||||
|
||||
status.setState(STATE_SNAPSHOT_DONE);
|
||||
status.setServerCount(allServerIdSet.size());
|
||||
status.setMissing(missing.size());
|
||||
status.setDeleted(deleted);
|
||||
writeState(status);
|
||||
|
||||
result.setMissingSourceIds(missing);
|
||||
result.setDeleted(deleted);
|
||||
result.setRevived(reviveIds.size());
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void finishSync(String sn, SmsSyncDoneReq req) {
|
||||
if (req == null || !StringUtils.hasText(req.getSyncId())) {
|
||||
throw new BusinessException("syncId 不能为空");
|
||||
}
|
||||
SmsSyncStatusVO status = readState(req.getSyncId());
|
||||
if (status == null || !sn.equals(status.getSn())) {
|
||||
throw new BusinessException("同步任务已过期");
|
||||
}
|
||||
status.setState(Boolean.FALSE.equals(req.getOk()) ? STATE_FAILED : STATE_DONE);
|
||||
status.setMessage(req.getMessage());
|
||||
status.setFinishedAt(System.currentTimeMillis());
|
||||
writeState(status);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String startSync(String sn) {
|
||||
return doStartSync(sn, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String startSyncFromDevice(String sn) {
|
||||
return doStartSync(sn, false);
|
||||
}
|
||||
|
||||
private String doStartSync(String sn, boolean pushToDevice) {
|
||||
if (!recordSettingService.isSmsLogEnabled(sn)) {
|
||||
throw new BusinessException("短信记录采集已关闭");
|
||||
}
|
||||
String currentKey = KEY_CURRENT + sn;
|
||||
String currentSyncId = redisTemplate.opsForValue().get(currentKey);
|
||||
if (StringUtils.hasText(currentSyncId)) {
|
||||
return currentSyncId;
|
||||
}
|
||||
|
||||
String syncId = UUID.randomUUID().toString().replace("-", "");
|
||||
Boolean acquired = redisTemplate.opsForValue()
|
||||
.setIfAbsent(currentKey, syncId, CURRENT_TTL);
|
||||
if (!Boolean.TRUE.equals(acquired)) {
|
||||
String existing = redisTemplate.opsForValue().get(currentKey);
|
||||
if (StringUtils.hasText(existing)) {
|
||||
return existing;
|
||||
}
|
||||
throw new BusinessException("同步任务正在进行,请稍后重试");
|
||||
}
|
||||
|
||||
SmsSyncStatusVO status = new SmsSyncStatusVO();
|
||||
status.setSyncId(syncId);
|
||||
status.setSn(sn);
|
||||
status.setState(STATE_RUNNING);
|
||||
status.setStartedAt(System.currentTimeMillis());
|
||||
writeState(status);
|
||||
|
||||
if (!pushToDevice) {
|
||||
return syncId;
|
||||
}
|
||||
|
||||
Map<String, Object> extras = new HashMap<>();
|
||||
extras.put("syncId", syncId);
|
||||
boolean pushed = deviceService.pushCustom(sn, PUSH_SMS_SYNC, "smsSync", "smsSync", extras);
|
||||
if (!pushed) {
|
||||
redisTemplate.delete(currentKey);
|
||||
status.setState(STATE_FAILED);
|
||||
status.setMessage("同步指令下发失败");
|
||||
status.setFinishedAt(System.currentTimeMillis());
|
||||
writeState(status);
|
||||
throw new BusinessException("同步指令下发失败,设备可能离线");
|
||||
}
|
||||
return syncId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SmsSyncStatusVO getSyncStatus(String sn, String syncId) {
|
||||
if (!StringUtils.hasText(syncId)) {
|
||||
throw new BusinessException("syncId 不能为空");
|
||||
}
|
||||
SmsSyncStatusVO status = readState(syncId);
|
||||
if (status == null || !sn.equals(status.getSn())) {
|
||||
throw new BusinessException("同步任务不存在或已过期");
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean requestContent(String sn, Long sourceId, String requestId) {
|
||||
if (!recordSettingService.isSmsLogEnabled(sn)) {
|
||||
throw new BusinessException("短信记录采集已关闭");
|
||||
}
|
||||
SnSmsLog row = lambdaQuery()
|
||||
.eq(SnSmsLog::getSerialno, sn)
|
||||
.eq(SnSmsLog::getSourceId, sourceId)
|
||||
.isNull(SnSmsLog::getDeletedAt)
|
||||
.one();
|
||||
if (row == null) {
|
||||
throw new BusinessException("短信记录不存在或已删除");
|
||||
}
|
||||
Map<String, Object> extras = new HashMap<>();
|
||||
extras.put("requestId", requestId);
|
||||
extras.put("sourceId", sourceId);
|
||||
return deviceService.pushCustom(sn, PUSH_SMS_CONTENT, "smsContent", "smsContent", extras);
|
||||
}
|
||||
|
||||
@Override
|
||||
public IPage<SmsLogVO> getPage(SmsLogQuery query) {
|
||||
if (query == null || !StringUtils.hasText(query.getSn())) {
|
||||
throw new BusinessException("设备序列号不能为空");
|
||||
}
|
||||
LambdaQueryWrapper<SnSmsLog> wrapper = new LambdaQueryWrapper<SnSmsLog>()
|
||||
.eq(SnSmsLog::getSerialno, query.getSn())
|
||||
.isNull(SnSmsLog::getDeletedAt)
|
||||
.eq(StringUtils.hasText(query.getDirection()), SnSmsLog::getDirection, query.getDirection())
|
||||
.ge(query.getStartTime() != null, SnSmsLog::getSentTime, query.getStartTime())
|
||||
.le(query.getEndTime() != null, SnSmsLog::getSentTime, query.getEndTime())
|
||||
.and(StringUtils.hasText(query.getKeyword()), w -> w
|
||||
.like(SnSmsLog::getAddress, query.getKeyword())
|
||||
.or()
|
||||
.like(SnSmsLog::getContactName, query.getKeyword()))
|
||||
.orderByDesc(SnSmsLog::getSentTime)
|
||||
.orderByDesc(SnSmsLog::getSourceId);
|
||||
|
||||
Page<SnSmsLog> page = page(new Page<>(query.getPageNum(), query.getPageSize()), wrapper);
|
||||
return page.convert(this::toVo);
|
||||
}
|
||||
|
||||
private SmsLogVO toVo(SnSmsLog row) {
|
||||
SmsLogVO vo = new SmsLogVO();
|
||||
vo.setSourceId(row.getSourceId());
|
||||
vo.setDirection(row.getDirection());
|
||||
vo.setAddress(row.getAddress());
|
||||
vo.setContactName(row.getContactName());
|
||||
vo.setSentTime(row.getSentTime());
|
||||
vo.setSimSlot(row.getSimSlot());
|
||||
return vo;
|
||||
}
|
||||
|
||||
private SmsSyncStatusVO readState(String syncId) {
|
||||
String json = redisTemplate.opsForValue().get(KEY_STATE + syncId);
|
||||
if (!StringUtils.hasText(json)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return JSONUtil.toBean(json, SmsSyncStatusVO.class);
|
||||
} catch (Exception e) {
|
||||
log.warn("sms sync state parse failed, syncId:{}", syncId, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void writeState(SmsSyncStatusVO status) {
|
||||
redisTemplate.opsForValue().set(KEY_STATE + status.getSyncId(),
|
||||
JSONUtil.toJsonStr(status), STATE_TTL);
|
||||
}
|
||||
|
||||
private Long parseLong(String value) {
|
||||
try {
|
||||
return Long.valueOf(value);
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private LocalDateTime toLocalDateTime(long epochMillis) {
|
||||
return LocalDateTime.ofInstant(Instant.ofEpochMilli(epochMillis), ZoneId.systemDefault());
|
||||
}
|
||||
|
||||
/** 完成设备回传的正文请求,唤醒挂起的家属端请求 */
|
||||
@Override
|
||||
public boolean completeContent(String sn, String requestId, Long sourceId, String content) {
|
||||
return contentRegistry.complete(requestId, sn, sourceId, content);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user