Debian Codegraph @

users.go

raw symbols SCIP
1 package slack
2
3 import (
4 "context"
5 "encoding/json"
6 "net/url"
7 "strconv"
8 "strings"
9 "time"
10 )
11
12 const (
13 DEFAULT_USER_PHOTO_CROP_X = -1
14 DEFAULT_USER_PHOTO_CROP_Y = -1
15 DEFAULT_USER_PHOTO_CROP_W = -1
16 )
17
18 // UserProfile contains all the information details of a given user
19 type UserProfile struct {
20 FirstName string `json:"first_name"`
21 LastName string `json:"last_name"`
22 RealName string `json:"real_name"`
23 RealNameNormalized string `json:"real_name_normalized"`
24 DisplayName string `json:"display_name"`
25 DisplayNameNormalized string `json:"display_name_normalized"`
26 Email string `json:"email"`
27 Skype string `json:"skype"`
28 Phone string `json:"phone"`
29 Image24 string `json:"image_24"`
30 Image32 string `json:"image_32"`
31 Image48 string `json:"image_48"`
32 Image72 string `json:"image_72"`
33 Image192 string `json:"image_192"`
34 Image512 string `json:"image_512"`
35 ImageOriginal string `json:"image_original"`
36 Title string `json:"title"`
37 BotID string `json:"bot_id,omitempty"`
38 ApiAppID string `json:"api_app_id,omitempty"`
39 StatusText string `json:"status_text,omitempty"`
40 StatusEmoji string `json:"status_emoji,omitempty"`
41 StatusExpiration int `json:"status_expiration"`
42 Team string `json:"team"`
43 Fields UserProfileCustomFields `json:"fields"`
44 }
45
46 // UserProfileCustomFields represents user profile's custom fields.
47 // Slack API's response data type is inconsistent so we use the struct.
48 // For detail, please see below.
49 // https://github.com/slack-go/slack/pull/298#discussion_r185159233
50 type UserProfileCustomFields struct {
51 fields map[string]UserProfileCustomField
52 }
53
54 // UnmarshalJSON is the implementation of the json.Unmarshaler interface.
55 func (fields *UserProfileCustomFields) UnmarshalJSON(b []byte) error {
56 // https://github.com/slack-go/slack/pull/298#discussion_r185159233
57 if string(b) == "[]" {
58 return nil
59 }
60 return json.Unmarshal(b, &fields.fields)
61 }
62
63 // MarshalJSON is the implementation of the json.Marshaler interface.
64 func (fields UserProfileCustomFields) MarshalJSON() ([]byte, error) {
65 if len(fields.fields) == 0 {
66 return []byte("[]"), nil
67 }
68 return json.Marshal(fields.fields)
69 }
70
71 // ToMap returns a map of custom fields.
72 func (fields *UserProfileCustomFields) ToMap() map[string]UserProfileCustomField {
73 return fields.fields
74 }
75
76 // Len returns the number of custom fields.
77 func (fields *UserProfileCustomFields) Len() int {
78 return len(fields.fields)
79 }
80
81 // SetMap sets a map of custom fields.
82 func (fields *UserProfileCustomFields) SetMap(m map[string]UserProfileCustomField) {
83 fields.fields = m
84 }
85
86 // FieldsMap returns a map of custom fields.
87 func (profile *UserProfile) FieldsMap() map[string]UserProfileCustomField {
88 return profile.Fields.ToMap()
89 }
90
91 // SetFieldsMap sets a map of custom fields.
92 func (profile *UserProfile) SetFieldsMap(m map[string]UserProfileCustomField) {
93 profile.Fields.SetMap(m)
94 }
95
96 // UserProfileCustomField represents a custom user profile field
97 type UserProfileCustomField struct {
98 Value string `json:"value"`
99 Alt string `json:"alt"`
100 Label string `json:"label"`
101 }
102
103 // User contains all the information of a user
104 type User struct {
105 ID string `json:"id"`
106 TeamID string `json:"team_id"`
107 Name string `json:"name"`
108 Deleted bool `json:"deleted"`
109 Color string `json:"color"`
110 RealName string `json:"real_name"`
111 TZ string `json:"tz,omitempty"`
112 TZLabel string `json:"tz_label"`
113 TZOffset int `json:"tz_offset"`
114 Profile UserProfile `json:"profile"`
115 IsBot bool `json:"is_bot"`
116 IsAdmin bool `json:"is_admin"`
117 IsOwner bool `json:"is_owner"`
118 IsPrimaryOwner bool `json:"is_primary_owner"`
119 IsRestricted bool `json:"is_restricted"`
120 IsUltraRestricted bool `json:"is_ultra_restricted"`
121 IsStranger bool `json:"is_stranger"`
122 IsAppUser bool `json:"is_app_user"`
123 IsInvitedUser bool `json:"is_invited_user"`
124 Has2FA bool `json:"has_2fa"`
125 HasFiles bool `json:"has_files"`
126 Presence string `json:"presence"`
127 Locale string `json:"locale"`
128 Updated JSONTime `json:"updated"`
129 Enterprise EnterpriseUser `json:"enterprise_user,omitempty"`
130 }
131
132 // UserPresence contains details about a user online status
133 type UserPresence struct {
134 Presence string `json:"presence,omitempty"`
135 Online bool `json:"online,omitempty"`
136 AutoAway bool `json:"auto_away,omitempty"`
137 ManualAway bool `json:"manual_away,omitempty"`
138 ConnectionCount int `json:"connection_count,omitempty"`
139 LastActivity JSONTime `json:"last_activity,omitempty"`
140 }
141
142 type UserIdentityResponse struct {
143 User UserIdentity `json:"user"`
144 Team TeamIdentity `json:"team"`
145 SlackResponse
146 }
147
148 type UserIdentity struct {
149 ID string `json:"id"`
150 Name string `json:"name"`
151 Email string `json:"email"`
152 Image24 string `json:"image_24"`
153 Image32 string `json:"image_32"`
154 Image48 string `json:"image_48"`
155 Image72 string `json:"image_72"`
156 Image192 string `json:"image_192"`
157 Image512 string `json:"image_512"`
158 }
159
160 // EnterpriseUser is present when a user is part of Slack Enterprise Grid
161 // https://api.slack.com/types/user#enterprise_grid_user_objects
162 type EnterpriseUser struct {
163 ID string `json:"id"`
164 EnterpriseID string `json:"enterprise_id"`
165 EnterpriseName string `json:"enterprise_name"`
166 IsAdmin bool `json:"is_admin"`
167 IsOwner bool `json:"is_owner"`
168 Teams []string `json:"teams"`
169 }
170
171 type TeamIdentity struct {
172 ID string `json:"id"`
173 Name string `json:"name"`
174 Domain string `json:"domain"`
175 Image34 string `json:"image_34"`
176 Image44 string `json:"image_44"`
177 Image68 string `json:"image_68"`
178 Image88 string `json:"image_88"`
179 Image102 string `json:"image_102"`
180 Image132 string `json:"image_132"`
181 Image230 string `json:"image_230"`
182 ImageDefault bool `json:"image_default"`
183 ImageOriginal string `json:"image_original"`
184 }
185
186 type userResponseFull struct {
187 Members []User `json:"members,omitempty"`
188 User `json:"user,omitempty"`
189 Users []User `json:"users,omitempty"`
190 UserPresence
191 SlackResponse
192 Metadata ResponseMetadata `json:"response_metadata"`
193 }
194
195 type UserSetPhotoParams struct {
196 CropX int
197 CropY int
198 CropW int
199 }
200
201 func NewUserSetPhotoParams() UserSetPhotoParams {
202 return UserSetPhotoParams{
203 CropX: DEFAULT_USER_PHOTO_CROP_X,
204 CropY: DEFAULT_USER_PHOTO_CROP_Y,
205 CropW: DEFAULT_USER_PHOTO_CROP_W,
206 }
207 }
208
209 func (api *Client) userRequest(ctx context.Context, path string, values url.Values) (*userResponseFull, error) {
210 response := &userResponseFull{}
211 err := api.postMethod(ctx, path, values, response)
212 if err != nil {
213 return nil, err
214 }
215
216 return response, response.Err()
217 }
218
219 // GetUserPresence will retrieve the current presence status of given user.
220 func (api *Client) GetUserPresence(user string) (*UserPresence, error) {
221 return api.GetUserPresenceContext(context.Background(), user)
222 }
223
224 // GetUserPresenceContext will retrieve the current presence status of given user with a custom context.
225 func (api *Client) GetUserPresenceContext(ctx context.Context, user string) (*UserPresence, error) {
226 values := url.Values{
227 "token": {api.token},
228 "user": {user},
229 }
230
231 response, err := api.userRequest(ctx, "users.getPresence", values)
232 if err != nil {
233 return nil, err
234 }
235 return &response.UserPresence, nil
236 }
237
238 // GetUserInfo will retrieve the complete user information
239 func (api *Client) GetUserInfo(user string) (*User, error) {
240 return api.GetUserInfoContext(context.Background(), user)
241 }
242
243 // GetUserInfoContext will retrieve the complete user information with a custom context
244 func (api *Client) GetUserInfoContext(ctx context.Context, user string) (*User, error) {
245 values := url.Values{
246 "token": {api.token},
247 "user": {user},
248 "include_locale": {strconv.FormatBool(true)},
249 }
250
251 response, err := api.userRequest(ctx, "users.info", values)
252 if err != nil {
253 return nil, err
254 }
255 return &response.User, nil
256 }
257
258 // GetUsersInfo will retrieve the complete multi-users information
259 func (api *Client) GetUsersInfo(users ...string) (*[]User, error) {
260 return api.GetUsersInfoContext(context.Background(), users...)
261 }
262
263 // GetUsersInfoContext will retrieve the complete multi-users information with a custom context
264 func (api *Client) GetUsersInfoContext(ctx context.Context, users ...string) (*[]User, error) {
265 values := url.Values{
266 "token": {api.token},
267 "users": {strings.Join(users, ",")},
268 "include_locale": {strconv.FormatBool(true)},
269 }
270
271 response, err := api.userRequest(ctx, "users.info", values)
272 if err != nil {
273 return nil, err
274 }
275 return &response.Users, nil
276 }
277
278 // GetUsersOption options for the GetUsers method call.
279 type GetUsersOption func(*UserPagination)
280
281 // GetUsersOptionLimit limit the number of users returned
282 func GetUsersOptionLimit(n int) GetUsersOption {
283 return func(p *UserPagination) {
284 p.limit = n
285 }
286 }
287
288 // GetUsersOptionPresence include user presence
289 func GetUsersOptionPresence(n bool) GetUsersOption {
290 return func(p *UserPagination) {
291 p.presence = n
292 }
293 }
294
295 // GetUsersOptionTeamID include team Id
296 func GetUsersOptionTeamID(teamId string) GetUsersOption {
297 return func(p *UserPagination) {
298 p.teamId = teamId
299 }
300 }
301
302 func newUserPagination(c *Client, options ...GetUsersOption) (up UserPagination) {
303 up = UserPagination{
304 c: c,
305 limit: 200, // per slack api documentation.
306 }
307
308 for _, opt := range options {
309 opt(&up)
310 }
311
312 return up
313 }
314
315 // UserPagination allows for paginating over the users
316 type UserPagination struct {
317 Users []User
318 limit int
319 presence bool
320 teamId string
321 previousResp *ResponseMetadata
322 c *Client
323 }
324
325 // Done checks if the pagination has completed
326 func (UserPagination) Done(err error) bool {
327 return err == errPaginationComplete
328 }
329
330 // Failure checks if pagination failed.
331 func (t UserPagination) Failure(err error) error {
332 if t.Done(err) {
333 return nil
334 }
335
336 return err
337 }
338
339 func (t UserPagination) Next(ctx context.Context) (_ UserPagination, err error) {
340 var (
341 resp *userResponseFull
342 )
343
344 if t.c == nil || (t.previousResp != nil && t.previousResp.Cursor == "") {
345 return t, errPaginationComplete
346 }
347
348 t.previousResp = t.previousResp.initialize()
349
350 values := url.Values{
351 "limit": {strconv.Itoa(t.limit)},
352 "presence": {strconv.FormatBool(t.presence)},
353 "token": {t.c.token},
354 "cursor": {t.previousResp.Cursor},
355 "team_id": {t.teamId},
356 "include_locale": {strconv.FormatBool(true)},
357 }
358
359 if resp, err = t.c.userRequest(ctx, "users.list", values); err != nil {
360 return t, err
361 }
362
363 t.c.Debugf("GetUsersContext: got %d users; metadata %v", len(resp.Members), resp.Metadata)
364 t.Users = resp.Members
365 t.previousResp = &resp.Metadata
366
367 return t, nil
368 }
369
370 // GetUsersPaginated fetches users in a paginated fashion, see GetUsersContext for usage.
371 func (api *Client) GetUsersPaginated(options ...GetUsersOption) UserPagination {
372 return newUserPagination(api, options...)
373 }
374
375 // GetUsers returns the list of users (with their detailed information)
376 func (api *Client) GetUsers(options ...GetUsersOption) ([]User, error) {
377 return api.GetUsersContext(context.Background(), options...)
378 }
379
380 // GetUsersContext returns the list of users (with their detailed information) with a custom context
381 func (api *Client) GetUsersContext(ctx context.Context, options ...GetUsersOption) (results []User, err error) {
382 p := api.GetUsersPaginated(options...)
383 for err == nil {
384 p, err = p.Next(ctx)
385 if err == nil {
386 results = append(results, p.Users...)
387 } else if rateLimitedError, ok := err.(*RateLimitedError); ok {
388 select {
389 case <-ctx.Done():
390 err = ctx.Err()
391 case <-time.After(rateLimitedError.RetryAfter):
392 err = nil
393 }
394 }
395 }
396
397 return results, p.Failure(err)
398 }
399
400 // GetUserByEmail will retrieve the complete user information by email
401 func (api *Client) GetUserByEmail(email string) (*User, error) {
402 return api.GetUserByEmailContext(context.Background(), email)
403 }
404
405 // GetUserByEmailContext will retrieve the complete user information by email with a custom context
406 func (api *Client) GetUserByEmailContext(ctx context.Context, email string) (*User, error) {
407 values := url.Values{
408 "token": {api.token},
409 "email": {email},
410 }
411 response, err := api.userRequest(ctx, "users.lookupByEmail", values)
412 if err != nil {
413 return nil, err
414 }
415 return &response.User, nil
416 }
417
418 // SetUserAsActive marks the currently authenticated user as active
419 func (api *Client) SetUserAsActive() error {
420 return api.SetUserAsActiveContext(context.Background())
421 }
422
423 // SetUserAsActiveContext marks the currently authenticated user as active with a custom context
424 func (api *Client) SetUserAsActiveContext(ctx context.Context) (err error) {
425 values := url.Values{
426 "token": {api.token},
427 }
428
429 _, err = api.userRequest(ctx, "users.setActive", values)
430 return err
431 }
432
433 // SetUserPresence changes the currently authenticated user presence
434 func (api *Client) SetUserPresence(presence string) error {
435 return api.SetUserPresenceContext(context.Background(), presence)
436 }
437
438 // SetUserPresenceContext changes the currently authenticated user presence with a custom context
439 func (api *Client) SetUserPresenceContext(ctx context.Context, presence string) error {
440 values := url.Values{
441 "token": {api.token},
442 "presence": {presence},
443 }
444
445 _, err := api.userRequest(ctx, "users.setPresence", values)
446 return err
447 }
448
449 // GetUserIdentity will retrieve user info available per identity scopes
450 func (api *Client) GetUserIdentity() (*UserIdentityResponse, error) {
451 return api.GetUserIdentityContext(context.Background())
452 }
453
454 // GetUserIdentityContext will retrieve user info available per identity scopes with a custom context
455 func (api *Client) GetUserIdentityContext(ctx context.Context) (response *UserIdentityResponse, err error) {
456 values := url.Values{
457 "token": {api.token},
458 }
459 response = &UserIdentityResponse{}
460
461 err = api.postMethod(ctx, "users.identity", values, response)
462 if err != nil {
463 return nil, err
464 }
465
466 if err := response.Err(); err != nil {
467 return nil, err
468 }
469
470 return response, nil
471 }
472
473 // SetUserPhoto changes the currently authenticated user's profile image
474 func (api *Client) SetUserPhoto(image string, params UserSetPhotoParams) error {
475 return api.SetUserPhotoContext(context.Background(), image, params)
476 }
477
478 // SetUserPhotoContext changes the currently authenticated user's profile image using a custom context
479 func (api *Client) SetUserPhotoContext(ctx context.Context, image string, params UserSetPhotoParams) (err error) {
480 response := &SlackResponse{}
481 values := url.Values{}
482 if params.CropX != DEFAULT_USER_PHOTO_CROP_X {
483 values.Add("crop_x", strconv.Itoa(params.CropX))
484 }
485 if params.CropY != DEFAULT_USER_PHOTO_CROP_Y {
486 values.Add("crop_y", strconv.Itoa(params.CropX))
487 }
488 if params.CropW != DEFAULT_USER_PHOTO_CROP_W {
489 values.Add("crop_w", strconv.Itoa(params.CropW))
490 }
491
492 err = postLocalWithMultipartResponse(ctx, api.httpclient, api.endpoint+"users.setPhoto", image, "image", api.token, values, response, api)
493 if err != nil {
494 return err
495 }
496
497 return response.Err()
498 }
499
500 // DeleteUserPhoto deletes the current authenticated user's profile image
501 func (api *Client) DeleteUserPhoto() error {
502 return api.DeleteUserPhotoContext(context.Background())
503 }
504
505 // DeleteUserPhotoContext deletes the current authenticated user's profile image with a custom context
506 func (api *Client) DeleteUserPhotoContext(ctx context.Context) (err error) {
507 response := &SlackResponse{}
508 values := url.Values{
509 "token": {api.token},
510 }
511
512 err = api.postMethod(ctx, "users.deletePhoto", values, response)
513 if err != nil {
514 return err
515 }
516
517 return response.Err()
518 }
519
520 // SetUserRealName changes the currently authenticated user's realName
521 //
522 // For more information see SetUserRealNameContextWithUser
523 func (api *Client) SetUserRealName(realName string) error {
524 return api.SetUserRealNameContextWithUser(context.Background(), "", realName)
525 }
526
527 // SetUserRealNameContextWithUser will set a real name for the provided user with a custom context
528 func (api *Client) SetUserRealNameContextWithUser(ctx context.Context, user, realName string) error {
529 profile, err := json.Marshal(
530 &struct {
531 RealName string `json:"real_name"`
532 }{
533 RealName: realName,
534 },
535 )
536
537 if err != nil {
538 return err
539 }
540
541 values := url.Values{
542 "token": {api.token},
543 "profile": {string(profile)},
544 }
545
546 // optional field. It should not be set if empty
547 if user != "" {
548 values["user"] = []string{user}
549 }
550
551 response := &userResponseFull{}
552 if err = api.postMethod(ctx, "users.profile.set", values, response); err != nil {
553 return err
554 }
555
556 return response.Err()
557 }
558
559 // SetUserCustomStatus will set a custom status and emoji for the currently
560 // authenticated user. If statusEmoji is "" and statusText is not, the Slack API
561 // will automatically set it to ":speech_balloon:". Otherwise, if both are ""
562 // the Slack API will unset the custom status/emoji. If statusExpiration is set to 0
563 // the status will not expire.
564 func (api *Client) SetUserCustomStatus(statusText, statusEmoji string, statusExpiration int64) error {
565 return api.SetUserCustomStatusContextWithUser(context.Background(), "", statusText, statusEmoji, statusExpiration)
566 }
567
568 // SetUserCustomStatusContext will set a custom status and emoji for the currently authenticated user with a custom context
569 //
570 // For more information see SetUserCustomStatus
571 func (api *Client) SetUserCustomStatusContext(ctx context.Context, statusText, statusEmoji string, statusExpiration int64) error {
572 return api.SetUserCustomStatusContextWithUser(ctx, "", statusText, statusEmoji, statusExpiration)
573 }
574
575 // SetUserCustomStatusWithUser will set a custom status and emoji for the provided user.
576 //
577 // For more information see SetUserCustomStatus
578 func (api *Client) SetUserCustomStatusWithUser(user, statusText, statusEmoji string, statusExpiration int64) error {
579 return api.SetUserCustomStatusContextWithUser(context.Background(), user, statusText, statusEmoji, statusExpiration)
580 }
581
582 // SetUserCustomStatusContextWithUser will set a custom status and emoji for the provided user with a custom context
583 //
584 // For more information see SetUserCustomStatus
585 func (api *Client) SetUserCustomStatusContextWithUser(ctx context.Context, user, statusText, statusEmoji string, statusExpiration int64) error {
586 // XXX(theckman): this anonymous struct is for making requests to the Slack
587 // API for setting and unsetting a User's Custom Status/Emoji. To change
588 // these values we must provide a JSON document as the profile POST field.
589 //
590 // We use an anonymous struct over UserProfile because to unset the values
591 // on the User's profile we cannot use the `json:"omitempty"` tag. This is
592 // because an empty string ("") is what's used to unset the values. Check
593 // out the API docs for more details:
594 //
595 // - https://api.slack.com/docs/presence-and-status#custom_status
596 profile, err := json.Marshal(
597 &struct {
598 StatusText string `json:"status_text"`
599 StatusEmoji string `json:"status_emoji"`
600 StatusExpiration int64 `json:"status_expiration"`
601 }{
602 StatusText: statusText,
603 StatusEmoji: statusEmoji,
604 StatusExpiration: statusExpiration,
605 },
606 )
607
608 if err != nil {
609 return err
610 }
611
612 values := url.Values{
613 "token": {api.token},
614 "profile": {string(profile)},
615 }
616
617 // optional field. It should not be set if empty
618 if user != "" {
619 values["user"] = []string{user}
620 }
621
622 response := &userResponseFull{}
623 if err = api.postMethod(ctx, "users.profile.set", values, response); err != nil {
624 return err
625 }
626
627 return response.Err()
628 }
629
630 // UnsetUserCustomStatus removes the custom status message for the currently
631 // authenticated user. This is a convenience method that wraps (*Client).SetUserCustomStatus().
632 func (api *Client) UnsetUserCustomStatus() error {
633 return api.UnsetUserCustomStatusContext(context.Background())
634 }
635
636 // UnsetUserCustomStatusContext removes the custom status message for the currently authenticated user
637 // with a custom context. This is a convenience method that wraps (*Client).SetUserCustomStatus().
638 func (api *Client) UnsetUserCustomStatusContext(ctx context.Context) error {
639 return api.SetUserCustomStatusContext(ctx, "", "", 0)
640 }
641
642 // GetUserProfileParameters are the parameters required to get user profile
643 type GetUserProfileParameters struct {
644 UserID string
645 IncludeLabels bool
646 }
647
648 // GetUserProfile retrieves a user's profile information.
649 func (api *Client) GetUserProfile(params *GetUserProfileParameters) (*UserProfile, error) {
650 return api.GetUserProfileContext(context.Background(), params)
651 }
652
653 type getUserProfileResponse struct {
654 SlackResponse
655 Profile *UserProfile `json:"profile"`
656 }
657
658 // GetUserProfileContext retrieves a user's profile information with a context.
659 func (api *Client) GetUserProfileContext(ctx context.Context, params *GetUserProfileParameters) (*UserProfile, error) {
660 values := url.Values{"token": {api.token}}
661
662 if params.UserID != "" {
663 values.Add("user", params.UserID)
664 }
665 if params.IncludeLabels {
666 values.Add("include_labels", "true")
667 }
668 resp := &getUserProfileResponse{}
669
670 err := api.postMethod(ctx, "users.profile.get", values, &resp)
671 if err != nil {
672 return nil, err
673 }
674
675 if err := resp.Err(); err != nil {
676 return nil, err
677 }
678
679 return resp.Profile, nil
680 }