-
Notifications
You must be signed in to change notification settings - Fork 1
/
lemmy.go
80 lines (71 loc) · 2.04 KB
/
lemmy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package opinions
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
)
// LemmyResponse represents some interesting fields of response from
// Lemmy Search API.
//
// See: https://join-lemmy.org/api/interfaces/SearchResponse.html
type LemmyResponse struct {
Posts []struct {
Post struct {
Name string `json:"name"`
URL string `json:"url"`
ID int `json:"id"`
} `json:"post"`
Counts struct {
Comments int `json:"comments"`
} `json:"counts"`
} `json:"posts"`
}
// SearchLemmy query Lemmy Search API for given prompt. It returns list
// of discussions sorted by rank based on the score and time of the latest
// comment, with decay over time.
//
// See: https://join-lemmy.org/docs/users/03-votes-and-ranking.html
func SearchLemmy(ctx context.Context, client GetRequester, query string) (discussions []Discussion, err error) {
searchURL := "https://lemmy.world/api/v3/search?listingType=All&sort=Active"
_, err = url.Parse(query)
switch {
case err == nil:
searchURL += "&type_=Url&q="
// URL query must contain trailing slash for more accurate results
if !strings.HasSuffix(query, "/") {
query += "/"
}
default:
searchURL += "&type_=Posts&q="
}
r, err := client.Get(ctx, searchURL+url.QueryEscape(query))
if err != nil {
return noDiscussions, err
}
defer func() {
if closeErr := r.Body.Close(); closeErr != nil && err == nil {
err = closeErr
}
}()
if r.StatusCode != http.StatusOK {
return noDiscussions, fmt.Errorf("`GET %s` responded with unexpected status code %d", r.Request.URL, r.StatusCode)
}
var response LemmyResponse
if err := json.NewDecoder(r.Body).Decode(&response); err != nil {
return noDiscussions, err
}
discussions = make([]Discussion, 0, len(response.Posts))
for _, entry := range response.Posts {
discussions = append(discussions, Discussion{
Service: "Lemmy",
URL: fmt.Sprintf("https://lemmy.world/post/%d", entry.Post.ID),
Title: entry.Post.Name,
Source: entry.Post.URL,
Comments: entry.Counts.Comments,
})
}
return discussions, nil
}