FirebaseService.kt 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package io.nexilis.service
  2. import android.util.Log
  3. import com.google.firebase.messaging.FirebaseMessagingService
  4. import com.google.firebase.messaging.RemoteMessage
  5. import dagger.hilt.android.EntryPointAccessors
  6. import io.nexilis.service.core.Data
  7. import io.nexilis.service.core.IncomingInterface
  8. import io.nexilis.service.core.Network
  9. import io.nexilis.service.core.getSharedPreferences
  10. import org.json.JSONObject
  11. class FirebaseService : FirebaseMessagingService() {
  12. override fun onNewToken(token: String) {
  13. super.onNewToken(token)
  14. Log.d(tag, "onNewToken:$token")
  15. Api.sendToken(applicationContext, token)
  16. }
  17. override fun onMessageReceived(message: RemoteMessage) {
  18. super.onMessageReceived(message)
  19. Log.d(tag, "onMessageReceived:${message.data}")
  20. try {
  21. val json = JSONObject(message.data.toMap())
  22. json.optString("message_id").let { messageId ->
  23. applicationContext.getSharedPreferences().getString("pin", null)?.let { me ->
  24. pullMessage(messageId, me)
  25. }
  26. }
  27. } catch (_: Exception) {
  28. }
  29. }
  30. private fun pullMessage(messageId: String, me: String) {
  31. Network().post(
  32. "https://202.158.33.27/pull_notification",
  33. "message_id=$messageId&pin=$me"
  34. ) { r, body ->
  35. if (r && !body.isNullOrEmpty()) {
  36. val data = JSONObject(body).optString("data")
  37. if (data.isNotEmpty()) {
  38. val d = Data()
  39. if (d.parse(data)) {
  40. val entryPoint = EntryPointAccessors.fromApplication(
  41. applicationContext,
  42. IncomingInterface::class.java
  43. )
  44. entryPoint.incoming().process(d) {
  45. if (it) {
  46. Network().post(
  47. "https://202.158.33.27/ack_message",
  48. "message_id=$messageId&pin=$me"
  49. ) { _, _ ->
  50. }
  51. }
  52. }
  53. }
  54. }
  55. }
  56. }
  57. }
  58. }