users.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package discourse
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "strings"
  8. "time"
  9. "github.com/sirupsen/logrus"
  10. )
  11. // GetUser - Get a discourse user
  12. func GetUser(config APIConfig, username string) (User, error) {
  13. url := fmt.Sprintf("%s/users/%s.json", config.Endpoint, username)
  14. fmt.Println(url)
  15. req, _ := newGetRequest(config, url)
  16. client := getClient(rl)
  17. response, _ := client.Do(req)
  18. var result *UserResponse
  19. json.NewDecoder(response.Body).Decode(&result)
  20. if result.ErrorType != "" {
  21. return User{}, fmt.Errorf("Failed to get discourse user. Error: %s", strings.Join(result.Errors, "; "))
  22. }
  23. return result.User, nil
  24. }
  25. func GetUserByID(config APIConfig, userID int) (User, error) {
  26. url := fmt.Sprintf("%s/admin/users/%d.json", config.Endpoint, userID)
  27. req, _ := newGetRequest(config, url)
  28. client := getClient(rl)
  29. response, _ := client.Do(req)
  30. if response.StatusCode != http.StatusOK {
  31. var errorResult *UserResponse
  32. json.NewDecoder(response.Body).Decode(&errorResult)
  33. if errorResult.ErrorType != "" {
  34. return User{}, fmt.Errorf("failed to get discourse user. Error: %s", strings.Join(errorResult.Errors, "; "))
  35. }
  36. }
  37. var result *User
  38. json.NewDecoder(response.Body).Decode(&result)
  39. return *result, nil
  40. }
  41. func GetUsersByMinTrustLevel(config APIConfig, minTrustLevel int64) ([]User, error) {
  42. page := 1
  43. getMoreResults := true
  44. var users []User
  45. for getMoreResults {
  46. var pageResults, _ = GetUsersPage(config, page)
  47. if len(pageResults) > 0 {
  48. for _, v := range pageResults {
  49. if v.Staged == false && v.TrustLevel >= minTrustLevel {
  50. u, err := GetUser(config, v.Username)
  51. if err != nil {
  52. return nil, err
  53. }
  54. users = append(users, u)
  55. }
  56. }
  57. page++
  58. } else {
  59. getMoreResults = false
  60. }
  61. }
  62. return users, nil
  63. }
  64. func GetUsersPage(config APIConfig, page int) ([]User, error) {
  65. url := fmt.Sprintf("%s/admin/users/list/active.json?page=%d&?filter=&show_emails=false", config.Endpoint, page)
  66. fmt.Println(url)
  67. req, _ := newGetRequest(config, url)
  68. client := getClient(rl)
  69. response, _ := client.Do(req)
  70. time.Sleep(1 * time.Second)
  71. bodyBytes, err := ioutil.ReadAll(response.Body)
  72. if err != nil {
  73. logrus.Fatal(err)
  74. }
  75. var users []User
  76. json.Unmarshal(bodyBytes, &users)
  77. return users, nil
  78. }