github.com/seeker-insurance/kit@v0.0.13/push/apn.go (about)

     1  package push
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  
     7  	"github.com/seeker-insurance/kit/config"
     8  	"github.com/seeker-insurance/kit/log"
     9  	"github.com/sideshow/apns2"
    10  	"github.com/sideshow/apns2/certificate"
    11  	"github.com/spf13/cobra"
    12  	"github.com/spf13/viper"
    13  	"os"
    14  )
    15  
    16  const (
    17  	alertTemplate = `{"aps":{"alert":"%v"}}`
    18  	defautFile    = `/etc/eyecue_keys/push.p12`
    19  )
    20  
    21  var (
    22  	client *apns2.Client
    23  	topic  string
    24  )
    25  
    26  func init() {
    27  	cobra.OnInitialize(setup, connectClient)
    28  }
    29  
    30  func setup() {
    31  	viper.SetDefault("push_key_file", defautFile)
    32  }
    33  
    34  func connectClient() {
    35  	topic = config.RequiredString("push_topic")
    36  	keyFile := viper.GetString("push_key_file")
    37  
    38  	if keyFile == "" {
    39  		log.Warnf("No push key location provided")
    40  		return
    41  	}
    42  
    43  	if _, err := os.Stat(keyFile); os.IsNotExist(err) {
    44  		log.Warnf("No push key found at: %s", keyFile)
    45  		return
    46  	}
    47  
    48  	cert, err := certificate.FromP12File(keyFile, "")
    49  
    50  	if err != nil {
    51  		log.Fatal(err)
    52  	}
    53  	client = apns2.NewClient(cert).Production()
    54  }
    55  
    56  func push(token string, payload string) error {
    57  	notification := &apns2.Notification{
    58  		DeviceToken: token,
    59  		Topic:       topic,
    60  		Payload:     payload,
    61  	}
    62  
    63  	res, err := client.Push(notification)
    64  
    65  	if err != nil {
    66  		return err
    67  	}
    68  
    69  	if res.StatusCode != http.StatusOK {
    70  		return fmt.Errorf("push error: %v", res.Reason)
    71  	}
    72  	return nil
    73  }
    74  
    75  func Alert(token string, message string) error {
    76  	return push(token, fmt.Sprintf(alertTemplate, message))
    77  }