diff --git a/groups.go b/groups.go index 06ab7d0..cb724b9 100644 --- a/groups.go +++ b/groups.go @@ -1 +1,64 @@ package main + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" +) + +func ListGroups(amount string, isPublic bool) (GroupListResponse, error) { + jwt, err := findToken() + if err != nil { + return GroupListResponse{}, err + } + url := fmt.Sprintf("https://api.pinata.cloud/v3/files/groups?") + + params := []string{} + + if amount != "" { + params = append(params, "limit="+amount) + } + + if isPublic { + params = append(params, "isPublic=true") + } + if len(params) > 0 { + url += strings.Join(params, "&") + } + + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return GroupListResponse{}, errors.Join(err, errors.New("failed to create the request")) + } + req.Header.Set("Authorization", "Bearer "+string(jwt)) + req.Header.Set("content-type", "application/json") + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + return GroupListResponse{}, errors.Join(err, errors.New("failed to send the request")) + } + defer resp.Body.Close() + + if resp.StatusCode != 200 { + return GroupListResponse{}, fmt.Errorf("server Returned an error %d", resp.StatusCode) + } + + var response GroupListResponse + + err = json.NewDecoder(resp.Body).Decode(&response) + if err != nil { + return GroupListResponse{}, err + } + formattedJSON, err := json.MarshalIndent(response.Data, "", " ") + if err != nil { + return GroupListResponse{}, errors.New("failed to format JSON") + } + + fmt.Println(string(formattedJSON)) + + return response, nil + +} diff --git a/main.go b/main.go index 9815c8e..14f57a3 100644 --- a/main.go +++ b/main.go @@ -62,12 +62,43 @@ func main() { return err }, }, + { + Name: "groups", + Aliases: []string{"g"}, + Usage: "Interact with file groups", + Subcommands: []*cli.Command{ + { + Name: "list", + Aliases: []string{"l"}, + Usage: "List groups on your account", + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "public", + Aliases: []string{"p"}, + Value: true, + Usage: "List only public groups", + }, + &cli.StringFlag{ + Name: "amount", + Aliases: []string{"a"}, + Value: "10", + Usage: "The number of groups you would like to return", + }, + }, + Action: func(ctx *cli.Context) error { + public := ctx.Bool("public") + amount := ctx.String("amount") + _, err := ListGroups(amount, public) + return err + }, + }, + }, + }, { Name: "files", Aliases: []string{"f"}, Usage: "Interact with your files on Pinata", Subcommands: []*cli.Command{ - { Name: "delete", Aliases: []string{"d"}, diff --git a/types.go b/types.go index 26e2985..abeff5c 100644 --- a/types.go +++ b/types.go @@ -51,6 +51,8 @@ type GroupResponseItem struct { } type GroupListResponse struct { - Groups []GroupResponseItem `json:"groups"` - NextPageToken string `json:"next_page_token"` + Data struct { + Groups []GroupResponseItem `json:"groups"` + NextPageToken string `json:"next_page_token"` + } `json:"data"` }