You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
3.1 KiB

package dev.garrettmills.starship.hyperlink.util;
import android.content.SharedPreferences;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import dev.garrettmills.starship.hyperlink.Hyperlink;
public class APIv1 {
/**
* Given an API endpoint, resolve the fully qualified URL using the stored server address.
* Example:
* resolveEndpoint("/auth/redeem") // => "https://hyperlink.url/api/v1/auth/redeem"
* @param endpoint un-qualified api endpoint
* @return The resolved string.
*/
public static String resolveEndpoint(String endpoint) {
if ( !endpoint.startsWith("/") ) {
endpoint = "/" + endpoint;
}
String server = Hyperlink.preferences.getString(Hyperlink.SERVER_ADDR, "");
if ( server.endsWith("/") ) {
server = server.substring(0, server.length() - 1);
}
return server + "/api/v1" + endpoint;
}
public static boolean isAuthenticated() {
return !Hyperlink.preferences.getString(Hyperlink.SERVER_ADDR, "").equals("")
&& !Hyperlink.preferences.getString(Hyperlink.ACCESS_TOKEN, "").equals("");
}
public static AccessToken getToken() throws NotAuthenticatedException {
if ( !isAuthenticated() ) {
throw new NotAuthenticatedException();
}
return new AccessToken(
Hyperlink.preferences.getString(Hyperlink.SERVER_ADDR, ""),
Hyperlink.preferences.getString(Hyperlink.ACCESS_TOKEN, "")
);
}
public static void logout() {
SharedPreferences.Editor editor = Hyperlink.preferences.edit();
editor.putString(Hyperlink.SERVER_ADDR, "");
editor.putString(Hyperlink.ACCESS_TOKEN, "");
editor.apply();
}
public static void login(LoginToken login, Runnable callback) {
Gson gson = new Gson();
String tokenJson = gson.toJson(login);
try {
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.POST,
resolveEndpoint("/login/redeem"),
new JSONObject(tokenJson),
response -> {
try {
String tokenValue = response.getString("token");
Log.d("APIv1", "Got access token: " + tokenValue);
SharedPreferences.Editor editor = Hyperlink.preferences.edit();
editor.putString(Hyperlink.SERVER_ADDR, login.getServer());
editor.putString(Hyperlink.ACCESS_TOKEN, tokenValue);
editor.apply();
} catch (JSONException e) {
callback.run();
}
},
error -> callback.run()
);
Hyperlink.httpRequestQueue.add(request);
} catch (JSONException e) {
callback.run();
}
}
}