|
@@ -15,6 +15,11 @@ import org.springframework.scheduling.annotation.EnableScheduling;
|
|
|
import org.springframework.scheduling.annotation.Scheduled;
|
|
import org.springframework.scheduling.annotation.Scheduled;
|
|
|
import org.springframework.stereotype.Service;
|
|
import org.springframework.stereotype.Service;
|
|
|
import org.springframework.transaction.annotation.Transactional;
|
|
import org.springframework.transaction.annotation.Transactional;
|
|
|
|
|
+import org.springframework.transaction.PlatformTransactionManager;
|
|
|
|
|
+import org.springframework.transaction.TransactionDefinition;
|
|
|
|
|
+import org.springframework.transaction.support.TransactionSynchronization;
|
|
|
|
|
+import org.springframework.transaction.support.TransactionSynchronizationManager;
|
|
|
|
|
+import org.springframework.transaction.support.TransactionTemplate;
|
|
|
import java.net.URI;
|
|
import java.net.URI;
|
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.nio.charset.StandardCharsets;
|
|
|
import java.security.MessageDigest;
|
|
import java.security.MessageDigest;
|
|
@@ -43,6 +48,13 @@ public class VideoDeviceService {
|
|
|
private final VideoSessionMapper sessions;
|
|
private final VideoSessionMapper sessions;
|
|
|
private final EquipmentBaseService equipmentService;
|
|
private final EquipmentBaseService equipmentService;
|
|
|
private final Clock clock;
|
|
private final Clock clock;
|
|
|
|
|
+ private TransactionTemplate rollbackCleanup;
|
|
|
|
|
+
|
|
|
|
|
+ @org.springframework.beans.factory.annotation.Autowired(required=false)
|
|
|
|
|
+ void configureRollbackCleanup(PlatformTransactionManager manager) {
|
|
|
|
|
+ rollbackCleanup=new TransactionTemplate(manager);
|
|
|
|
|
+ rollbackCleanup.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
|
|
|
|
+ }
|
|
|
|
|
|
|
|
@org.springframework.beans.factory.annotation.Autowired
|
|
@org.springframework.beans.factory.annotation.Autowired
|
|
|
public VideoDeviceService(EquipmentBaseMapper devices, VideoCollectorClient collector, VideoSessionMapper sessions, EquipmentBaseService equipmentService, EquipmentVideoBindingMapper bindings) {
|
|
public VideoDeviceService(EquipmentBaseMapper devices, VideoCollectorClient collector, VideoSessionMapper sessions, EquipmentBaseService equipmentService, EquipmentVideoBindingMapper bindings) {
|
|
@@ -167,21 +179,11 @@ public class VideoDeviceService {
|
|
|
String mode=range==null?"LIVE":"PLAYBACK";
|
|
String mode=range==null?"LIVE":"PLAYBACK";
|
|
|
// Capture under the video lock, before an insert error can abort the DB transaction.
|
|
// Capture under the video lock, before an insert error can abort the DB transaction.
|
|
|
long existingLive=range==null?activeLiveCount(id,null):0;
|
|
long existingLive=range==null?activeLiveCount(id,null):0;
|
|
|
- Object response;
|
|
|
|
|
if(range!=null) {
|
|
if(range!=null) {
|
|
|
requireGb(row);
|
|
requireGb(row);
|
|
|
validateRange(range);
|
|
validateRange(range);
|
|
|
if(sessions.selectCount(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getVideoId,id).eq(VideoSession::getMode,"PLAYBACK").eq(VideoSession::getStatus,"ACTIVE"))>0)throw new ServiceException("此通道已有录像回放,请结束后重试");
|
|
if(sessions.selectCount(new LambdaQueryWrapper<VideoSession>().eq(VideoSession::getVideoId,id).eq(VideoSession::getMode,"PLAYBACK").eq(VideoSession::getStatus,"ACTIVE"))>0)throw new ServiceException("此通道已有录像回放,请结束后重试");
|
|
|
- response=collector.get("/api/playback/start",rangeParams(row,range));
|
|
|
|
|
- }
|
|
|
|
|
- else if(GB28181.equals(row.getSourceType()))response=collector.get("/api/play/start/"+row.getGbDeviceId()+"/"+row.getGbChannelId(),Map.of());
|
|
|
|
|
- else {
|
|
|
|
|
- validateManualUrl(row.getVideoUrl());
|
|
|
|
|
- String scheme=URI.create(row.getVideoUrl()).getScheme().toLowerCase(Locale.ROOT);
|
|
|
|
|
- response=scheme.startsWith("rt")?collector.post("/internal/video/manual/start",Map.of("id",id,"url",row.getVideoUrl())):Map.of("url",row.getVideoUrl(),"native",true);
|
|
|
|
|
- }
|
|
|
|
|
- if(!(response instanceof Map))throw new ServiceException("媒体服务没有返回有效播放信息");
|
|
|
|
|
- Map<String,Object> data=new HashMap<>((Map<String,Object>)response);
|
|
|
|
|
|
|
+ } else if(!GB28181.equals(row.getSourceType()))validateManualUrl(row.getVideoUrl());
|
|
|
VideoSession session=new VideoSession();
|
|
VideoSession session=new VideoSession();
|
|
|
session.setSessionId(UUID.randomUUID().toString());
|
|
session.setSessionId(UUID.randomUUID().toString());
|
|
|
session.setVideoId(id);
|
|
session.setVideoId(id);
|
|
@@ -189,31 +191,79 @@ public class VideoDeviceService {
|
|
|
session.setAnonymousTokenHash(anonymousTokenHash);
|
|
session.setAnonymousTokenHash(anonymousTokenHash);
|
|
|
session.setMode(mode);
|
|
session.setMode(mode);
|
|
|
session.setStatus("ACTIVE");
|
|
session.setStatus("ACTIVE");
|
|
|
- session.setGbDeviceId(row.getGbDeviceId());
|
|
|
|
|
- session.setGbChannelId(row.getGbChannelId());
|
|
|
|
|
- session.setStreamId(data.get("stream") instanceof String?(String)data.get("stream"):null);
|
|
|
|
|
- Object proxyKey=data.remove("proxyKey");
|
|
|
|
|
- session.setProxyKey(proxyKey instanceof String?(String)proxyKey:null);
|
|
|
|
|
|
|
+ session.setGbDeviceId(GB28181.equals(row.getSourceType())?row.getGbDeviceId():null);
|
|
|
|
|
+ session.setGbChannelId(GB28181.equals(row.getSourceType())?row.getGbChannelId():null);
|
|
|
session.setCreateTime(LocalDateTime.now(clock));
|
|
session.setCreateTime(LocalDateTime.now(clock));
|
|
|
session.setLastSeen(session.getCreateTime());
|
|
session.setLastSeen(session.getCreateTime());
|
|
|
|
|
+ boolean deferredCleanup=false;
|
|
|
|
|
+ boolean responseReceived=false;
|
|
|
|
|
+ boolean mediaAttempted=false;
|
|
|
|
|
+ boolean nativeStream=!GB28181.equals(row.getSourceType())&&!URI.create(row.getVideoUrl()).getScheme().toLowerCase(Locale.ROOT).startsWith("rt");
|
|
|
try {
|
|
try {
|
|
|
|
|
+ deferredCleanup=cleanupOnRollback(session,nativeStream);
|
|
|
|
|
+ mediaAttempted=true;
|
|
|
|
|
+ Object response;
|
|
|
|
|
+ if(range!=null)response=collector.get("/api/playback/start",rangeParams(row,range));
|
|
|
|
|
+ else if(GB28181.equals(row.getSourceType()))response=collector.get("/api/play/start/"+row.getGbDeviceId()+"/"+row.getGbChannelId(),Map.of());
|
|
|
|
|
+ else {
|
|
|
|
|
+ String scheme=URI.create(row.getVideoUrl()).getScheme().toLowerCase(Locale.ROOT);
|
|
|
|
|
+ response=scheme.startsWith("rt")?collector.post("/internal/video/manual/start",Map.of("id",id,"url",row.getVideoUrl())):Map.of("url",row.getVideoUrl(),"native",true);
|
|
|
|
|
+ }
|
|
|
|
|
+ responseReceived=true;
|
|
|
|
|
+ if(!(response instanceof Map))throw new ServiceException("媒体服务没有返回有效播放信息");
|
|
|
|
|
+ Map<String,Object> data=new HashMap<>((Map<String,Object>)response);
|
|
|
|
|
+ session.setStreamId(data.get("stream") instanceof String?(String)data.get("stream"):null);
|
|
|
|
|
+ Object proxyKey=data.remove("proxyKey");
|
|
|
|
|
+ session.setProxyKey(proxyKey instanceof String?(String)proxyKey:null);
|
|
|
if(!List.of("url","flv","https_flv","ws_flv","wss_flv","hls","https_hls","webrtc").stream()
|
|
if(!List.of("url","flv","https_flv","ws_flv","wss_flv","hls","https_hls","webrtc").stream()
|
|
|
.map(data::get).anyMatch(VideoDeviceService::isPlayableAddress))throw new ServiceException("媒体服务没有返回有效播放地址");
|
|
.map(data::get).anyMatch(VideoDeviceService::isPlayableAddress))throw new ServiceException("媒体服务没有返回有效播放地址");
|
|
|
if(GB28181.equals(row.getSourceType())||!Boolean.TRUE.equals(data.get("native")))safeStream(session.getStreamId());
|
|
if(GB28181.equals(row.getSourceType())||!Boolean.TRUE.equals(data.get("native")))safeStream(session.getStreamId());
|
|
|
if(!GB28181.equals(row.getSourceType())&&!Boolean.TRUE.equals(data.get("native"))&&session.getProxyKey()==null)
|
|
if(!GB28181.equals(row.getSourceType())&&!Boolean.TRUE.equals(data.get("native"))&&session.getProxyKey()==null)
|
|
|
throw new ServiceException("媒体服务没有返回代理清理标识");
|
|
throw new ServiceException("媒体服务没有返回代理清理标识");
|
|
|
if(sessions.insert(session)!=1)throw new ServiceException("播放会话登记失败");
|
|
if(sessions.insert(session)!=1)throw new ServiceException("播放会话登记失败");
|
|
|
|
|
+ data.put("sessionId",session.getSessionId());
|
|
|
|
|
+ data.put("mode",mode);
|
|
|
|
|
+ return data;
|
|
|
} catch(RuntimeException registrationFailure) {
|
|
} catch(RuntimeException registrationFailure) {
|
|
|
|
|
+ if(!mediaAttempted)throw registrationFailure;
|
|
|
|
|
+ if(deferredCleanup)throw new ServiceException("视频启动或会话登记失败,媒体清理结果未确认");
|
|
|
try { stopMedia(session,existingLive); }
|
|
try { stopMedia(session,existingLive); }
|
|
|
catch(RuntimeException cleanupFailure) {
|
|
catch(RuntimeException cleanupFailure) {
|
|
|
log.warn("视频会话登记失败且媒体清理未确认: {}",session.getSessionId());
|
|
log.warn("视频会话登记失败且媒体清理未确认: {}",session.getSessionId());
|
|
|
throw new ServiceException("播放会话登记失败,媒体清理未确认,请联系管理员");
|
|
throw new ServiceException("播放会话登记失败,媒体清理未确认,请联系管理员");
|
|
|
}
|
|
}
|
|
|
- throw new ServiceException("播放会话登记失败");
|
|
|
|
|
|
|
+ throw new ServiceException(responseReceived?"播放会话登记失败":"视频启动失败,媒体结果与清理未确认");
|
|
|
}
|
|
}
|
|
|
- data.put("sessionId",session.getSessionId());
|
|
|
|
|
- data.put("mode",mode);
|
|
|
|
|
- return data;
|
|
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private boolean cleanupOnRollback(VideoSession session,boolean nativeStream) {
|
|
|
|
|
+ if(!TransactionSynchronizationManager.isActualTransactionActive())return false;
|
|
|
|
|
+ if(rollbackCleanup==null||!TransactionSynchronizationManager.isSynchronizationActive())
|
|
|
|
|
+ throw new ServiceException("视频事务清理未配置");
|
|
|
|
|
+ TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
|
|
|
|
+ @Override public void afterCompletion(int status) {
|
|
|
|
|
+ if(status==STATUS_COMMITTED||nativeStream)return;
|
|
|
|
|
+ try {
|
|
|
|
|
+ rollbackCleanup.execute(cleanupStatus -> {
|
|
|
|
|
+ sessions.lockVideo(session.getVideoId());
|
|
|
|
|
+ // A commit with an uncertain acknowledgement may have persisted the session.
|
|
|
|
|
+ // Keep it for the ordinary heartbeat reaper, never stop a registered viewer.
|
|
|
|
|
+ if(sessions.selectById(session.getSessionId())!=null)return null;
|
|
|
|
|
+ if("PLAYBACK".equals(session.getMode())&&sessions.selectCount(new LambdaQueryWrapper<VideoSession>()
|
|
|
|
|
+ .eq(VideoSession::getVideoId,session.getVideoId()).eq(VideoSession::getMode,"PLAYBACK")
|
|
|
|
|
+ .eq(VideoSession::getStatus,"ACTIVE"))>0)return null;
|
|
|
|
|
+ long others=activeLiveCount(session.getVideoId(),null);
|
|
|
|
|
+ if(others==0&&session.getGbDeviceId()==null&&session.getProxyKey()==null)
|
|
|
|
|
+ throw new ServiceException("未取得代理清理标识,媒体资源需人工核查");
|
|
|
|
|
+ stopMedia(session,others);
|
|
|
|
|
+ return null;
|
|
|
|
|
+ });
|
|
|
|
|
+ } catch(RuntimeException cleanupFailure) {
|
|
|
|
|
+ log.warn("视频事务结束后媒体清理未确认,需人工核查: {}",session.getSessionId());
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ });
|
|
|
|
|
+ return true;
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
public Object records(String id,VideoRequests.Range range) {
|
|
public Object records(String id,VideoRequests.Range range) {
|
|
@@ -253,7 +303,7 @@ public class VideoDeviceService {
|
|
|
if(!(value instanceof String))return false;
|
|
if(!(value instanceof String))return false;
|
|
|
try {
|
|
try {
|
|
|
URI uri=URI.create((String)value);
|
|
URI uri=URI.create((String)value);
|
|
|
- return uri.getHost()!=null&&Set.of("http","https","ws","wss").contains(uri.getScheme());
|
|
|
|
|
|
|
+ return uri.getHost()!=null&&uri.getScheme()!=null&&Set.of("http","https","ws","wss").contains(uri.getScheme().toLowerCase(Locale.ROOT));
|
|
|
} catch(IllegalArgumentException invalid) { return false; }
|
|
} catch(IllegalArgumentException invalid) { return false; }
|
|
|
}
|
|
}
|
|
|
|
|
|
|
@@ -264,12 +314,17 @@ public class VideoDeviceService {
|
|
|
} catch(NoSuchAlgorithmException impossible) { throw new IllegalStateException("SHA-256 unavailable", impossible); }
|
|
} catch(NoSuchAlgorithmException impossible) { throw new IllegalStateException("SHA-256 unavailable", impossible); }
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
|
|
+ private VideoSession activeAnonymousLocked(String id,String token) {
|
|
|
|
|
+ VideoSession session=ownedAnonymous(id,token);
|
|
|
|
|
+ sessions.lockVideo(session.getVideoId());
|
|
|
|
|
+ session=ownedAnonymous(id,token);
|
|
|
|
|
+ requireActiveAnonymous(session);
|
|
|
|
|
+ return session;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
@Transactional
|
|
@Transactional
|
|
|
public void heartbeat(String id,String token) {
|
|
public void heartbeat(String id,String token) {
|
|
|
- VideoSession s=ownedAnonymous(id,token);
|
|
|
|
|
- sessions.lockVideo(s.getVideoId());
|
|
|
|
|
- s=ownedAnonymous(id,token);
|
|
|
|
|
- requireActiveAnonymous(s);
|
|
|
|
|
|
|
+ VideoSession s=activeAnonymousLocked(id,token);
|
|
|
s.setLastSeen(LocalDateTime.now(clock));
|
|
s.setLastSeen(LocalDateTime.now(clock));
|
|
|
sessions.updateById(s);
|
|
sessions.updateById(s);
|
|
|
}
|
|
}
|
|
@@ -331,11 +386,7 @@ public class VideoDeviceService {
|
|
|
|
|
|
|
|
@Transactional
|
|
@Transactional
|
|
|
public void control(String id,String token,VideoRequests.Control input) {
|
|
public void control(String id,String token,VideoRequests.Control input) {
|
|
|
- VideoSession s=ownedAnonymous(id,token);
|
|
|
|
|
- sessions.lockVideo(s.getVideoId());
|
|
|
|
|
- s=ownedAnonymous(id,token);
|
|
|
|
|
- requireActiveAnonymous(s);
|
|
|
|
|
- controlSession(s,input);
|
|
|
|
|
|
|
+ controlSession(activeAnonymousLocked(id,token),input);
|
|
|
}
|
|
}
|
|
|
|
|
|
|
|
public void control(String id,VideoRequests.Control input) {
|
|
public void control(String id,VideoRequests.Control input) {
|