/
api.jl
62 lines (55 loc) · 1.76 KB
/
api.jl
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
module API
using PCloud
# import ..PCloud: PCloudClient, OPTS, PCloudError
using ..PCloud: HTTP, JSON3
include("pcloud_api.jl")
pushfiles!(body, file) = push!(body, :files => file)
function pushfiles!(body, file::Pair)
push!(body, :files => HTTP.Multipart(file.first, ioify(file.second)))
end
function pushfiles!(body, file::AbstractString)
push!(body, :files => open(file, "r"))
end
function pushfiles!(body, files::AbstractVector)
for file in files
pushfiles!(body, file)
end
end
ioify(elem::IO) = elem
ioify(elem) = IOBuffer(elem)
function ioify(elem::IOBuffer)
seekstart(elem)
return elem
end
function query(client::PCloud.PCloudClient, method, params)
response = if haskey(params, :files)
body = Pair[]
for (k, v) in params
k == :files && continue
# We need strings in multipart. Fortunately all parameters other then
# `files` should transform to String straightforwardly. But it is of
# course one of the possible source of errors.
push!(body, k => string(v))
end
pushfiles!(body, params[:files])
uri = client.apiep * method
HTTP.post(uri, ["Connection" => "Keep-Alive"], HTTP.Form(body); cookies = client.cookies)
else
uri = client.apiep * method * "?" * HTTP.URIs.escapeuri(params)
HTTP.get(uri, ["Connection" => "Keep-Alive"]; cookies = client.cookies)
end
res = JSON3.read(String(response.body))
if res.result == 0
return res
else
throw(PCloudError(res))
end
end
for (f, fdoc) in PCLOUD_API
@eval begin
$f(client::PCloud.PCloudClient = PCloud.OPTS.client; kwargs...) = query(client, String(Symbol($f)), Dict(kwargs))
@doc $fdoc $f
export $f
end
end
end # module