@@ -2,6 +2,8 @@ package gchatmeow
2
2
3
3
import (
4
4
"context"
5
+ "encoding/base64"
6
+ "errors"
5
7
"fmt"
6
8
"net/http"
7
9
"net/url"
@@ -46,7 +48,7 @@ func (c *Client) gcRequest(ctx context.Context, endpoint string, requestPB proto
46
48
return err
47
49
}
48
50
49
- if err := pb .Unmarshal (res , responsePB ); err != nil {
51
+ if err := pb .Unmarshal (res . Body , responsePB ); err != nil {
50
52
return fmt .Errorf ("failed to decode Protocol Buffer response: %v" , err )
51
53
}
52
54
@@ -63,7 +65,7 @@ func (c *Client) baseRequest(
63
65
headers http.Header ,
64
66
params url.Values ,
65
67
method string ,
66
- ) ([] byte , error ) {
68
+ ) (* FetchResponse , error ) {
67
69
if headers == nil {
68
70
headers = http.Header {}
69
71
}
@@ -88,7 +90,7 @@ func (c *Client) baseRequest(
88
90
return nil , err
89
91
}
90
92
91
- return res . Body , nil
93
+ return res , nil
92
94
}
93
95
94
96
func (c * Client ) getSelfUserStatus (ctx context.Context ) (* proto.GetSelfUserStatusResponse , error ) {
@@ -145,3 +147,49 @@ func (c *Client) GetGroup(ctx context.Context, request *proto.GetGroupRequest) (
145
147
err := c .gcRequest (ctx , "get_group" , request , response )
146
148
return response , err
147
149
}
150
+
151
+ func (c * Client ) UploadFile (ctx context.Context , data []byte , groupId string , fileName string , mimeType string ) (* proto.UploadMetadata , error ) {
152
+ headers := http.Header {
153
+ "x-goog-upload-protocol" : {"resumable" },
154
+ "x-goog-upload-command" : {"start" },
155
+ "x-goog-upload-content-length" : {string (len (data ))},
156
+ "x-goog-upload-content-type" : {mimeType },
157
+ "x-goog-upload-file-name" : {fileName },
158
+ }
159
+ res , err := c .baseRequest (
160
+ ctx , uploadURL , "" , "" , nil ,
161
+ headers , url.Values {"group_id" : []string {groupId }},
162
+ http .MethodPost ,
163
+ )
164
+ if err != nil {
165
+ return nil , err
166
+ }
167
+ newUploadURL := res .Headers .Get ("x-goog-upload-url" )
168
+ if newUploadURL == "" {
169
+ return nil , errors .New ("image upload failed: can not acquire an upload url" )
170
+ }
171
+
172
+ headers = http.Header {
173
+ "x-goog-upload-command" : {"upload, finalize" },
174
+ "x-goog-upload-protocol" : {"resumable" },
175
+ "x-goog-upload-offset" : {"0" },
176
+ }
177
+ res , err = c .baseRequest (
178
+ ctx , newUploadURL , "" , "" ,
179
+ data , headers , nil ,
180
+ http .MethodPut ,
181
+ )
182
+ if err != nil {
183
+ return nil , err
184
+ }
185
+ body , err := base64 .StdEncoding .DecodeString (string (res .Body ))
186
+ if err != nil {
187
+ return nil , err
188
+ }
189
+ uploadMetadata := & proto.UploadMetadata {}
190
+ err = pb .Unmarshal (body , uploadMetadata )
191
+ if err != nil {
192
+ return nil , err
193
+ }
194
+ return uploadMetadata , nil
195
+ }
0 commit comments