Skip to content

Commit

Permalink
Merge pull request #130 from PawWithU/feat/129-fcm-test
Browse files Browse the repository at this point in the history
[Feature] FCM Enum Message 생성 및 테스트 API 구현
  • Loading branch information
kyeong-hyeok authored Nov 20, 2023
2 parents dac8334 + f7a4eb9 commit 2aa40f8
Show file tree
Hide file tree
Showing 8 changed files with 79 additions and 22 deletions.
1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ dependencies {
// firebase
implementation 'com.google.firebase:firebase-admin:6.8.1'
implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.2.2'
implementation 'com.squareup.okio:okio:2.7.0'
}

// Querydsl 설정부
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospe
.requestMatchers(mvcMatcherBuilder.pattern("/swagger-resources/**")).permitAll()
.requestMatchers(mvcMatcherBuilder.pattern("/v3/api-docs/**")).permitAll()
.requestMatchers(mvcMatcherBuilder.pattern("/volunteers/nickname/isDuplicated")).permitAll()
.requestMatchers(mvcMatcherBuilder.pattern("/fcm-test")).permitAll()
.anyRequest().authenticated())
.addFilterAfter(customVolunteerAuthFilter(), LogoutFilter.class)
.addFilterAfter(customIntermediaryAuthFilter(), LogoutFilter.class)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.pawwithu.connectdog.domain.fcm.controller;

import com.pawwithu.connectdog.domain.fcm.dto.request.FcmTokenRequest;
import com.pawwithu.connectdog.domain.fcm.dto.request.IntermediaryFcmRequest;
import com.pawwithu.connectdog.domain.fcm.dto.request.VolunteerFcmRequest;
import com.pawwithu.connectdog.domain.fcm.service.FcmService;
Expand All @@ -18,6 +19,8 @@
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import static com.pawwithu.connectdog.domain.fcm.dto.NotificationMessage.APPLICATION;

@Tag(name = "Fcm", description = "Fcm API")
@RestController
@RequiredArgsConstructor
Expand Down Expand Up @@ -52,4 +55,17 @@ public ResponseEntity<Void> saveIntermediaryFcm(@AuthenticationPrincipal UserDet
fcmService.saveIntermediaryFcm(loginUser.getUsername(), request);
return ResponseEntity.noContent().build();
}

@Operation(summary = "FCM 토큰 테스트", description = "FCM 토큰을 테스트 합니다.",
responses = {@ApiResponse(responseCode = "200", description = "FCM 토큰 테스트 성공")
, @ApiResponse(responseCode = "400"
, description = "V1, fcm 토큰은 필수 입력 값입니다."
, content = @Content(schema = @Schema(implementation = ErrorResponse.class)))
})
@PostMapping("/fcm-test")
public ResponseEntity<Void> testFcmToken(@Valid @RequestBody FcmTokenRequest request) {
fcmService.sendMessageTo(request.fcmToken(), APPLICATION.getTitleWithLoc("서울 강남구", "서울 도봉구"), APPLICATION.getBodyWithName("포윗유"));
return ResponseEntity.noContent().build();
}

}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.pawwithu.connectdog.domain.fcm.dto.request;
package com.pawwithu.connectdog.domain.fcm.dto;

import lombok.AllArgsConstructor;
import lombok.Builder;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.pawwithu.connectdog.domain.fcm.dto;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public enum NotificationMessage {
APPLICATION("", "님이 이동봉사를 신청하셨어요. 지금 확인해 보세요!");

private final String title;
private final String body;

public String getTitleWithLoc(String departureLoc, String arrivalLoc) {
return departureLoc + "→" + arrivalLoc;
}

public String getBodyWithName(String name) {
return name + body;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.pawwithu.connectdog.domain.fcm.dto.request;

import jakarta.validation.constraints.NotBlank;

public record FcmTokenRequest(@NotBlank(message = "fcm 토큰은 필수 입력 값입니다.")
String fcmToken) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.common.net.HttpHeaders;
import com.pawwithu.connectdog.domain.fcm.dto.request.FcmMessage;
import com.pawwithu.connectdog.domain.fcm.dto.FcmMessage;
import com.pawwithu.connectdog.domain.fcm.dto.request.IntermediaryFcmRequest;
import com.pawwithu.connectdog.domain.fcm.dto.request.VolunteerFcmRequest;
import com.pawwithu.connectdog.domain.fcm.entity.IntermediaryFcm;
Expand All @@ -27,12 +27,10 @@
import java.io.IOException;
import java.util.Arrays;

import static com.pawwithu.connectdog.error.ErrorCode.INTERMEDIARY_NOT_FOUND;
import static com.pawwithu.connectdog.error.ErrorCode.VOLUNTEER_NOT_FOUND;
import static com.pawwithu.connectdog.error.ErrorCode.*;

@Slf4j
@Service
@Transactional
@RequiredArgsConstructor
public class FcmService {

Expand Down Expand Up @@ -91,31 +89,41 @@ public String makeMessage(String targetToken, String title, String body) throws
* 알림 푸쉬를 보내는 역할을 하는 메서드
* @param targetToken : 푸쉬 알림을 받을 클라이언트 앱의 식별 토큰
* */
public void sendMessageTo(String targetToken, String title, String body) throws IOException {

String message = makeMessage(targetToken, title, body);

OkHttpClient client = new OkHttpClient();
RequestBody requestBody = RequestBody.create(message, MediaType.get("application/json; charset=utf-8"));

Request request = new Request.Builder()
.url(FIREBASE_API_URL)
.post(requestBody)
.addHeader(HttpHeaders.AUTHORIZATION, "Bearer "+getAccessToken())
.addHeader(HttpHeaders.CONTENT_TYPE, "application/json; UTF-8")
.build();

Response response = client.newCall(request).execute();
log.info(response.body().string());
public void sendMessageTo(String targetToken, String title, String body) {

try {
String message = makeMessage(targetToken, title, body);

OkHttpClient client = new OkHttpClient();
RequestBody requestBody = RequestBody.create(message, MediaType.get("application/json; charset=utf-8"));

Request request = new Request.Builder()
.url(FIREBASE_API_URL)
.post(requestBody)
.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + getAccessToken())
.addHeader(HttpHeaders.CONTENT_TYPE, "application/json; UTF-8")
.build();

Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
log.error("FCM 푸시 알람 전송이 실패했습니다. 응답 코드: {}\n{}", response.code(), response.body().string());
}
}
catch (Exception e) {
log.error("Fcm 푸시 알람을 전송하는 도중에 에러가 발생했습니다. {}", e.getMessage());
throw new BadRequestException(NOTIFICATION_SEND_ERROR);
}
return;
}

@Transactional
public void saveVolunteerFcm(String email, VolunteerFcmRequest request) {
Volunteer volunteer = volunteerRepository.findByEmail(email).orElseThrow(() -> new BadRequestException(VOLUNTEER_NOT_FOUND));
VolunteerFcm volunteerFcm = VolunteerFcmRequest.volunteerToEntity(volunteer, request);
volunteerFcmRepository.save(volunteerFcm);
}

@Transactional
public void saveIntermediaryFcm(String email, IntermediaryFcmRequest request) {
Intermediary intermediary = intermediaryRepository.findByEmail(email).orElseThrow(() -> new BadRequestException(INTERMEDIARY_NOT_FOUND));
IntermediaryFcm intermediaryFcm = IntermediaryFcmRequest.IntermediaryToEntity(intermediary, request);
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/com/pawwithu/connectdog/error/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,9 @@ public enum ErrorCode {
APPLICATION_NOT_FOUND("AP2", "해당 신청 내역을 찾을 수 없습니다."),

REVIEW_NOT_FOUND("R1", "해당 후기를 찾을 수 없습니다."),
DOG_STATUS_NOT_FOUND("D1", "해당 근황을 찾을 수 없습니다.");
DOG_STATUS_NOT_FOUND("D1", "해당 근황을 찾을 수 없습니다."),

NOTIFICATION_SEND_ERROR("N1", "알림 전송을 실패했습니다.");


private final String code;
Expand Down

0 comments on commit 2aa40f8

Please sign in to comment.