Skip to content

Commit

Permalink
feat : sse
Browse files Browse the repository at this point in the history
  • Loading branch information
yyujin1231 committed Oct 8, 2024
2 parents e5a748c + 6742511 commit 28b88a5
Show file tree
Hide file tree
Showing 21 changed files with 205 additions and 169 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,6 @@ out/

### VS Code ###
.vscode/

### DBCODE ###
#!**/src/main/resources/application.properties
12 changes: 6 additions & 6 deletions src/main/generated/com/example/ai_jeju/domain/QUser.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,6 @@ public class QUser extends EntityPathBase<User> {

public static final QUser user = new QUser("user");

public final BooleanPath ag1 = createBoolean("ag1");

public final BooleanPath ag2 = createBoolean("ag2");

public final BooleanPath ag3 = createBoolean("ag3");

public final StringPath email = createString("email");

public final NumberPath<Long> id = createNumber("id", Long.class);
Expand All @@ -43,6 +37,12 @@ public class QUser extends EntityPathBase<User> {

public final StringPath rgtDate = createString("rgtDate");

public final BooleanPath selectedCk1 = createBoolean("selectedCk1");

public final BooleanPath selectedCk2 = createBoolean("selectedCk2");

public final BooleanPath valid = createBoolean("valid");

public QUser(String variable) {
super(User.class, forVariable(variable));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ public ResponseDto modifyAlbum(@RequestBody ModifyAlbumRequest modifyAlbumReques
}




@GetMapping("")
public ResponseDto getAlbumList(@RequestParam Long childId ,String rgtDate){
List<AlbumListResponse> albumResponses =albumService.getAlbumList(childId,rgtDate);
Expand All @@ -56,8 +54,10 @@ public ResponseDto getAlbumList(@RequestParam Long childId ,String rgtDate){

@GetMapping("/detail")
public ResponseDto getDetailAlbumList(@RequestParam Long albumId){

AlbumDetailResponse albumDetailResponse = albumService.getDetailAlbumList(albumId);
return ResponseUtil.SUCCESS("사진첩 조회이 성공하셨습니다",albumDetailResponse);

}

@GetMapping("/shares")
Expand Down
27 changes: 24 additions & 3 deletions src/main/java/com/example/ai_jeju/controller/ChatController.java
Original file line number Diff line number Diff line change
Expand Up @@ -98,30 +98,51 @@ public void message(ChatMessageDto messageDto, @Header("simpSessionAttributes")

log.info("Sending message to /sub/chat/room/" + messageDto.getRoomId() + ": " + messageDto.toString());
messagingTemplate.convertAndSend("/sub/chat/room/" + messageDto.getRoomId(), messageDto);
notificationService.notifyAllSubscribers(messageDto);

} catch (Exception e) {
log.error("Error processing message", e);
}
}


@GetMapping(value = "/api/chat/{roomId}/subscribe", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter subscribeToRoom(@PathVariable("roomId") Long roomId, @RequestHeader(value = "Authorization", required = false) String token) {
public SseEmitter subscribeToRoom(@PathVariable("roomId") Long roomId, @RequestParam(value = "token", required = false) String token) {
if (token != null && !token.isEmpty()) {
log.info("Received token: " + token);

String accessToken = token.replace("Bearer ", "");
log.info("Processed access token: " + accessToken);

if (tokenProvider.validToken(accessToken)) {
Long userId = tokenProvider.getUserId(accessToken);
log.info("User ID extracted from token: " + userId);

return notificationService.subscribeToRoom(userId, roomId);
return notificationService.subscribeToRoom(userId);
} else {
log.error("Invalid token: " + accessToken);
throw new IllegalArgumentException("유효하지 않은 토큰입니다.");
}
} else {
// 비회원 처리: 비회원의 경우에도 특별한 경우 처리할 수 있다면 작성
log.error("No token provided.");
throw new IllegalArgumentException("토큰이 존재하지 않습니다.");
}
}



@PostMapping("/send-data/{id}")
public void sendData(@PathVariable("roomId") Long id) {
notificationService.notify(id, "data");
}

@GetMapping(value = "/notifications/subscribe/{userId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter subscribe(@PathVariable("roomId") Long userId) {
return notificationService.subscribeToRoom(userId);
}



@GetMapping("/chatroom")
public String chat(@RequestParam("roomId") String roomId, Model model) {
model.addAttribute("roomId", roomId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,9 @@ public String getAllTests(Model model) {
model.addAttribute("tests", tests);
return "imgtest"; // This will map to testImages.html in the templates folder
}

@GetMapping("/sse-test")
public String sseTestPage() {
return "test"; // test.html 파일을 반환
}
}
19 changes: 11 additions & 8 deletions src/main/java/com/example/ai_jeju/controller/TokenController.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,22 @@ public TokenController(TokenProvider tokenProvider) {
}

@GetMapping("")
public ResponseDto getMyTokenInfo(@RequestHeader("Authorization") String token) {
public ResponseDto getMyTokenInfo(@RequestHeader("custom") String token) {
// Bearer 토큰 형식에서 "Bearer " 부분 제거
String accessToken = token.replace("Bearer ", "");

Date expiredDate = tokenProvider.getExpiredDate(token);
// 날짜 포맷 지정 (예: yyyy-MM-dd HH:mm:ss)
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// Date를 String으로 변환
String dateString = formatter.format(expiredDate);
if (tokenProvider.validToken(token)) {
return ResponseUtil.SUCCESS("유효한 토큰입니다.",dateString);
if (tokenProvider.validToken(accessToken)) {

Date expiredDate = tokenProvider.getExpiredDate(accessToken);
// 날짜 포맷 지정 (예: yyyy-MM-dd HH:mm:ss)
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(expiredDate);

return ResponseUtil.SUCCESS(true,dateString);
} else {
return ResponseUtil.ERROR("유효하지 않은 토큰입니다.", null);

return ResponseUtil.ERROR(false, null);
}


Expand Down
17 changes: 12 additions & 5 deletions src/main/java/com/example/ai_jeju/controller/UserController.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,17 @@ public ResponseDto CheckIfUser(@RequestParam(name = "email") String email, HttpS
}

//탈퇴하기
@PostMapping("/withdraw")
public ResponseEntity<String> signOut(@RequestBody WithdrawRequest withdrawRequest) {
String response = userService.withDraw(withdrawRequest);
return ResponseEntity.ok(response);
}
@DeleteMapping("/withdraw")
public ResponseDto signOut(@RequestHeader(value = "Authorization") String token, @RequestParam String email) {

String accessToken = token.replace("Bearer ","");

try {
userService.withDraw(accessToken, email);
return ResponseUtil.SUCCESS("탈퇴에 성공하였습니다.",null);
}catch (Exception e){
return ResponseUtil.FAILURE(e, null);
}

}
}
3 changes: 3 additions & 0 deletions src/main/java/com/example/ai_jeju/domain/Store.java
Original file line number Diff line number Diff line change
Expand Up @@ -81,16 +81,19 @@ public class Store {


@Column(name = "checkin",updatable = false,nullable = true)
@ColumnDefault("0")
String checkin;

@Column(name = "checkout",updatable = false,nullable = true)
@ColumnDefault("0")
String checkout;

@Column(name = "bookmarks")
@ColumnDefault("0")
int noBmk;

@Column
@ColumnDefault("0")
int rcmdType;

@Column(name = "rcmd")
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/example/ai_jeju/domain/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,4 @@ public class User {
private boolean selectedCk1;
@Column(name ="selectedCk2", nullable = false)
private boolean selectedCk2;
}
}
7 changes: 2 additions & 5 deletions src/main/java/com/example/ai_jeju/dto/SignUpRequest.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,8 @@ public class SignUpRequest {
private String provider;
private String phoneNum;
private Boolean ifRcmd;

private boolean mustCk;
private boolean selectedCk1;
private boolean selectedCk2;

private Boolean selectedCk1;
private Boolean selectedCk2;
/**
* 함께 보낼 동반 아동에 대한 정보 -> 여러명일 수도 있으므로 배열 형식으로 받는다.
* private List<Child> child;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ public interface BookmarkRepository extends JpaRepository<Bookmark,Long> {
List<Bookmark> findByStoreId(Long storeId);
List<Bookmark> findByUser(User user);
void deleteByUserAndStoreId(User user, Long storeId);
void deleteByUser(User user);




}
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,7 @@ public interface ChildRepository extends JpaRepository<Child, Long> {

Optional<Child> findByChildId(Long childId);

void deleteByUser(User user);


}
26 changes: 13 additions & 13 deletions src/main/java/com/example/ai_jeju/repository/EmitterRepository.java
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
package com.example.ai_jeju.repository;


import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Repository
public class EmitterRepository {
// 유저별 Emitter 저장 (roomId -> userId -> SseEmitter)
private final Map<Long, SseEmitter> emitters = new ConcurrentHashMap<>();

private final Map<Long, Map<Long, SseEmitter>> emittersByRoom = new ConcurrentHashMap<>();

public void save(Long userId, SseEmitter emitter) {
emitters.put(userId, emitter);
}

public void save(Long userId, Long roomId, SseEmitter emitter) {
emittersByRoom.computeIfAbsent(roomId, k -> new ConcurrentHashMap<>()).put(userId, emitter);
public SseEmitter findByUserId(Long userId) {
return emitters.get(userId);
}

public Map<Long, SseEmitter> findAllEmittersByRoomId(Long roomId) {
return emittersByRoom.getOrDefault(roomId, Collections.emptyMap());
public void deleteByUserId(Long userId) {
emitters.remove(userId);
}

public void deleteByRoomId(Long userId, Long roomId) {
Map<Long, SseEmitter> roomEmitters = emittersByRoom.get(roomId);
if (roomEmitters != null) {
roomEmitters.remove(userId);
}
public List<Long> findAllUserIds() {
return emitters.keySet().stream().collect(Collectors.toList());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,6 @@ public Map<String, Object> findByFilterDto(FilterDto filterDto, int randomSeed,
return response;
}


// 동적 쿼리 실행 (popularity가 null이거나 false인 경우)
List<Store> stores = queryFactory.selectFrom(qStore)
.where(builder)
Expand Down
20 changes: 19 additions & 1 deletion src/main/java/com/example/ai_jeju/repository/UserRepository.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package com.example.ai_jeju.repository;

import com.example.ai_jeju.domain.User;
import jakarta.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Optional;
Expand All @@ -10,10 +14,24 @@
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
Optional<User> findById(Long userId);

Optional<User>findUserByNickname(String nickname);


@Modifying
@Query("UPDATE User u set u.valid = :valid WHERE u.id = :id")
void updateUserByValid(@Param("id") Long userId, @Param("valid") Boolean valid);

@Modifying
@Transactional
@Query("UPDATE User u set u.valid = :valid, u.nickname = :nickname, u.profileImg = :profileImg," +
"u.provider = :provider , u.rgtDate = :rgtDate, u.phoneNum = :phoneNum," +
"u.ifRcmd = :ifRcmd, u.selectedCk1 = :selectedCk1, u.selectedCk2 = :selectedCk2 WHERE u.id = :id")
void updateUser(@Param("id") Long userId, @Param("valid") Boolean valid, @Param("nickname") String nickname,
@Param("profileImg") String profileImg, @Param("provider") String provider,
@Param("rgtDate") String rgtDate, @Param("phoneNum") String phoneNum,
@Param("ifRcmd") Boolean ifRcmd,
@Param("selectedCk1") Boolean selectedCk1, @Param("selectedCk2") Boolean selectedCk2);



}
23 changes: 18 additions & 5 deletions src/main/java/com/example/ai_jeju/service/AlbumService.java
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,23 @@ public void updateAlbum(ModifyAlbumRequest modifyAlbumRequest){
public AlbumDetailResponse getDetailAlbumList(Long albumId){

Optional<Album> optionalAlbum = albumRepository.findById(albumId);
if(optionalAlbum.isPresent()){
List<String> options = new ArrayList<>();
//albumOption이 존재하지 않은 경우도 있으니까.

Album album = optionalAlbum.get();
AlbumOption albumOption = albumOptionRepository.findByAlbum(album).get();
if(albumOption.isOptionalPet()) options.add("동물");
if(albumOption.isOptionalFriend()) options.add("친구");
if(albumOption.isOptionalFamily()) options.add("가족");
if(albumOption.isOptionalMorning()) options.add("아침");
if(albumOption.isOptionalAfterNoon()) options.add("낮");
if(albumOption.isOptionalNight()) options.add("저녁");
if(albumOption.isOptionalDining()) options.add("식사");
if(albumOption.isOptionalSnack()) options.add("간식");
if(albumOption.isOptionalPlay()) options.add("놀이");
if(albumOption.isOptionalStudy()) options.add("공부");
if(albumOption.isOptionalExperience()) options.add("체험");
if(albumOption.isOptionalWalk()) options.add("산책");
List<String> imgSrcDtos = new ArrayList<>();
//album Item list
List<AlbumItem> albumItems = albumItemRepository.findByAlbum(album);
Expand All @@ -189,14 +204,12 @@ public AlbumDetailResponse getDetailAlbumList(Long albumId){
.AlbumDesc(album.getAlbumDesc())
.rgtDate(album.getRgtDate())
.imgSrcDtos(imgSrcDtos)
.options(options)
.build();
return albumDetailResponse;
}else{
//album없을때
return null;
}

}



public ScheduleResponse getScheculeListByChild(Long childId){
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,17 +98,19 @@ public List<BookMarkItem> getBookmarkByCategoryId (Long userId, int categoryId){
Optional<Store> store = storeRepository.findByStoreId(bookmark.getStoreId());
List<Bookmark> bmks = bookmarkRepository.findByStoreId(store.get().getStoreId());
//그리고 카테고리 아이디가 내가 제시한 카테고리 아이디랑 같다면,
if(store.isPresent()&&categoryId==store.get().getCategoryId() ){
if(categoryId == store.get().getCategoryId()){
System.out.println("확인"+store.get().getCategoryId());
BookMarkItem bookMarkItem = BookMarkItem.builder()
.storeId(bookmark.getStoreId())
.storeName(store.get().getName())
.imgsrc(store.get().getImgSrc())
.noKidszone(store.get().getNoKidsZone())
.numOfBmk(bmks.size())
.build();
bookMarkItems.add(bookMarkItem);
return bookMarkItems;
}
}
return bookMarkItems;
}
return null;
}
Expand Down
Loading

0 comments on commit 28b88a5

Please sign in to comment.