tootle-linux-client/src/Request.vala

105 lines
2.1 KiB
Vala
Raw Normal View History

2020-05-29 14:19:35 +02:00
using Soup;
using Gee;
public class Tootle.Request : Soup.Message {
2020-06-20 12:04:58 +02:00
public string url { set; get; }
2020-07-10 16:22:38 +02:00
Network.SuccessCallback? cb;
Network.ErrorCallback? error_cb;
HashMap<string, string>? pars;
weak InstanceAccount? account;
bool needs_token = false;
weak Gtk.Widget? ctx;
bool has_ctx = false;
2020-05-29 14:19:35 +02:00
public Request.GET (string url) {
Object (method: "GET", url: url);
}
public Request.POST (string url) {
Object (method: "POST", url: url);
}
public Request.DELETE (string url) {
Object (method: "DELETE", url: url);
}
2020-07-10 16:22:38 +02:00
public Request with_ctx (Gtk.Widget ctx) {
this.has_ctx = true;
this.ctx = ctx;
this.ctx.destroy.connect (() => {
network.cancel (this);
this.ctx = null;
});
2020-05-29 14:19:35 +02:00
return this;
}
2020-07-10 16:22:38 +02:00
public Request then (owned Network.SuccessCallback cb) {
this.cb = (s, m) => {
Idle.add (() => {
cb (s, m);
return false;
});
2020-05-29 14:19:35 +02:00
};
return this;
}
public Request on_error (owned Network.ErrorCallback cb) {
this.error_cb = (owned) cb;
return this;
}
public Request with_account (InstanceAccount? account = null) {
this.needs_token = true;
if (account != null)
this.account = account;
return this;
}
public Request with_param (string name, string val) {
if (pars == null)
pars = new HashMap<string, string> ();
pars[name] = val;
return this;
}
2020-07-10 16:22:38 +02:00
public Request exec () {
2020-05-29 14:19:35 +02:00
var parameters = "";
if (pars != null) {
parameters = "?";
var parameters_counter = 0;
pars.@foreach (entry => {
parameters_counter++;
var key = (string) entry.key;
var val = (string) entry.value;
parameters += @"$key=$val";
if (parameters_counter < pars.size)
parameters += "&";
return true;
});
}
if (needs_token) {
if (account == null) {
2020-06-20 12:04:58 +02:00
warning (@"No account was specified or found for $method: $url$parameters");
2020-05-29 14:19:35 +02:00
return this;
}
2020-06-20 12:04:58 +02:00
request_headers.append ("Authorization", @"Bearer $(account.access_token)");
2020-05-29 14:19:35 +02:00
}
if (!("://" in url)) {
url = account.instance + url;
}
this.uri = new URI (url + "" + parameters);
url = uri.to_string (false);
2020-06-20 12:04:58 +02:00
debug (@"$method: $url");
2020-05-29 14:19:35 +02:00
network.queue (this, (owned) cb, (owned) error_cb);
return this;
}
}