|
| 1 | +package posts |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "io/ioutil" |
| 7 | + "log" |
| 8 | + "net/url" |
| 9 | + |
| 10 | + "github.com/rivo/tview" |
| 11 | +) |
| 12 | + |
| 13 | +func openResponses(t *tview.TextView, postcuid string, totalResponses int) { |
| 14 | + |
| 15 | + const defaultSortOrder = "totalReactions" |
| 16 | + |
| 17 | + r, err := getResponses(postcuid, totalResponses, 1, defaultSortOrder) |
| 18 | + if err != nil { |
| 19 | + log.Println(err) |
| 20 | + } |
| 21 | + var responsesAPI responsesAPI |
| 22 | + err = json.Unmarshal(r, &responsesAPI) |
| 23 | + if err != nil { |
| 24 | + log.Println(err) |
| 25 | + } |
| 26 | + |
| 27 | + noresponse := len(responsesAPI.Responses) |
| 28 | + for ind, response := range responsesAPI.Responses { |
| 29 | + writeToTextView( |
| 30 | + t, |
| 31 | + fmt.Sprintf("\n[green]Response %d/%d[white]", ind+1, noresponse), |
| 32 | + fmt.Sprintf("[green]--------------[green]"), |
| 33 | + renderTerminal(response.ContentMarkdown), |
| 34 | + ) |
| 35 | + if len(response.Replies) > 0 { |
| 36 | + writeToTextView(t, |
| 37 | + "\n[yellow]Replies[white]", |
| 38 | + "[yellow]=======[white]", |
| 39 | + ) |
| 40 | + noreplies := len(response.Replies) |
| 41 | + for indreply, reply := range response.Replies { |
| 42 | + writeToTextView( |
| 43 | + t, |
| 44 | + fmt.Sprintf("\n[yellow]Reply %d/%d[white]", indreply+1, noreplies), |
| 45 | + fmt.Sprintf("[yellow]~~~~~~~~~~~[white]"), |
| 46 | + fmt.Sprintf("Author: %s", reply.Author.Name), |
| 47 | + indentMarkdown(renderTerminal(reply.ContentMarkdown), "\t"), |
| 48 | + ) |
| 49 | + |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + } |
| 54 | + |
| 55 | +} |
| 56 | + |
| 57 | +func getResponses(postID string, perPage, page int, sortOrder string) ([]byte, error) { |
| 58 | + const apiURL = "https://hashnode.com/ajax/responses" |
| 59 | + u, err := url.Parse(apiURL) |
| 60 | + if err != nil { |
| 61 | + log.Fatal(err) |
| 62 | + } |
| 63 | + |
| 64 | + q := u.Query() |
| 65 | + q.Set("post_id", postID) |
| 66 | + q.Set("page", fmt.Sprintf("%d", page)) |
| 67 | + q.Set("per_page", fmt.Sprintf("%d", perPage)) |
| 68 | + q.Set("sort_order", sortOrder) |
| 69 | + u.RawQuery = q.Encode() |
| 70 | + |
| 71 | + client := getHttpClient() |
| 72 | + resp, err := client.Get(u.String()) |
| 73 | + if err != nil { |
| 74 | + return nil, err |
| 75 | + } |
| 76 | + defer resp.Body.Close() |
| 77 | + |
| 78 | + b, err := ioutil.ReadAll(resp.Body) |
| 79 | + if err != nil { |
| 80 | + return nil, err |
| 81 | + } |
| 82 | + return b, err |
| 83 | +} |
| 84 | + |
| 85 | +type responsesAPI struct { |
| 86 | + Pagination struct { |
| 87 | + Page string `json:"page"` |
| 88 | + PerPage string `json:"per_page"` |
| 89 | + Total int `json:"total"` |
| 90 | + } `json:"pagination"` |
| 91 | + Order string `json:"order"` |
| 92 | + Responses []Response |
| 93 | +} |
0 commit comments