Skip to content

Commit

Permalink
Merge pull request #14 from caiodearaujo/hotfix/unexpected-eof-on-get…
Browse files Browse the repository at this point in the history
…-device-by-id

Hotfix/unexpected eof on get device by
  • Loading branch information
caiodearaujo authored Oct 15, 2024
2 parents dcbe845 + 78230b9 commit 39e5b73
Show file tree
Hide file tree
Showing 9 changed files with 239 additions and 709 deletions.
16 changes: 9 additions & 7 deletions api/src/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ toolchain go1.23.1

require (
github.com/chai2010/webp v1.1.1
github.com/gin-contrib/cors v1.7.2
github.com/gin-gonic/gin v1.10.0
github.com/go-redis/redis/v8 v8.11.5
github.com/google/uuid v1.6.0
github.com/jackc/pgx/v4 v4.18.2
github.com/joho/godotenv v1.5.1
github.com/mattn/go-sqlite3 v1.14.23
Expand All @@ -18,15 +18,15 @@ require (
github.com/uptrace/bun/dialect/pgdialect v1.2.3
github.com/uptrace/bun/driver/pgdriver v1.2.3
github.com/ztrue/tracerr v0.4.0
go.mau.fi/whatsmeow v0.0.0-20240927134544-69ba055bef0f
google.golang.org/protobuf v1.34.2
go.mau.fi/whatsmeow v0.0.0-20241011190419-de8326a9d38d
google.golang.org/protobuf v1.35.1
)

require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/bytedance/sonic v1.11.9 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/bytedance/sonic v1.12.3 // indirect
github.com/bytedance/sonic/loader v0.2.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
Expand All @@ -37,7 +37,6 @@ require (
github.com/go-playground/validator/v10 v10.22.0 // indirect
github.com/goccy/go-json v0.10.3 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/websocket v1.5.3 // indirect
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
github.com/jackc/pgconn v1.14.3 // indirect
Expand All @@ -49,6 +48,7 @@ require (
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.8 // indirect
github.com/kr/pretty v0.3.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/lib/pq v1.10.9 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
Expand All @@ -57,6 +57,7 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/puzpuzpuz/xsync/v3 v3.4.0 // indirect
github.com/rogpeppe/go-internal v1.8.0 // indirect
github.com/tmthrgd/go-hex v0.0.0-20190904060850-447a3041c3bc // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
Expand All @@ -69,6 +70,7 @@ require (
golang.org/x/net v0.29.0 // indirect
golang.org/x/sys v0.25.0 // indirect
golang.org/x/text v0.18.0 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
mellium.im/sasl v0.3.1 // indirect
)
343 changes: 0 additions & 343 deletions api/src/go.sum

This file was deleted.

111 changes: 40 additions & 71 deletions api/src/helpers/whatsapp.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/skip2/go-qrcode"
"github.com/ztrue/tracerr"
"go.mau.fi/whatsmeow"
waStore "go.mau.fi/whatsmeow/store"
"go.mau.fi/whatsmeow/store/sqlstore"
"go.mau.fi/whatsmeow/types"
waLog "go.mau.fi/whatsmeow/util/log"
Expand All @@ -41,22 +42,13 @@ type DeviceResponse struct {
Timestamp time.Time `json:"timestamp"`
}

// ContactsResponse represents the contact information associated with a device.
type ContactsResponse struct {
Name string `json:"name"`
Number string `json:"number"`
ProfilePicture string `json:"profile_picture"`
}

// DeviceInfoResponse is the detailed response structure for device information.
type DeviceInfoResponse struct {
DeviceID int `json:"device_id"`
ProfilePicture string `json:"profile_picture"`
Webhook string `json:"webhook"`
PhoneNumber string `json:"phone_number"`
PushName string `json:"push_name"`
BusinessName string `json:"business_name"`
ContactsResponse []ContactsResponse `json:"contacts"`
DeviceID int `json:"device_id"`
Webhook string `json:"webhook"`
PhoneNumber string `json:"phone_number"`
PushName string `json:"push_name"`
BusinessName string `json:"business_name"`
}

// connectToDatabase establishes a connection to the PostgreSQL database and returns a WhatsMeow container.
Expand All @@ -78,24 +70,30 @@ func connectToDatabase() (*sqlstore.Container, error) {
return container, nil
}

// GetWhatsAppClientByJID retrieves a WhatsApp client by its JID (WhatsApp ID).
func GetWhatsAppClientByJID(whatsappID string) (*whatsmeow.Client, error) {
// GetDeviceStoreByJID retrieves the device store (store.Device) by its JID (WhatsApp ID).
func GetDeviceStoreByJID(whatsappID string) (*waStore.Device, error) {
dbMutex.Lock()
defer dbMutex.Unlock()

container, err := connectToDatabase()
container, err := connectToDatabase() // Conexão com o banco de dados
if err != nil {
return nil, err
}

jid, _ := types.ParseJID(whatsappID)

deviceStore, err := container.GetDevice(jid)
deviceStore, err := container.GetDevice(jid) // Supondo que retorna *store.Device
if err != nil {
return nil, tracerr.Wrap(fmt.Errorf("%w: %v", ErrDeviceNotFound, err))
}

client := whatsmeow.NewClient(deviceStore, wmLog)
return deviceStore, nil
}

// GetWhatsAppClientByDeviceStore retrieves a WhatsApp client using the store.Device.
func GetWhatsAppClientByDeviceStore(deviceStore *waStore.Device) (*whatsmeow.Client, error) {
client := whatsmeow.NewClient(deviceStore, wmLog) // Passa o store.Device

if client.Store.ID == nil {
return nil, tracerr.Wrap(fmt.Errorf("%w: %v", ErrClientConnection, client.Store.ID))
}
Expand All @@ -106,6 +104,24 @@ func GetWhatsAppClientByJID(whatsappID string) (*whatsmeow.Client, error) {
return nil, tracerr.Wrap(fmt.Errorf("%w: %v", ErrClientConnection, err))
}
}

return client, nil
}

// GetWhatsAppClientByJID retrieves a WhatsApp client by its JID (WhatsApp ID).
func GetWhatsAppClientByJID(whatsappID string) (*whatsmeow.Client, error) {
// Obter o device store
deviceStore, err := GetDeviceStoreByJID(whatsappID)
if err != nil {
return nil, err
}

// Obter o client usando o device store
client, err := GetWhatsAppClientByDeviceStore(deviceStore)
if err != nil {
return nil, err
}

return client, nil
}

Expand Down Expand Up @@ -230,51 +246,6 @@ func GenerateQRCode(qrCode string) (string, error) {
func GetClientInfo(deviceID int, client *whatsmeow.Client) DeviceInfoResponse {
clientJID := types.NewJID(client.Store.ID.User, types.DefaultUserServer)

// Get the profile picture of the client.
picInfo, _ := client.GetProfilePictureInfo(clientJID, nil)
var picURL string
if picInfo != nil {
picURL = picInfo.URL
}

// Get all contacts of the client.
contacts, _ := client.Store.Contacts.GetAllContacts()
var contactsResponse []ContactsResponse

var wg sync.WaitGroup
var mu sync.Mutex // Protects concurrent access to contactsResponse

// Function to process each contact and add it to the response.
processContact := func(key types.JID, contact types.ContactInfo) {
defer wg.Done()

contactName := contact.PushName
if contactName == "" {
contactName = contact.BusinessName
}

picContact, _ := client.GetProfilePictureInfo(key, nil)
var contactProfileURL string
if picContact != nil {
contactProfileURL = picContact.URL
}

mu.Lock()
contactsResponse = append(contactsResponse, ContactsResponse{
Name: contactName,
Number: key.User,
ProfilePicture: contactProfileURL,
})
mu.Unlock()
}

for key, contact := range contacts {
wg.Add(1)
go processContact(key, contact)
}

wg.Wait()

// Retrieve the active webhook URL for the device.
var webhookURL string
if webhook, err := GetWebhookActiveByDeviceID(deviceID); err == nil {
Expand All @@ -283,12 +254,10 @@ func GetClientInfo(deviceID int, client *whatsmeow.Client) DeviceInfoResponse {

// Return device information response.
return DeviceInfoResponse{
DeviceID: deviceID,
ProfilePicture: picURL,
Webhook: webhookURL,
PhoneNumber: clientJID.User,
PushName: client.Store.PushName,
BusinessName: client.Store.BusinessName,
ContactsResponse: contactsResponse,
DeviceID: deviceID,
Webhook: webhookURL,
PhoneNumber: clientJID.User,
PushName: client.Store.PushName,
BusinessName: client.Store.BusinessName,
}
}
7 changes: 7 additions & 0 deletions web/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"@mdi/font": "7.4.47",
"axios": "^1.7.7",
"core-js": "^3.37.1",
"intl-tel-input": "^24.6.0",
"roboto-fontface": "*",
"vue": "^3.4.31",
"vuetify": "^3.6.11"
Expand Down
12 changes: 1 addition & 11 deletions web/src/router/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,12 @@
import Connect from '@/views/Connect.vue'
import Dashboard from '@/views/Dashboard.vue'
import Device from '@/views/Device.vue'
import DeviceWebhook from '@/views/DeviceWebhook.vue'
import Login from '@/views/Login.vue'
import { createRouter, createWebHistory } from 'vue-router/auto'

const extraMenuItems = [
{ title: 'Device', icon: 'mdi-cellphone', to: { name: 'Device' } },
{ title: 'Webhook', icon: 'mdi-webhook', to: { name: 'DeviceWebhook' } },
// { title: 'Webhook', icon: 'mdi-webhook', to: { name: 'DeviceWebhook' } },
// { title: 'A.I.', icon: 'mdi-robot-happy', to: { name: 'DeviceAI' } },
// { title: 'Histórico', icon: 'mdi-history', to: { name: 'DeviceHistoric' } },
// { title: 'Estatística', icon: 'mdi-chart-box-outline', to: { name: 'DeviceNerd' } }, // Corrected name
Expand Down Expand Up @@ -58,15 +57,6 @@ const routes = [
extraMenuItems: extraMenuItems,
},
},
{
path: "/device/:id/webhook",
name: "DeviceWebhook",
component: DeviceWebhook,
meta: {
requiresAuth: true,
extraMenuItems: extraMenuItems,
},
},
];

const router = createRouter({
Expand Down
5 changes: 4 additions & 1 deletion web/src/views/Dashboard.vue
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ onMounted(async () => {
},
});
if (response.data === null) {
response.data = [];
}
devices.value = Array.isArray(response.data)
? response.data.map((deviceData: any) => new Device(deviceData))
: [];
Expand Down Expand Up @@ -56,7 +59,7 @@ onMounted(async () => {
<v-container v-else-if="noDevices">
<v-banner color="warning" icon="mdi-alert">
<template v-slot:actions>
<v-btn text @click="() => $router.push({ name: 'Connect' })">
<v-btn @click="() => $router.push({ name: 'Connect' })">
Conectar novo dispositivo
</v-btn>
</template>
Expand Down
Loading

0 comments on commit 39e5b73

Please sign in to comment.