Merge branch 'feature_lsl' of gitee.com:L-Shilin/go-fly-platform-services into feature_dzc

This commit is contained in:
2025-10-10 15:49:54 +08:00
6 changed files with 238 additions and 33 deletions
+74
View File
@@ -137,6 +137,80 @@ stateDiagram-v2
### 4. 关键接口设计 ### 4. 关键接口设计
#### 4.0 获取访问Token(OAuth2)
**接口地址:** `POST /api-uaa/oauth/token`
**认证方式:** HTTP Basic(`Authorization: Basic base64(clientId:clientSecret)`)
**请求头:**
- `Authorization: Basic {base64(clientId:clientSecret)}`
- `Content-Type: application/x-www-form-urlencoded`
**授权模式与参数:**
- 密码验证码模式(推荐)
- `grant_type=password_code`
- `username` 用户名
- `password` 密码
- `validCode` 校验码(图形/短信)
- `deviceId` 设备ID(可用于风控)
- 密码模式
- `grant_type=password`
- `username`
- `password`
- 客户端模式(服务器到服务器)
- `grant_type=client_credentials`
- 刷新令牌
- `grant_type=refresh_token`
- `refresh_token` 刷新令牌
**响应示例:**
```json
{
"access_token": "eyJraWQiOi...",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "def50200...",
"scope": "all openid profile"
}
```
**调用示例:**
- 密码验证码模式
```bash
curl -X POST 'https://{gateway}/api-uaa/oauth/token' \
-H 'Authorization: Basic {base64(clientId:clientSecret)}' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'grant_type=password_code&username=admin&password=123456&validCode=abcd&deviceId=web'
```
- 密码模式
```bash
curl -X POST 'https://{gateway}/api-uaa/oauth/token' \
-H 'Authorization: Basic {base64(clientId:clientSecret)}' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'grant_type=password&username=admin&password=123456'
```
- 客户端模式
```bash
curl -X POST 'https://{gateway}/api-uaa/oauth/token' \
-H 'Authorization: Basic {base64(clientId:clientSecret)}' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'grant_type=client_credentials'
```
- 刷新令牌
```bash
curl -X POST 'https://{gateway}/api-uaa/oauth/token' \
-H 'Authorization: Basic {base64(clientId:clientSecret)}' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'grant_type=refresh_token&refresh_token={refresh_token}'
```
> 说明:可用客户端在 `oauth_client_details` 管理(如 `webApp`、`app`、`zlt` 等示例);令牌类型支持不透明令牌与JWT,网关域名与前缀以实际环境为准。
#### 4.1 设备执行任务API #### 4.1 设备执行任务API
**接口地址:** `POST /api-device/execute/task` **接口地址:** `POST /api-device/execute/task`
@@ -20,6 +20,7 @@ import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@@ -27,6 +28,7 @@ import org.springframework.web.bind.annotation.*;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit;
/** /**
* 设备操作controller * 设备操作controller
@@ -47,6 +49,9 @@ public class ApiDeviceController {
@Autowired @Autowired
private RequestUtils requestUtils; private RequestUtils requestUtils;
@Autowired
private StringRedisTemplate redisTemplate;
private ControlMessageConstant controlMessageConstant = new ControlMessageConstant(); private ControlMessageConstant controlMessageConstant = new ControlMessageConstant();
@Autowired @Autowired
@@ -86,23 +91,36 @@ public class ApiDeviceController {
return Result.failed("参数错误"); return Result.failed("参数错误");
} }
// 2. 检查订单状态 // 2. 幂等性检查
String idempotencyKey = generateIdempotencyKey(deviceId, orderNo, control);
log.info("生成幂等性key: deviceId={}, orderNo={}, control={}, key={}", deviceId, orderNo, control, idempotencyKey);
if (isRequestProcessed(idempotencyKey)) {
log.info("检测到重复请求,返回幂等性响应: deviceId={}, orderNo={}, control={}", deviceId, orderNo, control);
return Result.succeed("请求已处理,请勿重复操作");
}
// 3. 立即标记请求已处理(防止并发请求)
markRequestAsProcessed(idempotencyKey);
log.info("幂等性检查通过,立即标记请求已处理: deviceId={}, orderNo={}, control={}", deviceId, orderNo, control);
// 4. 检查订单状态
String orderStatus = orderCenterService.getOrderStatusByOrderNo(orderNo); String orderStatus = orderCenterService.getOrderStatusByOrderNo(orderNo);
if (!isValidOrderStatus(orderStatus)) { if (!isValidOrderStatus(orderStatus)) {
return Result.failed("设备已处理,请关注订单详情"); return Result.failed("设备已处理,请关注订单详情");
} }
// 3. 构建控制消息 // 5. 构建控制消息
JsonObject controlMessage = buildControlMessage(control, orderNo, deviceId); JsonObject controlMessage = buildControlMessage(control, orderNo, deviceId);
if (controlMessage == null) { if (controlMessage == null) {
return Result.failed("暂未开放控制权限"); return Result.failed("暂未开放控制权限");
} }
// 4. 发送设备控制请求 // 6. 发送设备控制请求
String url = baseUrl + "/device/instance/" + deviceId + "/property"; String url = baseUrl + "/device/instance/" + deviceId + "/property";
Map<String, String> result = requestUtils.getPostRequestResultMap(url, controlMessage.toString()); Map<String, String> result = requestUtils.getPostRequestResultMap(url, controlMessage.toString());
// 5. 处理响应结果 // 7. 处理响应结果
return handleDeviceResponse(result, orderNo); return handleDeviceResponse(result, orderNo);
} catch (Exception e) { } catch (Exception e) {
@@ -305,4 +323,47 @@ public class ApiDeviceController {
return jsonObject; return jsonObject;
} }
/**
* 生成幂等性key
*/
private String generateIdempotencyKey(String deviceId, String orderNo, String control) {
return String.format("device:writeProperties:%s:%s:%s", deviceId, orderNo, control);
}
/**
* 检查请求是否已处理
*/
private boolean isRequestProcessed(String idempotencyKey) {
try {
Boolean hasKey = redisTemplate.hasKey(idempotencyKey);
log.info("检查幂等性key: key={}, hasKey={}", idempotencyKey, hasKey);
if (hasKey != null && hasKey) {
// 获取key的值进行额外验证
String value = redisTemplate.opsForValue().get(idempotencyKey);
log.info("幂等性key已存在: key={}, value={}", idempotencyKey, value);
return true;
}
log.info("幂等性key不存在: key={}", idempotencyKey);
return false;
} catch (Exception e) {
log.error("检查幂等性key异常: key={}, error={}", idempotencyKey, e.getMessage(), e);
return false; // Redis异常时不阻止请求
}
}
/**
* 标记请求已处理
*/
private void markRequestAsProcessed(String idempotencyKey) {
try {
// 设置5分钟过期时间,防止Redis内存占用过多
redisTemplate.opsForValue().set(idempotencyKey, "processed", 5, TimeUnit.MINUTES);
log.info("标记请求已处理: key={}", idempotencyKey);
} catch (Exception e) {
log.error("标记幂等性key异常: key={}, error={}", idempotencyKey, e.getMessage(), e);
}
}
} }
@@ -22,6 +22,9 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@@ -40,6 +43,8 @@ import java.util.Map;
@RequiredArgsConstructor @RequiredArgsConstructor
public class OrderFileController { public class OrderFileController {
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
@Autowired @Autowired
private IOrderFileService orderFileService; private IOrderFileService orderFileService;
@@ -256,6 +261,7 @@ public class OrderFileController {
/** /**
* 检查素材数量是否达到二维码要求,如果达到则更新订单状态为UPLOADED * 检查素材数量是否达到二维码要求,如果达到则更新订单状态为UPLOADED
* 并在7分钟后若仍为UPLOADED则自动更新为COMPLETE
* @param order 订单信息 * @param order 订单信息
*/ */
private void checkAndUpdateOrderStatus(Order order) { private void checkAndUpdateOrderStatus(Order order) {
@@ -274,28 +280,43 @@ public class OrderFileController {
log.info("检查素材数量,订单号: {}, 二维码要求数量: {}, 当前上传数量: {}", log.info("检查素材数量,订单号: {}, 二维码要求数量: {}, 当前上传数量: {}",
order.getOrderNo(), qrCode.getMaterialCount(), currentFileCount); order.getOrderNo(), qrCode.getMaterialCount(), currentFileCount);
// 如果当前文件数量达到或超过二维码要求的数量,则更新订单状态为素材上传完成 // 如果当前文件数量达到或超过二维码要求的数量,则更新订单状态为素材上传完成(UPLOADED)
if (currentFileCount >= qrCode.getMaterialCount()) { if (currentFileCount >= qrCode.getMaterialCount()) {
// 并发场景下,实时查询最新订单状态再做判断
Order latestOrder = orderService.getOrderByNumber(order.getOrderNo());
if (latestOrder == null) {
log.warn("达到素材数量阈值时订单不存在: orderNo={}", order.getOrderNo());
return;
}
Tourism tourism = tourismService.getTourismById(qrCode.getTourismId()); Tourism tourism = tourismService.getTourismById(qrCode.getTourismId());
// 自动更新订单状态为设备执行完成 boolean isComplete = OrderStatus.COMPLETE.getId().equals(latestOrder.getOrderStatus());
if (!OrderStatus.COMPLETE.getId().equals(order.getOrderStatus())) {
order.setOrderStatus(OrderStatus.COMPLETE.getId()); // 更新订单状态为UPLOADED(素材上传完成),但若已为COMPLETE则不更新
boolean updateResult = orderService.updateOrder(order); if (!isComplete && !OrderStatus.UPLOADED.getId().equals(latestOrder.getOrderStatus())) {
Integer oldStatus = latestOrder.getOrderStatus();
latestOrder.setOrderStatus(OrderStatus.UPLOADED.getId());
boolean updateResult = orderService.updateOrder(latestOrder);
if (updateResult) { if (updateResult) {
log.info("订单状态已自动更新为设备执行完成: orderNo={}, oldStatus={}, newStatus={}", log.info("订单状态已更新为UPLOADED: orderNo={}, oldStatus={}, newStatus={}",
order.getOrderNo(), order.getOrderStatus(), OrderStatus.COMPLETE.getId()); latestOrder.getOrderNo(), oldStatus, OrderStatus.UPLOADED.getId());
} else { } else {
log.error("订单状态更新失败: orderNo={}", order.getOrderNo()); log.error("订单状态更新为UPLOADED失败: orderNo={}", latestOrder.getOrderNo());
} }
} }
//发送用户素材上传成功通知 //发送用户素材上传成功通知
sendMessageForResouresUploaded(order,tourism); sendMessageForResouresUploaded(latestOrder,tourism);
// 预热订单相关的文件到CDN // 预热订单相关的文件到CDN
prefetchOrderFilesToCdn(order.getOrderNo()); prefetchOrderFilesToCdn(latestOrder.getOrderNo());
// 7分钟后如果状态仍为UPLOADED,则自动更新为COMPLETE;若已完成则不再安排
if (!isComplete) {
scheduleAutoCompleteIfStillUploaded(latestOrder.getOrderNo());
}
// 检查是否开启一键成片功能 // 检查是否开启一键成片功能
if (isVideoEditEnabled(qrCode)) { if (isVideoEditEnabled(qrCode)) {
@@ -303,30 +324,30 @@ public class OrderFileController {
order.getOrderNo(), order.getCodeId()); order.getOrderNo(), order.getCodeId());
// 检查是否存在进行中的编辑任务 // 检查是否存在进行中的编辑任务
EditTask existingTask = editTaskService.getTaskByOrderSn(order.getOrderNo()); EditTask existingTask = editTaskService.getTaskByOrderSn(latestOrder.getOrderNo());
if (existingTask != null && EditTaskStatus.isProcessing(existingTask.getStatus())) { if (existingTask != null && EditTaskStatus.isProcessing(existingTask.getStatus())) {
log.info("已存在进行中的编辑任务: orderNo={}, taskId={}", order.getOrderNo(), existingTask.getId()); log.info("已存在进行中的编辑任务: orderNo={}, taskId={}", latestOrder.getOrderNo(), existingTask.getId());
return ; return ;
} }
//触发一键成片 //触发一键成片
// 1. 创建新任务 // 1. 创建新任务
EditTask task = editTaskService.createTask(order.getOrderNo(), order.getUserId()); EditTask task = editTaskService.createTask(latestOrder.getOrderNo(), latestOrder.getUserId());
// 2. 获取素材文件 // 2. 获取素材文件
List<OrderFile> orderFiles = orderFileService.getOrderFileByOrderNo(order.getOrderNo()); List<OrderFile> orderFiles = orderFileService.getOrderFileByOrderNo(latestOrder.getOrderNo());
// 3. 提交编辑任务 // 3. 提交编辑任务
String jobId = videoEditService.submitEditTask(order.getOrderNo(), orderFiles); String jobId = videoEditService.submitEditTask(latestOrder.getOrderNo(), orderFiles);
log.info("提交一键成片任务成功: orderNo={}, jobId={}, totalMediaFiles={}", log.info("提交一键成片任务成功: orderNo={}, jobId={}, totalMediaFiles={}",
order.getOrderNo(), jobId, orderFiles.size()); latestOrder.getOrderNo(), jobId, orderFiles.size());
// 4. 更新任务信息 // 4. 更新任务信息
task.setJobId(jobId); task.setJobId(jobId);
task.setStatus(EditTaskStatus.PROCESSING); task.setStatus(EditTaskStatus.PROCESSING);
editTaskService.saveOrUpdateTask(task); editTaskService.saveOrUpdateTask(task);
} else { } else {
log.info("二维码未开启一键成片功能,跳过一键成片: orderNo={}, codeId={}, enableVideoEdit={}", log.info("二维码未开启一键成片功能,跳过一键成片: orderNo={}, codeId={}, enableVideoEdit={}",
order.getOrderNo(), order.getCodeId(), qrCode.getEnableVideoEdit()); latestOrder.getOrderNo(), latestOrder.getCodeId(), qrCode.getEnableVideoEdit());
} }
} }
} catch (Exception e) { } catch (Exception e) {
@@ -334,6 +355,41 @@ public class OrderFileController {
} }
} }
/**
* 7分钟后检查订单状态是否仍为UPLOADED,如是则自动置为COMPLETE
*/
private void scheduleAutoCompleteIfStillUploaded(String orderNo) {
try {
scheduler.schedule(() -> {
try {
Order latest = orderService.getOrderByNumber(orderNo);
if (latest == null) {
log.warn("延迟完成检查时订单不存在: orderNo={}", orderNo);
return;
}
if (OrderStatus.UPLOADED.getId().equals(latest.getOrderStatus())) {
Integer oldStatus = latest.getOrderStatus();
latest.setOrderStatus(OrderStatus.COMPLETE.getId());
boolean updated = orderService.updateOrder(latest);
if (updated) {
log.info("订单状态在7分钟后自动由UPLOADED更新为COMPLETE: orderNo={}, oldStatus={}, newStatus={}",
orderNo, oldStatus, OrderStatus.COMPLETE.getId());
} else {
log.error("订单状态在7分钟后自动更新为COMPLETE失败: orderNo={}", orderNo);
}
} else {
log.info("订单状态在7分钟后已非UPLOADED,跳过自动完成: orderNo={}, currentStatus={}",
orderNo, latest.getOrderStatus());
}
} catch (Exception e) {
log.error("订单状态7分钟后自动完成检查异常: orderNo={}", orderNo, e);
}
}, 7, TimeUnit.MINUTES);
} catch (Exception e) {
log.error("安排订单状态自动完成任务失败: orderNo={}", orderNo, e);
}
}
/** /**
* 检查是否开启一键成片功能 * 检查是否开启一键成片功能
*/ */
@@ -38,7 +38,7 @@ public class Order extends SuperEntity {
@Schema(description = "订单状态") @Schema(description = "订单状态")
private Integer orderStatus; private Integer orderStatus;
@Schema(description = "支付类型(1:微信支付,2:优惠券支付)") @Schema(description = "支付类型(1:微信支付,2:优惠券支付, 3: 第三方聚到核销)")
private Integer payType; private Integer payType;
private Date payTime; private Date payTime;
@@ -131,7 +131,7 @@ public class MediaServiceImpl implements IMediaService {
// 3. 获取视频文件 // 3. 获取视频文件
// List<OrderFile> videoFiles = orderFileService.getOrderVideoFiles(orderNo); // List<OrderFile> videoFiles = orderFileService.getOrderVideoFiles(orderNo);
if (orderFiles == null || orderFiles.size() < 7) { if (orderFiles == null || orderFiles.size() < qrCode.getMaterialCount()) {
throw new BusinessException("订单视频文件数量不足,至少需要2个视频文件"); throw new BusinessException("订单视频文件数量不足,至少需要2个视频文件");
} }
@@ -188,16 +188,17 @@ public class MediaServiceImpl implements IMediaService {
List<OrderFile> videoFiles = taskData.getVideoFiles(); List<OrderFile> videoFiles = taskData.getVideoFiles();
//@TODO 后期需要通过模板参数进行动态设置clips参数 //@TODO 后期需要通过模板参数进行动态设置clips参数
clips.put("1", fileCenterService.getViewUrlByPath(videoFiles.get(4).getFilePath())); // 保持既有模板顺序;当索引越界或无素材时返回空URL
clips.put("2", fileCenterService.getViewUrlByPath(videoFiles.get(5).getFilePath())); clips.put("1", getUrlBySafeIndex(videoFiles, 4));
clips.put("3", fileCenterService.getViewUrlByPath(videoFiles.get(6).getFilePath())); clips.put("2", getUrlBySafeIndex(videoFiles, 5));
clips.put("4", fileCenterService.getViewUrlByPath(videoFiles.get(0).getFilePath())); clips.put("3", getUrlBySafeIndex(videoFiles, 6));
clips.put("5", fileCenterService.getViewUrlByPath(videoFiles.get(1).getFilePath())); clips.put("4", getUrlBySafeIndex(videoFiles, 0));
clips.put("6", fileCenterService.getViewUrlByPath(videoFiles.get(2).getFilePath())); clips.put("5", getUrlBySafeIndex(videoFiles, 1));
clips.put("7", fileCenterService.getViewUrlByPath(videoFiles.get(3).getFilePath())); clips.put("6", getUrlBySafeIndex(videoFiles, 2));
clips.put("7", getUrlBySafeIndex(videoFiles, 3));
if (taskData.getVideoFiles().size() > 7) { if (videoFiles != null && videoFiles.size() > 7) {
clips.put("8", fileCenterService.getViewUrlByPath(videoFiles.get(7).getFilePath())); clips.put("8", getUrlBySafeIndex(videoFiles, 7));
} }
return JSON.toJSONString(clips); return JSON.toJSONString(clips);
@@ -206,6 +207,14 @@ public class MediaServiceImpl implements IMediaService {
} }
} }
private String getUrlBySafeIndex(List<OrderFile> videoFiles, int index) {
int size = (videoFiles == null) ? 0 : videoFiles.size();
if (size == 0 || index < 0 || index >= size) {
return "";
}
return fileCenterService.getViewUrlByPath(videoFiles.get(index).getFilePath());
}
/** /**
* 构建输出配置 * 构建输出配置
*/ */
@@ -103,7 +103,12 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
// 创建订单,初始状态为"待支付" // 创建订单,初始状态为"待支付"
@Override @Override
public boolean createOrder(Order order) { public boolean createOrder(Order order) {
order.setOrderStatus(OrderStatus.UNPAID.getId()); // payType=3 视为已支付,否则为待支付
if (order.getPayType() != null && order.getPayType() == 3) {
order.setOrderStatus(OrderStatus.PAID.getId());
} else {
order.setOrderStatus(OrderStatus.UNPAID.getId());
}
String orderNo = generateOrderNumber(order.getTourismId()); String orderNo = generateOrderNumber(order.getTourismId());
order.setOrderNo(orderNo); order.setOrderNo(orderNo);