/
convert.go
95 lines (84 loc) · 2.16 KB
/
convert.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
package convertapi
import (
"fmt"
"github.com/ConvertAPI/convertapi-go/config"
"github.com/ConvertAPI/convertapi-go/lib"
"github.com/ConvertAPI/convertapi-go/param"
"net/url"
"os"
)
func ConvDef(fromFormat string, toFormat string, params ...param.IParam) (result *Result) {
return Convert(fromFormat, toFormat, params, nil)
}
func Convert(fromFormat string, toFormat string, params []param.IParam, conf *config.Config) (result *Result) {
result = NewResult()
go func() {
if conf == nil {
conf = config.Default
}
ignoreParams := []string{"storefile", "async", "jobid", "converter"}
values := &url.Values{}
paramVals, err := prepareValues(params)
if err != nil {
result.reject(err)
return
}
converter := ""
if val, ok := paramVals["converter"]; ok && len(val) > 0 {
converter = fmt.Sprintf("/converter/%s", val[0])
}
for name, vals := range paramVals {
if !lib.Contains(ignoreParams, name) {
if len(vals) == 1 {
values.Add(name, vals[0])
} else {
for i, val := range vals {
values.Add(fmt.Sprintf("%s[%d]", name, i), val)
}
}
}
}
query := url.Values{}
conf.AddAuth(query)
query.Add("storefile", "true")
path := fmt.Sprintf("/convert/%s/to/%s%s?%s", fromFormat, toFormat, converter, query.Encode())
pathURL, err := url.Parse(path)
if err != nil {
result.reject(err)
return
}
convertURL := conf.BaseURL.ResolveReference(pathURL)
result.start(convertURL.String(), values, conf.HttpClient)
}()
return
}
func prepareValues(params []param.IParam) (vals map[string][]string, err error) {
vals = make(map[string][]string)
for _, p := range params {
paramVal, err := p.Values()
if err != nil {
return nil, err
}
v, ok := vals[p.Name()]
if ok {
v = append(v, paramVal...)
} else {
v = paramVal
}
vals[p.Name()] = v
}
return
}
func ConvertPath(fromPath string, toPath string) (file *os.File, errs []error) {
res := Convert(lib.PathExt(fromPath), lib.PathExt(toPath), []param.IParam{
param.NewPath("file", fromPath, nil),
}, nil)
if lib.AddErr(&errs, res.err) {
if files, e := res.ToPath(toPath); e == nil {
file = files[0]
} else {
errs = e
}
}
return
}