Listening for new messages

Although Google provides the ability to use push messaging, the setup is very complicated—so instead, we'll poll for new messages. Every 10 seconds, we should download any new messages that have arrived. To do this, we can use the history API, which returns any messages that appeared after a specific point in history (set using StartHistoryId()). HistoryId is a chronological number that marks the order that messages arrived in. Before we can use the history API, we need to have a valid HistoryId—we can do this by adding the following line to the downloadMessage() function:

g.history = uint64(math.Max(float64(g.history), float64(mail.HistoryId)))

Once we have a point in history to query from, we need a new function that can download any messages since this point in time. The following code is similar to downloadMessages() in the preceding code but will only download new messages:

func (g *gMailServer) downloadNewMessages(srv *gmail.Service) []*EmailMessage{
req := srv.Users.History.List(g.user)
req.StartHistoryId(g.history)
req.LabelId("INBOX")
resp, err := req.Do()
if err != nil {
log.Fatalf("Unable to retrieve Inbox items: %v", err)
}

var emails []*EmailMessage
for _, history := range resp.History {
for _, message := range history.Messages {
email := downloadMessage(srv, message)
emails = append(emails, email)
}
}

return emails
}

To complete the functionality, we update our Incoming() method so that it sets up the channel and starts a thread to poll for new messages. Every 10 seconds, we'll download any new messages that have appeared and pass each to the in channel that was created:

func (g *gMailServer) Incoming() chan *EmailMessage {
in := make(chan *EmailMessage)

go func() {
for {
time.Sleep(10 * time.Second)

for _, email := range downloadNewMessages(srv) {
g.emails = append([]*EmailMessage{email}, g.emails...)
in <- email
}
}
}()

return in
}

The complete code can be found in the client package of this book's code repository. Let's look at how to use this new email server in our previous examples.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.215.96