거의 막바지에 다다랐다...
이제 전역을 출발하면, 해당 역에 알림이 등록된 계정에 푸시 알림을 보내면 된다.
사실 6번 포스트에서 목적지 전역을 출발할 때 특정 코드를 실행하는 로직은 이미 구현해 놨고, 7번 포스트에서 푸시 알림을 전송하는 메서드도 구현해 놨기 때문에 이 둘을 그냥 합쳐주면 된다.
그러니까... 6번 포스트에서 작성한 로직을 조금만 수정해주면 되는 것.
...라고 했는데, Alarm 테이블에 저장한 값이 username이 아니라 User(Account 객체)였네...?
ㅋㅋㅋ... 저번 포스트에서 SendPushDTO에 username을 넣어놨어서... User로 수정해 주었다...
username은 Alarm 테이블에 없어서 활용할 수 없으니까...
< SendPushDTO.java >
@Getter
@Setter
@RequiredArgsConstructor
public class SendPushDTO {
private String title;
private String content;
private Account user; // 저번 포스트에서 String username으로 선언했었음...ㅋㅋ
}
그리고 저번 포스트에서 SendPush() 메서드에서 username으로 user 객체를 찾았었는데...
이제 user 그 자체를 매개변수로 줄 수 있으니 그럴 필요가 없어짐!
이건 뭐... 쉬우니까 코드는 따로 작성은 안 하겠음다.
여튼!! 다시 본론으로 돌아와서,
이제 Alarm 테이블을 돌면서 userId를 가져와서 그걸로 SendPushDTO를 만들 수 있다!!
그래서 아래와 같이 로직을 작성하면 됨.
@Transactional
//@Scheduled(fixedDelay = 15000) // 15초마다 아래 로직을 수행
@Scheduled(fixedDelay = 3000)
public void sendAlarm() {
// settedAlarm이 1 이상인 역들(알람이 하나 이상 설정된 역들)을 모두 찾는다.
ArrayList<Station> stations = stationRepository.findAllBySettedAlarmGreaterThanEqual(1);
stations.forEach(station -> {
RestTemplate rt = new RestTemplate();
String uri = "http://swopenAPI.seoul.go.kr/api/subway/" + HiddenData.subwayKey + "/json/realtimeStationArrival/0/10/" + station.getStationName();
String response = rt.getForEntity(uri, String.class).getBody();
ObjectMapper objectMapper = new ObjectMapper();
try {
JsonNode subways = objectMapper.readTree(response).get("realtimeArrivalList");
for (JsonNode subway : subways) {
// 해당 열차가 전역을 출발했을 경우
if (subway.get("arvlCd").asInt() == 0 || subway.get("arvlCd").asInt() == 3) {
int subwayLine = subway.get("subwayId").asInt(); // 지하철 노선
int subwayNo = subway.get("btrainNo").asInt(); // 해당 열차 번호
String stationID = station.getStationId(); // 목적지 역 id
String goingRoute = subway.get("updnLine").asText(); // 상행 or 하행
// 해당 역, 열차를 가지고 설정된 알림이 있는지 검사해서 알림 전송
ArrayList<Alarm> alarms = alarmRepository.findAllBySubwayLineAndSubwayNoAndStationIDAndGoingRoute(subwayLine, subwayNo, stationID, goingRoute);
// 삭제할 알람 목록을 담을 리스트
List<Alarm> alarmsToRemove = new ArrayList<>();
alarms.forEach(alarm -> {
SendPushDTO sdto = new SendPushDTO();
sdto.setTitle("목적지 도착 알림");
sdto.setContent("탑승하신 열차가 목적지의 전역을 출발했습니다. 이번 정차역에서 내리시면 됩니다!");
sdto.setUser(alarm.getUser());
try {
fcmService.sendPush(sdto);
} catch (FirebaseMessagingException e) {
e.printStackTrace();
}
alarmsToRemove.add(alarm);
// 해당 역에 설정된 알림 개수를 하나씩 줄인다.
Station destination = stationRepository.findByStationId(alarm.getStationID());
destination.setSettedAlarm(destination.getSettedAlarm() - 1);
});
// 푸시 알림 전송을 끝마친 DB 칼럼은 삭제한다
alarmRepository.deleteAll(alarmsToRemove);
}
}
} catch (JsonProcessingException e) {
e.printStackTrace();
}
});
}
여튼 이렇게 하면... 푸시 알림 전송 로직 자체는 구현이 완료될 것...
그런데 가끔 푸시가 전송이 안 되는 경우가 많은데... 왜 이럴까....??
아마 푸시를 전송하는 것까진 구현했는데... 아직 할 일이 더 남은 것 같다...
푸시가 운에 따라 전송되는데... 다음 포스트에서는 그 이유를 찾아보려고 한다..............
'프로젝트 > SUFY' 카테고리의 다른 글
[도착 알리미 SUFY] 10. 설정한 알림 조회 (0) | 2024.02.25 |
---|---|
[도착 알리미 SUFY] 9. FCM으로 포그라운드 푸시 알림 보내기 (0) | 2024.02.24 |
[도착 알리미 SUFY] 7. FCM을 활용하여 푸시 알림 전송하기 (0) | 2024.02.19 |
[도착 알리미 SUFY] 6. 일정 시각마다 특정 작업 수행 로직 구현하기 (1) | 2024.02.16 |
[도착 알리미 SUFY] 5. 알림 정보를 DB에 등록하기 (1) | 2024.02.15 |