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

feat: Adding new route for check if user is in whatsapp #231

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

Conversation

RuanAyram
Copy link

Context

  • This PR introduce a new route to check if user is in whatsapp

Changes

  • readme.md
  • src/domains/user/account.go
  • src/views/index.html
    and others files.

Copy link
Contributor

coderabbitai bot commented Jan 23, 2025

Warning

Rate limit exceeded

@RuanAyram has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 27 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between a1460c4 and bf49317.

📒 Files selected for processing (1)
  • src/services/user.go (1 hunks)

Walkthrough

This pull request introduces a new feature for checking a user's WhatsApp status. The changes span multiple files across the application, adding a new endpoint for user verification, updating the backend service, creating new data structures, and implementing frontend components for user checks. The implementation allows users to verify if a specific phone number is registered on WhatsApp, with support for API calls, validation, and a user-friendly interface.

Changes

File Change Summary
.gitignore Added storages and .tool-versions entries, removed previous storages entry
readme.md Added CURL API examples, new feature table entry for checking WhatsApp status, and user interface image for "Check User"
src/domains/user/account.go Introduced new types: CheckRequest, CheckResponseData, CheckResponse, UserCollection
src/domains/user/user.go Added Check method to IUserService interface
src/internal/rest/user.go Added UserCheck method and /user/check route
src/services/user.go Implemented Check method in userService for WhatsApp status verification
src/validations/user_validation.go Added ValidateUserCheck function for request validation
src/views/components/AccountUserCheck.js Created new Vue component for user check functionality
src/views/components/generic/FormCheckUserRecipient.js Created supporting form component for user checks
src/views/index.html Added <account-user-check> component to the UI and imported it

Sequence Diagram

sequenceDiagram
    participant User
    participant Frontend
    participant API
    participant UserService
    participant WhatsApp

    User->>Frontend: Initiate User Check
    Frontend->>API: Send Check Request
    API->>UserService: Validate Request
    UserService->>WhatsApp: Check User Status
    WhatsApp-->>UserService: Return User Status
    UserService-->>API: Prepare Response
    API-->>Frontend: Return User Details
    Frontend->>User: Display User Status
Loading

Possibly related PRs

  • feat: login with pair code #171: The changes in the .gitignore file do not relate to the login functionality introduced in this PR, but the modifications in the readme.md file regarding user interface updates may indirectly connect to the overall user experience improvements discussed in the main PR.
  • Refactored WebSocket URL construction into a separate constructWebSoc… #225: The changes in the src/views/index.html file, which include the addition of a new component for user authentication, are directly related to the enhancements in the login process described in the main PR.

Poem

🐰 A rabbit's tale of WhatsApp might,
Checking users with digital delight!
Phone numbers dance, status revealed,
A magical check, no secrets concealed.
Tech magic springs from code so bright! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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
Contributor

@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: 8

🧹 Nitpick comments (6)
src/validations/user_validation.go (1)

21-31: Consider enhancing phone number validation.

While the basic required field validation is implemented, consider adding more robust phone number validation:

  • Format validation (E.164 format)
  • Length checks
  • Country code validation

Example enhancement:

 func ValidateUserCheck(ctx context.Context, request domainUser.CheckRequest) error {
 	err := validation.ValidateStructWithContext(ctx, &request,
-		validation.Field(&request.Phone, validation.Required),
+		validation.Field(&request.Phone,
+			validation.Required,
+			validation.Match(regexp.MustCompile(`^\+[1-9]\d{1,14}$`)).
+				Error("phone number must be in E.164 format"),
+			validation.Length(8, 15).
+				Error("phone number length must be between 8 and 15 digits"),
+		),
 	)

 	if err != nil {
 		return pkgError.ValidationError(err.Error())
 	}

 	return nil
 }
src/internal/rest/user.go (1)

44-60: Update success message to reflect the actual operation.

The success message should be "Success check user" instead of "Success get user info" to accurately reflect the operation being performed.

-		Message: "Success get user info",
+		Message: "Success check user",
src/services/user.go (2)

89-95: Use String() method instead of fmt.Sprintf.

Replace fmt.Sprintf("%s", item.JID) with item.JID.String() for more idiomatic Go code.

 		if item.VerifiedName != nil {
-			var msg = domainUser.CheckResponseData{Query: item.Query, IsInWhatsapp: item.IsIn, JID: fmt.Sprintf("%s", item.JID), VerifiedName: item.VerifiedName.Details.GetVerifiedName()}
+			var msg = domainUser.CheckResponseData{Query: item.Query, IsInWhatsapp: item.IsIn, JID: item.JID.String(), VerifiedName: item.VerifiedName.Details.GetVerifiedName()}
 			uc.Users = append(uc.Users, msg)
 		} else {
-			var msg = domainUser.CheckResponseData{Query: item.Query, IsInWhatsapp: item.IsIn, JID: fmt.Sprintf("%s", item.JID), VerifiedName: ""}
+			var msg = domainUser.CheckResponseData{Query: item.Query, IsInWhatsapp: item.IsIn, JID: item.JID.String(), VerifiedName: ""}
 			uc.Users = append(uc.Users, msg)
 		}
🧰 Tools
🪛 golangci-lint (1.62.2)

90-90: S1025: should use String() instead of fmt.Sprintf

(gosimple)


93-93: S1025: should use String() instead of fmt.Sprintf

(gosimple)


98-101: Remove commented-out code.

Remove the commented line // response := string(responseJson) as it's not being used.

 	response.Data = append(response.Data, uc.Users[0])
-	// response := string(responseJson)
src/views/components/AccountUserCheck.js (2)

50-59: Refactor error handling to avoid code duplication.

The error handling code duplicates the null assignment of verified_name and jid. Consider moving these assignments to a single location.

             } catch (error) {
+                this.resetUserInfo();
                 if (error.response) {
-                    this.verified_name = null;
-                    this.jid = null;
                     throw new Error(error.response.data.message);
                 }
-                this.verified_name = null;
-                this.jid = null;
                 throw new Error(error.message);
             } finally {
                 this.loading = false;
             }
         },
+        resetUserInfo() {
+            this.verified_name = null;
+            this.jid = null;
+        },

100-113: Refactor template to avoid code duplication.

The template duplicates the user information display logic. Consider extracting it into a reusable template section.

-            <div v-if="is_in_whatsapp != null" class="center">
-                <ol>
-                    <li>Name: {{ verified_name }}</li>
-                    <li>JID: {{ jid }}</li>
-                </ol>
-            </div>
-            <div v-else class="center">
-                <div v-if="code == 'INVALID_JID'" class="center">
-                    <ol>
-                        <li>Name: {{ verified_name }}</li>
-                        <li>JID: {{ jid }}</li>
-                    </ol>
-                </div>
-            </div>
+            <div v-if="is_in_whatsapp != null || code == 'INVALID_JID'" class="center">
+                <ol>
+                    <li>Name: {{ verified_name }}</li>
+                    <li>JID: {{ jid }}</li>
+                </ol>
+            </div>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 93f42ec and 001236e.

📒 Files selected for processing (10)
  • .gitignore (1 hunks)
  • readme.md (3 hunks)
  • src/domains/user/account.go (2 hunks)
  • src/domains/user/user.go (1 hunks)
  • src/internal/rest/user.go (2 hunks)
  • src/services/user.go (1 hunks)
  • src/validations/user_validation.go (1 hunks)
  • src/views/components/AccountUserCheck.js (1 hunks)
  • src/views/components/generic/FormCheckUserRecipient.js (1 hunks)
  • src/views/index.html (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .gitignore
🧰 Additional context used
🪛 Markdownlint (0.37.0)
readme.md

108-108: Expected: h3; Actual: h4
Heading levels should only increment by one level at a time

(MD001, heading-increment)


110-110: null
Bare URL used

(MD034, no-bare-urls)


112-112: null
Bare URL used

(MD034, no-bare-urls)

🪛 Gitleaks (8.21.2)
readme.md

110-111:

(curl-auth-header)

🪛 golangci-lint (1.62.2)
src/services/user.go

90-90: S1025: should use String() instead of fmt.Sprintf

(gosimple)


93-93: S1025: should use String() instead of fmt.Sprintf

(gosimple)


81-81: ineffectual assignment to jids

(ineffassign)

🔇 Additional comments (5)
src/domains/user/user.go (1)

9-9: LGTM! Interface method signature is well-defined.

The new Check method follows the established pattern of the interface, with appropriate request/response types and error handling.

src/internal/rest/user.go (1)

17-17: LGTM!

The new route "/user/check" is properly registered in the InitRestUser function.

src/views/index.html (1)

104-104: LGTM!

The AccountUserCheck component is properly integrated into the application:

  1. Component is imported correctly
  2. Added to the Account section in the template
  3. Registered in the Vue app's components list

Also applies to: 162-162, 203-203

readme.md (2)

122-122: LGTM!

The feature table entry is well-formatted and consistent with the existing documentation.


176-176: LGTM!

The screenshot addition follows the established pattern and provides good visual documentation of the new feature.

src/domains/user/account.go Show resolved Hide resolved
src/domains/user/account.go Show resolved Hide resolved
src/domains/user/account.go Show resolved Hide resolved
src/services/user.go Outdated Show resolved Hide resolved
readme.md Show resolved Hide resolved
remove unused lines

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

@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: 2

🧹 Nitpick comments (1)
src/services/user.go (1)

75-78: Consider adding timeout handling and response validation.

The implementation could benefit from:

  1. Timeout handling similar to the Avatar method to prevent indefinite waits
  2. Response validation before processing to ensure resp is not nil or empty

Consider applying this pattern:

+	ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
+	defer cancel()
+
+	respChan := make(chan []whatsmeow.IsOnWhatsAppResponse)
+	errChan := make(chan error)
+
+	go func() {
 		resp, err := service.WaCli.IsOnWhatsApp([]string{request.Phone})
-		if err != nil {
-			return response, err
+		if err != nil {
+			errChan <- err
+			return
 		}
+		if len(resp) == 0 {
+			errChan <- errors.New("empty response from WhatsApp")
+			return
+		}
+		respChan <- resp
+	}()
+
+	select {
+	case <-ctx.Done():
+		return response, pkgError.ContextError("timeout checking WhatsApp status")
+	case err := <-errChan:
+		return response, err
+	case resp := <-respChan:
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 001236e and a1460c4.

📒 Files selected for processing (1)
  • src/services/user.go (1 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
src/services/user.go

83-83: S1025: should use String() instead of fmt.Sprintf

(gosimple)


86-86: S1025: should use String() instead of fmt.Sprintf

(gosimple)

🔇 Additional comments (1)
src/services/user.go (1)

69-73: LGTM! Good validation practices.

The implementation follows good practices with early validation return pattern and clear separation of concerns.

src/services/user.go Outdated Show resolved Hide resolved
src/services/user.go Outdated Show resolved Hide resolved
RuanAyram and others added 2 commits January 23, 2025 15:56
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@aldinokemal
Copy link
Owner

@RuanAyram Thanks for your effort, I will review this PR after new version (v5.0.0) has been released, to avoid conflict

@RuanAyram
Copy link
Author

RuanAyram commented Jan 24, 2025

Thanks for the answer @aldinokemal . So I'll wait for 5.0.0

Copy link
Owner

@aldinokemal aldinokemal left a comment

Choose a reason for hiding this comment

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

Currently IsOnWhatsapp function not working with 10 digit phone number

showErrorInfo(err)
}
},
async submitApi() {
Copy link
Owner

Choose a reason for hiding this comment

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

can you also add is validate method like existing else component?

@@ -0,0 +1,50 @@
export default {
Copy link
Owner

Choose a reason for hiding this comment

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

I don't think we need this generic

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