Files
aiscape/modernized-client/examples/ExampleLoginAgent.java
2025-09-06 08:33:20 -07:00

4 lines
17 KiB
Java

package com.openosrs.client.examples;
import com.openosrs.client.api.AgentAPI;
import com.openosrs.client.core.ClientCore;\nimport com.openosrs.client.core.EventSystem;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport java.util.Scanner;\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurrent.CountDownLatch;\n\n/**\n * ExampleLoginAgent - Demonstrates how AI agents can use the OpenOSRS login system.\n * \n * This example shows:\n * - Basic synchronous login\n * - Asynchronous login with callbacks\n * - OTP (One-Time Password) support\n * - Auto-reconnection handling\n * - Event monitoring\n * - Error handling for various login scenarios\n */\npublic class ExampleLoginAgent {\n private static final Logger logger = LoggerFactory.getLogger(ExampleLoginAgent.class);\n \n private final ClientCore clientCore;\n private final AgentAPI agentAPI;\n private final Scanner scanner;\n private volatile boolean running = true;\n \n public ExampleLoginAgent() {\n this.clientCore = new ClientCore();\n this.agentAPI = new AgentAPI(clientCore);\n this.scanner = new Scanner(System.in);\n }\n \n public static void main(String[] args) {\n ExampleLoginAgent agent = new ExampleLoginAgent();\n agent.run();\n }\n \n public void run() {\n logger.info(\"Starting ExampleLoginAgent\");\n \n try {\n // Initialize the client and API\n clientCore.initialize();\n agentAPI.initialize();\n \n // Set up event monitoring\n setupEventMonitoring();\n \n // Main interaction loop\n showMenu();\n \n while (running) {\n System.out.print(\"\\nChoose an option (1-8): \");\n String choice = scanner.nextLine().trim();\n \n switch (choice) {\n case \"1\":\n demonstrateBasicLogin();\n break;\n case \"2\":\n demonstrateAsyncLogin();\n break;\n case \"3\":\n demonstrateOTPLogin();\n break;\n case \"4\":\n demonstrateCallbackLogin();\n break;\n case \"5\":\n demonstrateAutoReconnect();\n break;\n case \"6\":\n demonstrateErrorHandling();\n break;\n case \"7\":\n showGameState();\n break;\n case \"8\":\n logout();\n running = false;\n break;\n default:\n System.out.println(\"Invalid choice. Please try again.\");\n break;\n }\n }\n \n } catch (Exception e) {\n logger.error(\"Error in ExampleLoginAgent\", e);\n } finally {\n shutdown();\n }\n }\n \n private void showMenu() {\n System.out.println(\"\\n======= OpenOSRS Login Agent Demo =======\");\n System.out.println(\"1. Basic Login (Synchronous)\");\n System.out.println(\"2. Async Login (CompletableFuture)\");\n System.out.println(\"3. Login with OTP\");\n System.out.println(\"4. Login with Callbacks\");\n System.out.println(\"5. Auto-Reconnection Demo\");\n System.out.println(\"6. Error Handling Demo\");\n System.out.println(\"7. Show Game State\");\n System.out.println(\"8. Logout and Exit\");\n System.out.println(\"=========================================\");\n }\n \n /**\n * Demonstrate basic synchronous login.\n */\n private void demonstrateBasicLogin() {\n System.out.println(\"\\n--- Basic Login Demo ---\");\n \n if (agentAPI.isLoggedIn()) {\n System.out.println(\"Already logged in! Current state: \" + agentAPI.getLoginState());\n return;\n }\n \n System.out.print(\"Enter username: \");\n String username = scanner.nextLine().trim();\n \n System.out.print(\"Enter password: \");\n String password = scanner.nextLine().trim();\n \n if (username.isEmpty() || password.isEmpty()) {\n System.out.println(\"Username and password are required!\");\n return;\n }\n \n System.out.println(\"Attempting login...\");\n \n // Synchronous login with 30 second timeout\n AgentAPI.LoginResult result = agentAPI.login(username, password);\n \n if (result.isSuccess()) {\n System.out.println(\"✅ Login successful!\");\n System.out.println(\" Session ID: \" + result.getSessionId());\n System.out.println(\" Session Token: \" + result.getSessionToken());\n } else {\n System.out.println(\"❌ Login failed: \" + result.getMessage());\n }\n }\n \n /**\n * Demonstrate asynchronous login using CompletableFuture.\n */\n private void demonstrateAsyncLogin() {\n System.out.println(\"\\n--- Async Login Demo ---\");\n \n if (agentAPI.isLoggedIn()) {\n System.out.println(\"Already logged in! Current state: \" + agentAPI.getLoginState());\n return;\n }\n \n System.out.print(\"Enter username: \");\n String username = scanner.nextLine().trim();\n \n System.out.print(\"Enter password: \");\n String password = scanner.nextLine().trim();\n \n if (username.isEmpty() || password.isEmpty()) {\n System.out.println(\"Username and password are required!\");\n return;\n }\n \n System.out.println(\"Starting async login...\");\n \n // Asynchronous login\n CompletableFuture<AgentAPI.LoginResult> loginFuture = \n agentAPI.loginAsync(username, password, null);\n \n // Handle result asynchronously\n loginFuture.thenAccept(result -> {\n if (result.isSuccess()) {\n System.out.println(\"\\n✅ Async login successful!\");\n System.out.println(\" Session ID: \" + result.getSessionId());\n System.out.println(\" Session Token: \" + result.getSessionToken());\n } else {\n System.out.println(\"\\n❌ Async login failed: \" + result.getMessage());\n }\n }).exceptionally(throwable -> {\n System.out.println(\"\\n💥 Async login error: \" + throwable.getMessage());\n return null;\n });\n \n System.out.println(\"Login request sent! Waiting for response...\");\n \n // Wait for completion (in real agent, you wouldn't block like this)\n try {\n loginFuture.get();\n } catch (Exception e) {\n System.out.println(\"Error waiting for login: \" + e.getMessage());\n }\n }\n \n /**\n * Demonstrate login with One-Time Password (OTP).\n */\n private void demonstrateOTPLogin() {\n System.out.println(\"\\n--- OTP Login Demo ---\");\n \n if (agentAPI.isLoggedIn()) {\n System.out.println(\"Already logged in! Current state: \" + agentAPI.getLoginState());\n return;\n }\n \n System.out.print(\"Enter username: \");\n String username = scanner.nextLine().trim();\n \n System.out.print(\"Enter password: \");\n String password = scanner.nextLine().trim();\n \n System.out.print(\"Enter OTP (6 digits, or press Enter to skip): \");\n String otp = scanner.nextLine().trim();\n \n if (username.isEmpty() || password.isEmpty()) {\n System.out.println(\"Username and password are required!\");\n return;\n }\n \n String otpDisplay = otp.isEmpty() ? \"(none)\" : \"****\" + otp.substring(Math.max(0, otp.length() - 2));\n System.out.println(\"Attempting login with OTP: \" + otpDisplay);\n \n AgentAPI.LoginResult result = agentAPI.login(username, password, otp);\n \n if (result.isSuccess()) {\n System.out.println(\"✅ OTP login successful!\");\n System.out.println(\" Session ID: \" + result.getSessionId());\n } else {\n System.out.println(\"❌ OTP login failed: \" + result.getMessage());\n }\n }\n \n /**\n * Demonstrate login with event callbacks.\n */\n private void demonstrateCallbackLogin() {\n System.out.println(\"\\n--- Callback Login Demo ---\");\n \n if (agentAPI.isLoggedIn()) {\n System.out.println(\"Already logged in! Current state: \" + agentAPI.getLoginState());\n return;\n }\n \n System.out.print(\"Enter username: \");\n String username = scanner.nextLine().trim();\n \n System.out.print(\"Enter password: \");\n String password = scanner.nextLine().trim();\n \n if (username.isEmpty() || password.isEmpty()) {\n System.out.println(\"Username and password are required!\");\n return;\n }\n \n CountDownLatch latch = new CountDownLatch(1);\n \n // Set up callbacks\n agentAPI.setLoginCallbacks(\n result -> {\n System.out.println(\"\\n🎉 Callback: Login successful!\");\n System.out.println(\" \" + result);\n latch.countDown();\n },\n error -> {\n System.out.println(\"\\n💔 Callback: Login failed!\");\n System.out.println(\" \" + error);\n latch.countDown();\n },\n progress -> {\n System.out.println(\"📊 Progress: \" + progress);\n }\n );\n \n System.out.println(\"Starting callback login...\");\n \n // Start async login\n agentAPI.loginAsync(username, password, null);\n \n // Wait for callback\n try {\n latch.await();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n \n /**\n * Demonstrate auto-reconnection feature.\n */\n private void demonstrateAutoReconnect() {\n System.out.println(\"\\n--- Auto-Reconnection Demo ---\");\n \n // Enable auto-reconnection\n agentAPI.setAutoReconnect(true, 5, 3); // 5 second delay, 3 max attempts\n \n System.out.println(\"Auto-reconnection enabled (5s delay, 3 max attempts)\");\n System.out.println(\"This would automatically reconnect if the connection is lost.\");\n System.out.println(\"In a real scenario, the agent would:\");\n System.out.println(\" 1. Detect disconnection\");\n System.out.println(\" 2. Wait 5 seconds\");\n System.out.println(\" 3. Attempt to reconnect using last credentials\");\n System.out.println(\" 4. Repeat up to 3 times\");\n \n // Simulate disconnection event for demonstration\n if (agentAPI.isLoggedIn()) {\n System.out.println(\"\\nSimulating disconnection event...\");\n clientCore.getEventSystem().fireEvent(EventSystem.EventType.DISCONNECTED, \n new EventSystem.Event(EventSystem.EventType.DISCONNECTED));\n } else {\n System.out.println(\"\\nNot currently logged in - auto-reconnect would activate on disconnection.\");\n }\n }\n \n /**\n * Demonstrate various error handling scenarios.\n */\n private void demonstrateErrorHandling() {\n System.out.println(\"\\n--- Error Handling Demo ---\");\n \n System.out.println(\"Testing various error scenarios:\");\n \n // Test 1: Empty credentials\n System.out.println(\"\\n1. Testing empty credentials...\");\n AgentAPI.LoginResult result1 = agentAPI.login(\"\", \"\");\n System.out.println(\" Result: \" + result1.getMessage());\n \n // Test 2: Invalid credentials (will be simulated)\n System.out.println(\"\\n2. Testing invalid credentials...\");\n AgentAPI.LoginResult result2 = agentAPI.login(\"invalid_user\", \"wrong_password\");\n System.out.println(\" Result: \" + result2.getMessage());\n \n // Test 3: Login while already logged in\n if (agentAPI.isLoggedIn()) {\n System.out.println(\"\\n3. Testing login while already logged in...\");\n AgentAPI.LoginResult result3 = agentAPI.login(\"test\", \"test\");\n System.out.println(\" Result: \" + result3.getMessage());\n } else {\n System.out.println(\"\\n3. Skipping 'already logged in' test (not logged in)\");\n }\n \n System.out.println(\"\\n✅ Error handling demonstrations complete.\");\n }\n \n /**\n * Show current game state information.\n */\n private void showGameState() {\n System.out.println(\"\\n--- Game State ---\");\n \n System.out.println(\"Login State: \" + agentAPI.getLoginState());\n System.out.println(\"Logged In: \" + agentAPI.isLoggedIn());\n System.out.println(\"Login In Progress: \" + agentAPI.isLoginInProgress());\n \n if (agentAPI.isLoggedIn()) {\n AgentAPI.Position pos = agentAPI.getPlayerPosition();\n System.out.println(\"Player Position: \" + pos);\n System.out.println(\"Player Health: \" + agentAPI.getPlayerHealth());\n System.out.println(\"Player Energy: \" + agentAPI.getPlayerEnergy());\n System.out.println(\"Player Moving: \" + agentAPI.isPlayerMoving());\n \n // Show inventory summary\n AgentAPI.InventoryState.InventoryItem[] items = agentAPI.getInventoryItems();\n int itemCount = 0;\n for (AgentAPI.InventoryState.InventoryItem item : items) {\n if (item.getItemId() != -1) itemCount++;\n }\n System.out.println(\"Inventory Items: \" + itemCount + \"/28\");\n } else {\n System.out.println(\"(Game state not available - not logged in)\");\n }\n }\n \n /**\n * Logout from the game.\n */\n private void logout() {\n System.out.println(\"\\n--- Logout ---\");\n \n if (agentAPI.isLoggedIn()) {\n agentAPI.logout();\n System.out.println(\"✅ Logout initiated\");\n } else {\n System.out.println(\"Not currently logged in\");\n }\n }\n \n /**\n * Set up event monitoring to show what's happening.\n */\n private void setupEventMonitoring() {\n // Monitor login events\n agentAPI.addEventListener(EventSystem.EventType.LOGIN_ATTEMPT_STARTED, event -> {\n System.out.println(\"🔄 Event: Login attempt started\");\n });\n \n agentAPI.addEventListener(EventSystem.EventType.LOGIN_SUCCESS, event -> {\n System.out.println(\"✅ Event: Login successful\");\n });\n \n agentAPI.addEventListener(EventSystem.EventType.LOGIN_FAILED, event -> {\n System.out.println(\"❌ Event: Login failed\");\n });\n \n agentAPI.addEventListener(EventSystem.EventType.LOGOUT, event -> {\n System.out.println(\"👋 Event: Logout\");\n });\n \n agentAPI.addEventListener(EventSystem.EventType.DISCONNECTED, event -> {\n System.out.println(\"🔌 Event: Disconnected\");\n });\n \n // Monitor game events\n agentAPI.addEventListener(EventSystem.EventType.CHAT_MESSAGE, event -> {\n System.out.println(\"💬 Event: Chat message received\");\n });\n \n agentAPI.addEventListener(EventSystem.EventType.PLAYER_MOVED, event -> {\n System.out.println(\"🚶 Event: Player moved\");\n });\n \n System.out.println(\"📡 Event monitoring set up\");\n }\n \n /**\n * Shutdown the agent and clean up resources.\n */\n private void shutdown() {\n logger.info(\"Shutting down ExampleLoginAgent\");\n \n try {\n agentAPI.shutdown();\n clientCore.shutdown();\n scanner.close();\n } catch (Exception e) {\n logger.error(\"Error during shutdown\", e);\n }\n \n System.out.println(\"\\n👋 ExampleLoginAgent shut down. Goodbye!\");\n }\n}\n