kokbee-Hive

이전 글에 이어서 이번에 안드로이드용 푸시 진행 후 중국(China) 진행했던 내용을 기록 및 공유합니다.

 

* 참고: firebase 사이트에서 앱 등록 및 세팅 다 가정되어 있고 그 이후에 내용입니다.

 

1.  개발 진행 전


  1.  요구사항 분석 (Android)
    1.  기존 백오피스에서 사용하던 올드한 방식의 푸시를 간편하게 개선
    2.  FCM을 사용할 수 없는 환경에서 안드로이드 푸시 전송
      1. 중국에서는 구글이 차단되어 구글이 제공하는 서비스를 사용할 수 없다. (구글플레이, FCM..)
    3.  타이틀 추가 및 bold 기능 (subtitle or title로 가능), 줄바꿈

https://pushy.me/docs/api/send-notifications

 

Pushy - Docs - API - Send Notifications

POST https://api.pushy.me/push?api_key=SECRET_API_KEY Note: Make sure to replace SECRET_API_KEY with your app's Secret API Key, available in the Pushy Dashboard (Click your app -> API Authentication tab). This is a backend API endpoint. Never expose your a

pushy.me

 

 

2.  모듈 교체 및 코드 작성


* FCM 할때와 플로우는 비슷하기 때문에 스킵합니다.
https://kokbee.tistory.com/3 페이지를 보고 와주시면 감사하겠습니다. 🙇‍♂️


임시로 블로그에 올리려고 짠 코드입니다.
대충 이런 느낌이라고 보시면 될것 같습니다.

 

const Pushy = require('pushy')
const request = require('request')

const provider = new Pushy(options.key)
const apiKey = myApiKey

//  pushy 의 경우 사용하지 않아도 token 은 계속 유효하기 때문에, presence API 결과 값의 기준으로 보낸다.
function send (options) {
  const { body, subtitle, ttl } = options

  const opt = {
    body,
    time_to_live: ttl,
    notification: {}
  }
  if (options.subtitle) opt.notification.title = options.subtitle

  const data = {
    ...opt.notification,
    message: options.body
  }
  const tokens = options.device_list.map((d) => d.device_token)


  let sent = []
  getDevicePresence(tokens)
    .then((result) => { //presence 30일 기준
      if (!result || !result.presence) {
        throw new Error('No presence information in pushy presence api response!')
      }

      result = result.presence.filter((d) => {
        const diff = new Date().getTime() - new Date(d.last_active * 1000)
        const isValid = diff < 3600 * 24 * 30 * 1000
        return isValid
      })
      sent = result.map((r) => r.id)
      if (sent.length === 0) return null

      return provider.sendPushNotification(data, sent, opt)
    })
    .then((id) => {
      const failed = tokens.filter((t) => sent.indexOf(t) < 0)
      console.log('failed: ', failed)
    })
    .catch((err) => console.log(err, { tokens }))
}

async function getDevicePresence (tokens) {
  const uri = `https://api.pushy.me/devices/presence?api_key=${apiKey}`
  const json = { tokens }
  return new Promise((resolve, reject) => {
    return request(uri, { method: 'POST', body: JSON.stringify(json) })
      .then((response, json) => resolve(json))
      .catch((err) => reject(err))
  })
}

 

3.  테스트 및 결과


사실상 FCM, APNS 보다는 쉽다.
토큰 길이 또한 짧으며, 무엇보다 모듈내의 인터페이스 사양이 간결하게 도큐먼트에 적혀 있었음
그리고 테스트로도 웹에서 사용가능하기 크게 걸림돌이 없었다.

이상으로 포스팅을 마칩니다. 

profile

kokbee-Hive

@콕비

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!