/
telegraph.go
74 lines (61 loc) · 1.32 KB
/
telegraph.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
package api
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"github.com/ailinykh/pullanusbot/v2/core"
)
// CreateTelegraphAPI is a default Telegraph factory
func CreateTelegraphAPI() *Telegraph {
return &Telegraph{}
}
// Telegraph uploads files to telegra.ph
type Telegraph struct {
}
type telegraphImage struct {
Src string `json:"src"`
}
// Upload is a core.IFileUploader interface implementation
func (t *Telegraph) Upload(file *core.File) (core.URL, error) {
fd, err := os.Open(file.Path)
if err != nil {
return "", err
}
defer fd.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", file.Name)
if err != nil {
return "", err
}
_, err = io.Copy(part, fd)
if err != nil {
return "", err
}
err = writer.Close()
if err != nil {
return "", err
}
req, _ := http.NewRequest("POST", "https://telegra.ph/upload", body)
req.Header.Set("Content-Type", writer.FormDataContentType())
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
body2, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
var images []telegraphImage
err = json.Unmarshal(body2, &images)
if err != nil {
return "", err
}
url := "https://telegra.ph" + images[0].Src
return url, nil
}