PushUtils.java 11 KB

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