PushUtils.java 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. package com.lemon.lifecenter.scheduler.common;
  2. import java.io.FileNotFoundException;
  3. import java.io.IOException;
  4. import java.text.DateFormat;
  5. import java.text.ParseException;
  6. import java.text.SimpleDateFormat;
  7. import java.time.Duration;
  8. import java.time.LocalTime;
  9. import java.util.Calendar;
  10. import java.util.Date;
  11. import java.util.HashMap;
  12. import java.util.Locale;
  13. import org.slf4j.Logger;
  14. import org.slf4j.LoggerFactory;
  15. import org.springframework.core.io.ClassPathResource;
  16. import org.springframework.stereotype.Component;
  17. import com.google.auth.oauth2.GoogleCredentials;
  18. import com.google.firebase.FirebaseApp;
  19. import com.google.firebase.FirebaseOptions;
  20. import com.google.firebase.messaging.AndroidConfig;
  21. import com.google.firebase.messaging.AndroidNotification;
  22. import com.google.firebase.messaging.ApnsConfig;
  23. import com.google.firebase.messaging.Aps;
  24. import com.google.firebase.messaging.ApsAlert;
  25. import com.google.firebase.messaging.AndroidNotification.Priority;
  26. import com.google.firebase.messaging.FirebaseMessaging;
  27. import com.google.firebase.messaging.FirebaseMessagingException;
  28. import com.google.firebase.messaging.Message;
  29. @Component
  30. public class PushUtils {
  31. private final Logger logger = LoggerFactory.getLogger(this.getClass());
  32. public HashMap<String, String> sendFcm(String deviceKey, String title, String content, String redirectUrl) {
  33. HashMap<String, String> result = new HashMap<String, String>();
  34. try {
  35. ClassPathResource cpr = new ClassPathResource("firebase/mcare-ctc-firebase-adminsdk-sn0dw-e165549145.json");
  36. FirebaseOptions options = new FirebaseOptions.Builder()
  37. .setCredentials(GoogleCredentials.fromStream(cpr.getInputStream()))
  38. .setDatabaseUrl("https://mcare-ctc.firebaseio.com/")
  39. .build();
  40. if (FirebaseApp.getApps().isEmpty()) {
  41. FirebaseApp.initializeApp(options);
  42. }
  43. String registrationToken = deviceKey;
  44. AndroidNotification notification = AndroidNotification.builder().setTitle(title).setBody(content).setSound("ctc_alarm.wav").setChannelId("ctc_alarm").setClickAction(".LoadingActivity").setPriority(Priority.MAX).build();
  45. AndroidConfig androidConfig = AndroidConfig.builder().setPriority(AndroidConfig.Priority.HIGH).setNotification(notification).setTtl(7200).build();
  46. ApsAlert apsAlert = ApsAlert.builder().setTitle(title).setBody(content).build();
  47. // Aps aps = Aps.builder().setSound("default").setAlert(apsAlert).build();
  48. Aps aps = Aps.builder().setSound("ctc_alarm.wav").setAlert(apsAlert).build();
  49. ApnsConfig apnsConfig = ApnsConfig.builder().setAps(aps).build();
  50. Message message = Message.builder()
  51. .setAndroidConfig(androidConfig)
  52. .setApnsConfig(apnsConfig)
  53. .putData("redirectUrl", redirectUrl)
  54. .setToken(registrationToken).build();
  55. // Message message = Message.builder()
  56. // .setAndroidConfig(androidConfig)
  57. // .setApnsConfig(apnsConfig)
  58. // .setToken(registrationToken).build();
  59. String response = FirebaseMessaging.getInstance().send(message);
  60. result.put("success", "success");
  61. return result;
  62. } catch (FileNotFoundException e) {
  63. // logger.error("fileNotFound -- > " + e);
  64. result.put("FileNotFound", "FileNotFound");
  65. } catch (IOException e) {
  66. logger.error("IOException -- > " + e);
  67. result.put("IOException", "IOException");
  68. } catch (FirebaseMessagingException e) {
  69. // logger.error("FirebaseMessagingException -- > " + e);
  70. // logger.error("FirebaseMessagingException -- > " + e.getErrorCode());
  71. // logger.error("FirebaseMessagingException -- > " + e.getMessage());
  72. // result = errorMsg(e.getErrorCode().toString().trim());
  73. result.put(e.getErrorCode().toString().trim(), e.getMessage());
  74. }
  75. return result;
  76. }
  77. // private String errorMsg(String e) {
  78. // String msg = "";
  79. // if (fcmErrorCode().get(e) != null) {
  80. // msg = fcmErrorCode().get(e);
  81. // } else {
  82. // msg = fcmErrorCode().get("FATAL");
  83. // }
  84. //
  85. // return msg;
  86. // }
  87. //
  88. // private HashMap<String, String> fcmErrorCode() {
  89. // HashMap<String, String> code = new HashMap<String, String>();
  90. // code.put("UNSPECIFIED_ERROR", "이 오류에 대한 추가 정보가 없습니다.");
  91. // code.put("INVALID_ARGUMENT", "(HTTP 오류 코드 = 400) 요청 매개 변수가 유효하지 않습니다. google.rpc.BadRequest 유형의 확장자가 리턴되어 유효하지 않은 필드를 지정합니다.");
  92. // code.put("UNREGISTERED", " (HTTP 오류 코드 = 404) FCM에서 앱 인스턴스가 등록 해제되었습니다. 이것은 일반적으로 사용 된 토큰이 더 이상 유효하지 않으며 새로운 토큰을 사용해야 함을 의미합니다.");
  93. // code.put("SENDER_ID_MISMATCH", "(HTTP 오류 코드 = 403) 인증 된 발신자 ID가 등록 토큰의 발신자 ID와 다릅니다.");
  94. // code.put("QUOTA_EXCEEDED", "(HTTP 오류 코드 = 429) 메시지 대상에 대한 전송 제한이 초과되었습니다. 초과 한 할당량을 지정하기 위해 google.rpc.QuotaFailure 유형의 확장이 반환됩니다..");
  95. // code.put("UNAVAILABLE", " (HTTP 오류 코드 = 503) 서버가 과부하되었습니다.");
  96. // code.put("INTERNAL", "(HTTP 오류 코드 = 500) 알 수없는 내부 오류가 발생했습니다.");
  97. // code.put("THIRD_PARTY_AUTH_ERROR", "(HTTP 오류 코드 = 401) APN 인증서 또는 웹 푸시 인증 키가 잘못되었거나 없습니다.");
  98. // code.put("FATAL", "알수없는 오류");
  99. // code.put("FileNotFound", "FileNotFound");
  100. // code.put("IOException", "IOException");
  101. // return code;
  102. // }
  103. public String getNowYm() {
  104. DateFormat dateFormat = new SimpleDateFormat("yyyyMM");
  105. Date date = new Date();
  106. return dateFormat.format(date);
  107. }
  108. public String getNextYm() {
  109. DateFormat dateFormat = new SimpleDateFormat("yyyyMM");
  110. Calendar cal = Calendar.getInstance();
  111. cal.add (cal.MONTH, + 1); //다음달
  112. return dateFormat.format(cal.getTime());
  113. }
  114. public String getNow() {
  115. DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  116. Date date = new Date();
  117. return dateFormat.format(date);
  118. }
  119. public boolean compareDateTime(String dateTime) {
  120. boolean result = false;
  121. try {
  122. DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
  123. Date date = new Date();
  124. Date nowTime = dateFormat.parse(dateFormat.format(date));
  125. Date sendTime = dateFormat.parse(dateTime);
  126. result = nowTime.after(sendTime) || nowTime.equals(sendTime);
  127. } catch (ParseException e) {
  128. // TODO Auto-generated catch block
  129. e.printStackTrace();
  130. result = false;
  131. }
  132. return result;
  133. }
  134. public boolean compareTime(String time) {
  135. boolean result = false;
  136. try {
  137. DateFormat dateFormat = new SimpleDateFormat("HH:mm");
  138. Date date = new Date();
  139. Date nowTime = dateFormat.parse(dateFormat.format(date));
  140. Date sendTime = dateFormat.parse(time);
  141. long between30m = (nowTime.getTime() - sendTime.getTime()) / (1000 * 60);
  142. if (between30m <= 30 && between30m >= 0) {
  143. result = true;
  144. }
  145. // if (nowTime.getTime() == sendTime.getTime()) {
  146. // result = true;
  147. // }
  148. } catch (ParseException e) {
  149. // TODO Auto-generated catch block
  150. e.printStackTrace();
  151. result = false;
  152. }
  153. return result;
  154. }
  155. // public void apnsSend() {
  156. // ClassPathResource cpr = new ClassPathResource("apns/dev/certify.p12");
  157. // logger.error("name -- > " + cpr.getFilename());
  158. // logger.error("path -- > " + cpr.getPath());
  159. // try {
  160. // logger.error("file -- > " + cpr.getFile().getAbsolutePath());
  161. //
  162. // ApnsService service =
  163. // APNS.newService()
  164. // .withCert(cpr.getFile().getAbsolutePath(), "jksong092") // 指定p12文件及密钥
  165. // .withSandboxDestination() // 使用苹果推送测试服务器
  166. // //.withProductionDestination() // 使用苹果推送生产服务器
  167. // .build();
  168. //
  169. // String payload = APNS.newPayload()
  170. //// .alertTitle("推送标题") // 标题
  171. // .alertBody("푸시발송 테스트") // 内容
  172. // .customField("sourceCode", "01") // 自定义字段
  173. // .customField("url", "https://www.qq.com") // 自定义字段
  174. // .sound("default") // 提示声音
  175. // //.sound("msgsound.caf") // 提示声音(自定义)
  176. // .badge(1) // 应用角标
  177. // .build();
  178. //
  179. // String token = "1EDAE24F474C7CB5497AD92BB92C506033218BF37E7C808C8CD3B28154D41B07";
  180. //
  181. // service.push(token, payload);
  182. //
  183. // } catch (IOException e) {
  184. // // TODO Auto-generated catch block
  185. // e.printStackTrace();
  186. // }
  187. //
  188. // }
  189. }