-
Notifications
You must be signed in to change notification settings - Fork 0
/
hosting.go
93 lines (81 loc) · 2.45 KB
/
hosting.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
package vkphotohosting
import (
"bytes"
"context"
"github.com/grulex/vk-photo-hosting/internal"
"github.com/grulex/vk-photo-hosting/internal/client"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"time"
)
type vkPhotoHosting struct {
vkApiClient vkApiClient
userToken string
groupId uint64
}
// NewHosting create hosting instance, see README.md for describe params
func NewHosting(userToken string, groupId uint64, httpTimeout time.Duration) *vkPhotoHosting {
httpClient := &http.Client{Timeout: httpTimeout}
apiClient := client.NewClient(httpClient)
return &vkPhotoHosting{
vkApiClient: apiClient,
userToken: userToken,
groupId: groupId,
}
}
func (h vkPhotoHosting) UploadByReader(ctx context.Context, albumId uint64, image io.Reader) (id uint64, variants internal.Variants, err error) {
server, err := h.vkApiClient.GetUploadServer(ctx, h.userToken, h.groupId, albumId)
if err != nil {
return
}
return h.vkApiClient.UploadPhoto(ctx, h.userToken, server, h.groupId, albumId, image)
}
func (h vkPhotoHosting) UploadByFile(ctx context.Context, albumId uint64, filePath string) (id uint64, variants internal.Variants, err error) {
file, err := os.Open(filePath)
defer func(file *os.File) {
_ = file.Close()
}(file)
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("photo", filepath.Base(filePath))
_, err = io.Copy(part, file)
err = writer.Close()
if err != nil {
return
}
server, err := h.vkApiClient.GetUploadServer(ctx, h.userToken, h.groupId, albumId)
if err != nil {
return
}
return h.vkApiClient.UploadPhoto(ctx, h.userToken, server, h.groupId, albumId, body)
}
func (h vkPhotoHosting) UploadByUrl(
ctx context.Context,
albumId uint64,
photoUrl string,
downloadTimeout time.Duration,
) (
id uint64,
variants internal.Variants,
err error,
) {
downloadClient := http.Client{Timeout: downloadTimeout}
req, _ := http.NewRequest("GET", photoUrl, nil)
req.Header.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.2 Safari/605.1.15")
req = req.WithContext(ctx)
resp, err := downloadClient.Do(req)
if err != nil {
return
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)
server, err := h.vkApiClient.GetUploadServer(ctx, h.userToken, h.groupId, albumId)
if err != nil {
return
}
return h.vkApiClient.UploadPhoto(ctx, h.userToken, server, h.groupId, albumId, resp.Body)
}