diff --git a/sql/app_icon.sql b/sql/app_icon.sql index c2b6c4a5..1f813aa2 100644 --- a/sql/app_icon.sql +++ b/sql/app_icon.sql @@ -27,6 +27,8 @@ CREATE TABLE `app_icon` `app_name` VARCHAR(128) DEFAULT NULL COMMENT '应用名称(上报时的展示名,可为空;新版本上报时刷新)', `icon_url` VARCHAR(500) NOT NULL COMMENT '图标访问地址(相对路径,如 /static/app_icon/{md5}.png)', `icon_md5` VARCHAR(64) DEFAULT NULL COMMENT '图标文件MD5(内容指纹,用于去重与换图标检测)', + `icon_sha1` VARCHAR(64) DEFAULT NULL COMMENT '图标文件SHA1', + `icon_sha256` VARCHAR(64) DEFAULT NULL COMMENT '图标文件SHA256', `version` INT NOT NULL DEFAULT 1 COMMENT '版本号(同包名内自增,从1开始)', `status` TINYINT NOT NULL DEFAULT 1 COMMENT '状态(1当前生效 0历史版本)', `locked` TINYINT NOT NULL DEFAULT 0 COMMENT '是否锁定(0未锁定 1已锁定,锁定后不可上传覆盖)', diff --git a/sql/sn_device_alarm.sql b/sql/sn_device_alarm.sql new file mode 100644 index 00000000..08f30160 --- /dev/null +++ b/sql/sn_device_alarm.sql @@ -0,0 +1,32 @@ +-- ============================================================================= +-- 设备闹钟表(sys_sn_alarm) +-- 说明:一设备多行,存放该设备的闹钟列表。家属端(/api/v1/client/sn/alarm) +-- 与设备端(/api/v1/sn/get_alarms|sync_alarms)共用; +-- 任意一端变更后推送 contentType=25,设备拉取整表覆盖本地 Room。 +-- ============================================================================= +CREATE TABLE IF NOT EXISTS `sys_sn_alarm` +( + `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `serialno` VARCHAR(64) NOT NULL COMMENT '设备序列号(关联 sys_sn.serialno)', + `hour` INT NOT NULL DEFAULT 0 COMMENT '时', + `minute` INT NOT NULL DEFAULT 0 COMMENT '分', + `label` VARCHAR(100) DEFAULT NULL COMMENT '标签', + `repeat_type` INT NOT NULL DEFAULT 0 COMMENT '重复类型(0一次 1每天 2工作日 3自定义)', + `custom_days` VARCHAR(50) DEFAULT NULL COMMENT '自定义星期(2,3,6,7,Calendar.MONDAY=2)', + `is_enabled` TINYINT NOT NULL DEFAULT 1 COMMENT '开关(0关 1开)', + `vibration` TINYINT NOT NULL DEFAULT 0 COMMENT '振动(0否 1是)', + `volume` INT NOT NULL DEFAULT 80 COMMENT '音量(0-100)', + `ringtone_uri` VARCHAR(300) DEFAULT NULL COMMENT '铃声URI', + `snooze_interval` INT NOT NULL DEFAULT 5 COMMENT '贪睡间隔(分钟)', + + -- ===================== 通用字段 ===================== + `create_time` DATETIME DEFAULT NULL COMMENT '创建时间', + `update_time` DATETIME DEFAULT NULL COMMENT '更新时间', + `is_deleted` TINYINT DEFAULT 0 COMMENT '逻辑删除(0未删 1已删)', + + PRIMARY KEY (`id`), + KEY `idx_serialno` (`serialno`), + KEY `idx_is_deleted` (`is_deleted`) +) ENGINE = InnoDB + DEFAULT CHARSET = utf8mb4 + COMMENT = '设备闹钟表'; diff --git a/sql/sn_device_key.sql b/sql/sn_device_key.sql new file mode 100644 index 00000000..1f898b47 --- /dev/null +++ b/sql/sn_device_key.sql @@ -0,0 +1,21 @@ +-- ============================================================================= +-- 设备 ECDSA P-256 签名公钥字段(sys_sn 表扩展) +-- 说明: +-- · 设备首次注册时上传 ECDSA P-256 公钥(X.509 SubjectPublicKeyInfo, Base64), +-- 服务端绑定 SN ↔ 公钥,后续 /api/v1/sn/** 请求用该公钥做 SHA256withECDSA 验签。 +-- · 封禁/吊销通过 sys_sn.status 字段:1=启用,0=封禁(验签前校验)。 +-- ============================================================================= + +-- 1. 为 sys_sn 表新增设备签名公钥字段(幂等:已存在则跳过) +SET @column_exists := ( + SELECT COUNT(*) FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = 'sys_sn' + AND COLUMN_NAME = 'public_key' +); +SET @ddl := IF(@column_exists = 0, + 'ALTER TABLE sys_sn ADD COLUMN public_key TEXT NULL COMMENT ''设备ECDSA P-256公钥(X.509 Base64)'' AFTER sn_mobile', + 'SELECT 1'); +PREPARE stmt FROM @ddl; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; diff --git a/sql/sn_device_picture.sql b/sql/sn_device_picture.sql new file mode 100644 index 00000000..64271438 --- /dev/null +++ b/sql/sn_device_picture.sql @@ -0,0 +1,28 @@ +-- ============================================================================= +-- 设备图片发送记录表(sys_sn_device_picture) +-- 说明:家属端从相册等入口上传图片发送给设备,设备收到推送(contentType=24) +-- 后弹窗显示该图片。本表独立于壁纸配置表,仅记录发送的图片地址。 +-- ============================================================================= +CREATE TABLE IF NOT EXISTS `sys_sn_device_picture` +( + `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `serialno` VARCHAR(64) NOT NULL COMMENT '设备序列号(关联 sys_sn.serialno)', + `image_url` VARCHAR(500) NOT NULL COMMENT '图片完整URL', + `favorite` TINYINT DEFAULT 0 COMMENT '是否收藏(0否 1是)', + `file_size` BIGINT DEFAULT 0 COMMENT '文件大小(字节)', + + -- ===================== 通用字段 ===================== + `create_time` DATETIME DEFAULT NULL COMMENT '创建时间', + `update_time` DATETIME DEFAULT NULL COMMENT '更新时间', + `is_deleted` TINYINT DEFAULT 0 COMMENT '逻辑删除(0未删 1已删)', + + PRIMARY KEY (`id`), + KEY `idx_serialno` (`serialno`), + KEY `idx_is_deleted` (`is_deleted`) +) ENGINE = InnoDB + DEFAULT CHARSET = utf8mb4 + COMMENT = '设备图片发送记录表'; + +-- 已建库的补充列(若表已存在且无对应列时执行): +-- ALTER TABLE `sys_sn_device_picture` ADD COLUMN `favorite` TINYINT DEFAULT 0 COMMENT '是否收藏(0否 1是)' AFTER `image_url`; +-- ALTER TABLE `sys_sn_device_picture` ADD COLUMN `file_size` BIGINT DEFAULT 0 COMMENT '文件大小(字节)' AFTER `favorite`; diff --git a/sql/sn_device_policy.sql b/sql/sn_device_policy.sql index 1f9231b2..d2da7b58 100644 --- a/sql/sn_device_policy.sql +++ b/sql/sn_device_policy.sql @@ -14,20 +14,37 @@ CREATE TABLE IF NOT EXISTS `sys_sn_device_policy` `storage_card` TINYINT NOT NULL DEFAULT 1 COMMENT '存储卡(0关闭 1开启)', `factory_reset` TINYINT NOT NULL DEFAULT 1 COMMENT '恢复出厂(0关闭 1开启)', `wifi_hotspot` TINYINT NOT NULL DEFAULT 1 COMMENT 'WiFi热点开关(0关闭 1开启)', - `bluetooth_switch` TINYINT NOT NULL DEFAULT 1 COMMENT '蓝牙开关(0关闭 1开启)', + `bluetooth` TINYINT NOT NULL DEFAULT 1 COMMENT '蓝牙开关(0关闭 1开启)', `wallpaper` TINYINT NOT NULL DEFAULT 1 COMMENT '壁纸功能(0关闭 1开启)', `notification_bar` TINYINT NOT NULL DEFAULT 1 COMMENT '通知栏显示(0关闭 1开启)', `status_bar_pull_down` TINYINT NOT NULL DEFAULT 1 COMMENT '状态栏下拉开关(0关闭 1开启)', `system_nav_bar_show` TINYINT NOT NULL DEFAULT 1 COMMENT '系统导航条显示(0关闭 1开启)', `system_nav_bar_setting` TINYINT NOT NULL DEFAULT 1 COMMENT '系统导航栏设置(0关闭 1开启)', `nav_bar_options` TINYINT NOT NULL DEFAULT 1 COMMENT '导航条选项(0关闭 1开启)', - `bluetooth_function` TINYINT NOT NULL DEFAULT 1 COMMENT '蓝牙功能开关(0关闭 1开启)', + `config_bluetooth` TINYINT NOT NULL DEFAULT 1 COMMENT '蓝牙功能开关(0关闭 1开启)', `ota_upgrade` TINYINT NOT NULL DEFAULT 1 COMMENT 'OTA升级管控(0关闭 1开启)', - `app_install` TINYINT NOT NULL DEFAULT 1 COMMENT '应用安装开关(0关闭 1开启)', + `install_apps` TINYINT NOT NULL DEFAULT 1 COMMENT '应用安装开关(0关闭 1开启)', `auto_rotate` TINYINT NOT NULL DEFAULT 1 COMMENT '自动旋转(0关闭 1开启)', `auto_brightness` TINYINT NOT NULL DEFAULT 1 COMMENT '自动亮度(0关闭 1开启)', `eye_protection` TINYINT NOT NULL DEFAULT 1 COMMENT '护眼模式(0关闭 1开启)', `dark_mode` TINYINT NOT NULL DEFAULT 1 COMMENT '深色模式(0关闭 1开启)', + `safe_boot` TINYINT NOT NULL DEFAULT 1 COMMENT '允许进入安全模式(0关闭 1开启)', + `adb_usb_debug` TINYINT NOT NULL DEFAULT 1 COMMENT '开启ADB/USB调试(0关闭 1开启)', + `mount_physical_storage` TINYINT NOT NULL DEFAULT 1 COMMENT '挂载外部存储(SD卡/U盘)(0关闭 1开启)', + `modify_system_time_zone` TINYINT NOT NULL DEFAULT 1 COMMENT '修改系统时间与时区(0关闭 1开启)', + `toggle_airplane_mode` TINYINT NOT NULL DEFAULT 1 COMMENT '切换飞行模式(0关闭 1开启)', + `modify_mobile_apn` TINYINT NOT NULL DEFAULT 1 COMMENT '修改移动网络/APN(0关闭 1开启)', + `uninstall_apps` TINYINT NOT NULL DEFAULT 1 COMMENT '卸载应用(0关闭 1开启)', + `camera` TINYINT NOT NULL DEFAULT 1 COMMENT '摄像头(0关闭 1开启)', + `usb_file_transfer` TINYINT NOT NULL DEFAULT 1 COMMENT 'USB文件传输(MTP)(0关闭 1开启)', + `modify_location_switch` TINYINT NOT NULL DEFAULT 1 COMMENT '修改定位开关(0关闭 1开启)', + `bluetooth_sharing` TINYINT NOT NULL DEFAULT 1 COMMENT '蓝牙对外分享(0关闭 1开启)', + `reset_network_settings` TINYINT NOT NULL DEFAULT 1 COMMENT '重置网络设置(0关闭 1开启)', + `adjust_global_volume` TINYINT NOT NULL DEFAULT 1 COMMENT '调节全局音量(0关闭 1开启)', + `modify_screen_timeout` TINYINT NOT NULL DEFAULT 1 COMMENT '修改屏幕超时休眠时间(0关闭 1开启)', + `manual_adjust_time_zone` TINYINT NOT NULL DEFAULT 1 COMMENT '手动调整系统时间与时区(0关闭 1开启)', + `modify_system_language` TINYINT NOT NULL DEFAULT 1 COMMENT '修改系统语言与区域设置(0关闭 1开启)', + `manual_adjust_brightness` TINYINT NOT NULL DEFAULT 1 COMMENT '手动调整系统亮度与自动亮度开关(0关闭 1开启)', -- ===================== 通用字段 ===================== `create_time` DATETIME DEFAULT NULL COMMENT '创建时间', diff --git a/sql/sn_device_wallpaper.sql b/sql/sn_device_wallpaper.sql new file mode 100644 index 00000000..9a6d0dec --- /dev/null +++ b/sql/sn_device_wallpaper.sql @@ -0,0 +1,31 @@ +-- ============================================================================= +-- 设备壁纸图片明细表(sys_sn_wallpaper_item) +-- 说明:设备的壁纸改为「一图一行」的多行存储,支持显式排序(sort_no)。 +-- mode 区分壁纸模式:0-单个壁纸(1 行),1-轮换壁纸(最多 7 行)。 +-- sort_no 升序即轮换展示顺序;单个壁纸固定为第 0 行。 +-- image_url 为可访问的完整图片 URL,如 /static/wallpaper/SN_xxx_1.jpg。 +-- 迁移说明:旧表 sys_sn_device_wallpaper(单行 JSON)已被本表取代; +-- 如需清理旧表请手工执行:DROP TABLE IF EXISTS `sys_sn_device_wallpaper`; +-- ============================================================================= +CREATE TABLE IF NOT EXISTS `sys_sn_wallpaper_item` +( + `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID', + `serialno` VARCHAR(64) NOT NULL COMMENT '设备序列号(关联 sys_sn.serialno)', + `mode` TINYINT NOT NULL DEFAULT 0 COMMENT '壁纸模式:0-单个壁纸 1-轮换壁纸', + `image_url` VARCHAR(500) NOT NULL COMMENT '壁纸图片完整URL', + `sort_no` INT NOT NULL DEFAULT 0 COMMENT '排序号(升序,轮换展示顺序)', + `md5` VARCHAR(64) DEFAULT NULL COMMENT '壁纸图片文件MD5', + `sha1` VARCHAR(64) DEFAULT NULL COMMENT '壁纸图片文件SHA1', + `sha256` VARCHAR(64) DEFAULT NULL COMMENT '壁纸图片文件SHA256', + + -- ===================== 通用字段 ===================== + `create_time` DATETIME DEFAULT NULL COMMENT '创建时间', + `update_time` DATETIME DEFAULT NULL COMMENT '更新时间', + `is_deleted` TINYINT DEFAULT 0 COMMENT '逻辑删除(0未删 1已删)', + + PRIMARY KEY (`id`), + KEY `idx_sn_mode` (`serialno`, `mode`), + KEY `idx_is_deleted` (`is_deleted`) +) ENGINE = InnoDB + DEFAULT CHARSET = utf8mb4 + COMMENT = '设备壁纸图片明细表'; diff --git a/src/main/java/com/youlai/boot/client/controller/ClientController.java b/src/main/java/com/youlai/boot/client/controller/ClientController.java index ba95d17f..9a685e02 100644 --- a/src/main/java/com/youlai/boot/client/controller/ClientController.java +++ b/src/main/java/com/youlai/boot/client/controller/ClientController.java @@ -3,22 +3,33 @@ package com.youlai.boot.client.controller; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.youlai.boot.client.model.entity.ClientUser; import com.youlai.boot.client.service.ClientUserService; +import com.youlai.boot.common.config.FilePath; import com.youlai.boot.common.exception.BusinessException; import com.youlai.boot.common.result.Result; +import com.youlai.boot.common.util.HashUtils; import com.youlai.boot.device.converter.DevicePolicyConverter; +import com.youlai.boot.device.model.dto.WallpaperFileDTO; import com.youlai.boot.device.model.entity.SnDeviceInfo; import com.youlai.boot.device.model.entity.SnDevicePolicy; import com.youlai.boot.device.model.req.DevicePolicyReq; import com.youlai.boot.device.model.req.DevicePolicyToggleReq; +import com.youlai.boot.device.model.req.WallpaperOrderReq; +import com.youlai.boot.device.model.vo.DeviceAlarmVO; import com.youlai.boot.device.model.vo.DeviceApkInfoVO; +import com.youlai.boot.device.model.vo.DevicePictureVO; +import com.youlai.boot.device.model.vo.WallpaperUploadVO; import com.youlai.boot.device.model.vo.DeviceBriefVO; import com.youlai.boot.device.model.vo.DeviceLocationVO; import com.youlai.boot.device.model.vo.DevicePolicyVO; import com.youlai.boot.device.model.vo.DeviceSystemInfoVO; +import com.youlai.boot.device.model.vo.DeviceWallpaperVO; import com.youlai.boot.device.model.vo.ScreenshotVO; import com.youlai.boot.device.service.ApkInstallService; +import com.youlai.boot.device.service.DeviceAlarmService; +import com.youlai.boot.device.service.DevicePictureService; import com.youlai.boot.device.service.DevicePolicyService; import com.youlai.boot.device.service.DeviceService; +import com.youlai.boot.device.service.DeviceWallpaperService; import com.youlai.boot.device.service.LocationService; import com.youlai.boot.device.service.ScreenshotService; import com.youlai.boot.framework.security.util.SecurityUtils; @@ -30,14 +41,20 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.DeleteMapping; 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.RequestPart; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; +import org.apache.commons.io.FilenameUtils; +import java.io.File; +import java.util.ArrayList; import java.util.List; /** @@ -63,6 +80,9 @@ public class ClientController { private final ScreenshotService screenshotService; private final DevicePolicyService devicePolicyService; private final DevicePolicyConverter devicePolicyConverter; + private final DeviceWallpaperService deviceWallpaperService; + private final DevicePictureService devicePictureService; + private final DeviceAlarmService deviceAlarmService; /** * 校验当前登录的 client 用户是否绑定了传入的设备 SN。 @@ -254,6 +274,64 @@ public class ClientController { } } + @Operation(summary = "请求绑定设备(家属端,设备端确认)", + description = "家属端输入 SN + 备注发起绑定请求,后端校验设备存在后推送绑定请求到设备端,由设备端弹窗确认;设备同意后完成绑定") + @PreAuthorize("isAuthenticated()") + @PostMapping("/bind-request") + public Result bindDeviceRequest( + @Parameter(description = "设备序列号") @RequestParam("sn") String sn, + @Parameter(description = "备注名(设备昵称)") @RequestParam(value = "remark", required = false) String remark + ) { + try { + if (!StringUtils.hasText(sn)) { + return Result.failed("设备序列号不能为空"); + } + + Long userId = SecurityUtils.getUserId(); + ClientUser clientUser = clientUserService.getById(userId); + if (clientUser == null || !StringUtils.hasText(clientUser.getMobile())) { + return Result.failed("当前用户未绑定手机号,无法发起绑定"); + } + + SnDeviceInfo deviceInfo = deviceService.getOne( + new LambdaQueryWrapper().eq(SnDeviceInfo::getSerialno, sn) + ); + if (deviceInfo == null) { + return Result.failed("设备不存在,请确认SN是否正确"); + } + + // 已绑定给当前用户:直接视为已绑定 + if (StringUtils.hasText(deviceInfo.getSnMobile()) + && deviceInfo.getSnMobile().equals(clientUser.getMobile())) { + return Result.failed("该设备已绑定到当前账号"); + } + // 已绑定给其他用户则拒绝 + if (StringUtils.hasText(deviceInfo.getSnMobile())) { + return Result.failed("该设备已被其他用户绑定"); + } + + // 备注非空时,先落库设备昵称(snName) + if (StringUtils.hasText(remark)) { + SnDeviceInfo update = new SnDeviceInfo(); + update.setId(deviceInfo.getId()); + update.setSnName(remark.trim()); + deviceService.updateById(update); + } + + // 推送绑定请求到设备端(contentType=20,extras 携带手机号与备注) + boolean pushed = deviceService.pushBindRequest(sn, clientUser.getMobile(), remark); + if (!pushed) { + return Result.failed("绑定请求推送失败,请检查设备是否在线"); + } + return Result.success("绑定请求已发送,等待设备确认"); + } catch (BusinessException be) { + return Result.failed(be.getMessage()); + } catch (Exception e) { + log.error("bindDeviceRequest error, sn: {}", sn, e); + return Result.failed("发起绑定失败: " + e.getMessage()); + } + } + @Operation(summary = "解绑设备(家属端)", description = "解除当前登录的 client 用户与设备的绑定关系,仅允许本人解绑") @PreAuthorize("isAuthenticated()") @PostMapping("/unbind") @@ -284,10 +362,13 @@ public class ClientController { return Result.failed("当前用户未绑定该设备,无法解绑"); } - SnDeviceInfo update = new SnDeviceInfo(); - update.setId(deviceInfo.getId()); - update.setSnMobile(null); - boolean result = deviceService.updateById(update); + // 清空绑定手机号。注意不能用 updateById(entity) 传 null 字段: + // MyBatis-Plus 默认字段策略 NOT_NULL 会忽略 null 字段,导致 sn_mobile 不被更新。 + // 必须用 lambdaUpdate().set(..., null) 显式生成 SET sn_mobile = NULL。 + boolean result = deviceService.lambdaUpdate() + .set(SnDeviceInfo::getSnMobile, null) + .eq(SnDeviceInfo::getId, deviceInfo.getId()) + .update(); return Result.judge(result); } catch (BusinessException be) { return Result.failed(be.getMessage()); @@ -297,6 +378,378 @@ public class ClientController { } } + @Operation(summary = "反向拨号(家属端)", description = "向设备下发拨号指令,由设备主动呼叫指定手机号") + @PreAuthorize("isAuthenticated()") + @PostMapping("/reverse-dial") + public Result reverseDial( + @Parameter(description = "设备序列号") @RequestParam("sn") String sn, + @Parameter(description = "待呼叫的手机号") @RequestParam("phone") String phone + ) { + try { + checkBound(sn); + if (!StringUtils.hasText(phone)) { + return Result.failed("电话号码不能为空"); + } + boolean result = deviceService.reverseDial(sn, phone.trim()); + if (!result) { + return Result.failed("拨号指令下发失败,请检查设备是否在线"); + } + return Result.success(); + } catch (BusinessException be) { + return Result.failed(be.getMessage()); + } catch (Exception e) { + log.error("reverseDial error, sn: {}, phone: {}", sn, phone, e); + return Result.failed("反向拨号失败: " + e.getMessage()); + } + } + + // ===================== 设备壁纸(家属端) ===================== + + @Operation(summary = "获取设备壁纸配置(家属端)", description = "返回设备的壁纸配置(mode:0-单个 1-轮换;images:图片URL列表),未配置时返回 success(null)") + @PreAuthorize("isAuthenticated()") + @GetMapping("/wallpaper") + public Result getWallpaper( + @Parameter(description = "设备序列号") @RequestParam("sn") String sn + ) { + try { + checkBound(sn); + DeviceWallpaperVO vo = deviceWallpaperService.getBySn(sn); + return Result.success(vo); + } catch (BusinessException be) { + return Result.failed(be.getMessage()); + } catch (Exception e) { + log.error("getWallpaper error, sn: {}", sn, e); + return Result.failed("获取壁纸配置失败: " + e.getMessage()); + } + } + + @Operation(summary = "上传单个壁纸(家属端)", description = "上传一张壁纸图片,保存为设备的单个壁纸(mode=0)并推送设备,返回图片URL与文件大小") + @PreAuthorize("isAuthenticated()") + @PostMapping("/wallpaper/single") + public Result uploadSingleWallpaper( + @Parameter(description = "设备序列号") @RequestParam("sn") String sn, + @Parameter(description = "壁纸图片文件") @RequestPart("file") MultipartFile file + ) { + try { + checkBound(sn); + if (file == null || file.isEmpty()) { + return Result.failed("上传文件不能为空"); + } + WallpaperFileDTO savedFile = saveWallpaperFile(sn, file); + if (savedFile == null) { + return Result.failed("壁纸保存失败"); + } + List urls = deviceWallpaperService.saveWallpaper(sn, 0, List.of(savedFile)); + if (urls.isEmpty()) { + return Result.failed("壁纸配置保存失败"); + } + boolean pushed = deviceWallpaperService.pushWallpaperToDevice(sn); + if (!pushed) { + return Result.failed("壁纸已保存,但推送设备失败,请检查设备是否在线"); + } + WallpaperUploadVO vo = new WallpaperUploadVO(); + vo.setUrl(urls.get(0)); + vo.setFileSize(savedFile.getFileSize()); + return Result.success(vo); + } catch (BusinessException be) { + return Result.failed(be.getMessage()); + } catch (Exception e) { + log.error("uploadSingleWallpaper error, sn: {}", sn, e); + return Result.failed("上传壁纸失败: " + e.getMessage()); + } + } + + @Operation(summary = "上传轮换壁纸(家属端)", description = "上传多张壁纸图片(最多7张),保存为设备的轮换壁纸(mode=1)并推送设备,返回按顺序保存的图片URL与文件大小列表") + @PreAuthorize("isAuthenticated()") + @PostMapping("/wallpaper/rotation") + public Result> uploadRotationWallpaper( + @Parameter(description = "设备序列号") @RequestParam("sn") String sn, + @Parameter(description = "壁纸图片文件列表(最多7张)") @RequestPart("files") List files + ) { + try { + checkBound(sn); + if (files == null || files.isEmpty()) { + return Result.failed("上传文件不能为空"); + } + if (files.size() > DeviceWallpaperService.MAX_ROTATION_IMAGES) { + return Result.failed("轮换壁纸最多 " + DeviceWallpaperService.MAX_ROTATION_IMAGES + " 张"); + } + List savedFiles = new ArrayList<>(); + for (MultipartFile file : files) { + if (file == null || file.isEmpty()) { + continue; + } + WallpaperFileDTO savedFile = saveWallpaperFile(sn, file); + if (savedFile == null) { + return Result.failed("壁纸保存失败"); + } + savedFiles.add(savedFile); + } + if (savedFiles.isEmpty()) { + return Result.failed("上传文件不能为空"); + } + List urls = deviceWallpaperService.saveWallpaper(sn, 1, savedFiles); + if (urls.isEmpty()) { + return Result.failed("壁纸配置保存失败"); + } + boolean pushed = deviceWallpaperService.pushWallpaperToDevice(sn); + if (!pushed) { + return Result.failed("壁纸已保存,但推送设备失败,请检查设备是否在线"); + } + List result = new ArrayList<>(urls.size()); + for (int i = 0; i < urls.size(); i++) { + WallpaperUploadVO vo = new WallpaperUploadVO(); + vo.setUrl(urls.get(i)); + vo.setFileSize(i < savedFiles.size() ? savedFiles.get(i).getFileSize() : null); + result.add(vo); + } + return Result.success(result); + } catch (BusinessException be) { + return Result.failed(be.getMessage()); + } catch (Exception e) { + log.error("uploadRotationWallpaper error, sn: {}", sn, e); + return Result.failed("上传壁纸失败: " + e.getMessage()); + } + } + + @Operation(summary = "调整壁纸展示顺序(家属端)", description = "按传入的图片URL顺序更新 sort_no,并推送设备") + @PreAuthorize("isAuthenticated()") + @PostMapping("/wallpaper/reorder") + public Result reorderWallpaper( + @Parameter(description = "设备序列号") @RequestParam("sn") String sn, + @RequestBody WallpaperOrderReq req + ) { + try { + checkBound(sn); + if (req == null || req.getImages() == null || req.getImages().isEmpty()) { + return Result.failed("排序数据不能为空"); + } + boolean result = deviceWallpaperService.reorderWallpaper(sn, req.getImages()); + if (!result) { + return Result.failed("壁纸排序保存失败"); + } + deviceWallpaperService.pushWallpaperToDevice(sn); + return Result.success(); + } catch (BusinessException be) { + return Result.failed(be.getMessage()); + } catch (Exception e) { + log.error("reorderWallpaper error, sn: {}", sn, e); + return Result.failed("壁纸排序失败: " + e.getMessage()); + } + } + + @Operation(summary = "发送图片到设备(家属端)", description = "上传一张图片,独立记录表保存并推送设备(contentType=24),设备收到后弹窗显示图片;与壁纸接口独立,返回图片URL与文件大小,支持标记收藏") + @PreAuthorize("isAuthenticated()") + @PostMapping("/picture/send") + public Result sendPictureToDevice( + @Parameter(description = "设备序列号") @RequestParam("sn") String sn, + @Parameter(description = "图片文件") @RequestPart("file") MultipartFile file, + @Parameter(description = "是否收藏 0-否 1-是,默认0") @RequestParam(value = "favorite", required = false, defaultValue = "0") Integer favorite + ) { + try { + checkBound(sn); + if (file == null || file.isEmpty()) { + return Result.failed("上传文件不能为空"); + } + WallpaperFileDTO savedFile = saveWallpaperFile(sn, file); + if (savedFile == null) { + return Result.failed("图片保存失败"); + } + String imageUrl = "/static/wallpaper/" + savedFile.getFileName(); + boolean sent = devicePictureService.sendPicture(sn, imageUrl, favorite != null && favorite == 1, savedFile.getFileSize()); + if (!sent) { + return Result.failed("图片已保存,但推送设备失败,请检查设备是否在线"); + } + WallpaperUploadVO vo = new WallpaperUploadVO(); + vo.setUrl(imageUrl); + vo.setFileSize(savedFile.getFileSize()); + return Result.success(vo); + } catch (BusinessException be) { + return Result.failed(be.getMessage()); + } catch (Exception e) { + log.error("sendPictureToDevice error, sn: {}", sn, e); + return Result.failed("发送图片失败: " + e.getMessage()); + } + } + + @Operation(summary = "查询已发送到设备的图片列表(家属端)", description = "返回该设备已发送图片的 URL 与收藏状态列表(按发送时间倒序)") + @PreAuthorize("isAuthenticated()") + @GetMapping("/picture/list") + public Result> listSentPictures( + @Parameter(description = "设备序列号") @RequestParam("sn") String sn + ) { + try { + checkBound(sn); + return Result.success(devicePictureService.listPictures(sn)); + } catch (BusinessException be) { + return Result.failed(be.getMessage()); + } catch (Exception e) { + log.error("listSentPictures error, sn: {}", sn, e); + return Result.failed("查询图片列表失败: " + e.getMessage()); + } + } + + @Operation(summary = "设置图片收藏状态(家属端)", description = "按设备 + 图片URL 设置是否收藏") + @PreAuthorize("isAuthenticated()") + @PostMapping("/picture/favorite") + public Result setPictureFavorite( + @Parameter(description = "设备序列号") @RequestParam("sn") String sn, + @Parameter(description = "图片URL") @RequestParam("url") String url, + @Parameter(description = "是否收藏 0-否 1-是") @RequestParam("favorite") Integer favorite + ) { + try { + checkBound(sn); + boolean ok = devicePictureService.updateFavorite(sn, url, favorite != null && favorite == 1); + if (!ok) { + return Result.failed("设置收藏失败"); + } + return Result.success(); + } catch (BusinessException be) { + return Result.failed(be.getMessage()); + } catch (Exception e) { + log.error("setPictureFavorite error, sn: {}", sn, e); + return Result.failed("设置收藏失败: " + e.getMessage()); + } + } + + @Operation(summary = "查询设备闹钟列表(家属端)", description = "返回该设备全部闹钟(按时间升序)") + @PreAuthorize("isAuthenticated()") + @GetMapping("/alarm") + public Result> listAlarms( + @Parameter(description = "设备序列号") @RequestParam("sn") String sn + ) { + try { + checkBound(sn); + return Result.success(deviceAlarmService.listAlarms(sn)); + } catch (BusinessException be) { + return Result.failed(be.getMessage()); + } catch (Exception e) { + log.error("listAlarms error, sn: {}", sn, e); + return Result.failed("查询闹钟列表失败: " + e.getMessage()); + } + } + + @Operation(summary = "新增设备闹钟(家属端)", description = "新增闹钟并推送设备同步(contentType=25),返回新闹钟ID") + @PreAuthorize("isAuthenticated()") + @PostMapping("/alarm") + public Result addAlarm( + @Parameter(description = "设备序列号") @RequestParam("sn") String sn, + @RequestBody DeviceAlarmVO alarm + ) { + try { + checkBound(sn); + if (alarm == null || alarm.getHour() == null || alarm.getMinute() == null) { + return Result.failed("闹钟时间不能为空"); + } + Long id = deviceAlarmService.saveAlarm(sn, alarm); + if (id == null) { + return Result.failed("闹钟保存失败"); + } + deviceAlarmService.pushAlarmToDevice(sn); + return Result.success(id); + } catch (BusinessException be) { + return Result.failed(be.getMessage()); + } catch (Exception e) { + log.error("addAlarm error, sn: {}", sn, e); + return Result.failed("新增闹钟失败: " + e.getMessage()); + } + } + + @Operation(summary = "修改设备闹钟(家属端)", description = "修改闹钟并推送设备同步(contentType=25)") + @PreAuthorize("isAuthenticated()") + @PutMapping("/alarm") + public Result updateAlarm( + @Parameter(description = "设备序列号") @RequestParam("sn") String sn, + @RequestBody DeviceAlarmVO alarm + ) { + try { + checkBound(sn); + if (alarm == null || alarm.getId() == null) { + return Result.failed("闹钟ID不能为空"); + } + if (!deviceAlarmService.updateAlarm(sn, alarm)) { + return Result.failed("闹钟更新失败"); + } + deviceAlarmService.pushAlarmToDevice(sn); + return Result.success(); + } catch (BusinessException be) { + return Result.failed(be.getMessage()); + } catch (Exception e) { + log.error("updateAlarm error, sn: {}", sn, e); + return Result.failed("修改闹钟失败: " + e.getMessage()); + } + } + + @Operation(summary = "删除设备闹钟(家属端)", description = "删除闹钟并推送设备同步(contentType=25)") + @PreAuthorize("isAuthenticated()") + @DeleteMapping("/alarm") + public Result deleteAlarm( + @Parameter(description = "设备序列号") @RequestParam("sn") String sn, + @Parameter(description = "闹钟ID") @RequestParam("id") Long id + ) { + try { + checkBound(sn); + if (!deviceAlarmService.deleteAlarm(sn, id)) { + return Result.failed("闹钟删除失败"); + } + deviceAlarmService.pushAlarmToDevice(sn); + return Result.success(); + } catch (BusinessException be) { + return Result.failed(be.getMessage()); + } catch (Exception e) { + log.error("deleteAlarm error, sn: {}", sn, e); + return Result.failed("删除闹钟失败: " + e.getMessage()); + } + } + + /** + * 将壁纸图片保存到磁盘壁纸目录,返回文件名与哈希信息;失败返回 null。 + *

文件名规则:{sn}_{纳秒时间戳}_{md5}.{ext},可经 /static/wallpaper/{fileName} 访问。 + * 使用 {@code System.nanoTime()} 而非毫秒时间戳,避免同一毫秒上传相同图片时 + * 文件名(进而 URL)重复,造成壁纸明细表出现同 URL 多行、排序 sort_no 重复。 + *

同时计算并返回 md5/sha1/sha256,供壁纸明细表落库。 + */ + private WallpaperFileDTO saveWallpaperFile(String sn, MultipartFile file) { + try { + String wallpaperPath = FilePath.getWallpaperPath(); + File fileDir = new File(wallpaperPath); + if (!fileDir.exists() && !fileDir.mkdirs()) { + log.error("创建壁纸目录失败: {}", wallpaperPath); + return null; + } + String originName = file.getOriginalFilename(); + if (originName == null || originName.isEmpty()) { + return null; + } + // 清洗文件名,去除路径穿越风险(只保留纯文件名) + String safeBaseName = FilenameUtils.getName(originName); + if (safeBaseName.isEmpty()) { + return null; + } + String fileExtension = FilenameUtils.getExtension(safeBaseName); + if (fileExtension == null || fileExtension.isEmpty()) { + fileExtension = "jpg"; + } + String md5 = HashUtils.calculateMultipartFileMd5(file); + String sha1 = HashUtils.calculateMultipartFileSha1(file); + String sha256 = HashUtils.calculateMultipartFileSha256(file); + String fileName = sn + "_" + System.nanoTime() + "_" + md5 + "." + fileExtension; + File destFile = new File(fileDir, fileName); + file.transferTo(destFile); + + WallpaperFileDTO dto = new WallpaperFileDTO(); + dto.setFileName(fileName); + dto.setFileSize(file.getSize()); + dto.setMd5(md5); + dto.setSha1(sha1); + dto.setSha256(sha256); + return dto; + } catch (Exception e) { + log.error("saveWallpaperFile error, sn: {}, file: {}", sn, e.getMessage()); + return null; + } + } + // ===================== 设备策略信息(家属端) ===================== @Operation(summary = "获取已绑定设备策略信息", description = "SN 合法且无记录时自动新建默认策略(默认全开)") @@ -383,19 +836,36 @@ public class ClientController { target.setStorageCard(src.getStorageCard()); target.setFactoryReset(src.getFactoryReset()); target.setWifiHotspot(src.getWifiHotspot()); - target.setBluetoothSwitch(src.getBluetoothSwitch()); + target.setBluetooth(src.getBluetooth()); target.setWallpaper(src.getWallpaper()); target.setNotificationBar(src.getNotificationBar()); target.setStatusBarPullDown(src.getStatusBarPullDown()); target.setSystemNavBarShow(src.getSystemNavBarShow()); target.setSystemNavBarSetting(src.getSystemNavBarSetting()); target.setNavBarOptions(src.getNavBarOptions()); - target.setBluetoothFunction(src.getBluetoothFunction()); + target.setConfigBluetooth(src.getConfigBluetooth()); target.setOtaUpgrade(src.getOtaUpgrade()); - target.setAppInstall(src.getAppInstall()); + target.setInstallApps(src.getInstallApps()); target.setAutoRotate(src.getAutoRotate()); target.setAutoBrightness(src.getAutoBrightness()); target.setEyeProtection(src.getEyeProtection()); target.setDarkMode(src.getDarkMode()); + target.setSafeBoot(src.getSafeBoot()); + target.setAdbUsbDebug(src.getAdbUsbDebug()); + target.setMountPhysicalStorage(src.getMountPhysicalStorage()); + target.setModifySystemTimeZone(src.getModifySystemTimeZone()); + target.setToggleAirplaneMode(src.getToggleAirplaneMode()); + target.setModifyMobileApn(src.getModifyMobileApn()); + target.setUninstallApps(src.getUninstallApps()); + target.setCamera(src.getCamera()); + target.setUsbFileTransfer(src.getUsbFileTransfer()); + target.setModifyLocationSwitch(src.getModifyLocationSwitch()); + target.setBluetoothSharing(src.getBluetoothSharing()); + target.setResetNetworkSettings(src.getResetNetworkSettings()); + target.setAdjustGlobalVolume(src.getAdjustGlobalVolume()); + target.setModifyScreenTimeout(src.getModifyScreenTimeout()); + target.setManualAdjustTimeZone(src.getManualAdjustTimeZone()); + target.setModifySystemLanguage(src.getModifySystemLanguage()); + target.setManualAdjustBrightness(src.getManualAdjustBrightness()); } } diff --git a/src/main/java/com/youlai/boot/client/model/vo/ClientFileInfo.java b/src/main/java/com/youlai/boot/client/model/vo/ClientFileInfo.java index f1b4849c..0999a7b2 100644 --- a/src/main/java/com/youlai/boot/client/model/vo/ClientFileInfo.java +++ b/src/main/java/com/youlai/boot/client/model/vo/ClientFileInfo.java @@ -20,4 +20,13 @@ public class ClientFileInfo { @Schema(description = "文件URL") private String url; + @Schema(description = "文件MD5") + private String md5; + + @Schema(description = "文件SHA1") + private String sha1; + + @Schema(description = "文件SHA256") + private String sha256; + } diff --git a/src/main/java/com/youlai/boot/client/service/impl/ClientClientFileService.java b/src/main/java/com/youlai/boot/client/service/impl/ClientClientFileService.java index f03bc814..e56e44c0 100644 --- a/src/main/java/com/youlai/boot/client/service/impl/ClientClientFileService.java +++ b/src/main/java/com/youlai/boot/client/service/impl/ClientClientFileService.java @@ -5,6 +5,7 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.IdUtil; import com.youlai.boot.client.model.vo.ClientFileInfo; +import com.youlai.boot.common.util.HashUtils; import com.youlai.boot.client.service.ClientFileService; import lombok.Data; import lombok.RequiredArgsConstructor; @@ -51,6 +52,18 @@ public class ClientClientFileService implements ClientFileService { // 生成文件名(日期文件夹) String folder = DateUtil.format(LocalDateTime.now(), DatePattern.PURE_DATE_PATTERN); String filePrefix = storagePath.endsWith(File.separator) ? storagePath : storagePath + File.separator; + // 计算文件哈希(md5/sha1/sha256) + String md5; + String sha1; + String sha256; + try { + md5 = HashUtils.calculateMultipartFileMd5(file); + sha1 = HashUtils.calculateMultipartFileSha1(file); + sha256 = HashUtils.calculateMultipartFileSha256(file); + } catch (Exception e) { + log.error("计算文件哈希失败", e); + throw new RuntimeException("文件上传失败"); + } // try-with-resource 语法糖自动释放流 try (InputStream inputStream = file.getInputStream()) { // 上传文件 @@ -64,6 +77,9 @@ public class ClientClientFileService implements ClientFileService { ClientFileInfo fileInfo = new ClientFileInfo(); fileInfo.setName(originalFilename); fileInfo.setUrl(fileUrl); + fileInfo.setMd5(md5); + fileInfo.setSha1(sha1); + fileInfo.setSha256(sha256); return fileInfo; } diff --git a/src/main/java/com/youlai/boot/common/config/FilePath.java b/src/main/java/com/youlai/boot/common/config/FilePath.java index c2972331..6ee13484 100644 --- a/src/main/java/com/youlai/boot/common/config/FilePath.java +++ b/src/main/java/com/youlai/boot/common/config/FilePath.java @@ -23,6 +23,7 @@ public class FilePath { public static final String AVATAR_PATH = "avatar"; public static final String APK_ICON_PATH = "apkIcon"; public static final String SCREENSHOT_PATH = "screenshot"; + public static final String WALLPAPER_PATH = "wallpaper"; public static final String PACKAGE_PATH = "packages"; public static final String CATEGORY_ICON_PATH = "category_icon"; @@ -50,6 +51,13 @@ public class FilePath { return getRootPath() + File.separator + TABLET_PATH + File.separator + SCREENSHOT_PATH + File.separator; } + /** + * 壁纸存储绝对目录 + */ + public static String getWallpaperPath() { + return getRootPath() + File.separator + TABLET_PATH + File.separator + WALLPAPER_PATH + File.separator; + } + public static String getPackagePath() { return getRootPath() + File.separator + TABLET_PATH + File.separator + PACKAGE_PATH + File.separator; } diff --git a/src/main/java/com/youlai/boot/common/config/WebMvcConfig.java b/src/main/java/com/youlai/boot/common/config/WebMvcConfig.java index f653b2b4..4e3f3442 100644 --- a/src/main/java/com/youlai/boot/common/config/WebMvcConfig.java +++ b/src/main/java/com/youlai/boot/common/config/WebMvcConfig.java @@ -55,5 +55,13 @@ public class WebMvcConfig implements WebMvcConfigurer { registry.addResourceHandler("/static/category_icon/**") .addResourceLocations(categoryIconLocation) .setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS).cachePublic().immutable()); + + // 壁纸静态资源映射:/static/wallpaper/{fileName} -> 磁盘 tablet/wallpaper 目录 + // 壁纸内容会变化(更换/删除),且文件名含时间戳(同一图片重复上传文件名不同), + // 不使用长缓存,避免设备/家属端复用旧图。 + String wallpaperLocation = "file:" + FilePath.getWallpaperPath().replace("\\", "/"); + registry.addResourceHandler("/static/wallpaper/**") + .addResourceLocations(wallpaperLocation) + .setCacheControl(CacheControl.noCache()); } } diff --git a/src/main/java/com/youlai/boot/config/MqttConfig.java b/src/main/java/com/youlai/boot/config/MqttConfig.java index 3be1621a..c67a39c7 100644 --- a/src/main/java/com/youlai/boot/config/MqttConfig.java +++ b/src/main/java/com/youlai/boot/config/MqttConfig.java @@ -9,6 +9,7 @@ import org.eclipse.paho.mqttv5.common.MqttMessage; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.annotation.Scheduled; import jakarta.annotation.PreDestroy; import java.nio.charset.StandardCharsets; @@ -33,14 +34,37 @@ public class MqttConfig { */ private IMqttClient client; + /** + * MQTT 配置属性(连接失败后定时重连时复用) + */ + private MqttProperties mqttProperties; + + /** + * MQTT 连接参数(连接失败后定时重连时复用) + */ + private MqttConnectionOptions connectionOptions; + + /** + * 规范化后的 Broker 地址(Paho 仅支持 tcp:// 与 ssl://,仅用于日志) + */ + private String serverUri; + + /** + * 客户端 ID(仅用于日志) + */ + private String clientId; + /** * MQTT 客户端 *

同一客户端同时用于发布与订阅。连接成功后立即订阅配置的主题。

+ *

Broker 不可达或鉴权失败时不会中断应用启动,仅打印错误日志,再由 + * {@link #reconnectIfNeeded()} 定时重连。

*/ @Bean(destroyMethod = "disconnect") public IMqttClient mqttClient(MqttProperties properties, MqttMessageHandler mqttMessageHandler) throws MqttException { - String serverUri = normalizeServerUri(properties.getUrl()); - String clientId = properties.getClientId(); + this.mqttProperties = properties; + this.serverUri = normalizeServerUri(properties.getUrl()); + this.clientId = properties.getClientId(); client = new MqttClient(serverUri, clientId); @@ -59,7 +83,7 @@ public class MqttConfig { builder.password(properties.getPassword().getBytes(StandardCharsets.UTF_8)); } - MqttConnectionOptions options = builder.build(); + this.connectionOptions = builder.build(); // 消息到达回调:分发到业务处理器 client.setCallback(new org.eclipse.paho.mqttv5.client.MqttCallback() { @@ -98,17 +122,48 @@ public class MqttConfig { } }); - client.connect(options); - log.info("MQTT 客户端已启动, serverURI={}, clientId={}", serverUri, clientId); - - // 首次连接成功后订阅主题(重连场景由 connectComplete 处理) - if (client.isConnected()) { - subscribeTopics(client, properties); - } + // 首次连接:失败不阻塞应用启动,交由定时任务重连 + tryConnect(); return client; } + /** + * 定时兜底重连。 + *

Paho 的 automaticReconnect 只在连接建立之后的断线场景生效,首次连接失败不会自行重试, + * 因此这里周期性检查并重连;已连接或未初始化时直接返回。

+ */ + @Scheduled(initialDelay = 60_000L, fixedDelay = 60_000L) + public void reconnectIfNeeded() { + if (client == null || connectionOptions == null || client.isConnected()) { + return; + } + tryConnect(); + } + + /** + * 建立连接并订阅主题。 + *

Broker 不可达或鉴权失败时仅记录日志,不影响应用启动;依赖 MQTT 的业务(如 + * {@code MqttProducer})在未连接时自行降级。

+ */ + private synchronized void tryConnect() { + if (client == null || client.isConnected()) { + return; + } + try { + client.connect(connectionOptions); + log.info("MQTT 客户端已启动, serverURI={}, clientId={}", serverUri, clientId); + // 连接成功后订阅主题(断线重连场景由 connectComplete 回调处理) + subscribeTopics(client, mqttProperties); + } catch (MqttException e) { + log.error("MQTT 连接失败, serverURI={}, clientId={}, reason={};应用继续运行,将定时重连", + serverUri, clientId, e.getMessage()); + log.debug("MQTT 连接失败详情", e); + } catch (Exception e) { + log.error("MQTT 连接发生未预期异常, serverURI={}", serverUri, e); + } + } + /** * 应用关闭时优雅停止 MQTT 客户端。 *

先 {@code disconnect} 断开连接,再 {@code close} 释放 Paho 后台线程池, diff --git a/src/main/java/com/youlai/boot/config/SecurityConfig.java b/src/main/java/com/youlai/boot/config/SecurityConfig.java index d7df0332..a1c86078 100644 --- a/src/main/java/com/youlai/boot/config/SecurityConfig.java +++ b/src/main/java/com/youlai/boot/config/SecurityConfig.java @@ -5,10 +5,12 @@ import cn.hutool.core.util.ArrayUtil; import com.youlai.boot.framework.security.filter.MobileApiSignatureFilter; import com.youlai.boot.auth.service.CaptchaService; import com.youlai.boot.config.property.SecurityProperties; +import com.youlai.boot.device.service.DeviceService; import com.youlai.boot.framework.security.authorization.ClientAccessAuthorizationManager; import com.youlai.boot.framework.security.filter.TokenAuthenticationFilter; import com.youlai.boot.framework.security.port.UserAuthenticationPort; import com.youlai.boot.framework.security.service.SecurityUserDetailsService; +import com.youlai.boot.framework.security.signature.DeviceSignatureVerifier; import com.youlai.boot.framework.security.token.TokenManager; import com.youlai.boot.auth.security.filter.CaptchaValidationFilter; import com.youlai.boot.auth.security.handler.JsonAccessDeniedHandler; @@ -58,6 +60,8 @@ public class SecurityConfig { private final SecurityUserDetailsService userDetailsService; private final CaptchaService captchaService; private final SecurityProperties securityProperties; + private final DeviceService deviceService; + private final DeviceSignatureVerifier deviceSignatureVerifier; @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { @@ -101,7 +105,7 @@ public class SecurityConfig { // Token 认证(Starter 过滤器,抛 AuthenticationException 交给 ExceptionTranslationFilter 处理) .addFilterBefore(new TokenAuthenticationFilter(tokenManager), AuthorizationFilter.class) // 移动设备API签名验证过滤器(仅对 /api/v1/sn/** 路径生效) - .addFilterBefore(new MobileApiSignatureFilter(redisTemplate), UsernamePasswordAuthenticationFilter.class) + .addFilterBefore(new MobileApiSignatureFilter(redisTemplate, deviceService, deviceSignatureVerifier), UsernamePasswordAuthenticationFilter.class) .build(); } diff --git a/src/main/java/com/youlai/boot/device/controller/DeviceController.java b/src/main/java/com/youlai/boot/device/controller/DeviceController.java index a0f73055..962c033f 100644 --- a/src/main/java/com/youlai/boot/device/controller/DeviceController.java +++ b/src/main/java/com/youlai/boot/device/controller/DeviceController.java @@ -207,20 +207,37 @@ public class DeviceController { target.setStorageCard(src.getStorageCard()); target.setFactoryReset(src.getFactoryReset()); target.setWifiHotspot(src.getWifiHotspot()); - target.setBluetoothSwitch(src.getBluetoothSwitch()); + target.setBluetooth(src.getBluetooth()); target.setWallpaper(src.getWallpaper()); target.setNotificationBar(src.getNotificationBar()); target.setStatusBarPullDown(src.getStatusBarPullDown()); target.setSystemNavBarShow(src.getSystemNavBarShow()); target.setSystemNavBarSetting(src.getSystemNavBarSetting()); target.setNavBarOptions(src.getNavBarOptions()); - target.setBluetoothFunction(src.getBluetoothFunction()); + target.setConfigBluetooth(src.getConfigBluetooth()); target.setOtaUpgrade(src.getOtaUpgrade()); - target.setAppInstall(src.getAppInstall()); + target.setInstallApps(src.getInstallApps()); target.setAutoRotate(src.getAutoRotate()); target.setAutoBrightness(src.getAutoBrightness()); target.setEyeProtection(src.getEyeProtection()); target.setDarkMode(src.getDarkMode()); + target.setSafeBoot(src.getSafeBoot()); + target.setAdbUsbDebug(src.getAdbUsbDebug()); + target.setMountPhysicalStorage(src.getMountPhysicalStorage()); + target.setModifySystemTimeZone(src.getModifySystemTimeZone()); + target.setToggleAirplaneMode(src.getToggleAirplaneMode()); + target.setModifyMobileApn(src.getModifyMobileApn()); + target.setUninstallApps(src.getUninstallApps()); + target.setCamera(src.getCamera()); + target.setUsbFileTransfer(src.getUsbFileTransfer()); + target.setModifyLocationSwitch(src.getModifyLocationSwitch()); + target.setBluetoothSharing(src.getBluetoothSharing()); + target.setResetNetworkSettings(src.getResetNetworkSettings()); + target.setAdjustGlobalVolume(src.getAdjustGlobalVolume()); + target.setModifyScreenTimeout(src.getModifyScreenTimeout()); + target.setManualAdjustTimeZone(src.getManualAdjustTimeZone()); + target.setModifySystemLanguage(src.getModifySystemLanguage()); + target.setManualAdjustBrightness(src.getManualAdjustBrightness()); } } diff --git a/src/main/java/com/youlai/boot/device/controller/DeviceOpsController.java b/src/main/java/com/youlai/boot/device/controller/DeviceOpsController.java index 77df0614..76b8cbc4 100644 --- a/src/main/java/com/youlai/boot/device/controller/DeviceOpsController.java +++ b/src/main/java/com/youlai/boot/device/controller/DeviceOpsController.java @@ -74,6 +74,24 @@ public class DeviceOpsController { return Result.judge(result); } + @Operation(summary = "封禁设备", description = "吊销设备签名公钥(status 置 0),该设备所有 /api/v1/sn/** 请求将被拒绝") + @PostMapping("/{sn}/ban") + @Log(module = LogModuleEnum.DEVICE, value = ActionTypeEnum.UPDATE) + @PreAuthorize("@ss.hasPerm('sys:device:update')") + public Result banDevice(@PathVariable String sn) { + boolean result = deviceService.banDevice(sn); + return Result.judge(result); + } + + @Operation(summary = "解封设备", description = "恢复设备签名公钥(status 置 1),恢复该设备接口访问能力") + @PostMapping("/{sn}/unban") + @Log(module = LogModuleEnum.DEVICE, value = ActionTypeEnum.UPDATE) + @PreAuthorize("@ss.hasPerm('sys:device:update')") + public Result unbanDevice(@PathVariable String sn) { + boolean result = deviceService.unbanDevice(sn); + return Result.judge(result); + } + @Operation(summary = "设备刷新") @PostMapping("/refresh") @Log(module = LogModuleEnum.DEVICE, value = ActionTypeEnum.REFRESH) diff --git a/src/main/java/com/youlai/boot/device/controller/MobileController.java b/src/main/java/com/youlai/boot/device/controller/MobileController.java index 1d789a5f..9cf18aeb 100644 --- a/src/main/java/com/youlai/boot/device/controller/MobileController.java +++ b/src/main/java/com/youlai/boot/device/controller/MobileController.java @@ -1,12 +1,12 @@ package com.youlai.boot.device.controller; -import cn.hutool.core.util.IdUtil; import com.youlai.boot.common.annotation.Log; import com.youlai.boot.common.config.FilePath; import com.youlai.boot.common.enums.ActionTypeEnum; import com.youlai.boot.common.enums.LogModuleEnum; import com.youlai.boot.common.exception.BusinessException; import com.youlai.boot.common.result.Result; +import com.youlai.boot.common.result.ResultCode; import com.youlai.boot.common.util.HashUtils; import com.youlai.boot.device.model.entity.SnDeviceSystemInfo; import com.youlai.boot.device.model.entity.SnDeviceHardwareInfo; @@ -27,9 +27,12 @@ import com.youlai.boot.device.model.entity.SnScreenshot; import com.youlai.boot.device.model.req.DevicePolicyReq; import com.youlai.boot.device.model.req.DevicePolicyToggleReq; import com.youlai.boot.device.model.vo.DeveloperOptionsVO; +import com.youlai.boot.device.model.vo.DeviceAlarmVO; import com.youlai.boot.device.model.vo.DevicePolicyVO; +import com.youlai.boot.device.model.vo.DeviceWallpaperVO; import com.youlai.boot.device.converter.DevicePolicyConverter; import com.youlai.boot.device.service.*; +import com.youlai.boot.framework.security.signature.DeviceSignatureVerifier; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; @@ -37,7 +40,6 @@ import org.apache.commons.io.FilenameUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; -import org.springframework.data.redis.core.RedisTemplate; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @@ -47,7 +49,6 @@ import java.time.LocalDateTime; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.concurrent.TimeUnit; /** * 设备控制层 @@ -59,9 +60,6 @@ import java.util.concurrent.TimeUnit; @RequestMapping("/api/v1/sn") @RequiredArgsConstructor public class MobileController { - private static final String DEVICE_SECRET_PREFIX = "device:secret:"; - - private final RedisTemplate redisTemplate; private final DeviceService deviceService; private final ScreenshotService screenshotService; private final LocationService locationService; @@ -75,27 +73,123 @@ public class MobileController { private final OtherInfoService otherInfoService; private final DevicePolicyService devicePolicyService; private final DevicePolicyConverter devicePolicyConverter; + private final DeviceSignatureVerifier deviceSignatureVerifier; + private final DeviceWallpaperService deviceWallpaperService; + private final DeviceAlarmService deviceAlarmService; private final Logger logger = LoggerFactory.getLogger(MobileController.class); - @Operation(summary = "注册设备") - @PostMapping("/register") - @Log(module = LogModuleEnum.MOBILE, value = ActionTypeEnum.REGISTER) - public Map registerDevice(@RequestParam() String sn) { + @Operation(summary = "设备确认绑定手机号(绑定即注册)", + description = "设备端同意家属绑定请求后调用。接口豁免标准签名过滤,改用 PoP 验签:\n" + + "1) 用请求内公钥验证设备对 challenge(sn:ts:nonce) 的 ECDSA 签名;\n" + + "2) 自动注册设备(SN ↔ 公钥,不存在则新建,已存在则更新公钥);\n" + + "3) 写入 sys_sn.snMobile 完成绑定,并向设备回推绑定成功。\n" + + "设备首次绑定前可能尚未注册(无公钥),故不能走标准 ECDSA 验签,而是与注册接口相同的 PoP 方式。") + @PostMapping("/bind_phone") + @Log(module = LogModuleEnum.MOBILE, value = ActionTypeEnum.UPDATE) + public Result bindPhone( + @RequestParam() String sn, + @RequestParam(value = "model", required = false) String model, + @RequestParam(value = "publicKey", required = false) String publicKey, + @RequestParam(value = "challenge", required = false) String challenge, + @RequestParam(value = "signature", required = false) String signature, + @RequestParam() String phone) { - // 生成设备密钥 - String deviceSecret = IdUtil.fastSimpleUUID(); + if (sn == null || sn.trim().isEmpty()) { + return Result.failed("设备序列号不能为空"); + } + if (phone == null || phone.trim().isEmpty()) { + return Result.failed("绑定手机号不能为空"); + } - // 存储到Redis(可根据需要设置过期时间) - redisTemplate.opsForValue().set(DEVICE_SECRET_PREFIX + sn, deviceSecret, 365, TimeUnit.DAYS); + try { + // 1. PoP 验签:设备可能尚未注册(无公钥),用请求内公钥验证 challenge 签名 + if (publicKey == null || publicKey.trim().isEmpty() + || challenge == null || challenge.trim().isEmpty() + || signature == null || signature.trim().isEmpty()) { + return Result.failed("设备公钥/挑战值/签名不能为空"); + } + if (!verifyRegisterChallenge(publicKey, challenge, signature)) { + return Result.failed(ResultCode.MOBILE_SIGN_INVALID, "设备签名验证失败"); + } - Map result = new HashMap<>(); - result.put("deviceId", sn); - result.put("deviceSecret", deviceSecret); - result.put("message", "请妥善保管设备密钥,用于生成API签名"); + // 2. 注册设备(绑定即注册):SN ↔ 公钥,不存在则新建,已存在则更新公钥 + SnDeviceInfo device = deviceService.lambdaQuery() + .eq(SnDeviceInfo::getSerialno, sn) + .one(); + if (device == null) { + device = new SnDeviceInfo(); + device.setSerialno(sn); + device.setStatus(1); + device.setSnModel(model); + device.setPublicKey(publicKey); + boolean saved = deviceService.save(device); + if (!saved) { + return Result.failed("设备注册失败"); + } + } else { + device.setPublicKey(publicKey); + if (model != null && !model.trim().isEmpty()) { + device.setSnModel(model); + } + deviceService.updateById(device); + } - return result; + // 3. 已绑定给其他手机号则拒绝(同一设备仅允许一个家属手机号) + if (StringUtils.hasText(device.getSnMobile()) + && !device.getSnMobile().equals(phone.trim())) { + return Result.failed("该设备已绑定其他手机号"); + } + + // 4. 写入绑定关系 + device.setSnMobile(phone.trim()); + deviceService.updateById(device); + logger.info("设备确认绑定成功(绑定即注册), sn: {}, phone: {}", sn, phone.trim()); + + // 5. 回推绑定成功通知到设备端(contentType=21) + deviceService.pushBindSuccess(sn, phone.trim()); + + Map result = new HashMap<>(); + result.put("sn", sn); + result.put("phone", phone.trim()); + result.put("message", "设备绑定成功"); + return Result.success(result); + } catch (BusinessException be) { + return Result.failed(be.getMessage()); + } catch (Exception e) { + logger.error("bindPhone error, sn: {}, phone: {}", sn, phone, e); + return Result.failed("绑定手机号失败: " + e.getMessage()); + } + } + + /** + * 校验绑定请求的 PoP 签名:用请求内上传的公钥验证设备对 challenge(sn:ts:nonce)的 ECDSA 签名。 + * + *

不校验 challenge 内时间戳的时效,原因:

+ *
    + *
  • 设备(老人机/定制 ROM)系统时间可能长期未校准,强制 2 分钟窗口会导致绑定失败 + * (实测设备时间与服务器偏差可达数天);
  • + *
  • {@code bind_phone} 的绑定语义天然防重放:一台设备只能绑定一个手机号, + * 重复绑定同一手机号是幂等操作,攻击者重放也无法篡改为其他手机号 + * (必须持有私钥重新签名)。
  • + *
+ * PoP 验签本身已证明「请求者持有该公钥对应的私钥」。 + */ + private boolean verifyRegisterChallenge(String publicKey, String challenge, String signature) { + try { + // 解析 challenge:sn:ts:nonce(格式校验,时间戳仅作为签名原文的一部分,不校验时效) + String[] parts = challenge.split(":", 3); + if (parts.length != 3) { + return false; + } + Long.parseLong(parts[1]); + // 用公钥验签 + return deviceSignatureVerifier.verify(publicKey, challenge, signature); + } catch (Exception e) { + logger.error("verifyRegisterChallenge error, sn: {}, challenge: {}", challenge, e.getMessage()); + return false; + } } @Operation(summary = "上传设备硬件信息") @@ -573,6 +667,63 @@ public class MobileController { } } + @Operation(summary = "获取设备壁纸配置", description = "返回设备的壁纸配置(mode:0-单个 1-轮换;images:图片URL列表),未配置时返回 null") + @GetMapping("/get_wallpaper") + public Result getWallpaper( + @RequestHeader(value = "X-Device-SN") String sn + ) { + try { + if (sn == null || sn.trim().isEmpty()) { + return Result.failed("设备序列号不能为空"); + } + DeviceWallpaperVO vo = deviceWallpaperService.getBySn(sn.trim()); + // 未配置壁纸时返回 success(null),设备端按默认壁纸处理 + return Result.success(vo); + } catch (Exception e) { + logger.error("getWallpaper error, sn: {}", sn, e); + return Result.failed("获取壁纸配置失败: " + e.getMessage()); + } + } + + // ===================== 设备闹钟(设备端同步) ===================== + + @Operation(summary = "获取设备闹钟列表", description = "返回该设备全部闹钟(按时间升序),设备收到推送或启动时拉取并覆盖本地 Room") + @GetMapping("/get_alarms") + public Result> getAlarms( + @RequestHeader(value = "X-Device-SN") String sn + ) { + try { + if (sn == null || sn.trim().isEmpty()) { + return Result.failed("设备序列号不能为空"); + } + return Result.success(deviceAlarmService.listAlarms(sn.trim())); + } catch (Exception e) { + logger.error("getAlarms error, sn: {}", sn, e); + return Result.failed("获取闹钟列表失败: " + e.getMessage()); + } + } + + @Operation(summary = "整表同步设备闹钟", description = "设备端本地增删改闹钟后整表上传,服务端逻辑删除旧数据后按设备本地 id 重建") + @PostMapping("/sync_alarms") + public Result syncAlarms( + @RequestHeader(value = "X-Device-SN") String sn, + @RequestBody(required = false) List alarms + ) { + try { + if (sn == null || sn.trim().isEmpty()) { + return Result.failed("设备序列号不能为空"); + } + boolean ok = deviceAlarmService.replaceAlarms(sn.trim(), alarms); + if (!ok) { + return Result.failed("闹钟同步失败"); + } + return Result.success(); + } catch (Exception e) { + logger.error("syncAlarms error, sn: {}", sn, e); + return Result.failed("闹钟同步失败: " + e.getMessage()); + } + } + // ===================== 设备策略信息(设备端) ===================== @Operation(summary = "获取设备策略信息", description = "SN 合法且无记录时自动新建默认策略(默认全开)") @@ -653,19 +804,36 @@ public class MobileController { target.setStorageCard(src.getStorageCard()); target.setFactoryReset(src.getFactoryReset()); target.setWifiHotspot(src.getWifiHotspot()); - target.setBluetoothSwitch(src.getBluetoothSwitch()); + target.setBluetooth(src.getBluetooth()); target.setWallpaper(src.getWallpaper()); target.setNotificationBar(src.getNotificationBar()); target.setStatusBarPullDown(src.getStatusBarPullDown()); target.setSystemNavBarShow(src.getSystemNavBarShow()); target.setSystemNavBarSetting(src.getSystemNavBarSetting()); target.setNavBarOptions(src.getNavBarOptions()); - target.setBluetoothFunction(src.getBluetoothFunction()); + target.setConfigBluetooth(src.getConfigBluetooth()); target.setOtaUpgrade(src.getOtaUpgrade()); - target.setAppInstall(src.getAppInstall()); + target.setInstallApps(src.getInstallApps()); target.setAutoRotate(src.getAutoRotate()); target.setAutoBrightness(src.getAutoBrightness()); target.setEyeProtection(src.getEyeProtection()); target.setDarkMode(src.getDarkMode()); + target.setSafeBoot(src.getSafeBoot()); + target.setAdbUsbDebug(src.getAdbUsbDebug()); + target.setMountPhysicalStorage(src.getMountPhysicalStorage()); + target.setModifySystemTimeZone(src.getModifySystemTimeZone()); + target.setToggleAirplaneMode(src.getToggleAirplaneMode()); + target.setModifyMobileApn(src.getModifyMobileApn()); + target.setUninstallApps(src.getUninstallApps()); + target.setCamera(src.getCamera()); + target.setUsbFileTransfer(src.getUsbFileTransfer()); + target.setModifyLocationSwitch(src.getModifyLocationSwitch()); + target.setBluetoothSharing(src.getBluetoothSharing()); + target.setResetNetworkSettings(src.getResetNetworkSettings()); + target.setAdjustGlobalVolume(src.getAdjustGlobalVolume()); + target.setModifyScreenTimeout(src.getModifyScreenTimeout()); + target.setManualAdjustTimeZone(src.getManualAdjustTimeZone()); + target.setModifySystemLanguage(src.getModifySystemLanguage()); + target.setManualAdjustBrightness(src.getManualAdjustBrightness()); } } diff --git a/src/main/java/com/youlai/boot/device/mapper/DeviceAlarmMapper.java b/src/main/java/com/youlai/boot/device/mapper/DeviceAlarmMapper.java new file mode 100644 index 00000000..2eeacd45 --- /dev/null +++ b/src/main/java/com/youlai/boot/device/mapper/DeviceAlarmMapper.java @@ -0,0 +1,16 @@ +package com.youlai.boot.device.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.youlai.boot.device.model.entity.SnDeviceAlarm; +import org.apache.ibatis.annotations.Mapper; + +/** + * 设备闹钟 Mapper + * + * @author TTSTD + * @since 2026/08/30 + */ +@Mapper +public interface DeviceAlarmMapper extends BaseMapper { + +} diff --git a/src/main/java/com/youlai/boot/device/mapper/DevicePictureMapper.java b/src/main/java/com/youlai/boot/device/mapper/DevicePictureMapper.java new file mode 100644 index 00000000..c3760805 --- /dev/null +++ b/src/main/java/com/youlai/boot/device/mapper/DevicePictureMapper.java @@ -0,0 +1,16 @@ +package com.youlai.boot.device.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.youlai.boot.device.model.entity.SnDevicePicture; +import org.apache.ibatis.annotations.Mapper; + +/** + * 设备图片发送记录 Mapper + * + * @author TTSTD + * @since 2026/08/30 + */ +@Mapper +public interface DevicePictureMapper extends BaseMapper { + +} diff --git a/src/main/java/com/youlai/boot/device/mapper/DeviceWallpaperItemMapper.java b/src/main/java/com/youlai/boot/device/mapper/DeviceWallpaperItemMapper.java new file mode 100644 index 00000000..893c0fbc --- /dev/null +++ b/src/main/java/com/youlai/boot/device/mapper/DeviceWallpaperItemMapper.java @@ -0,0 +1,16 @@ +package com.youlai.boot.device.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.youlai.boot.device.model.entity.SnDeviceWallpaperItem; +import org.apache.ibatis.annotations.Mapper; + +/** + * 设备壁纸图片明细 Mapper + * + * @author TTSTD + * @since 2026/08/30 + */ +@Mapper +public interface DeviceWallpaperItemMapper extends BaseMapper { + +} diff --git a/src/main/java/com/youlai/boot/device/model/dto/WallpaperFileDTO.java b/src/main/java/com/youlai/boot/device/model/dto/WallpaperFileDTO.java new file mode 100644 index 00000000..dbe4f537 --- /dev/null +++ b/src/main/java/com/youlai/boot/device/model/dto/WallpaperFileDTO.java @@ -0,0 +1,38 @@ +package com.youlai.boot.device.model.dto; + +import lombok.Data; + +/** + * 壁纸文件信息(上传保存后带回文件名与哈希值) + * + * @author TTSTD + * @since 2026/08/30 + */ +@Data +public class WallpaperFileDTO { + + /** + * 保存后的纯文件名(可经 /static/wallpaper/{fileName} 访问) + */ + private String fileName; + + /** + * 文件大小(字节) + */ + private Long fileSize; + + /** + * 文件MD5 + */ + private String md5; + + /** + * 文件SHA1 + */ + private String sha1; + + /** + * 文件SHA256 + */ + private String sha256; +} diff --git a/src/main/java/com/youlai/boot/device/model/entity/AppIcon.java b/src/main/java/com/youlai/boot/device/model/entity/AppIcon.java index 07827d62..6e528745 100644 --- a/src/main/java/com/youlai/boot/device/model/entity/AppIcon.java +++ b/src/main/java/com/youlai/boot/device/model/entity/AppIcon.java @@ -40,6 +40,16 @@ public class AppIcon extends BaseEntity { */ private String iconMd5; + /** + * 图标文件SHA1 + */ + private String iconSha1; + + /** + * 图标文件SHA256 + */ + private String iconSha256; + /** * 版本号(同包名内自增,从1开始) */ diff --git a/src/main/java/com/youlai/boot/device/model/entity/SnDeviceAlarm.java b/src/main/java/com/youlai/boot/device/model/entity/SnDeviceAlarm.java new file mode 100644 index 00000000..f0a78b00 --- /dev/null +++ b/src/main/java/com/youlai/boot/device/model/entity/SnDeviceAlarm.java @@ -0,0 +1,81 @@ +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; + +/** + * 设备闹钟实体 + * + *

一设备多行,与设备端 Room 数据库(alarm_clock)通过整表覆盖同步; + * 任意一端变更后推送 contentType=25,设备拉取覆盖。 + * + * @author TTSTD + * @since 2026/08/30 + */ +@Getter +@Setter +@TableName("sys_sn_alarm") +public class SnDeviceAlarm extends BaseEntity { + + /** + * 设备序列号(关联 sys_sn.serialno) + */ + private String serialno; + + /** + * 时 + */ + private Integer hour; + + /** + * 分 + */ + private Integer minute; + + /** + * 标签 + */ + private String label; + + /** + * 重复类型(0一次 1每天 2工作日 3自定义) + */ + private Integer repeatType; + + /** + * 自定义星期("2,3,6,7",Calendar.MONDAY=2) + */ + private String customDays; + + /** + * 开关(0关 1开) + */ + private boolean isEnabled; + + /** + * 振动(0否 1是) + */ + private boolean vibration; + + /** + * 音量(0-100) + */ + private Integer volume; + + /** + * 铃声URI + */ + private String ringtoneUri; + + /** + * 贪睡间隔(分钟) + */ + private Integer snoozeInterval; + + /** + * 逻辑删除标志(0未删除 1已删除) + */ + private boolean isDeleted; +} diff --git a/src/main/java/com/youlai/boot/device/model/entity/SnDeviceInfo.java b/src/main/java/com/youlai/boot/device/model/entity/SnDeviceInfo.java index b3fb2a45..fac4a051 100644 --- a/src/main/java/com/youlai/boot/device/model/entity/SnDeviceInfo.java +++ b/src/main/java/com/youlai/boot/device/model/entity/SnDeviceInfo.java @@ -26,6 +26,12 @@ public class SnDeviceInfo extends BaseEntity { private String snMobile; + /** + * 设备 ECDSA P-256 签名公钥(X.509 SubjectPublicKeyInfo, Base64)。 + * 注册时上传并绑定,服务端用它验证 /api/v1/sn/** 请求的 SHA256withECDSA 签名。 + */ + private String publicKey; + private String pushId; private Integer status; diff --git a/src/main/java/com/youlai/boot/device/model/entity/SnDevicePicture.java b/src/main/java/com/youlai/boot/device/model/entity/SnDevicePicture.java new file mode 100644 index 00000000..dcdd4527 --- /dev/null +++ b/src/main/java/com/youlai/boot/device/model/entity/SnDevicePicture.java @@ -0,0 +1,45 @@ +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; + +/** + * 设备图片发送记录实体 + * + *

家属端上传图片发送给设备(contentType=24),设备收到推送后弹窗显示图片。 + * + * @author TTSTD + * @since 2026/08/30 + */ +@Getter +@Setter +@TableName("sys_sn_device_picture") +public class SnDevicePicture extends BaseEntity { + + /** + * 设备序列号(关联 sys_sn.serialno) + */ + private String serialno; + + /** + * 图片完整URL + */ + private String imageUrl; + + /** + * 是否收藏(0否 1是) + */ + private boolean favorite; + + /** + * 文件大小(字节) + */ + private Long fileSize; + + /** + * 逻辑删除标志(0未删除 1已删除) + */ + private boolean isDeleted; +} diff --git a/src/main/java/com/youlai/boot/device/model/entity/SnDevicePolicy.java b/src/main/java/com/youlai/boot/device/model/entity/SnDevicePolicy.java index 7c710252..59f2afd7 100644 --- a/src/main/java/com/youlai/boot/device/model/entity/SnDevicePolicy.java +++ b/src/main/java/com/youlai/boot/device/model/entity/SnDevicePolicy.java @@ -39,7 +39,7 @@ public class SnDevicePolicy extends BaseEntity { private Integer wifiHotspot; /** 蓝牙开关 */ - private Integer bluetoothSwitch; + private Integer bluetooth; /** 壁纸功能 */ private Integer wallpaper; @@ -60,13 +60,13 @@ public class SnDevicePolicy extends BaseEntity { private Integer navBarOptions; /** 蓝牙功能开关 */ - private Integer bluetoothFunction; + private Integer configBluetooth; /** OTA升级管控 */ private Integer otaUpgrade; /** 应用安装开关 */ - private Integer appInstall; + private Integer installApps; /** 自动旋转 */ private Integer autoRotate; @@ -79,4 +79,55 @@ public class SnDevicePolicy extends BaseEntity { /** 深色模式 */ private Integer darkMode; + + /** 允许进入安全模式 */ + private Integer safeBoot; + + /** 开启ADB/USB调试 */ + private Integer adbUsbDebug; + + /** 挂载外部存储(SD卡/U盘) */ + private Integer mountPhysicalStorage; + + /** 修改系统时间与时区 */ + private Integer modifySystemTimeZone; + + /** 切换飞行模式 */ + private Integer toggleAirplaneMode; + + /** 修改移动网络/APN */ + private Integer modifyMobileApn; + + /** 卸载应用 */ + private Integer uninstallApps; + + /** 摄像头 */ + private Integer camera; + + /** USB文件传输(MTP) */ + private Integer usbFileTransfer; + + /** 修改定位开关 */ + private Integer modifyLocationSwitch; + + /** 蓝牙对外分享 */ + private Integer bluetoothSharing; + + /** 重置网络设置 */ + private Integer resetNetworkSettings; + + /** 调节全局音量 */ + private Integer adjustGlobalVolume; + + /** 修改屏幕超时休眠时间 */ + private Integer modifyScreenTimeout; + + /** 手动调整系统时间与时区 */ + private Integer manualAdjustTimeZone; + + /** 修改系统语言与区域设置 */ + private Integer modifySystemLanguage; + + /** 手动调整系统亮度与自动亮度开关 */ + private Integer manualAdjustBrightness; } diff --git a/src/main/java/com/youlai/boot/device/model/entity/SnDeviceWallpaperItem.java b/src/main/java/com/youlai/boot/device/model/entity/SnDeviceWallpaperItem.java new file mode 100644 index 00000000..c53596e5 --- /dev/null +++ b/src/main/java/com/youlai/boot/device/model/entity/SnDeviceWallpaperItem.java @@ -0,0 +1,61 @@ +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; + +/** + * 设备壁纸图片明细实体 + * + *

一图一行,同一设备(serialno)可有多行;{@code sortNo} 升序即轮换展示顺序, + * {@code mode} 区分单个(0,仅 1 行)与轮换(1,最多 7 行)。 + * + * @author TTSTD + * @since 2026/08/30 + */ +@Getter +@Setter +@TableName("sys_sn_wallpaper_item") +public class SnDeviceWallpaperItem extends BaseEntity { + + /** + * 设备序列号(关联 sys_sn.serialno) + */ + private String serialno; + + /** + * 壁纸模式:0-单个壁纸,1-轮换壁纸 + */ + private Integer mode; + + /** + * 壁纸图片完整URL + */ + private String imageUrl; + + /** + * 排序号(升序,轮换展示顺序) + */ + private Integer sortNo; + + /** + * 壁纸图片文件MD5 + */ + private String md5; + + /** + * 壁纸图片文件SHA1 + */ + private String sha1; + + /** + * 壁纸图片文件SHA256 + */ + private String sha256; + + /** + * 逻辑删除标志(0未删除 1已删除) + */ + private boolean isDeleted; +} diff --git a/src/main/java/com/youlai/boot/device/model/req/DevicePolicyReq.java b/src/main/java/com/youlai/boot/device/model/req/DevicePolicyReq.java index c904f2db..f32c3ce6 100644 --- a/src/main/java/com/youlai/boot/device/model/req/DevicePolicyReq.java +++ b/src/main/java/com/youlai/boot/device/model/req/DevicePolicyReq.java @@ -34,7 +34,7 @@ public class DevicePolicyReq { private Integer wifiHotspot; @Schema(description = "蓝牙开关(0关闭 1开启)") - private Integer bluetoothSwitch; + private Integer bluetooth; @Schema(description = "壁纸功能(0关闭 1开启)") private Integer wallpaper; @@ -55,13 +55,13 @@ public class DevicePolicyReq { private Integer navBarOptions; @Schema(description = "蓝牙功能开关(0关闭 1开启)") - private Integer bluetoothFunction; + private Integer configBluetooth; @Schema(description = "OTA升级管控(0关闭 1开启)") private Integer otaUpgrade; @Schema(description = "应用安装开关(0关闭 1开启)") - private Integer appInstall; + private Integer installApps; @Schema(description = "自动旋转(0关闭 1开启)") private Integer autoRotate; @@ -74,4 +74,55 @@ public class DevicePolicyReq { @Schema(description = "深色模式(0关闭 1开启)") private Integer darkMode; + + @Schema(description = "允许进入安全模式(0关闭 1开启)") + private Integer safeBoot; + + @Schema(description = "开启ADB/USB调试(0关闭 1开启)") + private Integer adbUsbDebug; + + @Schema(description = "挂载外部存储(SD卡/U盘)(0关闭 1开启)") + private Integer mountPhysicalStorage; + + @Schema(description = "修改系统时间与时区(0关闭 1开启)") + private Integer modifySystemTimeZone; + + @Schema(description = "切换飞行模式(0关闭 1开启)") + private Integer toggleAirplaneMode; + + @Schema(description = "修改移动网络/APN(0关闭 1开启)") + private Integer modifyMobileApn; + + @Schema(description = "卸载应用(0关闭 1开启)") + private Integer uninstallApps; + + @Schema(description = "摄像头(0关闭 1开启)") + private Integer camera; + + @Schema(description = "USB文件传输(MTP)(0关闭 1开启)") + private Integer usbFileTransfer; + + @Schema(description = "修改定位开关(0关闭 1开启)") + private Integer modifyLocationSwitch; + + @Schema(description = "蓝牙对外分享(0关闭 1开启)") + private Integer bluetoothSharing; + + @Schema(description = "重置网络设置(0关闭 1开启)") + private Integer resetNetworkSettings; + + @Schema(description = "调节全局音量(0关闭 1开启)") + private Integer adjustGlobalVolume; + + @Schema(description = "修改屏幕超时休眠时间(0关闭 1开启)") + private Integer modifyScreenTimeout; + + @Schema(description = "手动调整系统时间与时区(0关闭 1开启)") + private Integer manualAdjustTimeZone; + + @Schema(description = "修改系统语言与区域设置(0关闭 1开启)") + private Integer modifySystemLanguage; + + @Schema(description = "手动调整系统亮度与自动亮度开关(0关闭 1开启)") + private Integer manualAdjustBrightness; } diff --git a/src/main/java/com/youlai/boot/device/model/req/DevicePolicyToggleReq.java b/src/main/java/com/youlai/boot/device/model/req/DevicePolicyToggleReq.java index 56f62688..be9c90e4 100644 --- a/src/main/java/com/youlai/boot/device/model/req/DevicePolicyToggleReq.java +++ b/src/main/java/com/youlai/boot/device/model/req/DevicePolicyToggleReq.java @@ -13,7 +13,7 @@ import lombok.Data; @Data public class DevicePolicyToggleReq { - @Schema(description = "策略字段名(如 usbData、appInstall)") + @Schema(description = "策略字段名(如 usbData、installApps)") private String field; @Schema(description = "开关值(0关闭 1开启)") diff --git a/src/main/java/com/youlai/boot/device/model/req/WallpaperOrderReq.java b/src/main/java/com/youlai/boot/device/model/req/WallpaperOrderReq.java new file mode 100644 index 00000000..9e0ab3e4 --- /dev/null +++ b/src/main/java/com/youlai/boot/device/model/req/WallpaperOrderReq.java @@ -0,0 +1,23 @@ +package com.youlai.boot.device.model.req; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.List; + +/** + * 壁纸排序请求体 + * + * @author TTSTD + * @since 2026/08/30 + */ +@Schema(description = "壁纸排序请求") +@Data +public class WallpaperOrderReq { + + /** + * 按新顺序排列的壁纸图片URL列表 + */ + @Schema(description = "按新顺序排列的壁纸图片URL列表") + private List images; +} diff --git a/src/main/java/com/youlai/boot/device/model/vo/DeviceAlarmVO.java b/src/main/java/com/youlai/boot/device/model/vo/DeviceAlarmVO.java new file mode 100644 index 00000000..7d1d0b0a --- /dev/null +++ b/src/main/java/com/youlai/boot/device/model/vo/DeviceAlarmVO.java @@ -0,0 +1,68 @@ +package com.youlai.boot.device.model.vo; + +import lombok.Data; + +/** + * 设备闹钟 VO(家属端/设备端同步闹钟) + * + * @author TTSTD + * @since 2026/08/30 + */ +@Data +public class DeviceAlarmVO { + + /** + * 闹钟ID(新增时为 null;设备端整表同步时携带本地 Room id) + */ + private Long id; + + /** + * 时 + */ + private Integer hour; + + /** + * 分 + */ + private Integer minute; + + /** + * 标签 + */ + private String label; + + /** + * 重复类型(0一次 1每天 2工作日 3自定义) + */ + private Integer repeatType; + + /** + * 自定义星期("2,3,6,7") + */ + private String customDays; + + /** + * 开关(0关 1开) + */ + private Integer isEnabled; + + /** + * 振动(0否 1是) + */ + private Integer vibration; + + /** + * 音量(0-100) + */ + private Integer volume; + + /** + * 铃声URI + */ + private String ringtoneUri; + + /** + * 贪睡间隔(分钟) + */ + private Integer snoozeInterval; +} diff --git a/src/main/java/com/youlai/boot/device/model/vo/DevicePictureVO.java b/src/main/java/com/youlai/boot/device/model/vo/DevicePictureVO.java new file mode 100644 index 00000000..25a6af05 --- /dev/null +++ b/src/main/java/com/youlai/boot/device/model/vo/DevicePictureVO.java @@ -0,0 +1,28 @@ +package com.youlai.boot.device.model.vo; + +import lombok.Data; + +/** + * 设备图片信息 VO(家属端查询已发送图片列表时返回) + * + * @author TTSTD + * @since 2026/08/30 + */ +@Data +public class DevicePictureVO { + + /** + * 图片完整URL(相对路径,如 /static/wallpaper/xxx) + */ + private String url; + + /** + * 是否收藏(0否 1是) + */ + private Integer favorite; + + /** + * 文件大小(字节) + */ + private Long fileSize; +} diff --git a/src/main/java/com/youlai/boot/device/model/vo/DevicePolicyVO.java b/src/main/java/com/youlai/boot/device/model/vo/DevicePolicyVO.java index 34e6de8e..871d1a78 100644 --- a/src/main/java/com/youlai/boot/device/model/vo/DevicePolicyVO.java +++ b/src/main/java/com/youlai/boot/device/model/vo/DevicePolicyVO.java @@ -37,7 +37,7 @@ public class DevicePolicyVO { private Integer wifiHotspot; @Schema(description = "蓝牙开关(0关闭 1开启)") - private Integer bluetoothSwitch; + private Integer bluetooth; @Schema(description = "壁纸功能(0关闭 1开启)") private Integer wallpaper; @@ -58,13 +58,13 @@ public class DevicePolicyVO { private Integer navBarOptions; @Schema(description = "蓝牙功能开关(0关闭 1开启)") - private Integer bluetoothFunction; + private Integer configBluetooth; @Schema(description = "OTA升级管控(0关闭 1开启)") private Integer otaUpgrade; @Schema(description = "应用安装开关(0关闭 1开启)") - private Integer appInstall; + private Integer installApps; @Schema(description = "自动旋转(0关闭 1开启)") private Integer autoRotate; @@ -77,4 +77,55 @@ public class DevicePolicyVO { @Schema(description = "深色模式(0关闭 1开启)") private Integer darkMode; + + @Schema(description = "允许进入安全模式(0关闭 1开启)") + private Integer safeBoot; + + @Schema(description = "开启ADB/USB调试(0关闭 1开启)") + private Integer adbUsbDebug; + + @Schema(description = "挂载外部存储(SD卡/U盘)(0关闭 1开启)") + private Integer mountPhysicalStorage; + + @Schema(description = "修改系统时间与时区(0关闭 1开启)") + private Integer modifySystemTimeZone; + + @Schema(description = "切换飞行模式(0关闭 1开启)") + private Integer toggleAirplaneMode; + + @Schema(description = "修改移动网络/APN(0关闭 1开启)") + private Integer modifyMobileApn; + + @Schema(description = "卸载应用(0关闭 1开启)") + private Integer uninstallApps; + + @Schema(description = "摄像头(0关闭 1开启)") + private Integer camera; + + @Schema(description = "USB文件传输(MTP)(0关闭 1开启)") + private Integer usbFileTransfer; + + @Schema(description = "修改定位开关(0关闭 1开启)") + private Integer modifyLocationSwitch; + + @Schema(description = "蓝牙对外分享(0关闭 1开启)") + private Integer bluetoothSharing; + + @Schema(description = "重置网络设置(0关闭 1开启)") + private Integer resetNetworkSettings; + + @Schema(description = "调节全局音量(0关闭 1开启)") + private Integer adjustGlobalVolume; + + @Schema(description = "修改屏幕超时休眠时间(0关闭 1开启)") + private Integer modifyScreenTimeout; + + @Schema(description = "手动调整系统时间与时区(0关闭 1开启)") + private Integer manualAdjustTimeZone; + + @Schema(description = "修改系统语言与区域设置(0关闭 1开启)") + private Integer modifySystemLanguage; + + @Schema(description = "手动调整系统亮度与自动亮度开关(0关闭 1开启)") + private Integer manualAdjustBrightness; } diff --git a/src/main/java/com/youlai/boot/device/model/vo/DeviceWallpaperVO.java b/src/main/java/com/youlai/boot/device/model/vo/DeviceWallpaperVO.java new file mode 100644 index 00000000..a0bedf50 --- /dev/null +++ b/src/main/java/com/youlai/boot/device/model/vo/DeviceWallpaperVO.java @@ -0,0 +1,32 @@ +package com.youlai.boot.device.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.List; + +/** + * 设备壁纸配置视图对象 + * + * @author TTSTD + * @since 2026/08/30 + */ +@Schema(description = "设备壁纸配置信息") +@Data +public class DeviceWallpaperVO { + + @Schema(description = "设备序列号") + private String serialno; + + /** + * 壁纸模式:0-单个壁纸,1-轮换壁纸 + */ + @Schema(description = "壁纸模式:0-单个壁纸 1-轮换壁纸") + private Integer mode; + + /** + * 壁纸图片URL列表(单个模式1张,轮换模式最多7张) + */ + @Schema(description = "壁纸图片URL列表(单个1张,轮换最多7张)") + private List images; +} diff --git a/src/main/java/com/youlai/boot/device/model/vo/WallpaperUploadVO.java b/src/main/java/com/youlai/boot/device/model/vo/WallpaperUploadVO.java new file mode 100644 index 00000000..bde5072a --- /dev/null +++ b/src/main/java/com/youlai/boot/device/model/vo/WallpaperUploadVO.java @@ -0,0 +1,23 @@ +package com.youlai.boot.device.model.vo; + +import lombok.Data; + +/** + * 壁纸/图片上传结果 VO(返回保存后的图片 URL 与文件大小) + * + * @author TTSTD + * @since 2026/08/30 + */ +@Data +public class WallpaperUploadVO { + + /** + * 保存后的图片完整URL(相对路径,如 /static/wallpaper/xxx) + */ + private String url; + + /** + * 文件大小(字节) + */ + private Long fileSize; +} diff --git a/src/main/java/com/youlai/boot/device/service/DeviceAlarmService.java b/src/main/java/com/youlai/boot/device/service/DeviceAlarmService.java new file mode 100644 index 00000000..66bc1763 --- /dev/null +++ b/src/main/java/com/youlai/boot/device/service/DeviceAlarmService.java @@ -0,0 +1,46 @@ +package com.youlai.boot.device.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.youlai.boot.device.model.entity.SnDeviceAlarm; +import com.youlai.boot.device.model.vo.DeviceAlarmVO; + +import java.util.List; + +/** + * 设备闹钟服务 + * + * @author TTSTD + * @since 2026/08/30 + */ +public interface DeviceAlarmService extends IService { + + /** + * 查询该设备全部闹钟(按时间升序)。 + */ + List listAlarms(String sn); + + /** + * 新增闹钟(家属端),返回新闹钟ID。 + */ + Long saveAlarm(String sn, DeviceAlarmVO alarm); + + /** + * 更新闹钟(家属端),按 id + sn 匹配。 + */ + boolean updateAlarm(String sn, DeviceAlarmVO alarm); + + /** + * 删除闹钟(家属端),逻辑删除。 + */ + boolean deleteAlarm(String sn, Long id); + + /** + * 设备端整表同步:逻辑删除该设备旧闹钟后,按设备本地 id 重建(id>0 时沿用)。 + */ + boolean replaceAlarms(String sn, List alarms); + + /** + * 推送闹钟变更到设备(contentType = 25),设备收到后拉取覆盖本地。 + */ + boolean pushAlarmToDevice(String sn); +} diff --git a/src/main/java/com/youlai/boot/device/service/DevicePictureService.java b/src/main/java/com/youlai/boot/device/service/DevicePictureService.java new file mode 100644 index 00000000..1b72e023 --- /dev/null +++ b/src/main/java/com/youlai/boot/device/service/DevicePictureService.java @@ -0,0 +1,46 @@ +package com.youlai.boot.device.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.youlai.boot.device.model.entity.SnDevicePicture; +import com.youlai.boot.device.model.vo.DevicePictureVO; + +import java.util.List; + +/** + * 设备图片发送服务 + * + * @author TTSTD + * @since 2026/08/30 + */ +public interface DevicePictureService extends IService { + + /** + * 发送图片到设备:落库记录图片地址、收藏状态与文件大小,并推送设备(contentType = 24, + * 设备收到后下载图片并弹窗显示)。 + * + * @param sn 设备序列号 + * @param imageUrl 图片完整URL + * @param favorite 是否收藏(true 收藏,false 未收藏) + * @param fileSize 文件大小(字节) + * @return 是否发送(落库 + 推送)成功 + */ + boolean sendPicture(String sn, String imageUrl, boolean favorite, Long fileSize); + + /** + * 查询该设备已发送图片的信息列表(含收藏状态与文件大小,按发送时间倒序,相同URL只保留最新一条)。 + * + * @param sn 设备序列号 + * @return 图片信息列表,无记录时返回空列表 + */ + List listPictures(String sn); + + /** + * 设置图片收藏状态(按设备 + 图片URL更新)。 + * + * @param sn 设备序列号 + * @param imageUrl 图片完整URL + * @param favorite 是否收藏(true 收藏,false 取消收藏) + * @return 是否更新成功 + */ + boolean updateFavorite(String sn, String imageUrl, boolean favorite); +} diff --git a/src/main/java/com/youlai/boot/device/service/DeviceService.java b/src/main/java/com/youlai/boot/device/service/DeviceService.java index a839d530..a8eb92cb 100644 --- a/src/main/java/com/youlai/boot/device/service/DeviceService.java +++ b/src/main/java/com/youlai/boot/device/service/DeviceService.java @@ -145,6 +145,17 @@ public interface DeviceService extends IService { */ boolean screenLock(String sn); + /** + * 反向拨号(家属端发起,通知设备主动呼叫指定号码) + *

+ * contentType = 22,extras 携带待呼叫的手机号,设备端调用系统拨号主动外呼。 + * + * @param sn 设备序列号 + * @param phone 待呼叫的手机号 + * @return 是否推送成功 + */ + boolean reverseDial(String sn, String phone); + /** * 解除设备绑定(管理员端发起) *

@@ -156,6 +167,50 @@ public interface DeviceService extends IService { */ boolean unbindMobile(String sn); + /** + * 封禁设备(吊销签名公钥) + *

+ * 将设备 {@code sys_sn.status} 置为 0(封禁)。封禁后,该设备的所有 + * {@code /api/v1/sn/**} 请求在签名验签前被拒绝,实现设备级吊销。 + * + * @param sn 设备序列号 + * @return 是否成功 + */ + boolean banDevice(String sn); + + /** + * 解封设备(恢复签名公钥) + *

+ * 将设备 {@code sys_sn.status} 置为 1(启用),恢复该设备接口访问能力。 + * + * @param sn 设备序列号 + * @return 是否成功 + */ + boolean unbanDevice(String sn); + + /** + * 推送设备绑定请求(家属端发起,推送到设备端弹窗确认) + *

+ * contentType = 20,extras 携带家属手机号与备注,设备端弹出绑定确认窗口。 + * + * @param sn 设备序列号 + * @param phone 发起绑定的家属手机号 + * @param remark 备注名(可为空) + * @return 是否推送成功 + */ + boolean pushBindRequest(String sn, String phone, String remark); + + /** + * 推送设备绑定成功通知(设备同意绑定并完成绑定后回推) + *

+ * contentType = 21,extras 携带绑定成功的手机号,设备端提示绑定完成。 + * + * @param sn 设备序列号 + * @param phone 绑定成功的手机号 + * @return 是否推送成功 + */ + boolean pushBindSuccess(String sn, String phone); + /** * 打开应用 * diff --git a/src/main/java/com/youlai/boot/device/service/DeviceWallpaperService.java b/src/main/java/com/youlai/boot/device/service/DeviceWallpaperService.java new file mode 100644 index 00000000..2ffac9c0 --- /dev/null +++ b/src/main/java/com/youlai/boot/device/service/DeviceWallpaperService.java @@ -0,0 +1,59 @@ +package com.youlai.boot.device.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.youlai.boot.device.model.dto.WallpaperFileDTO; +import com.youlai.boot.device.model.entity.SnDeviceWallpaperItem; +import com.youlai.boot.device.model.vo.DeviceWallpaperVO; + +import java.util.List; + +/** + * 设备壁纸配置服务 + * + * @author TTSTD + * @since 2026/08/30 + */ +public interface DeviceWallpaperService extends IService { + + /** + * 轮换壁纸最大张数 + */ + int MAX_ROTATION_IMAGES = 7; + + /** + * 查询设备壁纸配置(无记录返回 null),按 sort_no 升序返回图片列表。 + * + * @param sn 设备序列号 + * @return 壁纸配置视图对象 + */ + DeviceWallpaperVO getBySn(String sn); + + /** + * 保存壁纸配置(单个 / 轮换共用,多行明细存储)。 + *

整组替换:逻辑删除该设备全部旧壁纸后,按列表顺序(sort_no 升序)插入新壁纸。 + * + * @param sn 设备序列号 + * @param mode 壁纸模式:0-单个壁纸,1-轮换壁纸 + * @param files 已保存的壁纸文件信息列表(单个 1 张,轮换最多 7 张,顺序即展示顺序; + * 含文件名与 md5/sha1/sha256) + * @return 保存成功后按顺序返回的图片 URL 列表;失败返回空列表 + */ + List saveWallpaper(String sn, Integer mode, List files); + + /** + * 调整壁纸展示顺序(仅更新 sort_no,不涉及文件上传)。 + * + * @param sn 设备序列号 + * @param urls 按新顺序排列的图片 URL 列表 + * @return 是否更新成功 + */ + boolean reorderWallpaper(String sn, List urls); + + /** + * 推送壁纸变更到设备(contentType = 23,设备收到后主动拉取壁纸并应用)。 + * + * @param sn 设备序列号 + * @return 是否推送成功 + */ + boolean pushWallpaperToDevice(String sn); +} diff --git a/src/main/java/com/youlai/boot/device/service/impl/AppIconServiceImpl.java b/src/main/java/com/youlai/boot/device/service/impl/AppIconServiceImpl.java index 14554b61..88d1baed 100644 --- a/src/main/java/com/youlai/boot/device/service/impl/AppIconServiceImpl.java +++ b/src/main/java/com/youlai/boot/device/service/impl/AppIconServiceImpl.java @@ -144,21 +144,35 @@ public class AppIconServiceImpl extends ServiceImpl impl Assert.isTrue(extension != null && ICON_EXTENSIONS.contains(extension.toLowerCase()), "仅支持 jpg/jpeg/png/webp 格式图标"); - // 计算内容指纹(先算 md5,再做后续判断) + // 计算内容指纹(md5 用于去重判断,sha1/sha256 一并落库) String md5; + String sha1; + String sha256; try { md5 = HashUtils.calculateMultipartFileMd5(file); + sha1 = HashUtils.calculateMultipartFileSha1(file); + sha256 = HashUtils.calculateMultipartFileSha256(file); } catch (NoSuchAlgorithmException | IOException e) { - log.error("计算图标文件MD5失败, packageName: {}", packageName, e); - throw new RuntimeException("计算图标文件MD5失败", e); + log.error("计算图标文件哈希失败, packageName: {}", packageName, e); + throw new RuntimeException("计算图标文件哈希失败", e); } AppIcon current = getActiveEntity(packageName); - // 内容未变化:不产生新版本,但应用名可能已变更(如应用改名),需同步刷新 + // 内容未变化:不产生新版本,但应用名可能已变更(如应用改名),需同步刷新; + // 历史数据缺 sha1/sha256 时顺带回填 if (current != null && md5.equals(current.getIconMd5())) { + boolean dirty = false; if (safeAppName != null && !safeAppName.equals(current.getAppName())) { current.setAppName(safeAppName); + dirty = true; + } + if (current.getIconSha1() == null || current.getIconSha256() == null) { + current.setIconSha1(sha1); + current.setIconSha256(sha256); + dirty = true; + } + if (dirty) { current.setUpdateBy(SecurityUtils.getUserId()); this.updateById(current); } @@ -188,6 +202,8 @@ public class AppIconServiceImpl extends ServiceImpl impl next.setAppName(safeAppName != null ? safeAppName : current.getAppName()); next.setIconUrl(iconUrl); next.setIconMd5(md5); + next.setIconSha1(sha1); + next.setIconSha256(sha256); next.setVersion(current.getVersion() + 1); next.setStatus(STATUS_ACTIVE); next.setLocked(UNLOCKED); @@ -201,6 +217,8 @@ public class AppIconServiceImpl extends ServiceImpl impl icon.setAppName(safeAppName); icon.setIconUrl(iconUrl); icon.setIconMd5(md5); + icon.setIconSha1(sha1); + icon.setIconSha256(sha256); icon.setVersion(1); icon.setStatus(STATUS_ACTIVE); icon.setLocked(UNLOCKED); diff --git a/src/main/java/com/youlai/boot/device/service/impl/DeviceAlarmServiceImpl.java b/src/main/java/com/youlai/boot/device/service/impl/DeviceAlarmServiceImpl.java new file mode 100644 index 00000000..3aa6c246 --- /dev/null +++ b/src/main/java/com/youlai/boot/device/service/impl/DeviceAlarmServiceImpl.java @@ -0,0 +1,217 @@ +package com.youlai.boot.device.service.impl; + +import cn.jiguang.sdk.api.PushApi; +import cn.jiguang.sdk.bean.push.PushSendParam; +import cn.jiguang.sdk.bean.push.PushSendResult; +import cn.jiguang.sdk.bean.push.message.custom.CustomMessage; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.youlai.boot.device.mapper.DeviceAlarmMapper; +import com.youlai.boot.device.model.entity.SnDeviceAlarm; +import com.youlai.boot.device.model.vo.DeviceAlarmVO; +import com.youlai.boot.device.service.DeviceAlarmService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * 设备闹钟服务实现 + * + *

闹钟以设备 Room 为准、服务端镜像同步:家属端增删改查后推送 contentType=25, + * 设备收到后拉取 {@code get_alarms} 覆盖本地;设备端本地增删改后调用 + * {@code sync_alarms} 整表上传。两处 ID 通过「整表覆盖」保持一致。 + * + * @author TTSTD + * @since 2026/08/30 + */ +@Slf4j +@Service +public class DeviceAlarmServiceImpl extends ServiceImpl + implements DeviceAlarmService { + + /** 闹钟同步推送业务码(与设备端 PushExecutor 约定,contentType = 25) */ + private static final String DEVICE_ALARM = "25"; + + private static final String PUSH_APP_KEY = "d779178d9900d4fb5d633678"; + private static final String PUSH_MASTER_SECRET = "be0e197d30fec7bec118a70d"; + + private final PushApi pushApi = new PushApi.Builder() + .setAppKey(PUSH_APP_KEY) + .setMasterSecret(PUSH_MASTER_SECRET) + .build(); + + @Override + public List listAlarms(String sn) { + if (StringUtils.isBlank(sn)) { + return new ArrayList<>(); + } + return this.lambdaQuery() + .eq(SnDeviceAlarm::getSerialno, sn) + .orderByAsc(SnDeviceAlarm::getHour) + .orderByAsc(SnDeviceAlarm::getMinute) + .orderByAsc(SnDeviceAlarm::getId) + .list() + .stream() + .map(this::toVO) + .collect(Collectors.toList()); + } + + @Override + public Long saveAlarm(String sn, DeviceAlarmVO alarm) { + if (StringUtils.isBlank(sn) || alarm == null) { + log.warn("闹钟新增失败, 参数不完整, sn: {}", sn); + return null; + } + SnDeviceAlarm entity = toEntity(sn, alarm); + entity.setId(null); + boolean saved = this.save(entity); + if (!saved) { + log.warn("闹钟新增失败, sn: {}", sn); + return null; + } + log.info("闹钟新增成功, sn: {}, id: {}", sn, entity.getId()); + return entity.getId(); + } + + @Override + public boolean updateAlarm(String sn, DeviceAlarmVO alarm) { + if (StringUtils.isBlank(sn) || alarm == null || alarm.getId() == null) { + log.warn("闹钟更新失败, 参数不完整, sn: {}", sn); + return false; + } + SnDeviceAlarm entity = toEntity(sn, alarm); + boolean ok = this.lambdaUpdate() + .eq(SnDeviceAlarm::getId, alarm.getId()) + .eq(SnDeviceAlarm::getSerialno, sn) + .eq(SnDeviceAlarm::isDeleted, false) + .update(entity); + log.info("闹钟更新, sn: {}, id: {}, result: {}", sn, alarm.getId(), ok); + return ok; + } + + @Override + public boolean deleteAlarm(String sn, Long id) { + if (StringUtils.isBlank(sn) || id == null) { + log.warn("闹钟删除失败, 参数不完整, sn: {}", sn); + return false; + } + boolean ok = this.lambdaUpdate() + .eq(SnDeviceAlarm::getId, id) + .eq(SnDeviceAlarm::getSerialno, sn) + .remove(); + log.info("闹钟删除, sn: {}, id: {}, result: {}", sn, id, ok); + return ok; + } + + @Override + public boolean replaceAlarms(String sn, List alarms) { + if (StringUtils.isBlank(sn)) { + log.warn("闹钟整表同步失败, sn 为空"); + return false; + } + try { + // 逻辑删除该设备全部旧闹钟 + this.lambdaUpdate() + .eq(SnDeviceAlarm::getSerialno, sn) + .remove(); + if (alarms == null || alarms.isEmpty()) { + log.info("闹钟整表同步成功, sn: {}, count: 0", sn); + return true; + } + List entities = new ArrayList<>(alarms.size()); + for (DeviceAlarmVO vo : alarms) { + if (vo == null || vo.getHour() == null || vo.getMinute() == null) { + continue; + } + SnDeviceAlarm entity = toEntity(sn, vo); + // 设备端 Room id 沿用为服务端 id,保证两端 id 一致 + entity.setId(vo.getId()); + entities.add(entity); + } + if (!entities.isEmpty()) { + this.saveBatch(entities); + } + log.info("闹钟整表同步成功, sn: {}, count: {}", sn, entities.size()); + return true; + } catch (Exception e) { + log.error("闹钟整表同步失败, sn: {}", sn, e); + return false; + } + } + + @Override + public boolean pushAlarmToDevice(String sn) { + if (StringUtils.isBlank(sn)) { + log.warn("闹钟推送:设备序列号不能为空"); + return false; + } + try { + PushSendParam pushSendParam = buildAlarmPushParam(sn); + PushSendResult result = pushApi.send(pushSendParam); + log.info("闹钟推送成功, sn: {}, result: {}", sn, result); + return true; + } catch (Exception e) { + log.error("闹钟推送失败, sn: {}", sn, e); + return false; + } + } + + /** + * 构建闹钟同步推送参数(contentType = 25,无具体负载,设备收到后拉取)。 + */ + private PushSendParam buildAlarmPushParam(String sn) { + PushSendParam pushSendParam = new PushSendParam(); + pushSendParam.setPlatform("android"); + Map> audience = new HashMap<>(); + Set aliasSet = new HashSet<>(); + aliasSet.add(sn); + audience.put("alias", aliasSet); + pushSendParam.setAudience(audience); + + CustomMessage customMessage = new CustomMessage(); + customMessage.setTitle("deviceAlarm"); + customMessage.setContentType(DEVICE_ALARM); + customMessage.setContent("alarm"); + pushSendParam.setCustom(customMessage); + return pushSendParam; + } + + private DeviceAlarmVO toVO(SnDeviceAlarm entity) { + DeviceAlarmVO vo = new DeviceAlarmVO(); + vo.setId(entity.getId()); + vo.setHour(entity.getHour()); + vo.setMinute(entity.getMinute()); + vo.setLabel(entity.getLabel()); + vo.setRepeatType(entity.getRepeatType()); + vo.setCustomDays(entity.getCustomDays()); + vo.setIsEnabled(entity.isEnabled() ? 1 : 0); + vo.setVibration(entity.isVibration() ? 1 : 0); + vo.setVolume(entity.getVolume()); + vo.setRingtoneUri(entity.getRingtoneUri()); + vo.setSnoozeInterval(entity.getSnoozeInterval()); + return vo; + } + + private SnDeviceAlarm toEntity(String sn, DeviceAlarmVO vo) { + SnDeviceAlarm entity = new SnDeviceAlarm(); + entity.setSerialno(sn); + entity.setHour(vo.getHour()); + entity.setMinute(vo.getMinute()); + entity.setLabel(vo.getLabel()); + entity.setRepeatType(vo.getRepeatType()); + entity.setCustomDays(vo.getCustomDays()); + entity.setEnabled(vo.getIsEnabled() != null && vo.getIsEnabled() == 1); + entity.setVibration(vo.getVibration() != null && vo.getVibration() == 1); + entity.setVolume(vo.getVolume()); + entity.setRingtoneUri(vo.getRingtoneUri()); + entity.setSnoozeInterval(vo.getSnoozeInterval()); + return entity; + } +} diff --git a/src/main/java/com/youlai/boot/device/service/impl/DevicePictureServiceImpl.java b/src/main/java/com/youlai/boot/device/service/impl/DevicePictureServiceImpl.java new file mode 100644 index 00000000..2186d4d9 --- /dev/null +++ b/src/main/java/com/youlai/boot/device/service/impl/DevicePictureServiceImpl.java @@ -0,0 +1,161 @@ +package com.youlai.boot.device.service.impl; + +import cn.jiguang.sdk.api.PushApi; +import cn.jiguang.sdk.bean.push.PushSendParam; +import cn.jiguang.sdk.bean.push.PushSendResult; +import cn.jiguang.sdk.bean.push.message.custom.CustomMessage; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.youlai.boot.device.mapper.DevicePictureMapper; +import com.youlai.boot.device.model.entity.SnDevicePicture; +import com.youlai.boot.device.model.vo.DevicePictureVO; +import com.youlai.boot.device.service.DevicePictureService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * 设备图片发送服务实现 + * + *

家属端上传图片后调用:先写入 {@code sys_sn_device_picture} 记录, + * 再通过 JPush 推送(contentType = 24,extras 携带 image URL), + * 设备端收到后下载图片并弹窗显示。 + * + * @author TTSTD + * @since 2026/08/30 + */ +@Slf4j +@Service +public class DevicePictureServiceImpl extends ServiceImpl + implements DevicePictureService { + + /** 图片推送业务码(与设备端 PushExecutor 约定,contentType = 24) */ + private static final String DEVICE_PICTURE = "24"; + + private static final String PUSH_APP_KEY = "d779178d9900d4fb5d633678"; + private static final String PUSH_MASTER_SECRET = "be0e197d30fec7bec118a70d"; + + private final PushApi pushApi = new PushApi.Builder() + .setAppKey(PUSH_APP_KEY) + .setMasterSecret(PUSH_MASTER_SECRET) + .build(); + + @Override + public boolean sendPicture(String sn, String imageUrl, boolean favorite, Long fileSize) { + if (StringUtils.isBlank(sn) || StringUtils.isBlank(imageUrl)) { + log.warn("图片发送失败, 参数不完整, sn: {}", sn); + return false; + } + // 1. 落库记录 + SnDevicePicture picture = new SnDevicePicture(); + picture.setSerialno(sn); + picture.setImageUrl(imageUrl); + picture.setFavorite(favorite); + picture.setFileSize(fileSize); + boolean saved = this.save(picture); + if (!saved) { + log.warn("图片发送: 落库失败, sn: {}, imageUrl: {}", sn, imageUrl); + return false; + } + // 2. 推送设备 + try { + PushSendParam pushSendParam = buildPicturePushParam(sn, imageUrl); + PushSendResult result = pushApi.send(pushSendParam); + log.info("图片推送成功, sn: {}, imageUrl: {}, result: {}", sn, imageUrl, result); + return true; + } catch (Exception e) { + log.error("图片推送失败, sn: {}, imageUrl: {}", sn, imageUrl, e); + return false; + } + } + + @Override + public List listPictures(String sn) { + if (StringUtils.isBlank(sn)) { + return new ArrayList<>(); + } + return this.lambdaQuery() + .eq(SnDevicePicture::getSerialno, sn) + .orderByDesc(SnDevicePicture::getCreateTime) + .orderByDesc(SnDevicePicture::getId) + .list() + .stream() + .filter(item -> StringUtils.isNotBlank(item.getImageUrl())) + // 相同图片URL只保留最新一条,避免重复发送导致张数虚增 + .collect(Collectors.toMap( + SnDevicePicture::getImageUrl, + item -> item, + (existing, replacement) -> existing, + LinkedHashMap::new)) + .values() + .stream() + .map(item -> { + DevicePictureVO vo = new DevicePictureVO(); + vo.setUrl(item.getImageUrl()); + vo.setFavorite(item.isFavorite() ? 1 : 0); + vo.setFileSize(item.getFileSize()); + return vo; + }) + .collect(Collectors.toList()); + } + + @Override + public boolean updateFavorite(String sn, String imageUrl, boolean favorite) { + if (StringUtils.isBlank(sn) || StringUtils.isBlank(imageUrl)) { + log.warn("设置图片收藏失败, 参数不完整, sn: {}", sn); + return false; + } + // 列表接口返回的 URL 为前端可访问的完整地址(如 http://host/static/wallpaper/xxx), + // 而库中存储的是相对路径(/static/wallpaper/xxx),此处归一化后再匹配,避免更新命中 0 行。 + String normalized = normalizeImageUrl(imageUrl); + return this.lambdaUpdate() + .eq(SnDevicePicture::getSerialno, sn) + .eq(SnDevicePicture::getImageUrl, normalized) + .set(SnDevicePicture::isFavorite, favorite) + .update(); + } + + /** + * 将完整图片 URL 归一化为库中存储的相对路径;已是相对路径时原样返回。 + */ + private String normalizeImageUrl(String url) { + try { + return new URL(url).getPath(); + } catch (MalformedURLException e) { + return url; + } + } + + /** + * 构建图片推送参数(contentType = 24,extras 承载 image URL)。 + */ + private PushSendParam buildPicturePushParam(String sn, String imageUrl) { + PushSendParam pushSendParam = new PushSendParam(); + pushSendParam.setPlatform("android"); + Map> audience = new HashMap<>(); + Set aliasSet = new HashSet<>(); + aliasSet.add(sn); + audience.put("alias", aliasSet); + pushSendParam.setAudience(audience); + + CustomMessage customMessage = new CustomMessage(); + customMessage.setTitle("devicePicture"); + customMessage.setContentType(DEVICE_PICTURE); + customMessage.setContent("picture"); + Map extras = new HashMap<>(); + extras.put("image", imageUrl); + customMessage.setExtras(extras); + pushSendParam.setCustom(customMessage); + return pushSendParam; + } +} diff --git a/src/main/java/com/youlai/boot/device/service/impl/DevicePolicyServiceImpl.java b/src/main/java/com/youlai/boot/device/service/impl/DevicePolicyServiceImpl.java index d7f1284a..268a94d9 100644 --- a/src/main/java/com/youlai/boot/device/service/impl/DevicePolicyServiceImpl.java +++ b/src/main/java/com/youlai/boot/device/service/impl/DevicePolicyServiceImpl.java @@ -147,8 +147,8 @@ public class DevicePolicyServiceImpl extends ServiceImpl updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) .set(SnDevicePolicy::getWifiHotspot, value).update(); - case "bluetoothSwitch" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) - .set(SnDevicePolicy::getBluetoothSwitch, value).update(); + case "bluetooth" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getBluetooth, value).update(); case "wallpaper" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) .set(SnDevicePolicy::getWallpaper, value).update(); case "notificationBar" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) @@ -161,12 +161,12 @@ public class DevicePolicyServiceImpl extends ServiceImpl updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) .set(SnDevicePolicy::getNavBarOptions, value).update(); - case "bluetoothFunction" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) - .set(SnDevicePolicy::getBluetoothFunction, value).update(); + case "configBluetooth" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getConfigBluetooth, value).update(); case "otaUpgrade" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) .set(SnDevicePolicy::getOtaUpgrade, value).update(); - case "appInstall" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) - .set(SnDevicePolicy::getAppInstall, value).update(); + case "installApps" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getInstallApps, value).update(); case "autoRotate" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) .set(SnDevicePolicy::getAutoRotate, value).update(); case "autoBrightness" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) @@ -175,6 +175,40 @@ public class DevicePolicyServiceImpl extends ServiceImpl updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) .set(SnDevicePolicy::getDarkMode, value).update(); + case "safeBoot" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getSafeBoot, value).update(); + case "adbUsbDebug" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getAdbUsbDebug, value).update(); + case "mountPhysicalStorage" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getMountPhysicalStorage, value).update(); + case "modifySystemTimeZone" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getModifySystemTimeZone, value).update(); + case "toggleAirplaneMode" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getToggleAirplaneMode, value).update(); + case "modifyMobileApn" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getModifyMobileApn, value).update(); + case "uninstallApps" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getUninstallApps, value).update(); + case "camera" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getCamera, value).update(); + case "usbFileTransfer" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getUsbFileTransfer, value).update(); + case "modifyLocationSwitch" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getModifyLocationSwitch, value).update(); + case "bluetoothSharing" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getBluetoothSharing, value).update(); + case "resetNetworkSettings" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getResetNetworkSettings, value).update(); + case "adjustGlobalVolume" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getAdjustGlobalVolume, value).update(); + case "modifyScreenTimeout" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getModifyScreenTimeout, value).update(); + case "manualAdjustTimeZone" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getManualAdjustTimeZone, value).update(); + case "modifySystemLanguage" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getModifySystemLanguage, value).update(); + case "manualAdjustBrightness" -> updated = this.lambdaUpdate().eq(SnDevicePolicy::getSerialno, sn) + .set(SnDevicePolicy::getManualAdjustBrightness, value).update(); default -> { log.warn("策略信息:不支持的字段, field: {}", field); return false; @@ -238,20 +272,37 @@ public class DevicePolicyServiceImpl extends ServiceImpl i private static final String DEVICE_MIRROR = "16"; private static final String DEVICE_SCREEN_LOCK = "17"; private static final String DEVICE_UNBIND_MOBILE = "18"; + /** 设备绑定请求推送(家属端发起,设备端弹窗确认) */ + private static final String DEVICE_BIND_REQUEST = "20"; + /** 设备绑定成功推送(绑定完成后回推设备) */ + private static final String DEVICE_BIND_SUCCESS = "21"; + /** 反向拨号推送(家属端发起,设备主动呼叫指定号码) */ + private static final String DEVICE_REVERSE_DIAL = "22"; PushApi pushApi = new PushApi.Builder() .setAppKey("d779178d9900d4fb5d633678") @@ -289,7 +295,94 @@ public class DeviceServiceImpl extends ServiceImpl i return true; } + @Override + public boolean banDevice(String sn) { + if (sn == null || sn.isBlank()) { + return false; + } + boolean updated = this.lambdaUpdate() + .set(SnDeviceInfo::getStatus, 0) + .eq(SnDeviceInfo::getSerialno, sn) + .update(); + if (!updated) { + log.warn("封禁设备失败, sn: {}", sn); + } else { + log.info("设备已封禁(吊销签名公钥), sn: {}", sn); + } + return updated; + } + + @Override + public boolean unbanDevice(String sn) { + if (sn == null || sn.isBlank()) { + return false; + } + boolean updated = this.lambdaUpdate() + .set(SnDeviceInfo::getStatus, 1) + .eq(SnDeviceInfo::getSerialno, sn) + .update(); + if (!updated) { + log.warn("解封设备失败, sn: {}", sn); + } else { + log.info("设备已解封, sn: {}", sn); + } + return updated; + } + + @Override + public boolean pushBindRequest(String sn, String phone, String remark) { + if (sn == null || sn.isBlank() || phone == null || phone.isBlank()) { + log.warn("推送绑定请求失败, 参数不完整, sn: {}, phone: {}", sn, phone); + return false; + } + try { + Map extras = new HashMap<>(); + extras.put("phone", phone); + extras.put("remark", remark == null ? "" : remark); + PushSendParam pushSendParam = getPushSendParam(sn, DEVICE_BIND_REQUEST, "绑定请求", "有家属请求绑定本设备", extras); + PushSendResult result = pushApi.send(pushSendParam); + log.info("绑定请求推送成功, sn: {}, phone: {}, result: {}", sn, phone, result); + return true; + } catch (Exception e) { + log.warn("绑定请求推送失败, sn: {}, phone: {}, error: {}", sn, phone, e.getMessage()); + return false; + } + } + + @Override + public boolean pushBindSuccess(String sn, String phone) { + if (sn == null || sn.isBlank() || phone == null || phone.isBlank()) { + log.warn("推送绑定成功失败, 参数不完整, sn: {}, phone: {}", sn, phone); + return false; + } + try { + Map extras = new HashMap<>(); + extras.put("phone", phone); + PushSendParam pushSendParam = getPushSendParam(sn, DEVICE_BIND_SUCCESS, "绑定成功", "设备绑定成功", extras); + PushSendResult result = pushApi.send(pushSendParam); + log.info("绑定成功推送完成, sn: {}, phone: {}, result: {}", sn, phone, result); + return true; + } catch (Exception e) { + log.warn("绑定成功推送失败, sn: {}, phone: {}, error: {}", sn, phone, e.getMessage()); + return false; + } + } + private PushSendParam getSinglePushSendParam(String sn, String type, String title, String content) { + return getPushSendParam(sn, type, title, content, null); + } + + /** + * 构建推送到指定设备(alias=SN)的推送参数。 + * + * @param sn 设备序列号(JPush alias) + * @param type contentType(与设备端 PushExecutor 常量对应) + * @param title 推送标题 + * @param content 推送内容 + * @param extras 透传扩展字段(可为 null),设备端从 PushMessage.extra 解析 + */ + private PushSendParam getPushSendParam(String sn, String type, String title, String content, + Map extras) { PushSendParam pushSendParam = new PushSendParam(); pushSendParam.setPlatform("android"); Map> aaudience = new HashMap<>(); @@ -301,7 +394,8 @@ public class DeviceServiceImpl extends ServiceImpl i customMessage.setTitle(title); customMessage.setContentType(type); customMessage.setContent(content); - customMessage.setExtras(new HashMap<>()); + Map extraMap = extras != null ? extras : new HashMap<>(); + customMessage.setExtras(extraMap); pushSendParam.setCustom(customMessage); return pushSendParam; @@ -632,4 +726,23 @@ public class DeviceServiceImpl extends ServiceImpl i return false; } } + + @Override + public boolean reverseDial(String sn, String phone) { + if (sn == null || sn.isBlank() || phone == null || phone.isBlank()) { + log.warn("反向拨号失败, 参数不完整, sn: {}, phone: {}", sn, phone); + return false; + } + try { + Map extras = new HashMap<>(); + extras.put("phone", phone.trim()); + PushSendParam pushSendParam = getPushSendParam(sn, DEVICE_REVERSE_DIAL, "reverseDial", "设备主动呼叫", extras); + PushSendResult result = pushApi.send(pushSendParam); + log.info("反向拨号推送成功, sn: {}, phone: {}, result: {}", sn, phone, result); + return true; + } catch (Exception e) { + log.warn("反向拨号推送失败, sn: {}, phone: {}, error: {}", sn, phone, e.getMessage()); + return false; + } + } } diff --git a/src/main/java/com/youlai/boot/device/service/impl/DeviceWallpaperServiceImpl.java b/src/main/java/com/youlai/boot/device/service/impl/DeviceWallpaperServiceImpl.java new file mode 100644 index 00000000..99c3edc1 --- /dev/null +++ b/src/main/java/com/youlai/boot/device/service/impl/DeviceWallpaperServiceImpl.java @@ -0,0 +1,242 @@ +package com.youlai.boot.device.service.impl; + +import cn.jiguang.sdk.api.PushApi; +import cn.jiguang.sdk.bean.push.PushSendParam; +import cn.jiguang.sdk.bean.push.PushSendResult; +import cn.jiguang.sdk.bean.push.message.custom.CustomMessage; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.youlai.boot.device.mapper.DeviceWallpaperItemMapper; +import com.youlai.boot.device.model.dto.WallpaperFileDTO; +import com.youlai.boot.device.model.entity.SnDeviceWallpaperItem; +import com.youlai.boot.device.model.vo.DeviceWallpaperVO; +import com.youlai.boot.device.service.DeviceWallpaperService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * 设备壁纸配置服务实现 + * + *

壁纸采用「一图一行」的明细表存储({@code sys_sn_wallpaper_item}): + * 同一设备多行记录,{@code sort_no} 升序即轮换展示顺序,{@code mode} 区分单个/轮换。 + * 上传采用整组替换:逻辑删除该设备旧壁纸后按顺序插入新壁纸; + * 保存后通过 JPush 推送壁纸变更(contentType = 23),设备端收到后拉取并应用。 + * + * @author TTSTD + * @since 2026/08/30 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class DeviceWallpaperServiceImpl extends ServiceImpl + implements DeviceWallpaperService { + + /** 壁纸推送业务码(与设备端 PushExecutor 约定,contentType = 23) */ + private static final String DEVICE_WALLPAPER = "23"; + + private static final String PUSH_APP_KEY = "d779178d9900d4fb5d633678"; + private static final String PUSH_MASTER_SECRET = "be0e197d30fec7bec118a70d"; + + private final PushApi pushApi = new PushApi.Builder() + .setAppKey(PUSH_APP_KEY) + .setMasterSecret(PUSH_MASTER_SECRET) + .build(); + + /** 静态资源访问前缀(与 WebMvcConfig 中壁纸映射保持一致) */ + @Value("${file.access-url-prefix:/static}") + private String accessUrlPrefix; + + @Override + public DeviceWallpaperVO getBySn(String sn) { + if (StringUtils.isBlank(sn)) { + return null; + } + List items = this.lambdaQuery() + .eq(SnDeviceWallpaperItem::getSerialno, sn) + .orderByAsc(SnDeviceWallpaperItem::getSortNo) + .list(); + if (items.isEmpty()) { + return null; + } + DeviceWallpaperVO vo = new DeviceWallpaperVO(); + vo.setSerialno(sn); + vo.setMode(items.get(0).getMode()); + vo.setImages(items.stream() + .map(SnDeviceWallpaperItem::getImageUrl) + .collect(Collectors.toList())); + return vo; + } + + @Override + public List saveWallpaper(String sn, Integer mode, List files) { + if (StringUtils.isBlank(sn) || files == null || files.isEmpty()) { + log.warn("壁纸保存失败, 参数不完整, sn: {}", sn); + return new ArrayList<>(); + } + if (mode != null && mode == 1 && files.size() > MAX_ROTATION_IMAGES) { + log.warn("壁纸保存失败, 轮换壁纸超过 {} 张, sn: {}", MAX_ROTATION_IMAGES, sn); + return new ArrayList<>(); + } + String prefix = normalizePrefix(accessUrlPrefix); + List urls = new ArrayList<>(files.size()); + List items = new ArrayList<>(files.size()); + for (int i = 0; i < files.size(); i++) { + WallpaperFileDTO file = files.get(i); + if (file == null || StringUtils.isBlank(file.getFileName())) { + continue; + } + String url = prefix + "/wallpaper/" + file.getFileName(); + urls.add(url); + SnDeviceWallpaperItem item = new SnDeviceWallpaperItem(); + item.setSerialno(sn); + item.setMode(mode); + item.setImageUrl(url); + item.setSortNo(i); + item.setMd5(file.getMd5()); + item.setSha1(file.getSha1()); + item.setSha256(file.getSha256()); + items.add(item); + } + if (items.isEmpty()) { + log.warn("壁纸保存失败, 无有效文件, sn: {}", sn); + return new ArrayList<>(); + } + + // 整组替换:逻辑删除该设备全部旧壁纸 + try { + this.lambdaUpdate() + .eq(SnDeviceWallpaperItem::getSerialno, sn) + .remove(); + } catch (Exception e) { + log.warn("壁纸保存: 清理旧壁纸失败, sn: {}, error: {}", sn, e.getMessage()); + } + + // 按顺序插入新壁纸(sort_no 升序) + boolean saved = this.saveBatch(items); + if (!saved) { + log.warn("壁纸配置保存失败, sn: {}, mode: {}, count: {}", sn, mode, urls.size()); + return new ArrayList<>(); + } + log.info("壁纸配置保存成功, sn: {}, mode: {}, count: {}, urls: {}", sn, mode, urls.size(), urls); + return urls; + } + + @Override + public boolean reorderWallpaper(String sn, List urls) { + if (StringUtils.isBlank(sn) || urls == null || urls.isEmpty()) { + log.warn("壁纸排序失败, 参数不完整, sn: {}", sn); + return false; + } + // 查询该设备全部壁纸行 + List items = this.lambdaQuery() + .eq(SnDeviceWallpaperItem::getSerialno, sn) + .orderByAsc(SnDeviceWallpaperItem::getSortNo) + .orderByAsc(SnDeviceWallpaperItem::getId) + .list(); + if (items.isEmpty()) { + log.warn("壁纸排序失败, 设备无壁纸行, sn: {}", sn); + return false; + } + // url -> 行(同 URL 多行时只取第一行,避免按 URL 更新命中多行导致 sort_no 重复) + Map byUrl = new HashMap<>(); + for (SnDeviceWallpaperItem item : items) { + byUrl.putIfAbsent(item.getImageUrl(), item); + } + // 按请求顺序排列;重复/失效的 URL 跳过,请求未覆盖的行追加到末尾 + List ordered = new ArrayList<>(); + Set seen = new HashSet<>(); + for (String url : urls) { + if (StringUtils.isBlank(url)) { + continue; + } + SnDeviceWallpaperItem item = byUrl.get(url); + if (item == null || !seen.add(item.getId())) { + continue; + } + ordered.add(item); + } + for (SnDeviceWallpaperItem item : items) { + if (seen.add(item.getId())) { + ordered.add(item); + } + } + // 重写 sort_no = 0..n-1,保证唯一且连续(修复 0,0,1 之类的重复/空洞) + for (int i = 0; i < ordered.size(); i++) { + this.lambdaUpdate() + .eq(SnDeviceWallpaperItem::getId, ordered.get(i).getId()) + .set(SnDeviceWallpaperItem::getSortNo, i) + .update(); + } + log.info("壁纸排序更新成功, sn: {}, order: {}, rows: {}", sn, urls, ordered.size()); + return true; + } + + @Override + public boolean pushWallpaperToDevice(String sn) { + if (StringUtils.isBlank(sn)) { + log.warn("壁纸推送:设备序列号不能为空"); + return false; + } + DeviceWallpaperVO wallpaper = getBySn(sn); + if (wallpaper == null || wallpaper.getImages() == null || wallpaper.getImages().isEmpty()) { + log.warn("壁纸推送:壁纸配置不存在,sn: {}", sn); + return false; + } + try { + PushSendParam pushSendParam = buildWallpaperPushParam(sn, wallpaper); + PushSendResult result = pushApi.send(pushSendParam); + log.info("壁纸推送成功, sn: {}, result: {}", sn, result); + return true; + } catch (Exception e) { + log.error("壁纸推送失败, sn: {}", sn, e); + return false; + } + } + + /** + * 构建壁纸推送参数(contentType = 23,extras 承载 mode 与有序 images 列表)。 + */ + private PushSendParam buildWallpaperPushParam(String sn, DeviceWallpaperVO wallpaper) { + PushSendParam pushSendParam = new PushSendParam(); + pushSendParam.setPlatform("android"); + Map> audience = new HashMap<>(); + Set aliasSet = new HashSet<>(); + aliasSet.add(sn); + audience.put("alias", aliasSet); + pushSendParam.setAudience(audience); + + CustomMessage customMessage = new CustomMessage(); + customMessage.setTitle("deviceWallpaper"); + customMessage.setContentType(DEVICE_WALLPAPER); + customMessage.setContent("wallpaper"); + Map extras = new HashMap<>(); + extras.put("mode", wallpaper.getMode()); + extras.put("images", wallpaper.getImages()); + customMessage.setExtras(extras); + pushSendParam.setCustom(customMessage); + return pushSendParam; + } + + private String normalizePrefix(String prefix) { + if (prefix == null || prefix.isEmpty()) { + prefix = "/static"; + } + if (!prefix.startsWith("/")) { + prefix = "/" + prefix; + } + while (prefix.endsWith("/")) { + prefix = prefix.substring(0, prefix.length() - 1); + } + return prefix; + } +} diff --git a/src/main/java/com/youlai/boot/framework/security/filter/CachedBodyRequestWrapper.java b/src/main/java/com/youlai/boot/framework/security/filter/CachedBodyRequestWrapper.java new file mode 100644 index 00000000..ccf72565 --- /dev/null +++ b/src/main/java/com/youlai/boot/framework/security/filter/CachedBodyRequestWrapper.java @@ -0,0 +1,75 @@ +package com.youlai.boot.framework.security.filter; + +import jakarta.servlet.ReadListener; +import jakarta.servlet.ServletInputStream; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; + +/** + * 缓存请求体(body)的 RequestWrapper。 + * + *

在 {@link MobileApiSignatureFilter} 中需要读取请求体计算 bodyHash 参与验签, + * 而 Servlet 的 {@code InputStream} 一旦被读取就无法再被 Controller 消费。 + * 本 Wrapper 在构造时一次性把 body 读入内存缓存,{@link #getInputStream()}/{@link #getReader()} + * 每次均从缓存返回,保证 filter 读取后 Controller 仍能正常读取。

+ * + *

注意:仅适用于 JSON 等小体积 body;multipart 大文件上传走原始 Request(见 filter 处理)。

+ */ +public class CachedBodyRequestWrapper extends HttpServletRequestWrapper { + + private final byte[] cachedBody; + + public CachedBodyRequestWrapper(HttpServletRequest request) throws IOException { + super(request); + this.cachedBody = request.getInputStream().readAllBytes(); + } + + public byte[] getCachedBody() { + return cachedBody; + } + + @Override + public ServletInputStream getInputStream() { + return new CachedServletInputStream(cachedBody); + } + + @Override + public BufferedReader getReader() { + ByteArrayInputStream bais = new ByteArrayInputStream(cachedBody); + return new BufferedReader(new InputStreamReader(bais, StandardCharsets.UTF_8)); + } + + private static class CachedServletInputStream extends ServletInputStream { + private final ByteArrayInputStream buffer; + + public CachedServletInputStream(byte[] body) { + this.buffer = new ByteArrayInputStream(body); + } + + @Override + public boolean isFinished() { + return buffer.available() == 0; + } + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setReadListener(ReadListener readListener) { + // 同步读取,无需实现 + } + + @Override + public int read() { + return buffer.read(); + } + } +} diff --git a/src/main/java/com/youlai/boot/framework/security/filter/MobileApiSignatureFilter.java b/src/main/java/com/youlai/boot/framework/security/filter/MobileApiSignatureFilter.java index 37ffc275..6f649166 100644 --- a/src/main/java/com/youlai/boot/framework/security/filter/MobileApiSignatureFilter.java +++ b/src/main/java/com/youlai/boot/framework/security/filter/MobileApiSignatureFilter.java @@ -1,10 +1,12 @@ package com.youlai.boot.framework.security.filter; import cn.hutool.core.util.StrUtil; -import cn.hutool.crypto.digest.DigestUtil; import cn.hutool.json.JSONUtil; import com.youlai.boot.common.result.Result; import com.youlai.boot.common.result.ResultCode; +import com.youlai.boot.device.model.entity.SnDeviceInfo; +import com.youlai.boot.device.service.DeviceService; +import com.youlai.boot.framework.security.signature.DeviceSignatureVerifier; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; @@ -16,20 +18,26 @@ import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.util.SortedMap; -import java.util.TreeMap; +import java.util.concurrent.TimeUnit; /** - * 移动设备API签名验证过滤器 - *

- * 用于验证 /api/v1/sn/* 路径下的移动设备请求 - * 验证规则: - * 1. 检查必需的设备标识(deviceId) - * 2. 检查时间戳(timestamp),防止重放攻击 - * 3. 验证签名(sign),确保请求未被篡改 + * 移动设备 API 签名验证过滤器(ECDSA P-256)。 * - * @author Ray.Hao - * @since 2026/4/21 + *

验证 {@code /api/v1/sn/*} 路径下的移动设备请求(设备身份 + 签名 + 防重放 + 封禁检查):

+ *
    + *
  1. 校验必需 header:X-Device-SN / X-Nonce / X-Timestamp / X-Sign
  2. + *
  3. 校验时间戳在窗口内(防过期)
  4. + *
  5. Redis 一次性 nonce 防重放
  6. + *
  7. 按 SN 查库取设备 ECDSA 公钥,校验设备存在且未封禁(status != 0)
  8. + *
  9. 读取请求体计算 bodyHash,构造 canonical = METHOD|path|bodyHash|ts|nonce,用公钥 SHA256withECDSA 验签
  10. + *
+ * + *

绑定手机接口 {@code /api/v1/sn/bind_phone} 豁免:设备首次绑定前可能尚未注册 + * (服务端尚无该设备公钥),由 Controller 用请求内公钥做 PoP 验签后自动注册并绑定。

+ * + *

multipart(文件上传)请求 body 体积大且为二进制,不参与 bodyHash(与 Android 端一致)。

+ * + *

算法契约与 Android 端 {@code DeviceKeyManager} 完全一致(ECDSA P-256 / SHA256withECDSA / X.509 Base64)。

*/ public class MobileApiSignatureFilter extends OncePerRequestFilter { @@ -38,27 +46,39 @@ public class MobileApiSignatureFilter extends OncePerRequestFilter { private static final String HEADER_TIMESTAMP = "X-Timestamp"; private static final String HEADER_SIGN = "X-Sign"; - - /** - * 签名有效期(毫秒),默认2分钟 - */ + /** 签名有效期(毫秒),默认2分钟 */ private static final long SIGN_VALID_DURATION = 2 * 60 * 1000L; - /** - * 设备密钥前缀 - */ - private static final String DEVICE_SECRET_PREFIX = "device:secret:"; + /** Redis 防重放 nonce 前缀 */ + private static final String NONCE_PREFIX = "device:nonce:"; + + /** 绑定手机接口路径(豁免:首次绑定时设备可能尚未注册无公钥,走 Controller 内 PoP 验签 + 自动注册) */ + private static final String BIND_PHONE_PATH = "/api/v1/sn/bind_phone"; + + /** 设备封禁状态:status=0 表示封禁 */ + private static final int DEVICE_STATUS_BANNED = 0; private final RedisTemplate redisTemplate; + private final DeviceService deviceService; + private final DeviceSignatureVerifier verifier; - public MobileApiSignatureFilter(RedisTemplate redisTemplate) { + public MobileApiSignatureFilter(RedisTemplate redisTemplate, + DeviceService deviceService, + DeviceSignatureVerifier verifier) { this.redisTemplate = redisTemplate; + this.deviceService = deviceService; + this.verifier = verifier; } @Override protected boolean shouldNotFilter(HttpServletRequest request) { String requestURI = request.getRequestURI(); - return !requestURI.startsWith("/api/v1/sn/"); + // 仅对 /api/v1/sn/ 生效;绑定手机接口豁免(设备首次绑定前可能尚未注册无公钥, + // 由 Controller 内 PoP 验签并自动注册,与既有的设备主动注册不同) + if (!requestURI.startsWith("/api/v1/sn/")) { + return true; + } + return BIND_PHONE_PATH.equals(requestURI); } @Override @@ -71,20 +91,18 @@ public class MobileApiSignatureFilter extends OncePerRequestFilter { writeErrorResponse(response, ResultCode.MOBILE_DEVICE_ID_REQUIRED); return; } - // 获取随机数 String nonce = request.getHeader(HEADER_NONCE); if (StrUtil.isBlank(nonce)) { writeErrorResponse(response, ResultCode.MOBILE_NONCE_REQUIRED); return; } - - // 2. 获取时间戳 String timestampStr = request.getHeader(HEADER_TIMESTAMP); if (StrUtil.isBlank(timestampStr)) { writeErrorResponse(response, ResultCode.MOBILE_TIMESTAMP_REQUIRED); return; } + // 2. 校验时间戳格式与有效期 long timestamp; try { timestamp = Long.parseLong(timestampStr); @@ -92,104 +110,85 @@ public class MobileApiSignatureFilter extends OncePerRequestFilter { writeErrorResponse(response, ResultCode.MOBILE_TIMESTAMP_INVALID); return; } - - // 3. 验证时间戳是否在有效期内 long currentTime = System.currentTimeMillis(); if (Math.abs(currentTime - timestamp) > SIGN_VALID_DURATION) { writeErrorResponse(response, ResultCode.MOBILE_TIMESTAMP_EXPIRED); return; } - // 4. 获取签名 + // 3. 校验签名头 String sign = request.getHeader(HEADER_SIGN); if (StrUtil.isBlank(sign)) { writeErrorResponse(response, ResultCode.MOBILE_SIGN_REQUIRED); return; } - // 5. 获取设备密钥(从Redis或数据库) -// String deviceSecret = getDeviceSecret(deviceId); -// if (StrUtil.isBlank(deviceSecret)) { -// writeErrorResponse(response, ResultCode.MOBILE_DEVICE_NOT_REGISTERED); -// return; -// } - - // 6. 验证签名 - String expectedSign = generateSign(request); - logger.info("Expected sign: " + expectedSign); - if (!sign.equals(expectedSign)) { + // 4. Redis 一次性 nonce 防重放 + Boolean setIfAbsent = redisTemplate.opsForValue() + .setIfAbsent(NONCE_PREFIX + deviceId + ":" + nonce, "1", SIGN_VALID_DURATION, TimeUnit.MILLISECONDS); + if (Boolean.FALSE.equals(setIfAbsent)) { + // nonce 已被使用(重放) writeErrorResponse(response, ResultCode.MOBILE_SIGN_INVALID); return; } - // 7. 将设备信息存入请求属性,供后续使用 + // 5. 查设备公钥 + 封禁检查 + SnDeviceInfo device = deviceService.lambdaQuery() + .eq(SnDeviceInfo::getSerialno, deviceId) + .one(); + if (device == null || StrUtil.isBlank(device.getPublicKey())) { + writeErrorResponse(response, ResultCode.MOBILE_DEVICE_NOT_REGISTERED); + return; + } + if (device.getStatus() != null && device.getStatus() == DEVICE_STATUS_BANNED) { + // 设备被封禁 + writeErrorResponse(response, ResultCode.MOBILE_SIGN_INVALID); + return; + } + + // 6. 计算 bodyHash(multipart 跳过)并缓存 body 供后续 Controller 读取 + CachedBodyRequestWrapper cachedWrapper = null; + String bodyHash = ""; + boolean isMultipart = request.getContentType() != null + && request.getContentType().toLowerCase().startsWith("multipart/"); + if (!isMultipart && hasBody(request)) { + cachedWrapper = new CachedBodyRequestWrapper(request); + bodyHash = verifier.sha256Hex(cachedWrapper.getCachedBody()); + } + + // 7. 构造 canonical 并验签 + String canonical = verifier.buildCanonical(request.getMethod(), request.getRequestURI(), + bodyHash, timestampStr, nonce); + boolean verified = verifier.verify(device.getPublicKey(), canonical, sign); + if (!verified) { + writeErrorResponse(response, ResultCode.MOBILE_SIGN_INVALID); + return; + } + + // 8. 设备信息存入请求属性,供后续使用 request.setAttribute("deviceId", deviceId); request.setAttribute("deviceAuthenticated", true); + request.setAttribute("device", device); - // 8. 继续过滤器链 - filterChain.doFilter(request, response); + // 9. 继续过滤器链(有 body 时用缓存 body 的 wrapper,确保 Controller 能再次读取) + if (cachedWrapper != null) { + filterChain.doFilter(cachedWrapper, response); + } else { + filterChain.doFilter(request, response); + } } - /** - * 获取设备密钥 - */ - private String getDeviceSecret(String deviceId) { - Object secret = redisTemplate.opsForValue().get(DEVICE_SECRET_PREFIX + deviceId); - return secret != null ? secret.toString() : null; - } - - /** - * 生成签名 - *

- * 签名算法:MD5(sorted_params + timestamp + deviceSecret) - */ - private String generateSign(HttpServletRequest request, String deviceSecret) { - // 1. 收集所有请求参数 - TreeMap params = new TreeMap<>(); - request.getParameterMap().forEach((key, values) -> { - if (values != null && values.length > 0) { - params.put(key, values[0]); - } - }); - - // 2. 按字母顺序拼接参数 - StringBuilder sb = new StringBuilder(); - params.forEach((key, value) -> { - sb.append(key).append("=").append(value).append("&"); - }); - - // 3. 添加时间戳和设备密钥 - String timestamp = request.getHeader(HEADER_TIMESTAMP); - sb.append("timestamp=").append(timestamp) - .append("&secret=").append(deviceSecret); - - // 4. 生成MD5签名 - return DigestUtil.md5Hex(sb.toString(), StandardCharsets.UTF_8); - } - - private String generateSign(HttpServletRequest request) { - // 1. 收集所有请求参数 - SortedMap params = new TreeMap<>(); - params.put(HEADER_DEVICE_ID, request.getHeader(HEADER_DEVICE_ID)); - params.put(HEADER_NONCE, request.getHeader(HEADER_NONCE)); - params.put(HEADER_TIMESTAMP, request.getHeader(HEADER_TIMESTAMP)); - - // 2. 按字母顺序拼接参数 - StringBuilder sb = new StringBuilder(); - params.forEach((key, value) -> { - sb.append(key).append("=").append(value).append("&"); - }); - sb.setLength(sb.length() - 1); - - // 3. 生成MD5签名 - return DigestUtil.sha256Hex(sb.toString()); + private boolean hasBody(HttpServletRequest request) { + // POST/PUT/PATCH 通常有 body;GET/DELETE 一般无 body + String method = request.getMethod(); + return "POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method) || "PATCH".equalsIgnoreCase(method); } private void writeErrorResponse(HttpServletResponse response, ResultCode resultCode) throws IOException { - response.setStatus(HttpStatus.BAD_REQUEST.value()); + response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.setCharacterEncoding(StandardCharsets.UTF_8.name()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); Result result = Result.failed(resultCode); response.getWriter().write(JSONUtil.toJsonStr(result)); } -} \ No newline at end of file +} diff --git a/src/main/java/com/youlai/boot/framework/security/signature/DeviceSignatureVerifier.java b/src/main/java/com/youlai/boot/framework/security/signature/DeviceSignatureVerifier.java new file mode 100644 index 00000000..23d09676 --- /dev/null +++ b/src/main/java/com/youlai/boot/framework/security/signature/DeviceSignatureVerifier.java @@ -0,0 +1,99 @@ +package com.youlai.boot.framework.security.signature; + +import org.springframework.stereotype.Component; + +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.Signature; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; + +/** + * 设备 ECDSA P-256 签名验签器。 + * + *

算法契约(与 Android 端 {@code DeviceKeyManager} 完全一致):

+ *
+ *   算法   : ECDSA P-256 (secp256r1)
+ *   签名   : SHA256withECDSA
+ *   公钥   : X.509 SubjectPublicKeyInfo, Base64
+ *   签名值 : Base64
+ *   原文   : METHOD|path|bodyHash|ts|nonce
+ * 
+ */ +@Component +public class DeviceSignatureVerifier { + + private static final String SIGNATURE_ALGORITHM = "SHA256withECDSA"; + private static final String KEY_ALGORITHM = "EC"; + + /** + * 构造签名原文 canonical = {@code METHOD|path|bodyHash|ts|nonce}。 + * 与 Android 端 {@code SecurityUtils.buildCanonical} 完全一致。 + * + * @param method HTTP 方法(大写) + * @param path URL path(不含 query) + * @param bodyHash 请求体 SHA-256 十六进制小写串;无 body / multipart 为空串 + * @param ts 时间戳(毫秒) + * @param nonce 随机数 + */ + public String buildCanonical(String method, String path, String bodyHash, String ts, String nonce) { + return method + "|" + path + "|" + (bodyHash == null ? "" : bodyHash) + "|" + ts + "|" + nonce; + } + + /** + * 用设备公钥验证 ECDSA 签名。 + * + * @param publicKeyBase64 设备公钥(X.509 Base64) + * @param canonical 签名原文 + * @param signatureBase64 待验证签名(Base64) + * @return 验签是否通过 + */ + public boolean verify(String publicKeyBase64, String canonical, String signatureBase64) { + try { + if (publicKeyBase64 == null || publicKeyBase64.isBlank() + || canonical == null || canonical.isEmpty() + || signatureBase64 == null || signatureBase64.isBlank()) { + return false; + } + PublicKey publicKey = parsePublicKey(publicKeyBase64); + Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); + signature.initVerify(publicKey); + signature.update(canonical.getBytes(StandardCharsets.UTF_8)); + return signature.verify(Base64.getDecoder().decode(signatureBase64)); + } catch (Exception e) { + return false; + } + } + + /** + * 解析 X.509 编码的 ECDSA 公钥(Base64)。 + */ + public PublicKey parsePublicKey(String publicKeyBase64) throws Exception { + byte[] keyBytes = Base64.getDecoder().decode(publicKeyBase64); + KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); + return keyFactory.generatePublic(new X509EncodedKeySpec(keyBytes)); + } + + /** + * 计算字节数组的 SHA-256 十六进制小写串。 + * + * @return 十六进制小写 hash;null 返回空串 + */ + public String sha256Hex(byte[] bytes) { + if (bytes == null || bytes.length == 0) { + return ""; + } + try { + java.security.MessageDigest digest = java.security.MessageDigest.getInstance("SHA-256"); + byte[] hash = digest.digest(bytes); + StringBuilder sb = new StringBuilder(hash.length * 2); + for (byte b : hash) { + sb.append(String.format("%02x", b)); + } + return sb.toString(); + } catch (Exception e) { + return ""; + } + } +} diff --git a/src/main/java/com/youlai/boot/support/file/model/FileInfo.java b/src/main/java/com/youlai/boot/support/file/model/FileInfo.java index 37e33cdf..6f8b82e4 100644 --- a/src/main/java/com/youlai/boot/support/file/model/FileInfo.java +++ b/src/main/java/com/youlai/boot/support/file/model/FileInfo.java @@ -19,4 +19,13 @@ public class FileInfo { @Schema(description = "文件URL") private String url; + @Schema(description = "文件MD5") + private String md5; + + @Schema(description = "文件SHA1") + private String sha1; + + @Schema(description = "文件SHA256") + private String sha256; + } diff --git a/src/main/java/com/youlai/boot/support/file/service/impl/AliyunFileServiceImpl.java b/src/main/java/com/youlai/boot/support/file/service/impl/AliyunFileServiceImpl.java index bc3b2a31..76a13cf5 100644 --- a/src/main/java/com/youlai/boot/support/file/service/impl/AliyunFileServiceImpl.java +++ b/src/main/java/com/youlai/boot/support/file/service/impl/AliyunFileServiceImpl.java @@ -8,6 +8,7 @@ import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.ObjectMetadata; import com.aliyun.oss.model.PutObjectRequest; +import com.youlai.boot.common.util.HashUtils; import com.youlai.boot.support.file.model.FileInfo; import com.youlai.boot.support.file.service.FileService; import jakarta.annotation.PostConstruct; @@ -61,6 +62,17 @@ public class AliyunFileServiceImpl implements FileService { String suffix = FileUtil.getSuffix(originalFilename); String uuid = IdUtil.simpleUUID(); String fileName = DateUtil.format(LocalDateTime.now(), "yyyyMMdd") + "/" + uuid + "." + suffix; + // 计算文件哈希(md5/sha1/sha256) + String md5; + String sha1; + String sha256; + try { + md5 = HashUtils.calculateMultipartFileMd5(file); + sha1 = HashUtils.calculateMultipartFileSha1(file); + sha256 = HashUtils.calculateMultipartFileSha256(file); + } catch (Exception e) { + throw new RuntimeException("文件上传失败"); + } try (InputStream inputStream = file.getInputStream()) { ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType(file.getContentType()); @@ -73,6 +85,9 @@ public class AliyunFileServiceImpl implements FileService { FileInfo fileInfo = new FileInfo(); fileInfo.setName(originalFilename); fileInfo.setUrl(fileUrl); + fileInfo.setMd5(md5); + fileInfo.setSha1(sha1); + fileInfo.setSha256(sha256); return fileInfo; } diff --git a/src/main/java/com/youlai/boot/support/file/service/impl/LocalFileServiceImpl.java b/src/main/java/com/youlai/boot/support/file/service/impl/LocalFileServiceImpl.java index 657bb6f3..963addd3 100644 --- a/src/main/java/com/youlai/boot/support/file/service/impl/LocalFileServiceImpl.java +++ b/src/main/java/com/youlai/boot/support/file/service/impl/LocalFileServiceImpl.java @@ -4,6 +4,7 @@ import cn.hutool.core.date.DatePattern; import cn.hutool.core.date.DateUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.IdUtil; +import com.youlai.boot.common.util.HashUtils; import com.youlai.boot.support.file.model.FileInfo; import com.youlai.boot.support.file.service.FileService; import lombok.Data; @@ -48,6 +49,18 @@ public class LocalFileServiceImpl implements FileService { String fileName = IdUtil.simpleUUID() + "." + suffix; String folder = DateUtil.format(LocalDateTime.now(), DatePattern.PURE_DATE_PATTERN); String filePrefix = path.endsWith(File.separator) ? path : path + File.separator; + // 计算文件哈希(md5/sha1/sha256) + String md5; + String sha1; + String sha256; + try { + md5 = HashUtils.calculateMultipartFileMd5(file); + sha1 = HashUtils.calculateMultipartFileSha1(file); + sha256 = HashUtils.calculateMultipartFileSha256(file); + } catch (Exception e) { + log.error("计算文件哈希失败", e); + throw new RuntimeException("文件上传失败"); + } try (InputStream inputStream = file.getInputStream()) { FileUtil.writeFromStream(inputStream, filePrefix + folder + File.separator + fileName); } catch (Exception e) { @@ -58,6 +71,9 @@ public class LocalFileServiceImpl implements FileService { FileInfo fileInfo = new FileInfo(); fileInfo.setName(originalFilename); fileInfo.setUrl(fileUrl); + fileInfo.setMd5(md5); + fileInfo.setSha1(sha1); + fileInfo.setSha256(sha256); return fileInfo; } diff --git a/src/main/java/com/youlai/boot/support/file/service/impl/MinioFileServiceImpl.java b/src/main/java/com/youlai/boot/support/file/service/impl/MinioFileServiceImpl.java index 072a1d81..440cf1b8 100644 --- a/src/main/java/com/youlai/boot/support/file/service/impl/MinioFileServiceImpl.java +++ b/src/main/java/com/youlai/boot/support/file/service/impl/MinioFileServiceImpl.java @@ -7,6 +7,7 @@ import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.StrUtil; import com.youlai.boot.common.exception.BusinessException; import com.youlai.boot.common.result.ResultCode; +import com.youlai.boot.common.util.HashUtils; import com.youlai.boot.support.file.model.FileInfo; import com.youlai.boot.support.file.service.FileService; import io.minio.*; @@ -74,6 +75,19 @@ public class MinioFileServiceImpl implements FileService { String dateFolder = DateUtil.format(LocalDateTime.now(), "yyyyMMdd"); String fileName = IdUtil.simpleUUID() + "." + suffix; + // 计算文件哈希(md5/sha1/sha256) + String md5; + String sha1; + String sha256; + try { + md5 = HashUtils.calculateMultipartFileMd5(file); + sha1 = HashUtils.calculateMultipartFileSha1(file); + sha256 = HashUtils.calculateMultipartFileSha256(file); + } catch (Exception e) { + log.error("计算文件哈希失败", e); + throw new BusinessException(ResultCode.UPLOAD_FILE_EXCEPTION, e.getMessage()); + } + try (InputStream inputStream = file.getInputStream()) { PutObjectArgs putObjectArgs = PutObjectArgs.builder() .bucket(bucket) @@ -99,6 +113,9 @@ public class MinioFileServiceImpl implements FileService { FileInfo fileInfo = new FileInfo(); fileInfo.setName(originalFilename); fileInfo.setUrl(fileUrl); + fileInfo.setMd5(md5); + fileInfo.setSha1(sha1); + fileInfo.setSha256(sha256); return fileInfo; } catch (Exception e) { log.error("上传文件失败", e);