This repository has been archived by the owner on May 9, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpostPublicationsHelperB64.go
88 lines (75 loc) · 1.96 KB
/
postPublicationsHelperB64.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
package main
import (
"bytes"
"encoding/base64"
"errors"
"gopkg.in/h2non/filetype.v1"
"io"
"os"
"path/filepath"
"strconv"
)
// Decode attachments and place them in the temporary directory
func (pubreq *postPublicationsRequest) decodeBase64Attachments() (pictures []string, videos []string, audio []string, documents []string, err error) {
if len(pubreq.PicturesBase64) != 0 {
pictures, err = decodeBase64Attachment("PIC", pubreq.PicturesBase64)
if err != nil {
return
}
}
if len(pubreq.VideosBase64) != 0 {
videos, err = decodeBase64Attachment("VID", pubreq.VideosBase64)
if err != nil {
return
}
}
if len(pubreq.AudioBase64) != 0 {
audio, err = decodeBase64Attachment("AUD", pubreq.AudioBase64)
if err != nil {
return
}
}
if len(pubreq.DocumentsBase64) != 0 {
documents, err = decodeBase64Attachment("DOC", pubreq.DocumentsBase64)
}
return
}
// Decode a particular attachment type
func decodeBase64Attachment(prefix string, attachments []string) ([]string, error) {
var paths []string = make([]string, len(attachments))
for index, encoded := range attachments {
// Decode the string
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return paths, err
}
// Detect MIME type & extension
kind, err := filetype.Match(decoded)
if err != nil {
return paths, err
}
// Make suffix (REPLACE WITH HASH ?)
suffix := strconv.FormatInt(int64(index+len(encoded)), 10)
// Build filename
filename := prefix + suffix + "." + kind.Extension
path := filepath.Join(tempDirPath, filename)
// Create file
file, err := os.Create(path)
if err != nil {
return paths, err
}
defer file.Close()
// Make buffer, decode & write to file
decodedReader := bytes.NewBuffer(decoded)
n, err := io.Copy(file, decodedReader)
if err == nil && n == 0 {
err = errors.New("ERROR: 0 bytes copied")
}
if err != nil {
return paths, err
}
// Detect file type
paths[index] = path
}
return paths, nil
}