xmpp.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. // Copyright 2011 Google Inc. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. /*
  5. Package xmpp provides the means to send and receive instant messages
  6. to and from users of XMPP-compatible services.
  7. To send a message,
  8. m := &xmpp.Message{
  9. To: []string{"kaylee@example.com"},
  10. Body: `Hi! How's the carrot?`,
  11. }
  12. err := m.Send(c)
  13. To receive messages,
  14. func init() {
  15. xmpp.Handle(handleChat)
  16. }
  17. func handleChat(c context.Context, m *xmpp.Message) {
  18. // ...
  19. }
  20. */
  21. package xmpp // import "google.golang.org/appengine/xmpp"
  22. import (
  23. "errors"
  24. "fmt"
  25. "net/http"
  26. "golang.org/x/net/context"
  27. "google.golang.org/appengine"
  28. "google.golang.org/appengine/internal"
  29. pb "google.golang.org/appengine/internal/xmpp"
  30. )
  31. // Message represents an incoming chat message.
  32. type Message struct {
  33. // Sender is the JID of the sender.
  34. // Optional for outgoing messages.
  35. Sender string
  36. // To is the intended recipients of the message.
  37. // Incoming messages will have exactly one element.
  38. To []string
  39. // Body is the body of the message.
  40. Body string
  41. // Type is the message type, per RFC 3921.
  42. // It defaults to "chat".
  43. Type string
  44. // RawXML is whether the body contains raw XML.
  45. RawXML bool
  46. }
  47. // Presence represents an outgoing presence update.
  48. type Presence struct {
  49. // Sender is the JID (optional).
  50. Sender string
  51. // The intended recipient of the presence update.
  52. To string
  53. // Type, per RFC 3921 (optional). Defaults to "available".
  54. Type string
  55. // State of presence (optional).
  56. // Valid values: "away", "chat", "xa", "dnd" (RFC 3921).
  57. State string
  58. // Free text status message (optional).
  59. Status string
  60. }
  61. var (
  62. ErrPresenceUnavailable = errors.New("xmpp: presence unavailable")
  63. ErrInvalidJID = errors.New("xmpp: invalid JID")
  64. )
  65. // Handle arranges for f to be called for incoming XMPP messages.
  66. // Only messages of type "chat" or "normal" will be handled.
  67. func Handle(f func(c context.Context, m *Message)) {
  68. http.HandleFunc("/_ah/xmpp/message/chat/", func(_ http.ResponseWriter, r *http.Request) {
  69. f(appengine.NewContext(r), &Message{
  70. Sender: r.FormValue("from"),
  71. To: []string{r.FormValue("to")},
  72. Body: r.FormValue("body"),
  73. })
  74. })
  75. }
  76. // Send sends a message.
  77. // If any failures occur with specific recipients, the error will be an appengine.MultiError.
  78. func (m *Message) Send(c context.Context) error {
  79. req := &pb.XmppMessageRequest{
  80. Jid: m.To,
  81. Body: &m.Body,
  82. RawXml: &m.RawXML,
  83. }
  84. if m.Type != "" && m.Type != "chat" {
  85. req.Type = &m.Type
  86. }
  87. if m.Sender != "" {
  88. req.FromJid = &m.Sender
  89. }
  90. res := &pb.XmppMessageResponse{}
  91. if err := internal.Call(c, "xmpp", "SendMessage", req, res); err != nil {
  92. return err
  93. }
  94. if len(res.Status) != len(req.Jid) {
  95. return fmt.Errorf("xmpp: sent message to %d JIDs, but only got %d statuses back", len(req.Jid), len(res.Status))
  96. }
  97. me, any := make(appengine.MultiError, len(req.Jid)), false
  98. for i, st := range res.Status {
  99. if st != pb.XmppMessageResponse_NO_ERROR {
  100. me[i] = errors.New(st.String())
  101. any = true
  102. }
  103. }
  104. if any {
  105. return me
  106. }
  107. return nil
  108. }
  109. // Invite sends an invitation. If the from address is an empty string
  110. // the default (yourapp@appspot.com/bot) will be used.
  111. func Invite(c context.Context, to, from string) error {
  112. req := &pb.XmppInviteRequest{
  113. Jid: &to,
  114. }
  115. if from != "" {
  116. req.FromJid = &from
  117. }
  118. res := &pb.XmppInviteResponse{}
  119. return internal.Call(c, "xmpp", "SendInvite", req, res)
  120. }
  121. // Send sends a presence update.
  122. func (p *Presence) Send(c context.Context) error {
  123. req := &pb.XmppSendPresenceRequest{
  124. Jid: &p.To,
  125. }
  126. if p.State != "" {
  127. req.Show = &p.State
  128. }
  129. if p.Type != "" {
  130. req.Type = &p.Type
  131. }
  132. if p.Sender != "" {
  133. req.FromJid = &p.Sender
  134. }
  135. if p.Status != "" {
  136. req.Status = &p.Status
  137. }
  138. res := &pb.XmppSendPresenceResponse{}
  139. return internal.Call(c, "xmpp", "SendPresence", req, res)
  140. }
  141. var presenceMap = map[pb.PresenceResponse_SHOW]string{
  142. pb.PresenceResponse_NORMAL: "",
  143. pb.PresenceResponse_AWAY: "away",
  144. pb.PresenceResponse_DO_NOT_DISTURB: "dnd",
  145. pb.PresenceResponse_CHAT: "chat",
  146. pb.PresenceResponse_EXTENDED_AWAY: "xa",
  147. }
  148. // GetPresence retrieves a user's presence.
  149. // If the from address is an empty string the default
  150. // (yourapp@appspot.com/bot) will be used.
  151. // Possible return values are "", "away", "dnd", "chat", "xa".
  152. // ErrPresenceUnavailable is returned if the presence is unavailable.
  153. func GetPresence(c context.Context, to string, from string) (string, error) {
  154. req := &pb.PresenceRequest{
  155. Jid: &to,
  156. }
  157. if from != "" {
  158. req.FromJid = &from
  159. }
  160. res := &pb.PresenceResponse{}
  161. if err := internal.Call(c, "xmpp", "GetPresence", req, res); err != nil {
  162. return "", err
  163. }
  164. if !*res.IsAvailable || res.Presence == nil {
  165. return "", ErrPresenceUnavailable
  166. }
  167. presence, ok := presenceMap[*res.Presence]
  168. if ok {
  169. return presence, nil
  170. }
  171. return "", fmt.Errorf("xmpp: unknown presence %v", *res.Presence)
  172. }
  173. // GetPresenceMulti retrieves multiple users' presence.
  174. // If the from address is an empty string the default
  175. // (yourapp@appspot.com/bot) will be used.
  176. // Possible return values are "", "away", "dnd", "chat", "xa".
  177. // If any presence is unavailable, an appengine.MultiError is returned
  178. func GetPresenceMulti(c context.Context, to []string, from string) ([]string, error) {
  179. req := &pb.BulkPresenceRequest{
  180. Jid: to,
  181. }
  182. if from != "" {
  183. req.FromJid = &from
  184. }
  185. res := &pb.BulkPresenceResponse{}
  186. if err := internal.Call(c, "xmpp", "BulkGetPresence", req, res); err != nil {
  187. return nil, err
  188. }
  189. presences := make([]string, 0, len(res.PresenceResponse))
  190. errs := appengine.MultiError{}
  191. addResult := func(presence string, err error) {
  192. presences = append(presences, presence)
  193. errs = append(errs, err)
  194. }
  195. anyErr := false
  196. for _, subres := range res.PresenceResponse {
  197. if !subres.GetValid() {
  198. anyErr = true
  199. addResult("", ErrInvalidJID)
  200. continue
  201. }
  202. if !*subres.IsAvailable || subres.Presence == nil {
  203. anyErr = true
  204. addResult("", ErrPresenceUnavailable)
  205. continue
  206. }
  207. presence, ok := presenceMap[*subres.Presence]
  208. if ok {
  209. addResult(presence, nil)
  210. } else {
  211. anyErr = true
  212. addResult("", fmt.Errorf("xmpp: unknown presence %q", *subres.Presence))
  213. }
  214. }
  215. if anyErr {
  216. return presences, errs
  217. }
  218. return presences, nil
  219. }
  220. func init() {
  221. internal.RegisterErrorCodeMap("xmpp", pb.XmppServiceError_ErrorCode_name)
  222. }