Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 콕 찌르기 알림 서비스 기능 구현 #26

Merged
merged 22 commits into from
Nov 3, 2023
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
c477f2d
feat: Redis 초기 설정
hongdosan Nov 1, 2023
27537c2
feat: FCM 초기 설정 및 예외처리
hongdosan Nov 1, 2023
06288b6
feat: 콕 찌르기 기능 서비스 및 레포지토리 구현
hongdosan Nov 1, 2023
3491268
fix: Redis Reposi 추상 클래스 제거 및 테스트 Profile 변경
hongdosan Nov 1, 2023
86ee90a
test: StringRedisRepository 테스트
hongdosan Nov 1, 2023
bba57ec
test: NotificationRepository 테스트
hongdosan Nov 1, 2023
c15760b
feat: NullPointerException 예외 핸들링 처리
hongdosan Nov 1, 2023
5572f83
feat: 희빈님 코드 Merge
hongdosan Nov 1, 2023
303a83a
test: NotificationService 테스트
hongdosan Nov 1, 2023
aa0f8c4
refacotr: PostConstruct를 Bean으로 변경
hongdosan Nov 1, 2023
951d608
refactor : 테스트 코드 Profile 변경
hongdosan Nov 1, 2023
c2069a9
fix: redis 테스트 삭제
hongdosan Nov 1, 2023
9c17a04
fix : Redis 테스트 클래스 삭제
hongdosan Nov 1, 2023
6720767
fix : Member Role Default 문제 해결
hongdosan Nov 1, 2023
0afc004
fix: firebase config 경로 변경
hongdosan Nov 1, 2023
a0093b2
fix: 에러 찾기 위한 로그 설정
hongdosan Nov 1, 2023
3d20a3f
fix: CI가 서브모듈 경로를 못찾는 에러 해결
hongdosan Nov 1, 2023
46a6983
test: Redis Repository 테스트 및 로그 삭제
hongdosan Nov 2, 2023
0be59d9
chore: Develop -> Merge
hongdosan Nov 2, 2023
bddf87a
style: 메서드명 및 줄바꿈 설정
hongdosan Nov 2, 2023
5774cfd
refactor: 콕 찌르기 알림 저장 시, 키값 및 만료시간 변경
hongdosan Nov 2, 2023
3fecca9
refactor: 리뷰 코드 수정
hongdosan Nov 3, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 38 additions & 36 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,46 +1,48 @@
name: ci

on:
pull_request:
branches: [ "main", "develop" ]
pull_request:
branches: [ "main", "develop" ]

jobs:
build:
name: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
build:
name: build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
submodules: true
token: ${{ secrets.MOABAM_SUBMODULE_KEY }}

- name: JDK 17 셋업
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'corretto'
- name: JDK 17 셋업
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'corretto'

- name: Gradle 캐싱
uses: actions/cache@v3
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
${{ runner.os }}-gradle-
- name: Gradle 캐싱
uses: actions/cache@v3
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
restore-keys: |
${{ runner.os }}-gradle-

- name: Gradle Grant 권한 부여
run: chmod +x gradlew
- name: Gradle Grant 권한 부여
run: chmod +x gradlew

- name: SonarCloud 캐싱
uses: actions/cache@v3
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar
- name: SonarCloud 캐싱
uses: actions/cache@v3
with:
path: ~/.sonar/cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar

- name: 빌드 및 분석
run: ./gradlew build jacocoTestReport sonar --info --stacktrace
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SONAR_TOKEN: ${{ secrets.SONAR_CLOUD_TOKEN }}
- name: 빌드 및 분석
run: ./gradlew build jacocoTestReport sonar --info --stacktrace
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SONAR_TOKEN: ${{ secrets.SONAR_CLOUD_TOKEN }}
6 changes: 6 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ dependencies {

// Configuration Binding
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"

// Redis
implementation 'org.springframework.boot:spring-boot-starter-data-redis'

// Firebase Admin
implementation 'com.google.firebase:firebase-admin:9.2.0'
}

tasks.named('test') {
Expand Down
50 changes: 50 additions & 0 deletions src/main/java/com/moabam/api/application/NotificationService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.moabam.api.application;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.Notification;
import com.moabam.api.domain.repository.NotificationRepository;
import com.moabam.api.dto.NotificationMapper;
import com.moabam.global.common.annotation.MemberTest;
import com.moabam.global.error.exception.ConflictException;
import com.moabam.global.error.exception.NotFoundException;
import com.moabam.global.error.model.ErrorMessage;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class NotificationService {

private final FirebaseMessaging firebaseMessaging;
private final NotificationRepository notificationRepository;

@Transactional
public void sendKnockNotification(MemberTest member, Long targetId, Long roomId) {
validateFcmToken(targetId);
validateKnockNotification(member.memberId(), targetId, roomId);

String fcmToken = notificationRepository.findFcmTokenByMemberId(targetId);
Notification notification = NotificationMapper.toKnockNotificationEntity(member.memberId());
Message message = NotificationMapper.toMessageEntity(notification, fcmToken);

firebaseMessaging.sendAsync(message);
notificationRepository.saveKnockNotification(member.memberId(), targetId, roomId);
}

private void validateFcmToken(Long memberId) {
if (!notificationRepository.existsFcmTokenByMemberId(memberId)) {
throw new NotFoundException(ErrorMessage.FCM_TOKEN_NOT_FOUND);
}
}

private void validateKnockNotification(Long memberId, Long targetId, Long roomId) {
if (notificationRepository.existsKnockByMemberId(memberId, targetId, roomId)) {
throw new ConflictException(ErrorMessage.KNOCK_CONFLICT);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package com.moabam.api.domain.repository;

import static com.moabam.global.common.util.GlobalConstant.*;
import static java.util.Objects.*;

import java.time.Duration;

import org.springframework.stereotype.Repository;

import com.moabam.global.common.repository.StringRedisRepository;

import lombok.RequiredArgsConstructor;

@Repository
@RequiredArgsConstructor
public class NotificationRepository {

private static final long EXPIRE_KNOCK = 12;
private static final long EXPIRE_FCM_TOKEN = 60;
private static final String TO = "_TO_";

private final StringRedisRepository stringRedisRepository;

// TODO : 세연님 로그인 시, 해당 메서드 사용해서 해당 유저의 FCM TOKEN 저장하면 됩니다.
public void saveFcmToken(Long key, String value) {
stringRedisRepository.save(
String.valueOf(requireNonNull(key)),
requireNonNull(value),
requireNonNull(Duration.ofDays(EXPIRE_FCM_TOKEN))
);
}

public void saveKnockNotification(Long memberId, Long targetId, Long roomId) {
String key = requireNonNull(roomId) + UNDER_BAR + requireNonNull(memberId) + TO + requireNonNull(targetId);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

apache common 영명님이 올려주시면 사용에 대해 고민해보는건 어떨까요
Ex) StringUtils

stringRedisRepository.save(key, BLANK, requireNonNull(Duration.ofHours(EXPIRE_KNOCK)));
}

// TODO : 세연님 로그아웃 시, 해당 메서드 사용해서 해당 유저의 FCM TOKEN 삭제하시면 됩니다.
public void deleteFcmTokenByMemberId(Long memberId) {
stringRedisRepository.delete(String.valueOf(requireNonNull(memberId)));
}

public String findFcmTokenByMemberId(Long memberId) {
return stringRedisRepository.get(String.valueOf(requireNonNull(memberId)));
}

public boolean existsFcmTokenByMemberId(Long memberId) {
return stringRedisRepository.hasKey(String.valueOf(requireNonNull(memberId)));
}

public boolean existsKnockByMemberId(Long memberId, Long targetId, Long roomId) {
String key = requireNonNull(roomId) + UNDER_BAR + requireNonNull(memberId) + TO + requireNonNull(targetId);
return stringRedisRepository.hasKey(key);
}
}
28 changes: 28 additions & 0 deletions src/main/java/com/moabam/api/dto/NotificationMapper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.moabam.api.dto;

import com.google.firebase.messaging.Message;
import com.google.firebase.messaging.Notification;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class NotificationMapper {

private static final String TITLE = "모아밤";
private static final String KNOCK_BODY = "님이 콕 찔렀습니다.";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ID 님이 -> nickname이 더 나을 거 같습니다.
nickname까지 어노테이션으로 같이 전달해 드릴게요


public static Notification toKnockNotificationEntity(Long memberId) {
return Notification.builder()
.setTitle(TITLE)
.setBody(memberId + KNOCK_BODY)
.build();
}

public static Message toMessageEntity(Notification notification, String fcmToken) {
return Message.builder()
.setNotification(notification)
.setToken(fcmToken)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.moabam.global.common.annotation;

public record MemberTest(
Long memberId
) {

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.moabam.global.common.repository;

import java.time.Duration;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import lombok.RequiredArgsConstructor;

@Repository
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class StringRedisRepository {

private final StringRedisTemplate stringRedisTemplate;

@Transactional
public void save(String key, String value, Duration timeout) {
stringRedisTemplate
.opsForValue()
.set(key, value, timeout);
}

@Transactional
public void delete(String key) {
stringRedisTemplate.delete(key);
}

public String get(String key) {
return stringRedisTemplate
.opsForValue()
.get(key);
}

public Boolean hasKey(String email) {
return stringRedisTemplate.hasKey(email);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class GlobalConstant {

public static final String BLANK = "";
public static final String UNDER_BAR = "_";
public static final String COMMA = ",";
public static final String CHARSET_UTF_8 = ";charset=UTF-8";
}
45 changes: 45 additions & 0 deletions src/main/java/com/moabam/global/config/FcmConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.moabam.global.config;

import java.io.IOException;
import java.io.InputStream;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.messaging.FirebaseMessaging;
import com.moabam.global.error.exception.FcmException;
import com.moabam.global.error.model.ErrorMessage;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
@EnableScheduling
public class FcmConfig {

private static final String FIREBASE_PATH = "config/moabam-firebase.json";

@Bean
public FirebaseMessaging firebaseMessaging() {
try (InputStream inputStream = new ClassPathResource(FIREBASE_PATH).getInputStream()) {
GoogleCredentials credentials = GoogleCredentials.fromStream(inputStream);
FirebaseOptions firebaseOptions = FirebaseOptions.builder()
.setCredentials(credentials)
.build();
if (FirebaseApp.getApps().isEmpty()) {
FirebaseApp.initializeApp(firebaseOptions);
log.info("======= Firebase init start =======");
}

return FirebaseMessaging.getInstance();
} catch (IOException e) {
log.error("======= firebase moabam error =======" + e + "");
throw new FcmException(ErrorMessage.FCM_INIT_FAILED);
}
}
}
34 changes: 34 additions & 0 deletions src/main/java/com/moabam/global/config/RedisConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.moabam.global.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

@Value("${spring.data.redis.host}")
private String redisHost;

@Value("${spring.data.redis.port}")
private int redisPort;

@Bean
public RedisConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(redisHost, redisPort);
}

@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
stringRedisTemplate.setKeySerializer(new StringRedisSerializer());
stringRedisTemplate.setValueSerializer(new StringRedisSerializer());
stringRedisTemplate.setConnectionFactory(redisConnectionFactory);

return stringRedisTemplate;
}
}
10 changes: 10 additions & 0 deletions src/main/java/com/moabam/global/error/exception/FcmException.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.moabam.global.error.exception;

import com.moabam.global.error.model.ErrorMessage;

public class FcmException extends MoabamException {

public FcmException(ErrorMessage errorMessage) {
super(errorMessage);
}
}
Loading