-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
imgur.go
88 lines (75 loc) · 2.03 KB
/
imgur.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
81
82
83
84
85
86
87
88
package fetch
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/slurdge/goeland/internal/goeland"
"github.com/spf13/viper"
)
type imgurImage struct {
ID string `json:"id"`
Type string `json:"type"`
Animated bool `json:"animated"`
Description string `json:"description"`
Link string `json:"link"`
}
type imgurItem struct {
ID string `json:"id"`
Title string `json:"title"`
Link string `json:"link"`
DateTime int64 `json:"datetime"`
Images []imgurImage `json:"images"`
}
type imgurData struct {
Items []imgurItem `json:"items"`
}
type imgurRoot struct {
Data imgurData `json:"data"`
}
var clientID = ""
func fetchImgurTag(source *goeland.Source, tag string, sort string) error {
url := "https://api.imgur.com/3/gallery/t/" + tag + "/" + sort + "/0/day"
client := http.Client{Timeout: time.Second * 3}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return err
}
if clientID == "" {
config := viper.GetViper()
clientID = config.GetString("imgur-cid")
}
req.Header.Set("Authorization", "Client-ID "+clientID)
res, err := client.Do(req)
if err != nil {
return err
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
imgurData := new(imgurRoot)
if err := json.Unmarshal(data, imgurData); err != nil {
return err
}
for _, item := range imgurData.Data.Items {
if len(item.Images) < 1 {
continue
}
image := item.Images[0]
if image.Animated {
continue
}
entry := goeland.Entry{}
entry.Title = item.Title
entry.Content = `<a href="` + item.Link + `"><img src="` + image.Link + `"></a><br>` + image.Description
entry.UID = item.ID
entry.Date = time.Unix(item.DateTime, 0)
entry.URL = item.Link
source.Entries = append(source.Entries, entry)
}
source.Title = fmt.Sprintf("Imgur pictures for tag #%s", tag)
source.URL = fmt.Sprintf("https://imgur.com/t/%s", tag)
return nil
}