forked from matterbridge/go-xmpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpupload.go
283 lines (257 loc) · 6.94 KB
/
httpupload.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
// Copyright 2020 - 2021 Martin Dosch.
// Use of this source code is governed by the BSD-2-clause
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"crypto/rand"
"encoding/xml"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"github.com/gabriel-vasile/mimetype" // MIT License
"github.com/mattn/go-xmpp" // BSD-3-Clause"
)
func getID() string {
b := make([]byte, 12)
_, err := rand.Read(b)
if err != nil {
log.Fatal(err)
}
id := fmt.Sprintf("%x-%x-%x", b[0:4], b[4:8], b[8:])
return id
}
func httpUpload(client *xmpp.Client, jserver string, filePath string) string {
// Created with https://github.com/miku/zek
type IQDiscoItemsType struct {
XMLName xml.Name `xml:"query"`
Text string `xml:",chardata"`
Xmlns string `xml:"xmlns,attr"`
Item []struct {
Text string `xml:",chardata"`
Jid string `xml:"jid,attr"`
} `xml:"item"`
}
// Created with https://github.com/miku/zek
type IQDiscoInfoType struct {
XMLName xml.Name `xml:"query"`
Text string `xml:",chardata"`
Xmlns string `xml:"xmlns,attr"`
Identity struct {
Text string `xml:",chardata"`
Type string `xml:"type,attr"`
Name string `xml:"name,attr"`
Category string `xml:"category,attr"`
} `xml:"identity"`
Feature []struct {
Text string `xml:",chardata"`
Var string `xml:"var,attr"`
} `xml:"feature"`
X []struct {
Text string `xml:",chardata"`
Type string `xml:"type,attr"`
Xmlns string `xml:"xmlns,attr"`
Field []struct {
Text string `xml:",chardata"`
Type string `xml:"type,attr"`
Var string `xml:"var,attr"`
Value string `xml:"value"`
} `xml:"field"`
} `xml:"x"`
}
type IQHttpUploadSlotRequest struct {
XMLName xml.Name `xml:"request"`
Xmlns string `xml:"xmlns,attr"`
FileName string `xml:"filename,attr"`
FileType string `xml:"mime-type,attr"`
FileSize int64 `xml:"size,attr"`
}
// Created with https://github.com/miku/zek
type IQHttpUploadSlot struct {
XMLName xml.Name `xml:"slot"`
Text string `xml:",chardata"`
Xmlns string `xml:"xmlns,attr"`
Get struct {
Text string `xml:",chardata"`
URL string `xml:"url,attr"`
} `xml:"get"`
Put struct {
Text string `xml:",chardata"`
URL string `xml:"url,attr"`
Headers []struct {
Name string `xml:"name,attr"`
Value string `xml:",chardata"`
} `xml:"header"`
} `xml:"put"`
}
var iqDiscoItemsXML IQDiscoItemsType
var iqDiscoInfoXML IQDiscoInfoType
var iqHttpUploadSlotXML IQHttpUploadSlot
var uploadComponent string
var maxFileSize int64
// Get file size
fileInfo, err := os.Stat(filePath)
if err != nil {
log.Fatal(err)
}
fileSize := fileInfo.Size()
// Open File
f, err := os.Open(filePath)
if err != nil {
log.Fatal(err)
}
defer f.Close()
// Read file
buffer := make([]byte, fileSize)
_, err = f.Read(buffer)
if err != nil {
log.Fatal(err)
}
// Get mime type
mimeType := mimetype.Detect(buffer).String()
var mimeTypeEscaped bytes.Buffer
xml.Escape(&mimeTypeEscaped, []byte(mimeType))
// Get file name
fileName := filepath.Base(filePath)
// Just use alphanumerical characters for now to work around
// https://github.com/mattn/go-xmpp/issues/132
reg, err := regexp.Compile(`[^a-zA-Z0-9\+\-\_\.]+`)
if err != nil {
log.Fatal(err)
}
fileNameEscaped := reg.ReplaceAllString(fileName, "_")
//var fileNameEscaped bytes.Buffer
//xml.Escape(&fileNameEscaped, []byte(fileName))
// Query server for disco#items
id := getID()
c := make(chan xmpp.IQ)
go getIQ(client, id, c)
_, err = client.RawInformation(client.JID(), jserver, id,
"get", "<query xmlns='http://jabber.org/protocol/disco#items'/>")
if err != nil {
log.Fatal(err)
}
iqContent := <-c
close(c)
if iqContent.Type != "result" {
log.Fatal("Error while disco#items query.")
}
err = xml.Unmarshal(iqContent.Query, &iqDiscoItemsXML)
if err != nil {
log.Fatal(err)
}
// Check the services reported by disco#items for the http upload service
for _, r := range iqDiscoItemsXML.Item {
id = getID()
c := make(chan xmpp.IQ)
go getIQ(client, id, c)
_, err = client.RawInformation(client.JID(), r.Jid, id, "get",
"<query xmlns='http://jabber.org/protocol/disco#info'/>")
if err != nil {
log.Fatal(err)
}
iqDiscoInfo := <-c
close(c)
if iqDiscoInfo.Type != "result" {
log.Fatal("Error while disco#info query.")
}
err = xml.Unmarshal(iqDiscoInfo.Query, &iqDiscoInfoXML)
if err != nil {
log.Fatal(err)
}
if iqDiscoInfoXML.Identity.Type == "file" && iqDiscoInfoXML.Identity.Category == "store" {
uploadComponent = r.Jid
}
}
if uploadComponent == "" {
log.Fatal("No http upload component found.")
}
for _, r := range iqDiscoInfoXML.X {
for i, t := range r.Field {
if t.Var == "max-file-size" && r.Field[i-1].Value == "urn:xmpp:http:upload:0" {
maxFileSize, err = strconv.ParseInt(t.Value, 10, 64)
if err != nil {
log.Fatal("Error while checking server maximum http upload file size.")
}
}
}
}
// Check if the file size doesn't exceed the maximum file size of the http upload
// component if a maximum file size is reported, if not just continue and hope for
// the best.
if maxFileSize != 0 {
if fileSize > maxFileSize {
log.Fatal("File size " + strconv.FormatInt(fileSize/1024/1024, 10) +
" MB is larger than the maximum file size allowed (" +
strconv.FormatInt(maxFileSize/1024/1024, 10) + " MB).")
}
}
var request IQHttpUploadSlotRequest
request.Xmlns = "urn:xmpp:http:upload:0"
request.FileName = fileNameEscaped
request.FileSize = fileSize
request.FileType = mimeType
r, err := xml.Marshal(request)
if err != nil {
log.Fatal(err)
}
// Request http upload slot
id = getID()
c = make(chan xmpp.IQ)
go getIQ(client, id, c)
_, err = client.RawInformation(client.JID(), uploadComponent, id, "get", string(r))
if err != nil {
log.Fatal(err)
}
uploadSlot := <-c
close(c)
if uploadSlot.Type != "result" {
log.Fatal("Error while requesting upload slot.")
}
err = xml.Unmarshal(uploadSlot.Query, &iqHttpUploadSlotXML)
if err != nil {
log.Fatal(err)
}
// Upload file
httpClient := &http.Client{}
req, err := http.NewRequest(http.MethodPut, iqHttpUploadSlotXML.Put.URL, bytes.NewBuffer(buffer))
if err != nil {
log.Fatal(err)
}
req.Header.Set("Content-Type", mimeTypeEscaped.String())
for _, h := range iqHttpUploadSlotXML.Put.Headers {
switch h.Name {
case "Authorization", "Cookie", "Expires":
req.Header.Set(h.Name, h.Value)
}
}
resp, err := httpClient.Do(req)
if err != nil {
log.Fatal(err)
}
// Test for http status code "200 OK" or "201 Created"
if resp.StatusCode != 200 && resp.StatusCode != 201 {
log.Fatal("Http upload failed.")
}
// Return http link
return iqHttpUploadSlotXML.Get.URL
}
func getIQ(client *xmpp.Client, id string, c chan xmpp.IQ) {
for {
msg, err := client.Recv()
if err != nil {
log.Fatal(err)
}
switch v := msg.(type) {
case xmpp.IQ:
if v.ID == id {
c <- v
return
}
}
}
}