Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

api v2 #30

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open

api v2 #30

wants to merge 3 commits into from

Conversation

thewilloftheshadow
Copy link
Member

@thewilloftheshadow thewilloftheshadow commented Feb 13, 2025

Summary by CodeRabbit

  • New Features
    • Introduced a user class encapsulating detailed user-related data and metrics.
  • Refactor
    • Upgraded the service to utilize the latest Kiai API endpoint version.
    • Simplified methods for handling messages and experience adjustments, enhancing error handling and robustness.
  • Chores
    • Updated dependency versions and repository URLs for improved compatibility and functionality.

Copy link

coderabbitai bot commented Feb 13, 2025

Walkthrough

This pull request updates components that interact with the Kiai API. In the KiaiMC class, the base URL is updated from version 1 to version 2. The Kiai class has been refactored to simplify role ID extraction, adjust endpoint paths by removing the /guild/ prefix, modify XP handling by negating values for removal, and update the getUser method to return a parsed User object instead of a raw String. Additionally, a new User class is introduced to encapsulate user-related data with public getters for various attributes.

Changes

File(s) Summary
src/main/.../KiaiMC.java, src/main/.../api/Kiai.java Updated API endpoints and request handling: changed base URL to v2; refactored virtualMessage to directly map role IDs; streamlined endpoint paths in queueRequest; modified removeXp to negate XP; updated getUser to parse the JSON response into a User object.
src/main/.../api/User.java New User class added with private fields (id, guildId, currentLevel, nextLevel, nextLevelXp, xp, messagesSent, voiceMinutes, rankCardBackground, currentXpStreak, streakDoneToday) and corresponding public getter methods to access user data.
build.gradle.kts Updated repository URL for PaperMC and dependency versions for Paper API (from 1.21.1-R0.1-SNAPSHOT to 1.21.4-R0.1-SNAPSHOT) and Command API Bukkit shade dependency (from 9.5.3 to 9.7.0).

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant K as Kiai API Handler
    participant A as Kiai API
    C->>K: Invoke getUser(guildId, userId)
    K->>A: Send HTTP request (endpoint without "/guild/" prefix)
    A-->>K: Return JSON response with user data
    K->>K: Parse JSON using Gson into User object
    K-->>C: Return CompletableFuture<User>
Loading

Poem

I’m a happy rabbit in a code burrow so bright,
Hopping to new endpoints with all my might.
The API now dances to a version two tune,
With User data blooming like a bright afternoon.
I nibble on bugs and cheer every change in sight! 🐰
Code hops along—ever joyful, ever light.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1640ff9 and b7628a2.

📒 Files selected for processing (1)
  • src/main/java/com/buape/kiaimc/api/Kiai.java (3 hunks)
🔇 Additional comments (4)
src/main/java/com/buape/kiaimc/api/Kiai.java (4)

7-8: LGTM! Thread-safe Gson initialization.

The Gson imports and static initialization are correctly implemented.

Also applies to: 12-12


36-36: Add null safety to role handling and fix endpoint URL.

The previously identified issues still persist:

  1. Role ID extraction needs null safety
  2. Endpoint URL should not have a leading slash

Apply this diff to fix both issues:

-        member.put("roleIds", guildMember.getRoles().stream().map(role -> role.getId()).toList());
+        member.put("roleIds", guildMember.getRoles().stream()
+                .filter(role -> role != null)
+                .map(role -> role.getId())
+                .toList());

-        requestQueueManager.queueRequest("/virtual_message", "POST", jsonMap);
+        requestQueueManager.queueRequest("virtual_message", "POST", jsonMap);

Also applies to: 46-46


50-60: LGTM! Robust XP handling implementation.

The XP methods now include:

  • Input validation for negative amounts
  • Error handling with logging
  • Proper XP negation for removal

Also applies to: 63-73


76-82: Add error handling for JSON parsing.

The getUser method needs robust error handling for:

  • Null responses
  • Missing data field
  • JSON parsing exceptions

Apply this diff to add error handling:

     public CompletableFuture<User> getUser(String guildId, String userId) {
-        return requestQueueManager.queueRequest("/" + guildId + "/member/" + userId, "GET", null)
+        return requestQueueManager.queueRequest(guildId + "/member/" + userId, "GET", null)
                 .thenApply(response -> {
+                    if (response == null) {
+                        throw new IllegalStateException("Received null response from API");
+                    }
                     JsonObject jsonObject = gson.fromJson(response, JsonObject.class);
+                    if (!jsonObject.has("data")) {
+                        throw new IllegalStateException("Response missing 'data' field");
+                    }
                     return gson.fromJson(jsonObject.get("data"), User.class);
-                });
+                })
+                .exceptionally(throwable -> {
+                    logger.severe("Failed to get user: " + throwable.getMessage());
+                    throw new CompletionException(throwable);
+                });
     }
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (3)
src/main/java/com/buape/kiaimc/api/User.java (1)

3-14: Add constructor and field validations.

Consider the following improvements:

  1. Add a constructor to initialize fields.
  2. Add @Nullable annotation for potentially nullable fields like rankCardBackground.
  3. Add validation for numeric fields to ensure they are non-negative.
+import javax.annotation.Nullable;
+
 public class User {
 	private String id;
 	private String guildId;
 	private int currentLevel;
 	private int nextLevel;
 	private int nextLevelXp;
 	private int xp;
 	private int messagesSent;
 	private int voiceMinutes;
+	@Nullable
 	private String rankCardBackground;
 	private int currentXpStreak;
 	private boolean streakDoneToday;
+
+	public User(String id, String guildId, int currentLevel, int nextLevel,
+			int nextLevelXp, int xp, int messagesSent, int voiceMinutes,
+			@Nullable String rankCardBackground, int currentXpStreak,
+			boolean streakDoneToday) {
+		this.id = id;
+		this.guildId = guildId;
+		this.currentLevel = validateNonNegative(currentLevel, "currentLevel");
+		this.nextLevel = validateNonNegative(nextLevel, "nextLevel");
+		this.nextLevelXp = validateNonNegative(nextLevelXp, "nextLevelXp");
+		this.xp = validateNonNegative(xp, "xp");
+		this.messagesSent = validateNonNegative(messagesSent, "messagesSent");
+		this.voiceMinutes = validateNonNegative(voiceMinutes, "voiceMinutes");
+		this.rankCardBackground = rankCardBackground;
+		this.currentXpStreak = validateNonNegative(currentXpStreak, "currentXpStreak");
+		this.streakDoneToday = streakDoneToday;
+	}
+
+	private static int validateNonNegative(int value, String fieldName) {
+		if (value < 0) {
+			throw new IllegalArgumentException(fieldName + " cannot be negative");
+		}
+		return value;
+	}
src/main/java/com/buape/kiaimc/api/Kiai.java (1)

12-12: Configure Gson for robust JSON handling.

Consider configuring Gson with custom type adapters and null handling:

-    private static final Gson gson = new Gson();
+    private static final Gson gson = new GsonBuilder()
+            .serializeNulls()
+            .setDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
+            .create();
src/main/java/com/buape/kiaimc/KiaiMC.java (1)

47-47: Add base URL validation and version change logging.

Consider adding URL validation and logging the API version change:

-                baseUrl = "https://api.kiai.app/v2";
+                baseUrl = validateBaseUrl("https://api.kiai.app/v2");
+                logger.info("Using Kiai API v2");

+    private String validateBaseUrl(String url) {
+        if (!url.matches("^https?://[^\\s/$.?#].[^\\s]*$")) {
+            throw new IllegalArgumentException("Invalid base URL format");
+        }
+        return url;
+    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 056e466 and 1846fbb.

📒 Files selected for processing (3)
  • src/main/java/com/buape/kiaimc/KiaiMC.java (1 hunks)
  • src/main/java/com/buape/kiaimc/api/Kiai.java (3 hunks)
  • src/main/java/com/buape/kiaimc/api/User.java (1 hunks)
🔇 Additional comments (1)
src/main/java/com/buape/kiaimc/api/User.java (1)

16-58: LGTM!

The getter methods are well-implemented, following Java naming conventions and providing clean access to the private fields.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants