本文整理汇总了Golang中github.com/alexjlockwood/gcm.NewMessage函数的典型用法代码示例。如果您正苦于以下问题:Golang NewMessage函数的具体用法?Golang NewMessage怎么用?Golang NewMessage使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewMessage函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: CreateCard
func CreateCard(notif me.NotifModel, ts int) string {
db.CardCounter += 1
cardId := strconv.Itoa(db.CardCounter)
db.Card[cardId] = me.CardModel{cardId, notif.Id, ts, false}
if owner, ok := db.User[notif.OwnerId]; ok {
if client, okk := db.User[notif.ClientId]; okk {
owner.CardIds = append(owner.CardIds, cardId)
db.User[notif.OwnerId] = owner
data := map[string]interface{}{"title": notif.Name, "id": cardId}
regIDs := []string{client.RegId}
msg := gcm.NewMessage(data, regIDs...)
// Create a Sender to send the message.
sender := &gcm.Sender{ApiKey: "AIzaSyDhdyFnigm2EfKj4LgccjytRYcvUWl6aLA"}
// Send the message and receive the response after at most two retries.
_, err := sender.Send(msg, 2)
if err != nil {
fmt.Println("Failed to send message: %v", err)
} else {
fmt.Println("Message is sent.")
}
return cardId
}
}
return ""
}
示例2: sendAndroidNotification
func sendAndroidNotification(msg *PushNotification) {
var data map[string]interface{}
if msg.Type == PUSH_TYPE_CLEAR {
data = map[string]interface{}{"type": PUSH_TYPE_CLEAR, "channel_id": msg.ChannelId, "team_id": msg.TeamId}
} else {
data = map[string]interface{}{"type": PUSH_TYPE_MESSAGE, "message": emoji.Sprint(msg.Message), "channel_id": msg.ChannelId, "channel_name": msg.ChannelName, "team_id": msg.TeamId}
}
regIDs := []string{msg.DeviceId}
gcmMsg := gcm.NewMessage(data, regIDs...)
sender := &gcm.Sender{ApiKey: CfgPP.AndroidApiKey}
if len(CfgPP.AndroidApiKey) > 0 {
LogInfo("Sending android push notification")
resp, err := sender.Send(gcmMsg, 2)
if err != nil {
LogError(fmt.Sprintf("Failed to send GCM push sid=%v did=%v err=%v", msg.ServerId, msg.DeviceId, err))
return
}
if resp.Failure > 0 {
LogError(fmt.Sprintf("Android response failure: %v", resp))
}
}
}
示例3: sendMessageToGCM
func (gcmConnector *GCMConnector) sendMessageToGCM(msg server.MsgAndRoute) {
gcmId := msg.Route.ApplicationId
payload := gcmConnector.parseMessageToMap(msg.Message)
var messageToGcm = gcm.NewMessage(payload, gcmId)
guble.Info("sending message to %v ...", gcmId)
result, err := gcmConnector.sender.Send(messageToGcm, 5)
if err != nil {
guble.Err("error sending message to cgmid=%v: %v", gcmId, err.Error())
return
}
errorJson := result.Results[0].Error
if errorJson != "" {
gcmConnector.handleJsonError(errorJson, gcmId, msg.Route)
} else {
guble.Debug("delivered message to gcm cgmid=%v: %v", gcmId, errorJson)
}
//we only send to one receiver, so we know that we can replace the old id with the first registration id (=canonical id)
if result.CanonicalIDs != 0 {
gcmConnector.replaceSubscriptionWithCanonicalID(msg.Route, result.Results[0].RegistrationID)
}
}
示例4: Done
/* Mark the card as completed and
Send a notification to the owner of the card
*/
func Done(c *gin.Context) {
cardId := c.Param("card_id")
if card, ok := db.Card[cardId]; ok {
card.Completed = true
db.Card[cardId] = card
if notif, okk := db.Notif[card.NotifId]; okk {
if user, okkk := db.User[notif.OwnerId]; okkk {
data := map[string]interface{}{"title": notif.Name + " is done.", "id": cardId}
regIDs := []string{user.RegId}
msg := gcm.NewMessage(data, regIDs...)
// Create a Sender to send the message.
sender := &gcm.Sender{ApiKey: "AIzaSyDhdyFnigm2EfKj4LgccjytRYcvUWl6aLA"}
// Send the message and receive the response after at most two retries.
_, err := sender.Send(msg, 2)
if err != nil {
c.String(http.StatusInternalServerError, fmt.Sprintf("Failed to send message: %v", err))
} else {
c.String(http.StatusOK, "Message is sent.")
}
}
}
} else {
c.String(http.StatusNotFound, "")
}
}
示例5: broadcastMessage
func (gcmConnector *GCMConnector) broadcastMessage(msg server.MsgAndRoute) {
topic := msg.Message.Path
payload := gcmConnector.parseMessageToMap(msg.Message)
guble.Info("broadcasting message with topic %v ...", string(topic))
subscriptions := gcmConnector.kvStore.Iterate(GCM_REGISTRATIONS_SCHEMA, "")
count := 0
for {
select {
case entry, ok := <-subscriptions:
if !ok {
guble.Info("send message to %v receivers", count)
return
}
gcmId := entry[0]
//TODO collect 1000 gcmIds and send them in one request!
broadcastMessage := gcm.NewMessage(payload, gcmId)
go func() {
//TODO error handling of response!
_, err := gcmConnector.sender.Send(broadcastMessage, 3)
guble.Debug("sent broadcast message to gcmId=%v", gcmId)
if err != nil {
guble.Err("error sending broadcast message to cgmid=%v: %v", gcmId, err.Error())
}
}()
count++
}
}
}
示例6: notify
func notify(meeting Meeting, status int) {
data := map[string]interface{}{
"action": "meeting_started",
"meeting_id": meeting.Id.Hex(),
"meeting_goal": meeting.Goal,
}
devices := devices(meeting)
msg := gcm.NewMessage(data, devices...)
cfg := config.Section("gcm")
apikey := cfg.Key("apikey").String()
sender := &gcm.Sender{ApiKey: apikey}
_, err := sender.Send(msg, cfg.Key("retries").MustInt(3))
if err != nil {
log.Fatal("Failed to send message:", err)
} else {
log.Print(len(devices), " devices notified that ", meeting.String(), " changed to ", status)
}
}
示例7: NotifyUsers
func NotifyUsers(deviceTokens []string) error {
sender := &gcm.Sender{ApiKey: "AIzaSyBEHLA1FR4OlCRQE1vPv_mfqQaIF0ICZeA"}
message := gcm.NewMessage(nil, deviceTokens...)
_, err := sender.Send(message, 2)
fmt.Println("Successfully sent a notification to device token : ", deviceTokens)
if err != nil {
return fmt.Errorf("Error sending notifications: %s", err)
}
return nil
}
示例8: Send
func (n *Notification) Send() (errList Notification, err error) {
// GCM
apnTask := make(chan bool)
gcmTask := make(chan bool)
var (
apnWG sync.WaitGroup
gcmWG sync.WaitGroup
)
go func() { // parallel between APN and GCM
// APN
p := apns.NewPayload()
p.APS.Alert.Body = n.Message
p.APS.ContentAvailable = 1
m := apns.NewNotification()
m.Payload = p
m.Priority = apns.PriorityImmediate
apnWG.Add(len(n.APNReceivers))
for _, v := range APNReceivers {
go func() {
m.DeviceToken = v
apnClient.Send(m)
apnWG.Done()
}() // parallel for APN
}
// HERE err handling for APN
go func() {
for _, f := range apnClient.FailedNotifs {
errList.APNReceivers = append(errList.APNReceivers, f.Notif.ID)
}
}()
apnWG.Wait()
apnTask <- true
}()
// GCM
go func() {
gcmWG.Add(len(n.GCMReceivers))
data := map[string]interface{}{"message": n.Message}
for _, v := range GCMReceivers() {
go func() {
d := gcm.NewMessage(data, v)
_, err := gcmClient.Send(d, 0)
if err != nil {
errList.GCMReceivers = append(errList.GCMReceivers, v)
}
gcmWG.Done()
}()
}
gcmWG.Wait()
gcmTask <- true
}()
<-apnTask
<-gcmTask
return
}
示例9: Send
// Send Push
func (self *Gcm) Send() (interface{}, error) {
msg := gcm.NewMessage(self.Data, self.RegIds...)
// Create a Sender to send the message.
sender := &gcm.Sender{ApiKey: APIKEY}
// Send the message and receive the response after at most two retries.
response, err := sender.Send(msg, 2)
if err != nil {
return response, err
}
return response, nil
}
示例10: Check
// Check returns nil if health-check succeeds, or an error if health-check fails
// by sending a request with only apikey. If the response is processed by the GCM endpoint
// the gcmStatus will be UP, otherwise the error from sending the message will be returned.
func (conn *GCMConnector) Check() error {
payload := conn.parseMessageToMap(&protocol.Message{Body: []byte(`{"registration_ids":["ABC"]}`)})
_, err := conn.Sender.Send(gcm.NewMessage(payload, ""), sendRetries)
if err != nil {
log.WithFields(log.Fields{
"module": "GCM",
"err": err,
}).Error("Error sending ping message")
return err
}
return nil
}
示例11: gcmNotify
func gcmNotify(att string, msg string, errHandle *[]string, wg *sync.WaitGroup) (status bool) {
status = true
d := map[string]interface{}{"message": msg}
sender := &gcm.Sender{ApiKey: gcmauth}
data := gcm.NewMessage(d, att)
_, err := sender.Send(data, 0)
if err != nil {
status = false
}
wg.Done()
if status == false {
*errHandle = append(*errHandle, att)
}
return
}
示例12: pushNotificationAndroid
func pushNotificationAndroid(req RequestGaurunNotification) bool {
LogError.Debug("START push notification for Android")
data := map[string]interface{}{"message": req.Message}
if len(req.Extend) > 0 {
for _, extend := range req.Extend {
data[extend.Key] = extend.Value
}
}
msg := gcm.NewMessage(data, req.Tokens...)
msg.CollapseKey = req.CollapseKey
msg.DelayWhileIdle = req.DelayWhileIdle
msg.TimeToLive = req.TimeToLive
stime := time.Now()
resp, err := GCMClient.SendNoRetry(msg)
etime := time.Now()
ptime := etime.Sub(stime).Seconds()
if err != nil {
atomic.AddInt64(&StatGaurun.Android.PushError, 1)
for i, token := range req.Tokens {
LogPush(req.IDs[i], StatusFailedPush, token, ptime, req, err)
}
return false
}
if resp.Failure > 0 {
atomic.AddInt64(&StatGaurun.Android.PushSuccess, int64(resp.Success))
atomic.AddInt64(&StatGaurun.Android.PushError, int64(resp.Failure))
if len(resp.Results) == len(req.Tokens) {
for i, token := range req.Tokens {
if resp.Results[i].Error != "" {
LogPush(req.IDs[i], StatusFailedPush, token, ptime, req, errors.New(resp.Results[i].Error))
}
}
}
return true
}
for i, token := range req.Tokens {
LogPush(req.IDs[i], StatusSucceededPush, token, ptime, req, nil)
}
StatGaurun.Android.PushSuccess += int64(len(req.Tokens))
LogError.Debug("END push notification for Android")
return true
}
示例13: broadcastMessage
func (conn *GCMConnector) broadcastMessage(msg *server.MessageForRoute) {
topic := msg.Message.Path
payload := conn.parseMessageToMap(msg.Message)
log.WithFields(log.Fields{
"module": "GCM",
"topic": string(topic),
"channel_length": len(conn.routerC),
}).Debug("Broadcasting message with ")
subscriptions := conn.kvStore.Iterate(registrationsSchema, "")
count := 0
for {
select {
case entry, ok := <-subscriptions:
if !ok {
log.WithFields(log.Fields{
"module": "GCM",
"receivers_count": count,
}).Info("Sent to message to ")
return
}
gcmID := entry[0]
//TODO collect 1000 gcmIds and send them in one request!
broadcastMessage := gcm.NewMessage(payload, gcmID)
go func() {
//TODO error handling of response!
_, err := conn.Sender.Send(broadcastMessage, broadcastRetries)
log.WithFields(log.Fields{
"module": "GCM",
"gcmID": gcmID,
}).Debug("Sent broadcast message to")
if err != nil {
log.WithFields(log.Fields{
"module": "GCM",
"gmcId": gcmID,
"err": err,
}).Error("Error sending broadcast message to")
}
}()
count++
}
}
}
示例14: pushAndroid
func (this *CommandMsg) pushAndroid(server *Server) {
registration_ids, registration_ids_ok := this.Command["registration_ids"]
if !registration_ids_ok {
log.Println("Registration ID(s) not provided!")
return
}
msg, err := this.formatMessage()
if err != nil {
log.Println("Could not format message")
return
}
data := map[string]interface{}{"event": msg.Event, "data": msg.Data, "time": msg.Time}
regIDs := strings.Split(registration_ids, ",")
gcmMessage := gcm.NewMessage(data, regIDs...)
sender := server.GetGCMClient()
server.Stats.LogGCMPush()
gcmResponse, gcmErr := sender.Send(gcmMessage, 2)
if gcmErr != nil {
server.Stats.LogGCMError()
log.Printf("Error (Android): %s\n", gcmErr)
return
}
if gcmResponse.Failure > 0 {
server.Stats.LogGCMFailure()
if !server.Config.GetBool("redis_enabled") {
log.Println("Could not push to android_error_queue since redis is not enabled")
return
}
failurePayload := map[string]interface{}{"registration_ids": regIDs, "results": gcmResponse.Results}
msg_str, _ := json.Marshal(failurePayload)
server.Store.redis.Push(server.Config.Get("android_error_queue"), string(msg_str))
}
}
示例15: CreateNotif
func CreateNotif(card me.CardModel, ts int) {
if notif, ok := db.Notif[card.NotifId]; ok {
if client, okk := db.User[notif.ClientId]; okk {
data := map[string]interface{}{"title": notif.Name, "id": card.Id}
regIDs := []string{client.RegId}
msg := gcm.NewMessage(data, regIDs...)
// Create a Sender to send the message.
sender := &gcm.Sender{ApiKey: "AIzaSyDhdyFnigm2EfKj4LgccjytRYcvUWl6aLA"}
// Send the message and receive the response after at most two retries.
_, err := sender.Send(msg, 2)
if err != nil {
fmt.Println("Failed to send message: %v", err)
} else {
fmt.Println("Message is sent.")
}
}
}
}