This repository has been archived by the owner on Jul 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reupload.go
108 lines (88 loc) · 2.17 KB
/
reupload.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package actions
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"strings"
"github.com/chronophylos/chb3/buildinfo"
"github.com/rs/zerolog/log"
)
type reuploadAction struct {
options *Options
}
func newReuploadAction() *reuploadAction {
return &reuploadAction{
options: &Options{
Name: "reupload",
Re: regexp.MustCompile(
`(https?:\/\/)?((damn-community\.com|screenshots\.relentless\.wtf|puddelgaming\.de\/upload)\/.*\.(png|jpe?g))`,
),
},
}
}
func (a reuploadAction) GetOptions() *Options {
return a.options
}
func (a reuploadAction) Run(e *Event) error {
link := e.Match[2]
link = "https://" + link
newLink, err := reupload(link, e.ImgurClientID, "ChronophylosBot/"+buildinfo.Version())
if err != nil {
e.Log.Error().
Err(err).
Str("link", link).
Msg("Reuploading an image to imgur")
} else {
e.Log.Info().
Str("link", link).
Msg("Reuploading an image to imgur")
e.Say("Did you mean " + newLink + " ?")
}
return nil
}
type imgurBody struct {
Data struct {
Link string `json:"link"`
Error string `json:"error"`
} `json:"data"`
Success bool `json:"success"`
}
func reupload(link string, clientID, userAgent string) (string, error) {
client := &http.Client{}
form := url.Values{}
form.Add("image", link)
req, err := http.NewRequest(
"POST",
"https://api.imgur.com/3/upload",
strings.NewReader(form.Encode()),
)
if err != nil {
return "", fmt.Errorf(
"could not make POST request for https://api.imgur.com/3/upload: %v",
err,
)
}
req.Header.Add("Authorization", "Client-ID "+clientID)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("User-Agent", userAgent)
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("could not post to imgur: %v", err)
}
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("could not bytes from response: %v", err)
}
log.Debug().Bytes("data", bytes).Send()
var body imgurBody
if err = json.Unmarshal(bytes, &body); err != nil {
return "", err
}
if !body.Success {
return "", fmt.Errorf("imgur api returned: %s", body.Data.Error)
}
return body.Data.Link, nil
}