Просмотр исходного кода

feat(video): 驾驶舱历史录像查询与匿名回放接口

Kazerin 3 недель назад
Родитель
Сommit
541ea8366d

+ 28 - 0
pipe-network-service/zksy-admin/src/main/java/com/zksy/web/controller/cockpit/CockpitVideoController.java

@@ -48,6 +48,22 @@ public class CockpitVideoController {
         return success(videos.startPrepared(sessionId(id), field(body, "sessionToken")), request);
         return success(videos.startPrepared(sessionId(id), field(body, "sessionToken")), request);
     }
     }
 
 
+    /** Existing device/NVR recordings for one bounded UTC+8 window. */
+    @GetMapping("/records")
+    public ResponseEntity<AjaxResult> records(@RequestParam("deviceCode") String code,
+            @RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime,
+            HttpServletRequest request) {
+        return success(videos.records(code, startTime, endTime), request);
+    }
+
+    /** Starts one anonymous playback session over an already-listed recording window. */
+    @PostMapping("/playback")
+    public ResponseEntity<AjaxResult> playback(@RequestBody Map<String, Object> body, HttpServletRequest request) {
+        Map<String, String> input = fields(body, "deviceCode", "startTime", "endTime");
+        return success(videos.playback(input.get("deviceCode"), input.get("startTime"),
+                input.get("endTime")), request);
+    }
+
     @PostMapping("/sessions/{id}/status")
     @PostMapping("/sessions/{id}/status")
     public ResponseEntity<AjaxResult> sessionStatus(@PathVariable("id") String id,
     public ResponseEntity<AjaxResult> sessionStatus(@PathVariable("id") String id,
             @RequestBody Map<String, Object> body, HttpServletRequest request) {
             @RequestBody Map<String, Object> body, HttpServletRequest request) {
@@ -78,6 +94,18 @@ public class CockpitVideoController {
         return (String) body.get(field);
         return (String) body.get(field);
     }
     }
 
 
+    /** A playback request carries three required strings and nothing else. */
+    private static Map<String, String> fields(Map<String, Object> body, String... names) {
+        if (body == null || body.size() != names.length)
+            throw new CockpitVideoException(400, "INVALID_REQUEST", "视频请求参数无效");
+        Map<String, String> values = new java.util.LinkedHashMap<>();
+        for (String name : names) {
+            if (!(body.get(name) instanceof String)) throw new CockpitVideoException(400, "INVALID_REQUEST", "视频请求参数无效");
+            values.put(name, (String) body.get(name));
+        }
+        return values;
+    }
+
     @ExceptionHandler({org.springframework.http.converter.HttpMessageNotReadableException.class,
     @ExceptionHandler({org.springframework.http.converter.HttpMessageNotReadableException.class,
             org.springframework.web.bind.MissingServletRequestParameterException.class,
             org.springframework.web.bind.MissingServletRequestParameterException.class,
             org.springframework.web.method.annotation.MethodArgumentTypeMismatchException.class})
             org.springframework.web.method.annotation.MethodArgumentTypeMismatchException.class})

+ 75 - 5
pipe-network-service/zksy-admin/src/test/java/com/zksy/web/controller/cockpit/CockpitVideoControllerTest.java

@@ -61,6 +61,7 @@ import java.util.concurrent.ConcurrentHashMap;
 
 
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.*;
 import static org.mockito.Mockito.*;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@@ -139,6 +140,74 @@ class CockpitVideoControllerTest {
         SecurityContextHolder.clearContext();
         SecurityContextHolder.clearContext();
     }
     }
 
 
+    private static final String RECORD_QUERY = "/api/gb_record/query";
+
+    @Test
+    void anonymousHistoryListsOnlyRealReturnedRecordingsForTheRequestedWindow() throws Exception {
+        when(collector.get(RECORD_QUERY, Map.of("deviceId", GB, "channelId", CHANNEL,
+                "startTime", "2026-11-10 00:00:00", "endTime", "2026-11-10 12:00:00", "type", "all")))
+                .thenReturn(Map.of("recordList", List.of(Map.of("name", "通道01", "startTime", "2026-11-10 01:00:00",
+                        "endTime", "2026-11-10 02:00:00", "type", "time"))));
+        mvc.perform(get(ROOT + "/records").param("deviceCode", CODE)
+                        .param("startTime", "2026-11-10 00:00:00").param("endTime", "2026-11-10 12:00:00"))
+                .andExpect(status().isOk()).andExpect(jsonPath("$.code").value(200))
+                .andExpect(jsonPath("$.data.deviceCode").value(CODE))
+                .andExpect(jsonPath("$.data.empty").value(false))
+                .andExpect(jsonPath("$.data.records[0].name").value("通道01"))
+                .andExpect(jsonPath("$.data.records[0].startTime").value("2026-11-10 01:00:00"))
+                .andExpect(jsonPath("$.data.records[0].endTime").value("2026-11-10 02:00:00"));
+    }
+
+    @Test
+    void emptyRecordingWindowIsAnAnswerNotAFailure() throws Exception {
+        when(collector.get(RECORD_QUERY, Map.of("deviceId", GB, "channelId", CHANNEL,
+                "startTime", "2026-11-10 00:00:00", "endTime", "2026-11-10 12:00:00", "type", "all")))
+                .thenReturn(Map.of("recordList", List.of()));
+        mvc.perform(get(ROOT + "/records").param("deviceCode", CODE)
+                        .param("startTime", "2026-11-10 00:00:00").param("endTime", "2026-11-10 12:00:00"))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.empty").value(true))
+                .andExpect(jsonPath("$.data.records").isEmpty());
+    }
+
+    @Test
+    void recordingRangeOverSevenDaysIsRejectedBeforeTouchingTheDevice() throws Exception {
+        mvc.perform(get(ROOT + "/records").param("deviceCode", CODE)
+                        .param("startTime", "2026-11-01 00:00:00").param("endTime", "2026-11-10 00:00:00"))
+                .andExpect(status().isBadRequest())
+                .andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"));
+    }
+
+    @Test
+    void playbackReusesTheAnonymousSeamAndPublishesOnlyTheReturnedMedia() throws Exception {
+        when(collector.get(eq("/api/playback/start"), any())).thenReturn(Map.of("stream", "stream_pb", "native", true,
+                "rtcs", "https://media.invalid/index/api/webrtc?app=rtp&stream=stream_pb&type=play",
+                "flv", "https://media.invalid/pb.flv", "secret", "internal-secret", "proxyKey", "internal-key"));
+        mvc.perform(post(ROOT + "/playback").contentType(MediaType.APPLICATION_JSON)
+                        .content(JSON.toJSONString(Map.of("deviceCode", CODE,
+                                "startTime", "2026-11-10 01:00:00", "endTime", "2026-11-10 02:00:00"))))
+                .andExpect(status().isOk())
+                .andExpect(jsonPath("$.data.mode").value("PLAYBACK"))
+                .andExpect(jsonPath("$.data.startTime").value("2026-11-10 01:00:00"))
+                .andExpect(jsonPath("$.data.sessionToken").isNotEmpty())
+                .andExpect(jsonPath("$.data.media.webrtc").exists())
+                .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("internal-key"))));
+    }
+
+    @Test
+    void aBusyChannelReportsOccupancyInsteadOfStoppingTheExistingPlayback() throws Exception {
+        // The single-active-playback rule is enforced by the reused session store, not by the media adapter.
+        when(sessions.selectCount(any())).thenReturn(1L);
+        mvc.perform(post(ROOT + "/playback").contentType(MediaType.APPLICATION_JSON)
+                        .content(JSON.toJSONString(Map.of("deviceCode", CODE,
+                                "startTime", "2026-11-10 01:00:00", "endTime", "2026-11-10 02:00:00"))))
+                .andExpect(status().isConflict())
+                .andExpect(jsonPath("$.data.category").value("PLAYBACK_OCCUPIED"));
+        // Never stop somebody else's playback just because this request lost the race.
+        verify(collector, never()).get(STOP, Map.of());
+        verify(collector, never()).get(eq("/api/playback/start"), any());
+    }
+
     @Test
     @Test
     void anonymousDeviceLookupKeepsExactBusinessCodeAndPublishesOnlyConfirmedLiveCapability() throws Exception {
     void anonymousDeviceLookupKeepsExactBusinessCodeAndPublishesOnlyConfirmedLiveCapability() throws Exception {
         mvc.perform(get(ROOT + "/device").param("deviceCode", CODE).header("X-Request-Id", "video-lookup-1"))
         mvc.perform(get(ROOT + "/device").param("deviceCode", CODE).header("X-Request-Id", "video-lookup-1"))
@@ -148,8 +217,9 @@ class CockpitVideoControllerTest {
                 .andExpect(jsonPath("$.data.typeCode").value("20"))
                 .andExpect(jsonPath("$.data.typeCode").value("20"))
                 .andExpect(jsonPath("$.data.bound").value(true))
                 .andExpect(jsonPath("$.data.bound").value(true))
                 .andExpect(jsonPath("$.data.capabilities.live").value(true))
                 .andExpect(jsonPath("$.data.capabilities.live").value(true))
-                .andExpect(jsonPath("$.data.capabilities.records").value(false))
-                .andExpect(jsonPath("$.data.capabilities.playback").value(false))
+                // Records and playback follow the GB28181 binding; control stays grey until a real device confirms it.
+                .andExpect(jsonPath("$.data.capabilities.records").value(true))
+                .andExpect(jsonPath("$.data.capabilities.playback").value(true))
                 .andExpect(jsonPath("$.data.capabilities.playbackControl").value(false))
                 .andExpect(jsonPath("$.data.capabilities.playbackControl").value(false))
                 .andExpect(jsonPath("$.data.capabilities.ptz").value(false))
                 .andExpect(jsonPath("$.data.capabilities.ptz").value(false))
                 .andExpect(jsonPath("$.data.capabilities.ptzStopGuaranteed").value(false))
                 .andExpect(jsonPath("$.data.capabilities.ptzStopGuaranteed").value(false))
@@ -197,10 +267,10 @@ class CockpitVideoControllerTest {
 
 
     @ParameterizedTest
     @ParameterizedTest
     @CsvSource({"GET,/live", "GET,/sessions/example/stop", "GET,/sessions/example/heartbeat",
     @CsvSource({"GET,/live", "GET,/sessions/example/stop", "GET,/sessions/example/heartbeat",
-            "GET,/devices/remove", "GET,/records", "POST,/device", "PUT,/live", "DELETE,/live",
-            "POST,/sessions/example/control", "POST,/ptz", "POST,/playback", "POST,/devices",
+            "GET,/devices/remove", "GET,/record", "POST,/device", "PUT,/live", "DELETE,/live",
+            "POST,/sessions/example/control", "POST,/ptz", "POST,/playback/control", "POST,/devices",
             "POST,/sessions/example/nested/stop", "POST,/live/nested"})
             "POST,/sessions/example/nested/stop", "POST,/live/nested"})
-    void onlyTheFourPublishedMethodAndPathPairsAreAnonymous(String method, String path) throws Exception {
+    void onlyTheSixPublishedMethodAndPathPairsAreAnonymous(String method, String path) throws Exception {
         mvc.perform(request(org.springframework.http.HttpMethod.valueOf(method), ROOT + path))
         mvc.perform(request(org.springframework.http.HttpMethod.valueOf(method), ROOT + path))
                 .andExpect(status().isUnauthorized()).andExpect(jsonPath("$.code").value(401));
                 .andExpect(status().isUnauthorized()).andExpect(jsonPath("$.code").value(401));
         verifyNoInteractions(devices, bindings, sessions, collector);
         verifyNoInteractions(devices, bindings, sessions, collector);

+ 3 - 1
pipe-network-service/zksy-framework/src/main/java/com/zksy/framework/config/SecurityConfig.java

@@ -123,8 +123,10 @@ public class SecurityConfig
             // 注解标记允许匿名访问的url
             // 注解标记允许匿名访问的url
             .authorizeHttpRequests((requests) -> {
             .authorizeHttpRequests((requests) -> {
                 // Video is a narrow anonymous exception, before any broad GET/annotation rule.
                 // Video is a narrow anonymous exception, before any broad GET/annotation rule.
-                requests.antMatchers(HttpMethod.GET, "/api/cockpit/v1/video/device").permitAll()
+                requests.antMatchers(HttpMethod.GET, "/api/cockpit/v1/video/device",
+                        "/api/cockpit/v1/video/records").permitAll()
                     .antMatchers(HttpMethod.POST, "/api/cockpit/v1/video/live",
                     .antMatchers(HttpMethod.POST, "/api/cockpit/v1/video/live",
+                        "/api/cockpit/v1/video/playback",
                         "/api/cockpit/v1/video/sessions/prepare",
                         "/api/cockpit/v1/video/sessions/prepare",
                         "/api/cockpit/v1/video/sessions/*/live",
                         "/api/cockpit/v1/video/sessions/*/live",
                         "/api/cockpit/v1/video/sessions/*/status",
                         "/api/cockpit/v1/video/sessions/*/status",

+ 109 - 1
pipe-network-service/zksy-system/src/main/java/com/zksy/cockpit/video/CockpitVideoService.java

@@ -6,9 +6,11 @@ import com.zksy.base.mapper.EquipmentBaseMapper;
 import com.zksy.base.mapper.EquipmentVideoBindingMapper;
 import com.zksy.base.mapper.EquipmentVideoBindingMapper;
 import com.zksy.base.video.VideoDeviceRecord;
 import com.zksy.base.video.VideoDeviceRecord;
 import com.zksy.base.video.VideoDeviceService;
 import com.zksy.base.video.VideoDeviceService;
+import com.zksy.base.video.VideoRequests;
 import com.zksy.common.exception.ServiceException;
 import com.zksy.common.exception.ServiceException;
 import org.springframework.stereotype.Service;
 import org.springframework.stereotype.Service;
 
 
+import java.util.ArrayList;
 import java.util.LinkedHashMap;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.List;
 import java.util.Map;
 import java.util.Map;
@@ -32,17 +34,123 @@ public class CockpitVideoService {
         VideoDeviceRecord binding = findBinding(device);
         VideoDeviceRecord binding = findBinding(device);
         boolean bound = binding != null;
         boolean bound = binding != null;
         boolean live = liveSupported(binding);
         boolean live = liveSupported(binding);
+        // Records and playback are properties of a GB28181-bound channel, not of the live probe.
+        boolean records = gbBound(binding);
         Map<String, Object> data = new LinkedHashMap<>();
         Map<String, Object> data = new LinkedHashMap<>();
         data.put("deviceCode", device.getEquipmentCode());
         data.put("deviceCode", device.getEquipmentCode());
         data.put("deviceName", device.getEquipmentName());
         data.put("deviceName", device.getEquipmentName());
         data.put("typeCode", device.getEquipmentTypeId() == null ? null : device.getEquipmentTypeId().toString());
         data.put("typeCode", device.getEquipmentTypeId() == null ? null : device.getEquipmentTypeId().toString());
         data.put("bound", bound);
         data.put("bound", bound);
-        data.put("capabilities", Map.of("live", live, "records", false, "playback", false,
+        // playbackControl stays false until a real device confirms pause/speed/seek support.
+        data.put("capabilities", Map.of("live", live, "records", records, "playback", records,
                 "playbackControl", false, "ptz", false, "ptzStopGuaranteed", false));
                 "playbackControl", false, "ptz", false, "ptzStopGuaranteed", false));
         data.put("unavailableReason", live ? null : "设备未绑定或实时视频能力未确认");
         data.put("unavailableReason", live ? null : "设备未绑定或实时视频能力未确认");
         return data;
         return data;
     }
     }
 
 
+    /** Existing device/NVR recordings in a bounded UTC+8 window; never invents a recording. */
+    public Map<String, Object> records(String code, String startTime, String endTime) {
+        EquipmentBase device = findDevice(code);
+        VideoDeviceRecord binding = findBinding(device);
+        if (!gbBound(binding))
+            throw new CockpitVideoException(409, "VIDEO_UNAVAILABLE", "设备未绑定国标通道,无法查询录像");
+        VideoRequests.Range range = range(startTime, endTime);
+        Object raw;
+        try {
+            raw = videos.records(device.getEquipmentId(), range);
+        } catch (RuntimeException failure) {
+            if (invalidRange(failure))
+                throw new CockpitVideoException(400, "INVALID_REQUEST", "录像时间格式为 yyyy-MM-dd HH:mm:ss,结束时间须晚于开始时间且范围不超过 7 天");
+            throw new CockpitVideoException(502, "VIDEO_READ_FAILED", "录像查询失败,请稍后重试");
+        }
+        List<Map<String, Object>> items = recordItems(raw);
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("deviceCode", device.getEquipmentCode());
+        data.put("deviceName", device.getEquipmentName());
+        data.put("startTime", range.getStartTime());
+        data.put("endTime", range.getEndTime());
+        data.put("records", items);
+        // An empty list is a legitimate answer, not a failure.
+        data.put("empty", items.isEmpty());
+        return data;
+    }
+
+    /** Starts an anonymous playback session over one already-listed recording window. */
+    public Map<String, Object> playback(String code, String startTime, String endTime) {
+        EquipmentBase device = findDevice(code);
+        VideoDeviceRecord binding = findBinding(device);
+        if (!gbBound(binding))
+            throw new CockpitVideoException(409, "VIDEO_UNAVAILABLE", "设备未绑定国标通道,无法回放录像");
+        VideoRequests.Range range = range(startTime, endTime);
+        Map<String, Object> started;
+        try {
+            started = videos.startAnonymous(device.getEquipmentId(), range);
+        } catch (RuntimeException failure) {
+            // A busy channel is an expected, distinguishable outcome, not a broken stream.
+            if (failure.getMessage() != null && failure.getMessage().contains("已有录像回放"))
+                throw new CockpitVideoException(409, "PLAYBACK_OCCUPIED", "此通道已有录像回放,请结束后重试");
+            if (invalidRange(failure))
+                throw new CockpitVideoException(400, "INVALID_REQUEST", "录像时间格式为 yyyy-MM-dd HH:mm:ss,结束时间须晚于开始时间且范围不超过 7 天");
+            throw new CockpitVideoException(502, "VIDEO_START_FAILED", "录像回放启动失败,请稍后重试");
+        }
+        Map<String, Object> media = CockpitVideoMedia.publish(started, binding);
+        if (media.isEmpty()) {
+            try {
+                videos.stop((String) started.get("sessionId"), (String) started.get("sessionToken"));
+            } catch (RuntimeException failure) {
+                throw new CockpitVideoException(503, "CLEANUP_UNCONFIRMED", "媒体不可用且清理未确认,请等待回收");
+            }
+            throw new CockpitVideoException(502, "VIDEO_START_FAILED", "未取得可公开播放的媒体地址");
+        }
+        Map<String, Object> data = new LinkedHashMap<>();
+        data.put("deviceCode", device.getEquipmentCode());
+        data.put("deviceName", device.getEquipmentName());
+        data.put("sessionId", started.get("sessionId"));
+        data.put("sessionToken", started.get("sessionToken"));
+        data.put("mode", "PLAYBACK");
+        data.put("startTime", range.getStartTime());
+        data.put("endTime", range.getEndTime());
+        data.put("media", media);
+        return data;
+    }
+
+    /** The window is validated by the reused service seam; this only shapes the request. */
+    private static VideoRequests.Range range(String startTime, String endTime) {
+        VideoRequests.Range range = new VideoRequests.Range();
+        range.setStartTime(startTime);
+        range.setEndTime(endTime);
+        return range;
+    }
+
+    /** Only existing device/NVR recordings are exposed; a stray payload never becomes a recording. */
+    private static List<Map<String, Object>> recordItems(Object raw) {
+        Object list = raw instanceof Map ? ((Map<?, ?>) raw).get("recordList") : raw;
+        if (!(list instanceof List)) return List.of();
+        List<Map<String, Object>> items = new ArrayList<>();
+        for (Object entry : (List<?>) list) {
+            if (!(entry instanceof Map)) continue;
+            Map<?, ?> row = (Map<?, ?>) entry;
+            Map<String, Object> item = new LinkedHashMap<>();
+            item.put("name", row.get("name"));
+            item.put("startTime", row.get("startTime"));
+            item.put("endTime", row.get("endTime"));
+            item.put("type", row.get("type"));
+            items.add(item);
+        }
+        return items;
+    }
+
+    /** Range validation is a caller error, not an upstream failure. */
+    private static boolean invalidRange(RuntimeException failure) {
+        String message = failure.getMessage();
+        return message != null && message.contains("录像时间格式为");
+    }
+
+    private static boolean gbBound(VideoDeviceRecord binding) {
+        return binding != null && "GB28181".equals(binding.getSourceType())
+                && gbId(binding.getGbDeviceId()) && gbId(binding.getGbChannelId());
+    }
+
     public Map<String, Object> live(String code) {
     public Map<String, Object> live(String code) {
         EquipmentBase device = findDevice(code);
         EquipmentBase device = findDevice(code);
         VideoDeviceRecord binding = findBinding(device);
         VideoDeviceRecord binding = findBinding(device);