Exemple #1
0
// Run consume available job based on tube watched and proceed the task
func (w *ApnsWorker) Run() {
	fmt.Printf("[worker] Starting APNS worker\n")
	tube := beanstalk.NewTubeSet(w.Conn, w.TubeName)
	for {
		id, body, err := tube.Reserve(24 * time.Hour)
		if err != nil {
			panic(err)
		}

		var data Job
		err = json.Unmarshal(body, &data)

		if w.ApnsConn == nil {
			certPem, err := ioutil.ReadFile(data.Config.CertPem)
			if err != nil {
				panic(err)
			}
			keyPem, err := ioutil.ReadFile(data.Config.KeyPem)
			if err != nil {
				panic(err)
			}

			w.ApnsConn, _ = apns.NewAPNSConnection(&apns.APNSConfig{
				CertificateBytes: certPem,
				KeyBytes:         keyPem,
			})

			defer w.ApnsConn.Disconnect()
		}

		customField := make(map[string]interface{})
		customField["type"] = data.Data.PushType

		payload := &apns.Payload{
			Token:        data.Data.DeviceToken,
			AlertText:    data.Data.Alert,
			Sound:        data.Data.Sound,
			Badge:        apns.NewBadgeNumber(1),
			CustomFields: customField,
		}

		w.ApnsConn.SendChannel <- payload

		w.Conn.Delete(id)
	}
}
func apnsService(config *apns.APNSConfig, sendChannel <-chan *apns.Payload, closeErrFn HandleCloseErrorFn, shutdownChannel chan bool) {
	shutdown := false
	connectionGood := false
	var lastConn *apns.APNSConnection = nil

	for {
		if shutdown {
			break
		}

		log.Printf("establishing connection")
		conn, err := apns.NewAPNSConnection(config)

		if err != nil {
			connectionGood = false
			fmt.Println(err)

			select {
			case <-time.After(time.Second * 5):
				continue
			case <-shutdownChannel:
				shutdown = true
			}
		} else {
			lastConn = conn
			connectionGood = true
		}

		for {
			if !connectionGood || shutdown {
				break
			}

			select {
			case payload := <-sendChannel:
				log.Printf("sending id %v\n", payload.ExtraData)
				select {
				case <-time.After(time.Second * 1):
					break
				case conn.SendChannel <- payload:
					break
				}
				break
			case closeError := <-conn.CloseChannel:
				closeErrFn(closeError)
				connectionGood = false
				log.Printf("Received error, closing connection")
				break
			case <-shutdownChannel:
				log.Printf("Received shutdown signal, closing connection")
				conn.Disconnect()
				shutdown = true
			}
		}
		log.Printf("Connection killed attempting re-establish")
	}

	if lastConn != nil {
		select {
		case <-time.After(time.Second * 5):
			break
		case closeError := <-lastConn.CloseChannel:
			closeErrFn(closeError)
		}
	}

	log.Printf("going to shutdown")
	shutdownChannel <- true
}