aur/client.v

83 lines
1.3 KiB
Coq
Raw Normal View History

2022-06-22 11:42:16 +02:00
module aur
import net.urllib
import net.http
import json
pub struct Client {
2022-06-22 11:51:03 +02:00
url string = aur_rpc_url
2022-06-22 11:42:16 +02:00
}
pub fn new() &Client {
2022-06-22 11:51:03 +02:00
return &Client{}
2022-06-22 11:42:16 +02:00
}
pub fn new_with_url(url string) &Client {
2022-06-22 11:51:03 +02:00
if !url.ends_with('/') {
return &Client{
2023-02-08 10:44:13 +01:00
url: '${url}/'
2022-06-22 11:51:03 +02:00
}
}
return &Client{
url: url
}
2022-06-22 11:42:16 +02:00
}
2022-06-22 13:46:35 +02:00
struct Response {
@type string [json: 'type']
error string
results []Package
2022-06-22 11:42:16 +02:00
}
2022-11-01 20:58:27 +01:00
fn (c Client) request(params map[string][]string) ![]Package {
2022-06-22 13:42:55 +02:00
mut param_strings := []string{}
2022-06-22 11:51:03 +02:00
for k, v in params {
2023-02-08 10:44:13 +01:00
param_strings << v.map(urllib.query_escape(it)).map('${k}=${it}')
2022-06-22 11:51:03 +02:00
}
2022-06-22 11:42:16 +02:00
2023-02-08 10:44:13 +01:00
url := '${c.url}?${param_strings.join('&')}'
2022-06-22 11:42:16 +02:00
2022-11-01 20:58:27 +01:00
res := http.get(url)!
2022-06-22 11:42:16 +02:00
2022-06-22 11:51:03 +02:00
if res.status_code < 200 || res.status_code >= 300 {
// temporary
return error('error')
}
2022-06-22 11:42:16 +02:00
2022-11-01 20:58:27 +01:00
data := json.decode(Response, res.body)!
2022-06-22 13:46:35 +02:00
if data.@type == 'error' {
2023-02-08 10:44:13 +01:00
return error('Server responded with an error: ${data.error}')
2022-06-22 13:46:35 +02:00
}
2022-06-22 11:42:16 +02:00
2022-06-22 11:51:03 +02:00
return data.results
2022-06-22 11:42:16 +02:00
}
2022-06-22 13:42:55 +02:00
2022-11-01 20:58:27 +01:00
pub fn (c Client) search_by(arg string, st SearchType) ![]Package {
2022-06-22 13:42:55 +02:00
params := {
'v': ['5']
'type': ['search']
2023-02-08 10:44:13 +01:00
'by': ['${st}']
2022-06-22 13:42:55 +02:00
'arg': [arg]
}
return c.request(params)
}
// search performs a search by name_desc.
2022-11-01 20:58:27 +01:00
pub fn (c Client) search(arg string) ![]Package {
2022-06-22 13:42:55 +02:00
return c.search_by(arg, .name_desc)
}
2022-11-01 20:58:27 +01:00
pub fn (c Client) info(pkgs []string) ![]Package {
2022-06-22 13:42:55 +02:00
params := {
'v': ['5']
'type': ['info']
'arg[]': pkgs
}
return c.request(params)
}