diff --git a/src/cmd/root.go b/src/cmd/root.go index 200e378..8f12a56 100644 --- a/src/cmd/root.go +++ b/src/cmd/root.go @@ -113,7 +113,7 @@ func runRest(_ *cobra.Command, _ []string) { }) }) - websocket.RegisterRoutes(app) + websocket.RegisterRoutes(app, appService) go websocket.RunHub() // Set auto reconnect to whatsapp server after booting diff --git a/src/domains/app/devices.go b/src/domains/app/devices.go index cfe9fc2..34c6406 100644 --- a/src/domains/app/devices.go +++ b/src/domains/app/devices.go @@ -1,6 +1,6 @@ package app type FetchDevicesResponse struct { - Name string - Device string + Name string `json:"name"` + Device string `json:"device"` } diff --git a/src/internal/websocket/websocket.go b/src/internal/websocket/websocket.go index bf5098f..15f337c 100644 --- a/src/internal/websocket/websocket.go +++ b/src/internal/websocket/websocket.go @@ -1,7 +1,9 @@ package websocket import ( + "context" "encoding/json" + domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app" "github.com/gofiber/fiber/v2" "github.com/gofiber/websocket/v2" "log" @@ -11,6 +13,7 @@ type client struct{} // Add more data to this type if needed type BroadcastMessage struct { Code string `json:"code"` Message string `json:"message"` + Result any `json:"result"` } var Clients = make(map[*websocket.Conn]client) // Note: although large maps with pointer-like types (e.g. strings) as keys are slow, using pointers themselves as keys is acceptable and fast @@ -61,7 +64,7 @@ func RunHub() { } } -func RegisterRoutes(app *fiber.App) { +func RegisterRoutes(app *fiber.App, service domainApp.IAppService) { app.Use("/ws", func(c *fiber.Ctx) error { if websocket.IsWebSocketUpgrade(c) { // Returns true if the client requested upgrade to the WebSocket protocol return c.Next() @@ -96,7 +99,15 @@ func RegisterRoutes(app *fiber.App) { log.Println("error unmarshal message:", err) return } - Broadcast <- messageData + if messageData.Code == "FETCH_DEVICES" { + devices, _ := service.FetchDevices(context.Background()) + Broadcast <- BroadcastMessage{ + Code: "LIST_DEVICES", + Message: "Device found", + Result: devices, + } + } + } else { log.Println("websocket message received of type", messageType) } diff --git a/src/services/app_service.go b/src/services/app_service.go index 4f8f09a..04fed66 100644 --- a/src/services/app_service.go +++ b/src/services/app_service.go @@ -119,7 +119,7 @@ func (service serviceApp) Reconnect(_ context.Context) (err error) { return service.WaCli.Connect() } -func (service serviceApp) FetchDevices(ctx context.Context) (response []domainApp.FetchDevicesResponse, err error) { +func (service serviceApp) FetchDevices(_ context.Context) (response []domainApp.FetchDevicesResponse, err error) { if service.WaCli == nil { return response, errors.New("wa cli nil cok") } diff --git a/src/utils/whatsapp.go b/src/utils/whatsapp.go index 8bbeb04..5a19498 100644 --- a/src/utils/whatsapp.go +++ b/src/utils/whatsapp.go @@ -140,6 +140,11 @@ func handler(rawEvt interface{}) { Code: "LOGIN_SUCCESS", Message: fmt.Sprintf("Successfully pair with %s", evt.ID.String()), } + case *events.LoggedOut: + websocket.Broadcast <- websocket.BroadcastMessage{ + Code: "LIST_DEVICES", + Result: nil, + } case *events.Connected, *events.PushNameSetting: if len(cli.Store.PushName) == 0 { return diff --git a/src/views/index.html b/src/views/index.html index 00b5cc6..6689029 100644 --- a/src/views/index.html +++ b/src/views/index.html @@ -27,6 +27,15 @@

[[ app_name ]]

+
+
+ Device is connected +
+

+ Device ID: [[ connected_devices[0].device ]] +

+
+
App
@@ -668,6 +677,9 @@ try { await this.logoutApi() showSuccessInfo("Logout success") + + // fetch devices + this.app_ws.send(JSON.stringify({"code": "FETCH_DEVICES"})) } catch (err) { showErrorInfo(err) } @@ -696,6 +708,8 @@ try { await this.reconnectApi() showSuccessInfo("Reconnect success") + // fetch devices + this.app_ws.send(JSON.stringify({"code": "FETCH_DEVICES"})) } catch (err) { showErrorInfo(err) } @@ -1289,9 +1303,11 @@ delimiters: ['[[', ']]'], data() { return { + app_ws: null, app_host: {{ .AppHost }}, app_name: 'Whatsapp API Multi Device ({{ .AppVersion }})', is_logged_in: false, + connected_devices: null, type_group: "g.us", type_user: "s.whatsapp.net" } @@ -1299,19 +1315,27 @@ mounted() { if (window["WebSocket"]) { let wsType = location.protocol !== 'https:' ? 'ws://' : 'wss://'; - let conn = new WebSocket(wsType + document.location.host + "/ws"); + this.app_ws = new WebSocket(wsType + document.location.host + "/ws"); - conn.onclose = (evt) => { - console.log(evt) + this.app_ws.onopen = (evt) => { + this.app_ws.send(JSON.stringify({ + "code": "FETCH_DEVICES", + "message": "List device" + })) }; - conn.onmessage = (evt) => { - console.log(evt) + this.app_ws.onmessage = (evt) => { const message = JSON.parse(evt.data) switch (message.code) { case 'LOGIN_SUCCESS': showSuccessInfo(message.message) $('#modalLogin').modal('hide'); + + // fetch devices + this.app_ws.send(JSON.stringify({"code": "FETCH_DEVICES"})) + break; + case 'LIST_DEVICES': + this.connected_devices = message.result break; default: console.log(message)