11package io .exterminator3618 .client .api ;
22
3- import com .fasterxml .jackson .core .JsonProcessingException ;
4- import com .fasterxml .jackson .databind .DeserializationFeature ;
5- import com .fasterxml .jackson .databind .json .JsonMapper ;
63import io .exterminator3618 .client .Exterminator3618 ;
4+ import org .slf4j .Logger ;
5+ import org .slf4j .LoggerFactory ;
76
87import java .io .IOException ;
98import java .net .*;
109import java .net .http .HttpClient ;
1110import java .net .http .HttpRequest ;
11+ import java .net .http .HttpResponse ;
12+ import java .time .Duration ;
13+ import java .util .ArrayList ;
14+ import java .util .concurrent .atomic .AtomicReference ;
1215
16+ public class ApiClient implements FriendsApi , MatchApi , UserApi {
1317
14- public class ApiClient implements FriendsApi , UserApi {
18+ private static final Logger logger = LoggerFactory . getLogger ( ApiClient . class );
1519
1620 protected final Exterminator3618 game ;
17- protected final UserInfo userInfo = new UserInfo ();
1821 protected final HttpClient httpClient ;
19- protected final JsonMapper jsonMapper = JsonMapper .builder ()
20- .disable (DeserializationFeature .FAIL_ON_TRAILING_TOKENS )
21- .build ();
2222
23- private ApiClient (Exterminator3618 game , HttpClient httpClient ) throws IOException {
23+ protected final UserInfo userInfo = new UserInfo ();
24+ protected final ArrayList <UserInfo > friendsList = new ArrayList <>();
25+
26+ private ApiClient (Exterminator3618 game , HttpClient httpClient ) {
2427 this .game = game ;
2528 this .httpClient = httpClient ;
2629 }
2730
2831 public static ApiClient create (Exterminator3618 game ) throws IOException {
2932 CookieManager cookieManager = new CookieManager ();
30- HttpClient httpClient = HttpClient .newBuilder ()
31- .cookieHandler (cookieManager )
32- .build ();
33+ HttpClient httpClient = createHttpClient (cookieManager );
3334 ApiClient client = new ApiClient (game , httpClient );
3435 HttpCookie authCookie = new HttpCookie ("auth" , game .getPreferences ().getString ("auth" ));
3536 authCookie .setDomain (client .getBaseServerUrl ());
3637 authCookie .setPath ("/" );
3738 authCookie .setHttpOnly (true );
3839 cookieManager .getCookieStore ().add (URI .create (client .getBaseServerUrl ()), authCookie );
40+ if (!client .fetchUserInfo ()) {
41+ throw new IOException ("Failed to fetch user info" );
42+ } else {
43+ logger .info ("Authenticated as {} successfully" , client .getUserInfo ().getUsername ());
44+ }
3945 return client ;
4046 }
4147
42- public static ApiClient login (Exterminator3618 game , String username , String password ) throws IOException {
43- HttpClient httpClient = HttpClient . newHttpClient ( );
48+ public static ApiClient login (Exterminator3618 game , String loginUsername , String loginPassword ) throws IOException , InterruptedException {
49+ HttpClient httpClient = createHttpClient ( null );
4450 ApiClient client = new ApiClient (game , httpClient );
45- HttpRequest req = client .createJsonPostRequest ("/api/user /login" , new Object () {
46- public final String usernameField = username ;
47- public final String passwordField = password ;
51+ HttpRequest req = client .createJsonPostRequest ("/account /login" , new Object () {
52+ public final String username = loginUsername ;
53+ public final String password = loginPassword ;
4854 });
55+ HttpResponse <OperationResponse > res = httpClient .send (req , DataProcessor .getOperationResponseHandler ());
56+ if (res .statusCode () != 200 ) {
57+ throw new IOException ("Login failed with status code: " + res .statusCode ());
58+ } else if (!res .body ().isSuccess ()) {
59+ throw new IOException ("Login failed: " + res .body ().getMessage ());
60+ }
61+ logger .info ("Logged in as {} successfully" , loginUsername );
62+ if (!client .fetchUserInfo ()) {
63+ throw new IOException ("Failed to fetch user info after login" );
64+ }
4965 return client ;
5066 }
5167
52- public static ApiClient register (Exterminator3618 game , String name , String username , String password ) throws IOException {
53- HttpClient httpClient = HttpClient . newHttpClient ( );
68+ public static ApiClient register (Exterminator3618 game , String registerName , String registerUsername , String registerPassword ) throws IOException , InterruptedException {
69+ HttpClient httpClient = createHttpClient ( null );
5470 ApiClient client = new ApiClient (game , httpClient );
71+ HttpRequest req = client .createJsonPostRequest ("/account/register" , new Object () {
72+ public final String name = registerName ;
73+ public final String username = registerUsername ;
74+ public final String password = registerPassword ;
75+ });
76+ HttpResponse <OperationResponse > res = httpClient .send (req , DataProcessor .getOperationResponseHandler ());
77+ if (res .statusCode () != 200 ) {
78+ throw new IOException ("Registration failed with status code: " + res .statusCode ());
79+ } else if (!res .body ().isSuccess ()) {
80+ throw new IOException ("Registration failed: " + res .body ().getMessage ());
81+ }
82+ logger .info ("Registered account {} successfully" , registerUsername );
83+ if (!client .fetchUserInfo ()) {
84+ throw new IOException ("Failed to fetch user info after registration" );
85+ }
5586 return client ;
5687 }
5788
5889 @ Override
5990 public String getBaseServerUrl () {
91+ // return "http://localhost:36018/api"; // mock server URL
6092 return game .getPreferences ().getString ("server_url" , "http://localhost:36018/api" );
6193 }
6294
@@ -66,16 +98,52 @@ public HttpClient getHttpClient() {
6698 }
6799
68100 @ Override
69- public String jsonSerializeObject (Object o ) {
70- try {
71- return jsonMapper .writeValueAsString (o );
72- } catch (JsonProcessingException e ) {
73- throw new RuntimeException (e );
101+ public UserInfo getUserInfo () {
102+ return userInfo ;
103+ }
104+
105+ @ Override
106+ public Logger getLogger () {
107+ return logger ;
108+ }
109+
110+ public String exportAuthToken () {
111+ AtomicReference <String > authToken = new AtomicReference <>();
112+ getHttpClient ().cookieHandler ().ifPresent (cookieHandler -> {
113+ if (cookieHandler instanceof CookieManager cookieManager ) {
114+ for (HttpCookie cookie : cookieManager .getCookieStore ().getCookies ()) {
115+ if (cookie .getName ().equals ("auth" )) {
116+ authToken .set (cookie .getValue ());
117+ break ;
118+ }
119+ }
120+ }
121+ });
122+ return authToken .get ();
123+ }
124+
125+ public void saveAuthToken () {
126+ String authToken = exportAuthToken ();
127+ if (authToken != null ) {
128+ logger .info ("Saving auth token to preferences" );
129+ game .getPreferences ().putString ("auth" , authToken );
130+ } else {
131+ logger .warn ("No auth token found, removing from preferences" );
132+ game .getPreferences ().remove ("auth" );
74133 }
75134 }
76135
77- public UserInfo internalUserInfoObject () {
78- return userInfo ;
136+ private static HttpClient createHttpClient (CookieManager cookieManager ) {
137+ CookieManager useCookieManager = cookieManager ;
138+ if (useCookieManager == null ) {
139+ useCookieManager = new CookieManager ();
140+ }
141+ useCookieManager .setCookiePolicy (CookiePolicy .ACCEPT_ALL );
142+ return HttpClient .newBuilder ()
143+ .cookieHandler (useCookieManager )
144+ .connectTimeout (Duration .ofSeconds (6 ))
145+ .followRedirects (HttpClient .Redirect .NORMAL )
146+ .build ();
79147 }
80148
81149}
0 commit comments