Skip to content

Commit

Permalink
Merge pull request #129 from My-Own-Weapon/develop
Browse files Browse the repository at this point in the history
[FEAT]/#-LiveRoomParticipant 부분 추가, 및 openvidu 수정
  • Loading branch information
rlawogkr authored Jul 23, 2024
2 parents 327740d + 330b5f1 commit 5ec9ad2
Show file tree
Hide file tree
Showing 6 changed files with 195 additions and 25 deletions.
119 changes: 101 additions & 18 deletions src/main/java/com/chimaera/wagubook/controller/OpenviduController.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package com.chimaera.wagubook.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.chimaera.wagubook.entity.LiveRoom;
import com.chimaera.wagubook.entity.Location;
import com.chimaera.wagubook.entity.Store;
import com.chimaera.wagubook.entity.*;
import com.chimaera.wagubook.service.LiveRoomService;
import com.chimaera.wagubook.service.MemberService;
import com.chimaera.wagubook.service.StoreService;
import jakarta.annotation.PostConstruct;
Expand All @@ -31,6 +32,7 @@ public class OpenviduController {

private final MemberService memberService;
private final StoreService storeService;
private final LiveRoomService liveRoomService;

@Value("${OPENVIDU_URL}")
private String OPENVIDU_URL;
Expand Down Expand Up @@ -102,22 +104,39 @@ public ResponseEntity<Map<String, Object>> initializeSession(@RequestBody(requir
}
// 기존 LiveRoom 확인
LiveRoom existingLiveRoom = memberService.findLiveRoomByMemberId(memberId);
if(existingLiveRoom !=null)
System.out.println("exiting : " + existingLiveRoom.getSessionId());


System.out.println("=====================liveRoom 연결 : " + existingLiveRoom);
// 기존 LiveRoom이 있으면 삭제
if(existingLiveRoom != null){
memberService.deleteLiveRoom(existingLiveRoom.getSessionId());
liveRoomService.deleteLiveRoom(existingLiveRoom.getSessionId());
}

// 기존 LiveRoom이 없으면 새로 생성
// 기존 LiveRoom이 없으면 새로 생성
LiveRoom liveRoom = LiveRoom.newBuilder()
.member(memberService.findById(memberId))
.sessionId(session.getSessionId())
.store(store)
.build();

memberService.saveLiveRoom(liveRoom);

//이미 LiveRoomParticipant 일 경우 추가하지 않음
LiveRoomParticipant existingLiveRoomParticipant = liveRoomService.getLiveRoomParticipantByMemberId(memberId);
if(existingLiveRoomParticipant != null){
liveRoomService.deleteLiveRoomParticipant(existingLiveRoomParticipant.getMember().getId());
}

//LiveRoomParticipant 추가
LiveRoomParticipant liveRoomParticipant = LiveRoomParticipant.newBuilder()
.member(memberService.findById(memberId))
.sessionId(session.getSessionId())
.liveRoom(liveRoom)
.build();


liveRoomService.saveLiveRoomParticipant(liveRoomParticipant);

// 세션 생성자 정보 저장
sessionCreatorMap.put(session.getSessionId(), memberId);

Expand Down Expand Up @@ -149,12 +168,28 @@ public ResponseEntity<Map<String, Object>> createConnection(@PathVariable("sessi
ConnectionProperties properties = ConnectionProperties.fromJson(params).build();
Connection connection = session.createConnection(properties);

System.out.println("=====================connection 연결 : " + connection.getToken());
System.out.println("=====================connection 연결 : " + memberId);

// 연결한 사용자 ID 저장
connectionMemberMap.put(connection.getToken(), memberId);

//이미 LiveRoomParticipant 일 경우 추가하지 않음
LiveRoomParticipant existingLiveRoomParticipant = liveRoomService.getLiveRoomParticipantByMemberId(memberId);
if(existingLiveRoomParticipant != null){
liveRoomService.deleteLiveRoomParticipant(existingLiveRoomParticipant.getMember().getId());
}

// LiveRoomParticipant 추가
Member member = memberService.findById(memberId);
LiveRoom liveRoom = liveRoomService.getLiveRoomBySessionId(sessionId); // LiveRoom 찾기
if(liveRoom != null){
LiveRoomParticipant liveRoomParticipant = LiveRoomParticipant.newBuilder()
.member(member)
.sessionId(sessionId)
.liveRoom(liveRoom)
.build();
liveRoomService.saveLiveRoomParticipant(liveRoomParticipant);
}

// 응답 생성
Map<String, Object> response = new HashMap<>();
response.put("token", connection.getToken());
Expand All @@ -173,42 +208,52 @@ public ResponseEntity<Map<String, Object>> getSessionCreator(@PathVariable("sess
if (creatorMemberId == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
Boolean isCreator = (creatorMemberId == (Long) httpSession.getAttribute("memberId"));
Boolean isCreator = (creatorMemberId.equals((Long) httpSession.getAttribute("memberId")));

Map<String, Object> response = new HashMap<>();
response.put("creatorMemberId", creatorMemberId);
response.put("isCreator", isCreator);
return new ResponseEntity<>(response, HttpStatus.OK);
}

/**
* TODO: 방에 참여한 사람이 나갔을 때 Live_Room_Participant에서 삭제.
*/
@DeleteMapping("/api/sessions/{sessionId}/member/{memberId}")
public ResponseEntity<String> closeConnection(@PathVariable("sessionId") String sessionId, @PathVariable("memberId") Long memberId) {
LiveRoomParticipant liveRoomParticipant = liveRoomService.getLiveRoomParticipantByMemberId(memberId);
if (liveRoomParticipant == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
liveRoomService.deleteLiveRoomParticipant(memberId);
return new ResponseEntity<>("라이브스트리밍 참여자가 나갔습니다.", HttpStatus.OK);
}

/**
* 라이브를 종료하고 세션을 삭제.
* TODO: 종료 시 DB에서 LiveRoom에서도 제거. store에 있는 liveRoom list에서 제거.
*
*/
@DeleteMapping("/api/sessions/{sessionId}")
public ResponseEntity<String> closeSession(@PathVariable("sessionId") String sessionId, HttpSession httpSession) {
// 멤버 확인
Long memberId = (Long) httpSession.getAttribute("memberId");

// 라이브를 끔
memberService.turnLive(memberId);

// 세션 삭제
Session session = openvidu.getActiveSession(sessionId);

if (session == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
try {
// LiveRoom에서 삭제. store에 있는 liveRoom list에서 제거.
memberService.deleteLiveRoom(sessionId);
LiveRoom liveRoom = liveRoomService.getLiveRoomBySessionId(sessionId);
if (liveRoom != null) {
liveRoomService.deleteLiveRoom(liveRoom.getSessionId());
}
session.close();
} catch (OpenViduJavaClientException | OpenViduHttpException e) {
throw new RuntimeException(e);
}
sessionCreatorMap.remove(sessionId);


return new ResponseEntity<>("라이브스트리밍이 종료되었습니다.", HttpStatus.OK);
}

Expand Down Expand Up @@ -262,11 +307,49 @@ public ResponseEntity<Map<String, Object>> createConnectionVoice(@PathVariable("
// 연결한 사용자 ID 저장
connectionMemberMap.put(connection.getToken(), memberId);

// LiveRoomParticipant 추가
LiveRoom liveRoom = liveRoomService.getLiveRoomBySessionId(sessionId);
if (liveRoom != null) {
LiveRoomParticipant liveRoomParticipant = LiveRoomParticipant.newBuilder()
.member(memberService.findById(memberId))
.sessionId(session.getSessionId())
.liveRoom(liveRoom)
.build();
liveRoomService.saveLiveRoomParticipant(liveRoomParticipant);
}

// 응답 생성
Map<String, Object> response = new HashMap<>();
response.put("token", connection.getToken());
response.put("memberId", memberId);
return new ResponseEntity<>(response, HttpStatus.OK);
}

/**
* 현재 session 방에 몇 명이 있는지 return 하는 api
* Integer 로 return.
*/
@GetMapping("/api/sessions/{sessionId}/connections")
public ResponseEntity<Integer> getConnections(@PathVariable("sessionId") String sessionId) {
List<LiveRoomParticipant> liveRoomParticipant = liveRoomService.getLiveRoomParticipantBySessionId(sessionId);
for (LiveRoomParticipant roomParticipant : liveRoomParticipant) {
System.out.println(roomParticipant.getMember().getId());
}
return new ResponseEntity<>(liveRoomParticipant.size(), HttpStatus.OK);
}
/**
* 현재 얘가 session 방에 있는 앤지 check 하는 api
* boolean으로 return.
*/
@GetMapping("/api/sessions/find/{sessionId}")
public ResponseEntity<Boolean> findSession(@PathVariable("sessionId") String sessionId, HttpSession httpSession) {
Long memberId = (Long) httpSession.getAttribute("memberId");
List<LiveRoomParticipant> liveRoomParticipant = liveRoomService.getLiveRoomParticipantBySessionId(sessionId);
for (LiveRoomParticipant roomParticipant : liveRoomParticipant) {
if (roomParticipant.getMember().getId().equals(memberId)) {
return new ResponseEntity<>(true, HttpStatus.OK);
}
}
return new ResponseEntity<>(false, HttpStatus.OK);
}
}
4 changes: 4 additions & 0 deletions src/main/java/com/chimaera/wagubook/entity/LiveRoom.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,5 +31,9 @@ public class LiveRoom {

private String sessionId; // 라이브 스트리밍 세션 ID

//liveRoom에 대한 참여자 목록
@OneToMany(mappedBy = "liveRoom", fetch = FetchType.LAZY)
private List<LiveRoomParticipant> liveRoomParticipants = new ArrayList<>();


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.chimaera.wagubook.entity;

import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Entity
@Getter
@NoArgsConstructor(access = lombok.AccessLevel.PROTECTED)
@Builder(builderMethodName = "newBuilder")
@AllArgsConstructor(access = lombok.AccessLevel.PRIVATE)
public class LiveRoomParticipant {

@Id
@GeneratedValue(strategy = jakarta.persistence.GenerationType.AUTO)
@Column(name = "live_room_participant_id")
private Long id;

private String sessionId; // 라이브 스트리밍 세션 ID

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_id")
private Member member; // 라이브 스트리밍 참여자

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "live_room_id")
private LiveRoom liveRoom; // 라이브 스트리밍 룸
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.chimaera.wagubook.repository.liveRoom;

import com.chimaera.wagubook.entity.LiveRoomParticipant;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface LiveRoomParticipantRepository extends JpaRepository<LiveRoomParticipant, Long> {
void deleteBySessionId(String sessionId);
LiveRoomParticipant findByMemberId(Long memberId);
void deleteByMemberId(Long memberId);
List<LiveRoomParticipant> findBySessionId(String sessionId);
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ public interface LiveRoomRepository extends JpaRepository<LiveRoom, Long>, LiveR
LiveRoom findByMemberId(Long memberId);
void deleteBySessionId(String sessionId);
List<LiveRoom> findByStoreId(Long storeId);
LiveRoom findBySessionId(String sessionId);
}
53 changes: 46 additions & 7 deletions src/main/java/com/chimaera/wagubook/service/LiveRoomService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.chimaera.wagubook.dto.response.LiveResponse;
import com.chimaera.wagubook.entity.*;
import com.chimaera.wagubook.repository.liveRoom.LiveRoomParticipantRepository;
import com.chimaera.wagubook.repository.liveRoom.LiveRoomRepository;
import com.chimaera.wagubook.repository.member.FollowRepository;
import com.chimaera.wagubook.repository.member.MemberRepository;
Expand All @@ -21,10 +22,11 @@
public class LiveRoomService {

private final LiveRoomRepository liveRoomRepository;
private final FollowRepository followRepository;
private final MemberRepository memberRepository;
private final StoreRepository storeRepository;
private final JPAQueryFactory queryFactory;
private final LiveRoomParticipantRepository liveRoomParticipantRepository;



@Transactional
Expand Down Expand Up @@ -86,6 +88,17 @@ public void captureLiveRoom(Long liveRoomId, Member member) {
// 캡쳐 로직
}


public List<LiveResponse> getFollowedLiveRooms(Long memberId) {
// 팔로우한 사용자의 라이브 룸 가져오기
List<LiveRoom> allFollowedRooms = liveRoomRepository.findAllFollowedRooms(memberId);

if(allFollowedRooms.isEmpty())
return new ArrayList<>();

return allFollowedRooms.stream().map(room -> new LiveResponse(room)).collect(Collectors.toList());
}

@Transactional
public void endLiveRoom(Long liveRoomId, Member member) {
LiveRoom liveRoom = liveRoomRepository.findById(liveRoomId)
Expand All @@ -99,15 +112,41 @@ public void endLiveRoom(Long liveRoomId, Member member) {
}
}

public List<LiveResponse> getFollowedLiveRooms(Long memberId) {
// 팔로우한 사용자의 라이브 룸 가져오기
List<LiveRoom> allFollowedRooms = liveRoomRepository.findAllFollowedRooms(memberId);
// TODO: 수정
@Transactional
public void saveLiveRoomParticipant(LiveRoomParticipant liveRoomParticipant) {
liveRoomParticipantRepository.save(liveRoomParticipant);
}

if(allFollowedRooms.isEmpty())
return new ArrayList<>();
public LiveRoom getLiveRoomBySessionId(String sessionId) {
return liveRoomRepository.findBySessionId(sessionId);
}

return allFollowedRooms.stream().map(room -> new LiveResponse(room)).collect(Collectors.toList());
// TODO: 수정
@Transactional
public void deleteLiveRoom(String sessionId){
// 먼저 liveRoomParticipant 삭제
liveRoomParticipantRepository.deleteBySessionId(sessionId);

// 그 다음 LiveRoom 삭제
liveRoomRepository.deleteBySessionId(sessionId);
}

public LiveRoomParticipant getLiveRoomParticipantByMemberId(Long memberId) {
return liveRoomParticipantRepository.findByMemberId(memberId);
}

@Transactional
public void deleteLiveRoomParticipant(Long memberId){
liveRoomParticipantRepository.deleteByMemberId(memberId);
}

// sessionId로 LiveRoomParticipant 찾기
public List<LiveRoomParticipant> getLiveRoomParticipantBySessionId(String sessionId) {
return liveRoomParticipantRepository.findBySessionId(sessionId);
}




}

0 comments on commit 5ec9ad2

Please sign in to comment.