github.com/nesv/gothub@v0.0.0-20140406181320-f0c824044d5f/users.go (about)

     1  package gothub
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"errors"
     7  	"fmt"
     8  	"io/ioutil"
     9  	"net/http"
    10  	"regexp"
    11  	"strconv"
    12  	"strings"
    13  	"time"
    14  )
    15  
    16  // Represents information about a user's account as defined here:
    17  // http://developer.github.com/v3/users/#get-a-single-user
    18  //
    19  // Please take note that you cannot use the User struct to modify the details of a user's account.
    20  // To do this, please look at the CurrentUser struct.
    21  type User struct {
    22  	Login       string    `json:"login"`
    23  	Id          int       `json:"id"`
    24  	AvatarUrl   string    `json:"avatar_url"`
    25  	GravatarId  string    `json:"gravatar_id"`
    26  	Url         string    `json:"url"`
    27  	Name        string    `json:"name"`
    28  	Company     string    `json:"company"`
    29  	Blog        string    `json:"blog"`
    30  	Location    string    `json:"location"`
    31  	Email       string    `json:"email"`
    32  	Hireable    bool      `json:"hireable"`
    33  	Bio         string    `json:"bio"`
    34  	PublicRepos int       `json:"public_repos"`
    35  	PublicGists int       `json:"public_gists"`
    36  	Followers   int       `json:"followers"`
    37  	Following   int       `json:"following"`
    38  	HtmlUrl     string    `json:"html_url"`
    39  	CreatedAt   time.Time `json:"created_at"`
    40  	Type        string    `json:"type"`
    41  	g           *GitHub
    42  }
    43  
    44  // A minimized form of the User struct, for holding information about a follower.
    45  type Follower struct {
    46  	Login             string `json:"login"`
    47  	Id                int    `json:"id"`
    48  	AvatarUrl         string `json:"avatar_url"`
    49  	GravatarId        string `json:"gravatar_id"`
    50  	Url               string `json:"url"`
    51  	HtmlUrl           string `json:"html_url"`
    52  	FollowersUrl      string `json:"followers_url"`
    53  	FollowingUrl      string `json:"following_url"`
    54  	GistsUrl          string `json:"gists_url"`
    55  	StarredUrl        string `json:"starred_url"`
    56  	SubscriptionsUrl  string `json:"subscriptions_url"`
    57  	OrganizationsUrl  string `json:"organizations_url"`
    58  	ReposUrl          string `json:"repos_url"`
    59  	EventsUrl         string `json:"events_url"`
    60  	ReceivedEventsUrl string `json:"received_events_url"`
    61  	Type              string `json:"type"`
    62  }
    63  
    64  // Gets a detailed list of a user's followers.
    65  func (u User) GetFollowers() (followers []Follower, err error) {
    66  	uri := fmt.Sprintf("/users/%s/followers", u.Login)
    67  	fs := make([]Follower, 0)
    68  	err = u.g.callGithubApi("GET", uri, &fs)
    69  	if err != nil {
    70  		return
    71  	}
    72  	/*
    73  		if len(response.Header.Get("Link")) > 0 {
    74  			// It would appear that we have to make several more requests, so as 
    75  			// to get all of the user's followers (read: pagination).
    76  			pages := parseLinkHeader(response)
    77  			for _, page := range pages {
    78  				url, _ := url.Parse(page.Url)
    79  				f := make([]Follower, 0)
    80  				response, err = u.g.callGithubApi("GET", url.RequestURI(), &f)
    81  				fs = append(fs, f...)
    82  			}
    83  		}
    84  	*/
    85  	followers = fs
    86  	return
    87  }
    88  
    89  // Gets a list of users the user is following.
    90  func (u User) GetFollowing() (following []Follower, err error) {
    91  	uri := fmt.Sprintf("/users/%s/following", u.Login)
    92  	following = make([]Follower, 0)
    93  	err = u.g.callGithubApi("GET", uri, &following)
    94  	return
    95  }
    96  
    97  // Holds information about user's public SSH keys that they have provided to GitHub.
    98  type PublicKey struct {
    99  	Id    int    `json:"id,omitempty"`
   100  	Key   string `json:"key"`
   101  	Url   string `json:"url,omitempty"`
   102  	Title string `json:"title"`
   103  }
   104  
   105  // Gets the verified public SSH keys for a user.
   106  func (u User) GetPublicKeys() (keys []PublicKey, err error) {
   107  	uri := fmt.Sprintf("/users/%s/keys", u.Login)
   108  	keys = make([]PublicKey, 0)
   109  	err = u.g.callGithubApi("GET", uri, &keys)
   110  	return
   111  }
   112  
   113  // Returns the details of a single user, as specified by their "login".
   114  //
   115  // The term "login" is synonymous with "username":
   116  //
   117  //    https://github.com/<login>
   118  func (g *GitHub) GetUser(login string) (*User, error) {
   119  	var user User
   120  	err := g.callGithubApi("GET", fmt.Sprintf("/users/%s", login), &user)
   121  	if err != nil {
   122  		return nil, err
   123  	}
   124  	user.g = g
   125  	return &user, nil
   126  }
   127  
   128  // Returns the currently-authenticated user, as a pointer to a User struct.
   129  func (g *GitHub) GetCurrentUser() (*User, error) {
   130  	var user User
   131  	err := g.callGithubApi("GET", "/user", &user)
   132  	if err != nil {
   133  		return nil, err
   134  	}
   135  	user.g = g
   136  	return &user, nil
   137  }
   138  
   139  // Returns a list of the email accounts associated with the currently-
   140  // authenticated user.
   141  func (g *GitHub) Emails() (emails []string, err error) {
   142  	response, err := call(g, "GET", "/user/emails")
   143  	if err != nil {
   144  		return
   145  	}
   146  
   147  	body, err := ioutil.ReadAll(response.Body)
   148  	if err != nil {
   149  		return
   150  	}
   151  
   152  	rs := strings.Trim(string(body), "[]")
   153  	for _, email := range strings.Split(rs, ",") {
   154  		emails = append(emails, strings.Trim(email, "\""))
   155  	}
   156  	return
   157  }
   158  
   159  // Associate a list of emails with the currently-authenticated user's account.
   160  func (g *GitHub) AddEmails(emails []string) (err error) {
   161  	addresses := fmt.Sprintf("%v", emails)
   162  	buf := bytes.NewBufferString(addresses)
   163  	response, err := g.httpPost("/user/emails", nil, buf)
   164  	if err != nil {
   165  		return
   166  	}
   167  	if response.StatusCode != http.StatusCreated {
   168  		e := "GitHub returned a %d status code; was expecting %d"
   169  		err = errors.New(fmt.Sprintf(e, response.StatusCode, http.StatusCreated))
   170  	}
   171  	return
   172  }
   173  
   174  // Disassociate a list of emails from the currently-authenticated user's
   175  // account.
   176  func (g *GitHub) DeleteEmails(emails []string) (err error) {
   177  	addresses := fmt.Sprintf("%v", emails)
   178  	buf := bytes.NewBufferString(addresses)
   179  	response, err := g.httpDelete("/user/emails", nil, buf)
   180  	if err != nil {
   181  		return
   182  	}
   183  	if response.StatusCode != http.StatusNoContent {
   184  		e := "GitHub returned a %d status code; was expecting %d"
   185  		err = errors.New(fmt.Sprintf(e, response.StatusCode, http.StatusNoContent))
   186  	}
   187  	return
   188  }
   189  
   190  // Check to see whether or not the current user `u` is following another user.
   191  func (g GitHub) IsFollowing(anotherUser string) (following bool, err error) {
   192  	uri := fmt.Sprintf("/user/following/%s", anotherUser)
   193  	response, err := g.httpGet(uri, nil)
   194  	if err != nil {
   195  		return
   196  	}
   197  	switch response.StatusCode {
   198  	case http.StatusNoContent:
   199  		following = true
   200  	case http.StatusNotFound:
   201  		following = false
   202  	}
   203  	return
   204  }
   205  
   206  // Follow a user.
   207  func (g GitHub) Follow(user string) (err error) {
   208  	uri := fmt.Sprintf("/user/following/%s", user)
   209  	response, err := g.httpPut(uri, nil, nil)
   210  	if err != nil {
   211  		return
   212  	}
   213  
   214  	if response.StatusCode != http.StatusNoContent {
   215  		e := "Bad HTTP status; wanted %d got %d"
   216  		err = errors.New(fmt.Sprintf(e, http.StatusNoContent, response.StatusCode))
   217  	}
   218  
   219  	return
   220  }
   221  
   222  // Unfollow a user.
   223  func (g GitHub) Unfollow(user string) (err error) {
   224  	uri := fmt.Sprintf("/user/following/%s", user)
   225  	response, err := g.httpDelete(uri, nil, nil)
   226  	if err != nil {
   227  		return
   228  	} else if response.StatusCode != http.StatusNoContent {
   229  		e := "Bad HTTP status; wanted %d got %d"
   230  		err = errors.New(fmt.Sprintf(e, http.StatusNoContent, response.StatusCode))
   231  	}
   232  	return
   233  }
   234  
   235  // Fetch a listing of the currently-authenticated user's public SSH keys.
   236  func (g GitHub) PublicKeys() (keys []PublicKey, err error) {
   237  	keys = make([]PublicKey, 0)
   238  	err = g.callGithubApi("GET", "/user/keys", &keys)
   239  	return
   240  }
   241  
   242  // Fetch a singular public SSH key.
   243  func (g GitHub) GetPublicKey(id int) (key PublicKey, err error) {
   244  	uri := fmt.Sprintf("/user/keys/%d", id)
   245  	err = g.callGithubApi("GET", uri, &key)
   246  	return
   247  }
   248  
   249  // Add a public key to your account.
   250  //
   251  // When the creation of your new key is successful, this function will return
   252  // the new ID of the key, which will be retrievable at:
   253  //
   254  //     https://api.github.com/user/keys/:id
   255  //
   256  func (g GitHub) AddPublicKey(title, key string) (id int, err error) {
   257  	b, err := json.Marshal(PublicKey{Title: title, Key: key})
   258  	if err != nil {
   259  		return
   260  	}
   261  
   262  	buf := bytes.NewBuffer(b)
   263  	response, err := g.httpPost("/user/keys", nil, buf)
   264  	if err != nil {
   265  		return
   266  	}
   267  
   268  	switch response.StatusCode {
   269  	case 422:
   270  		err = errors.New("That key already exists")
   271  
   272  	case http.StatusCreated:
   273  		re := regexp.MustCompile(`(\d+)$`)
   274  		matches := re.FindStringSubmatch(response.Header.Get("Location"))
   275  		if len(matches) > 1 {
   276  			id, err = strconv.Atoi(matches[1])
   277  		} else {
   278  			e := "Cannot find new pubkey ID in \"%s\""
   279  			err = errors.New(fmt.Sprintf(e, response.Header.Get("Location")))
   280  		}
   281  
   282  	default:
   283  		e := "Bad HTTP status; wanted %d got %d"
   284  		err = errors.New(fmt.Sprintf(e, http.StatusCreated, response.StatusCode))
   285  	}
   286  
   287  	return
   288  }
   289  
   290  // Removes a public key from your account.
   291  func (g GitHub) RemovePublicKey(id int) (err error) {
   292  	uri := fmt.Sprintf("/user/keys/%d", id)
   293  	response, err := g.httpDelete(uri, nil, nil)
   294  	if response.StatusCode != http.StatusNoContent {
   295  		e := "Bad HTTP status; wanted %d got %d"
   296  		err = errors.New(fmt.Sprintf(e, http.StatusNoContent, response.StatusCode))
   297  	}
   298  	return
   299  }