forked from hekmon/plexwebhooks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextract.go
70 lines (67 loc) · 1.73 KB
/
extract.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
package plexwebhooks
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
)
// Thumbnail contains all the relevant data about the thumbnail file (if sended).
type Thumbnail struct {
Filename string
Data []byte
}
// Extract extracts the payload and the thumbnail (if present) from a multipart reader
func Extract(mpr *multipart.Reader) (payload *Payload, thumbnail *Thumbnail, err error) {
if mpr == nil {
err = errors.New("multipart reader can't be nil")
return
}
// Read
var formPart *multipart.Part
for formPart, err = mpr.NextPart(); err == nil; formPart, err = mpr.NextPart() {
switch formPart.FormName() {
case "payload":
// Only one payload
if payload != nil {
err = errors.New("payload part is present more than once")
return
}
// Extract payload
payload = new(Payload)
decoder := json.NewDecoder(formPart)
// decoder.DisallowUnknownFields() // dev
if err = decoder.Decode(payload); err != nil {
err = fmt.Errorf("payload JSON decode failed: %v", err)
return
}
case "thumb":
// Only one thumb can be present
if thumbnail != nil {
err = errors.New("thumb part is present more than once")
return
}
// Prepare thumb event payload & set filename
thumbnail = &Thumbnail{
Filename: formPart.FileName(),
}
// Extract thumb data
if thumbnail.Data, err = ioutil.ReadAll(formPart); err != nil {
err = fmt.Errorf("error while reading thumb form part data: %v", err)
}
default:
err = fmt.Errorf("unexpected form part encountered: %s", formPart.FormName())
return
}
}
// Handle errors
if err == io.EOF {
err = nil
}
if err == nil && payload == nil {
err = errors.New("payload not found within request")
}
// Done
return
}