Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

feat!: standalone gowa-ui dashboard — pure API backend + runtime-downloaded UI (#766)

Aldino Kemal80f306176d47
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 15d0837f..07bf32cb 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -1,13 +1,21 @@
openapi: "3.0.0"
info:
title: WhatsApp API MultiDevice
- version: 8.9.0
+ version: 8.11.0
description: |
This API is used for sending whatsapp via API.
+ The web dashboard is a separate project (gowa-ui); the server downloads its
+ latest release asset and serves it at `/` (or returns a JSON banner when
+ APP_UI_ENABLED=false).
+
Device scoping:
- Send `X-Device-Id` on all device-scoped REST calls.
- WebSocket: connect to `/ws?device_id=<id>`.
+ - WebSocket auth (when basic auth is enabled): browsers cannot set an
+ Authorization header on WebSocket connections, so also pass
+ `&authorization=<base64(user:pass)>` in the query string. Use TLS in
+ production since the credential is visible in the URL.
servers:
- url: http://localhost:3000
tags:
@@ -319,6 +327,69 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/ErrorInternalServer'
+ /app/info:
+ get:
+ operationId: appInfo
+ tags:
+ - app
+ summary: Get server metadata
+ description: >
+ Returns server version, base path, media size limits, and enabled
+ features. Requires no device; intended for standalone UIs (gowa-ui)
+ that previously read these values from the embedded dashboard HTML.
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ status:
+ type: integer
+ example: 200
+ code:
+ type: string
+ example: SUCCESS
+ message:
+ type: string
+ example: Fetch app info success
+ results:
+ type: object
+ properties:
+ version:
+ type: string
+ example: 'v8.11.0'
+ os:
+ type: string
+ example: 'GOWA'
+ base_path:
+ type: string
+ example: ''
+ max_file_size:
+ type: integer
+ format: int64
+ description: Max document upload size in bytes
+ example: 50000000
+ max_video_size:
+ type: integer
+ format: int64
+ description: Max video upload size in bytes
+ example: 100000000
+ max_image_size:
+ type: integer
+ format: int64
+ description: Max image upload size in bytes
+ example: 20000000
+ chatwoot_enabled:
+ type: boolean
+ description: Whether Chatwoot integration routes are registered
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
# Device Management API (v8)
/devices:
@@ -2423,7 +2494,7 @@ paths:
schema:
type: string
required: true
- description: Chat JID (e.g., [email protected] for individual or [email protected] for group)
+ description: Chat JID (e.g., [email protected] for individual or [email protected] for group). Percent-encoded values (e.g., groupid%40g.us) are accepted.
example: '[email protected]'
- name: limit
in: query
@@ -2511,7 +2582,7 @@ paths:
schema:
type: string
required: true
- description: Chat JID (e.g., [email protected] for individual or [email protected] for group)
+ description: Chat JID (e.g., [email protected] for individual or [email protected] for group). Percent-encoded values (e.g., groupid%40g.us) are accepted.
example: '[email protected]'
requestBody:
content:
@@ -2571,7 +2642,7 @@ paths:
schema:
type: string
required: true
- description: Chat JID (e.g., [email protected] for individual or [email protected] for group)
+ description: Chat JID (e.g., [email protected] for individual or [email protected] for group). Percent-encoded values (e.g., groupid%40g.us) are accepted.
example: '[email protected]'
requestBody:
content:
@@ -2619,7 +2690,7 @@ paths:
schema:
type: string
required: true
- description: Chat JID (e.g., [email protected] for individual or [email protected] for group)
+ description: Chat JID (e.g., [email protected] for individual or [email protected] for group). Percent-encoded values (e.g., groupid%40g.us) are accepted.
example: '[email protected]'
requestBody:
content:
diff --git a/src/views/assets/gowa.svg b/gallery/gowa.svg
similarity index 100%
rename from src/views/assets/gowa.svg
rename to gallery/gowa.svg
diff --git a/readme.md b/readme.md
index a753eb9f..67a4ea3c 100644
--- a/readme.md
+++ b/readme.md
@@ -2,7 +2,7 @@
<!-- markdownlint-disable-next-line MD033 -->
<div align="center">
<!-- markdownlint-disable-next-line MD033 -->
- <img src="src/views/assets/gowa.svg" alt="GoWA Logo" width="200" height="200">
+ <img src="gallery/gowa.svg" alt="GoWA Logo" width="200" height="200">
## Golang WhatsApp - Built with Go for efficient memory use
@@ -49,6 +49,11 @@ Download:
- `device_id` query parameter
- If only one device is registered, it will be used as the default
- **WebSocket device scoping**: Connect to `/ws?device_id=<id>` to scope WebSocket to a specific device
+ - **Remote UI support**: CORS allows the `Authorization` and `X-Device-Id` headers, so a standalone web UI
+ (e.g. [gowa-ui](https://github.com/aldinokemal/gowa-ui)) hosted on another origin can call the API directly.
+ `GET /app/info` exposes version and media size limits. Since browsers cannot set headers on WebSocket
+ connections, pass `/ws?device_id=<id>&authorization=<base64(user:pass)>` when basic auth is enabled
+ (use TLS — the credential is visible in the URL)
- **Webhook payload changes**: All webhook payloads now include a top-level `device_id` field identifying which
device received the event:
@@ -218,6 +223,7 @@ To use environment variables:
| `APP_BASIC_AUTH` | Basic authentication credentials | - | `APP_BASIC_AUTH=user1:pass1,user2:pass2` |
| `APP_BASE_PATH` | Base path for subpath deployment | - | `APP_BASE_PATH=/gowa` |
| `APP_TRUSTED_PROXIES` | Trusted proxy IP ranges for reverse proxy | - | `APP_TRUSTED_PROXIES=0.0.0.0/0` |
+| `APP_CORS_ALLOWED_ORIGINS` | Allowed CORS origins (any origin when empty) | - | `APP_CORS_ALLOWED_ORIGINS=https://ui.example.com` |
| `DB_URI` | Database connection URI | `file:storages/whatsapp.db` | `DB_URI=postgres://user:pass@host/db` |
| `DB_KEYS_URI` | Optional database URI for encryption/session key cache. Leave blank to use `DB_URI`; avoid in-memory storage in production because restarts can lose WhatsApp session state. | - | `DB_KEYS_URI=file:storages/whatsapp-keys.db?_foreign_keys=on` |
| `CHAT_STORAGE_MAX_OPEN_CONNS` | Max concurrent SQLite connections for chat storage | `5` | `CHAT_STORAGE_MAX_OPEN_CONNS=10` |
@@ -600,6 +606,7 @@ You can fork or edit this source code !
| ✅ | Reconnect | GET | /app/reconnect |
| ✅ | Devices | GET | /app/devices |
| ✅ | Connection Status | GET | /app/status |
+| ✅ | App Info (version, limits) | GET | /app/info |
| ✅ | User Info | GET | /user/info |
| ✅ | User Avatar | GET | /user/avatar |
| ✅ | User Change Avatar | POST | /user/avatar |
@@ -685,32 +692,31 @@ You can fork or edit this source code !
- Successfully setup MCP
![Success MCP](https://i.ibb.co/1fCx0Myc/mcpsuccess.png)
-### HTTP REST API UI
-
-| Description | Image |
-|----------------------|---------------------------------------------------------------|
-| Homepage | ![Homepage](./gallery/homepage.png?v=1) |
-| Login | ![Login](./gallery/login.png) |
-| Login With Code | ![Login With Code](./gallery/login-with-code.png) |
-| Send Message | ![Send Message](./gallery/send-message.png) |
-| Send Image | ![Send Image](./gallery/send-image.png) |
-| Send File | ![Send File](./gallery/send-file.png) |
-| Send Video | ![Send Video](./gallery/send-video.png) |
-| Send Sticker | ![Send Sticker](./gallery/send-sticker.png) |
-| Send Contact | ![Send Contact](./gallery/send-contact.png) |
-| Send Location | ![Send Location](./gallery/send-location.png) |
-| Send Audio | ![Send Audio](./gallery/send-audio.png) |
-| Send Poll | ![Send Poll](./gallery/send-poll.png) |
-| Send Presence | ![Send Presence](./gallery/send-presence.png) |
-| Send Link | ![Send Link](./gallery/send-link.png) |
-| My Group | ![My Group](./gallery/group-list.png) |
-| Group Info From Link | ![Group Info From Link](./gallery/group-info-from-link.png) |
-| Create Group | ![Create Group](./gallery/group-create.png) |
-| Join Group with Link | ![Join Group with Link](./gallery/group-join-link.png) |
-| Manage Participant | ![Manage Participant](./gallery/group-manage-participant.png) |
-| My Newsletter | ![My Newsletter](./gallery/newsletter-list.png) |
-| My Contacts | ![My Contacts](./gallery/contact-list.png) |
-| Business Profile | ![Business Profile](./gallery/business-profile.png) |
+### Web dashboard (gowa-ui)
+
+The dashboard lives in its own repository: [aldinokemal/gowa-ui](https://github.com/aldinokemal/gowa-ui). Each
+gowa-ui release publishes a single self-contained `gowa-ui.html`; the server downloads the latest release at
+startup (and every `APP_UI_UPDATE_INTERVAL`, default 3h), verifies its sha256 digest, caches it under
+`storages/ui/`, and serves it at `/` behind basic auth.
+
+| Setting | Default | Purpose |
+|--------------------------|----------------------|---------------------------------------------------------------------|
+| `APP_UI_ENABLED` | `true` | Serve the dashboard at `/`; `false` returns a JSON banner (API-only) |
+| `APP_UI_AUTO_UPDATE` | `true` | Download/refresh from GitHub; disable for air-gapped deployments |
+| `APP_UI_REPO` | `aldinokemal/gowa-ui`| Repository the updater follows — always its latest release, not a version pin |
+| `APP_UI_ASSET_NAME` | `gowa-ui.html` | Release asset filename to download |
+| `APP_UI_UPDATE_INTERVAL` | `3h` | How often to check `releases/latest` |
+| `APP_UI_GITHUB_TOKEN` | (empty) | Optional token to raise the GitHub API rate limit |
+| `APP_UI_ASSET_SHA256` | (empty) | Supply-chain pin: refuse any dashboard whose sha256 differs |
+
+Trust model: the release digest proves the download matches what GitHub advertises, not who published it.
+Operators who audit a specific build can pin it with `APP_UI_ASSET_SHA256` (each release ships a `.sha256`
+asset — this is the only setting that pins an exact build), point `APP_UI_REPO` at a fork they control
+(the updater still tracks that repo's latest release), or pre-seed the cache and disable auto-update entirely.
+
+Air-gapped servers: place a downloaded `gowa-ui.html` at `storages/ui/index.html` and set
+`APP_UI_AUTO_UPDATE=false`. The dashboard can also be self-hosted anywhere static and pointed at this
+server's URL (see the gowa-ui readme).
### Mac OS NOTE
diff --git a/src/.env.example b/src/.env.example
index ffbb4930..98969284 100644
--- a/src/.env.example
+++ b/src/.env.example
@@ -6,6 +6,22 @@ APP_OS=Chrome
APP_BASIC_AUTH=user1:pass1,user2:pass2
APP_BASE_PATH=
APP_TRUSTED_PROXIES=0.0.0.0/0
+# Restrict cross-origin browser access to specific origins (comma-separated); empty allows any origin
+APP_CORS_ALLOWED_ORIGINS=
+
+# Web UI (gowa-ui) Settings
+# The dashboard is downloaded from the latest GitHub release of APP_UI_REPO
+# and served at "/". Air-gap: pre-seed storages/ui/index.html and set
+# APP_UI_AUTO_UPDATE=false, or turn the UI off entirely.
+APP_UI_ENABLED=true
+APP_UI_AUTO_UPDATE=true
+APP_UI_REPO=aldinokemal/gowa-ui
+APP_UI_ASSET_NAME=gowa-ui.html
+APP_UI_UPDATE_INTERVAL=3h
+APP_UI_GITHUB_TOKEN=
+# Optional supply-chain pin: refuse any dashboard whose sha256 differs
+# (hex digest; each release ships a gowa-ui.html.sha256 asset)
+APP_UI_ASSET_SHA256=
# Database Settings
DB_URI=file:storages/whatsapp.db?_foreign_keys=on
diff --git a/src/cmd/rest.go b/src/cmd/rest.go
index 7ec81e05..d6339dc2 100644
--- a/src/cmd/rest.go
+++ b/src/cmd/rest.go
@@ -13,18 +13,18 @@ import (
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/uiasset"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest"
"github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest/helpers"
"github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest/middleware"
"github.com/aldinokemal/go-whatsapp-web-multidevice/ui/websocket"
- "github.com/dustin/go-humanize"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/basicauth"
"github.com/gofiber/fiber/v3/middleware/cors"
"github.com/gofiber/fiber/v3/middleware/logger"
"github.com/gofiber/fiber/v3/middleware/static"
- "github.com/gofiber/template/html/v2"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
@@ -41,12 +41,7 @@ func init() {
rootCmd.AddCommand(restCmd)
}
func restServer(_ *cobra.Command, _ []string) {
- engine := html.NewFileSystem(http.FS(EmbedIndex), ".html")
- engine.AddFunc("isEnableBasicAuth", func(token any) bool {
- return token != nil
- })
fiberConfig := fiber.Config{
- Views: engine,
TrustProxy: true,
BodyLimit: int(config.WhatsappSettingMaxVideoSize),
}
@@ -59,26 +54,17 @@ func restServer(_ *cobra.Command, _ []string) {
app := fiber.New(fiberConfig)
+ // CORS must precede the static routes so cross-origin UIs (gowa-ui) can
+ // fetch media under /statics and authenticate with the headers below.
+ app.Use(newCORSMiddleware())
+
app.Use(config.AppBasePath+"/statics", static.New("./statics"))
- app.Use(config.AppBasePath+"/components", static.New("views/components", static.Config{
- FS: EmbedViews,
- Browse: true,
- }))
- app.Use(config.AppBasePath+"/assets", static.New("views/assets", static.Config{
- FS: EmbedViews,
- Browse: true,
- }))
app.Use(middleware.Recovery())
app.Use(middleware.RequestTimeout(middleware.DefaultRequestTimeout))
- app.Use(middleware.BasicAuth())
if config.AppDebug {
app.Use(logger.New())
}
- app.Use(cors.New(cors.Config{
- AllowOrigins: []string{"*"},
- AllowHeaders: []string{"Origin", "Content-Type", "Accept"},
- }))
// Device manager - needed for chatwoot webhook and health check
dm := whatsapp.GetDeviceManager()
@@ -123,6 +109,7 @@ func restServer(_ *cobra.Command, _ []string) {
account[ba[0]] = ba[1]
}
+ app.Use(middleware.WebsocketQueryAuth())
app.Use(newBasicAuthMiddleware(account))
}
@@ -147,6 +134,9 @@ func restServer(_ *cobra.Command, _ []string) {
// Device management routes (no device_id required)
rest.InitRestDevice(apiGroup, deviceUsecase)
+ // App info (version, limits) for standalone UIs; no device required
+ rest.InitRestAppInfo(apiGroup)
+
// Device-scoped operations (header-based)
headerDeviceGroup := apiGroup.Group("", middleware.DeviceMiddleware(dm))
registerDeviceScopedRoutes(headerDeviceGroup)
@@ -162,16 +152,12 @@ func restServer(_ *cobra.Command, _ []string) {
apiGroup.Delete("/devices/:device_id/chatwoot/config", chatwootHandler.DeleteChatwootConfig)
}
- apiGroup.Get("/", func(c fiber.Ctx) error {
- return c.Render("views/index", fiber.Map{
- "AppHost": fmt.Sprintf("%s://%s", c.Scheme(), c.Hostname()),
- "AppVersion": config.AppVersion,
- "AppBasePath": config.AppBasePath,
- "BasicAuthToken": c.Context().Value(middleware.AuthorizationValue("BASIC_AUTH")),
- "MaxFileSize": humanize.Bytes(uint64(config.WhatsappSettingMaxFileSize)),
- "MaxVideoSize": humanize.Bytes(uint64(config.WhatsappSettingMaxVideoSize)),
- })
- })
+ // Dashboard: gowa-ui is a separate project released as one HTML file;
+ // serve the runtime-downloaded copy at "/" (behind basic auth like the
+ // rest of the API surface).
+ uiCtx, uiCancel := context.WithCancel(context.Background())
+ defer uiCancel()
+ registerUIRoute(apiGroup, uiCtx)
go websocket.RunHub()
@@ -221,6 +207,67 @@ func restServer(_ *cobra.Command, _ []string) {
}
}
+func registerUIRoute(apiGroup fiber.Router, ctx context.Context) {
+ if !config.AppUIEnabled {
+ apiGroup.Get("/", func(c fiber.Ctx) error {
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: fmt.Sprintf("gowa %s — UI disabled", config.AppVersion),
+ })
+ })
+ return
+ }
+
+ uiManager := uiasset.New(uiasset.Config{
+ Repo: config.AppUIRepo,
+ AssetName: config.AppUIAssetName,
+ CacheDir: config.PathUICache,
+ GithubToken: config.AppUIGithubToken,
+ Interval: config.AppUIUpdateInterval,
+ PinnedSHA256: config.AppUIAssetSHA256,
+ })
+ if err := uiManager.LoadCache(); err != nil {
+ logrus.Infof("[UI_ASSET] no cached dashboard yet: %v", err)
+ }
+ if config.AppUIAutoUpdate {
+ go func() {
+ if err := uiManager.EnsureLatest(ctx); err != nil {
+ logrus.Warnf("[UI_ASSET] initial dashboard download failed: %v", err)
+ }
+ }()
+ go uiManager.StartAutoUpdate(ctx)
+ }
+
+ apiGroup.Get("/", func(c fiber.Ctx) error {
+ content, etag, ok := uiManager.Content()
+ if !ok {
+ c.Type("html")
+ return c.Send(uiasset.FallbackHTML(config.AppVersion, config.AppUIRepo))
+ }
+ quoted := `"` + etag + `"`
+ c.Set(fiber.HeaderCacheControl, "no-cache")
+ c.Set(fiber.HeaderETag, quoted)
+ if c.Get(fiber.HeaderIfNoneMatch) == quoted {
+ return c.SendStatus(fiber.StatusNotModified)
+ }
+ c.Type("html")
+ return c.Send(content)
+ })
+}
+
+func newCORSMiddleware() fiber.Handler {
+ origins := []string{"*"}
+ if len(config.AppCORSAllowedOrigins) > 0 {
+ origins = config.AppCORSAllowedOrigins
+ }
+ return cors.New(cors.Config{
+ AllowOrigins: origins,
+ AllowMethods: []string{"GET", "POST", "HEAD", "PUT", "PATCH", "DELETE"},
+ AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization", middleware.DeviceIDHeader},
+ })
+}
+
func newBasicAuthMiddleware(accounts map[string]string) fiber.Handler {
return basicauth.New(basicauth.Config{
Authorizer: func(username, password string, _ fiber.Ctx) bool {
diff --git a/src/cmd/rest_test.go b/src/cmd/rest_test.go
index 6b05ed09..aece45b5 100644
--- a/src/cmd/rest_test.go
+++ b/src/cmd/rest_test.go
@@ -1,9 +1,17 @@
package cmd
import (
+ "encoding/base64"
+ "encoding/json"
+ "io"
+ "net/http"
"net/http/httptest"
+ "strings"
"testing"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest/middleware"
"github.com/gofiber/fiber/v3"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -53,3 +61,144 @@ func TestBasicAuthMiddleware(t *testing.T) {
})
}
}
+
+func TestCORSPreflightAllowsUIHeaders(t *testing.T) {
+ app := fiber.New()
+ app.Use(newCORSMiddleware())
+ app.Get("/app/info", func(c fiber.Ctx) error {
+ return c.SendStatus(fiber.StatusOK)
+ })
+
+ req := httptest.NewRequest("OPTIONS", "/app/info", nil)
+ req.Header.Set("Origin", "https://ui.example.com")
+ req.Header.Set("Access-Control-Request-Method", "GET")
+ req.Header.Set("Access-Control-Request-Headers", "authorization,x-device-id")
+
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ assert.Equal(t, fiber.StatusNoContent, resp.StatusCode)
+ assert.Equal(t, "*", resp.Header.Get("Access-Control-Allow-Origin"))
+ allowedHeaders := strings.ToLower(resp.Header.Get("Access-Control-Allow-Headers"))
+ assert.Contains(t, allowedHeaders, "authorization")
+ assert.Contains(t, allowedHeaders, "x-device-id")
+}
+
+func TestWebsocketQueryAuth(t *testing.T) {
+ validQuery := base64.StdEncoding.EncodeToString([]byte("user:secret"))
+ wrongQuery := base64.StdEncoding.EncodeToString([]byte("user:wrong"))
+
+ newApp := func() *fiber.App {
+ app := fiber.New()
+ app.Use(middleware.WebsocketQueryAuth())
+ app.Use(newBasicAuthMiddleware(map[string]string{"user": "secret"}))
+ app.Get("/ws", func(c fiber.Ctx) error {
+ return c.SendStatus(fiber.StatusOK)
+ })
+ return app
+ }
+
+ setUpgradeHeaders := func(req *http.Request) {
+ req.Header.Set("Connection", "Upgrade")
+ req.Header.Set("Upgrade", "websocket")
+ }
+
+ tests := []struct {
+ name string
+ query string
+ upgrade bool
+ wantStatus int
+ }{
+ {
+ name: "upgrade with valid query credentials passes",
+ query: "?authorization=" + validQuery,
+ upgrade: true,
+ wantStatus: fiber.StatusOK,
+ },
+ {
+ name: "upgrade with wrong query credentials is rejected",
+ query: "?authorization=" + wrongQuery,
+ upgrade: true,
+ wantStatus: fiber.StatusUnauthorized,
+ },
+ {
+ name: "upgrade without credentials is rejected",
+ query: "",
+ upgrade: true,
+ wantStatus: fiber.StatusUnauthorized,
+ },
+ {
+ name: "non-upgrade request ignores query credentials",
+ query: "?authorization=" + validQuery,
+ upgrade: false,
+ wantStatus: fiber.StatusUnauthorized,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ req := httptest.NewRequest("GET", "/ws"+tt.query, nil)
+ if tt.upgrade {
+ setUpgradeHeaders(req)
+ }
+
+ resp, err := newApp().Test(req)
+ require.NoError(t, err)
+ assert.Equal(t, tt.wantStatus, resp.StatusCode)
+ })
+ }
+
+ t.Run("plus signs decoded as spaces are restored", func(t *testing.T) {
+ app := fiber.New()
+ app.Use(middleware.WebsocketQueryAuth())
+ app.Get("/ws", func(c fiber.Ctx) error {
+ return c.SendString(string(c.Request().Header.Peek(fiber.HeaderAuthorization)))
+ })
+
+ req := httptest.NewRequest("GET", "/ws?authorization=AB+CD", nil)
+ setUpgradeHeaders(req)
+
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ body, err := io.ReadAll(resp.Body)
+ require.NoError(t, err)
+ assert.Equal(t, "Basic AB+CD", string(body))
+ })
+}
+
+func TestAppInfo(t *testing.T) {
+ t.Run("returns server metadata", func(t *testing.T) {
+ app := fiber.New()
+ rest.InitRestAppInfo(app)
+
+ resp, err := app.Test(httptest.NewRequest("GET", "/app/info", nil))
+ require.NoError(t, err)
+ assert.Equal(t, fiber.StatusOK, resp.StatusCode)
+
+ var payload struct {
+ Code string `json:"code"`
+ Results map[string]any `json:"results"`
+ }
+ require.NoError(t, json.NewDecoder(resp.Body).Decode(&payload))
+ assert.Equal(t, "SUCCESS", payload.Code)
+ assert.Equal(t, config.AppVersion, payload.Results["version"])
+ assert.EqualValues(t, config.WhatsappSettingMaxFileSize, payload.Results["max_file_size"])
+ assert.EqualValues(t, config.WhatsappSettingMaxVideoSize, payload.Results["max_video_size"])
+ assert.EqualValues(t, config.WhatsappSettingMaxImageSize, payload.Results["max_image_size"])
+ })
+
+ t.Run("requires credentials when basic auth is enabled", func(t *testing.T) {
+ app := fiber.New()
+ app.Use(newBasicAuthMiddleware(map[string]string{"user": "secret"}))
+ rest.InitRestAppInfo(app)
+
+ resp, err := app.Test(httptest.NewRequest("GET", "/app/info", nil))
+ require.NoError(t, err)
+ assert.Equal(t, fiber.StatusUnauthorized, resp.StatusCode)
+
+ authed := httptest.NewRequest("GET", "/app/info", nil)
+ authed.SetBasicAuth("user", "secret")
+ resp, err = app.Test(authed)
+ require.NoError(t, err)
+ assert.Equal(t, fiber.StatusOK, resp.StatusCode)
+ })
+}
diff --git a/src/cmd/root.go b/src/cmd/root.go
index 7e14d55e..f0e58223 100644
--- a/src/cmd/root.go
+++ b/src/cmd/root.go
@@ -3,7 +3,6 @@ package cmd
import (
"context"
"database/sql"
- "embed"
"fmt"
"os"
"strings"
@@ -35,9 +34,6 @@ import (
)
var (
- EmbedIndex embed.FS
- EmbedViews embed.FS
-
// Whatsapp
whatsappCli *whatsmeow.Client
@@ -106,6 +102,36 @@ func initEnvConfig() {
proxies := strings.Split(envTrustedProxies, ",")
config.AppTrustedProxies = proxies
}
+ if envCORSOrigins := viper.GetString("app_cors_allowed_origins"); envCORSOrigins != "" {
+ config.AppCORSAllowedOrigins = strings.Split(envCORSOrigins, ",")
+ }
+
+ // Web UI settings. Guard on GetString != "" rather than viper.IsSet:
+ // IsSet does not consult AutomaticEnv, so plain environment variables
+ // (e.g. in Docker) would be ignored for bool/duration keys.
+ if viper.GetString("app_ui_enabled") != "" {
+ config.AppUIEnabled = viper.GetBool("app_ui_enabled")
+ }
+ if viper.GetString("app_ui_auto_update") != "" {
+ config.AppUIAutoUpdate = viper.GetBool("app_ui_auto_update")
+ }
+ if envUIRepo := viper.GetString("app_ui_repo"); envUIRepo != "" {
+ config.AppUIRepo = envUIRepo
+ }
+ if envUIAsset := viper.GetString("app_ui_asset_name"); envUIAsset != "" {
+ config.AppUIAssetName = envUIAsset
+ }
+ if viper.GetString("app_ui_update_interval") != "" {
+ if interval := viper.GetDuration("app_ui_update_interval"); interval > 0 {
+ config.AppUIUpdateInterval = interval
+ }
+ }
+ if envUIToken := viper.GetString("app_ui_github_token"); envUIToken != "" {
+ config.AppUIGithubToken = envUIToken
+ }
+ if envUIPin := viper.GetString("app_ui_asset_sha256"); envUIPin != "" {
+ config.AppUIAssetSHA256 = envUIPin
+ }
// Database settings
if envDBURI := viper.GetString("db_uri"); envDBURI != "" {
@@ -312,6 +338,50 @@ func initFlags() {
config.AppTrustedProxies,
`trusted proxy IP ranges for reverse proxy deployments --trusted-proxies <string> | example: --trusted-proxies="0.0.0.0/0" or --trusted-proxies="10.0.0.0/8,172.16.0.0/12"`,
)
+ rootCmd.PersistentFlags().StringSliceVarP(
+ &config.AppCORSAllowedOrigins,
+ "cors-allowed-origins", "",
+ config.AppCORSAllowedOrigins,
+ `allowed CORS origins, any origin when empty --cors-allowed-origins <string> | example: --cors-allowed-origins="https://ui.example.com,https://ops.example.com"`,
+ )
+
+ // Web UI flags
+ rootCmd.PersistentFlags().BoolVarP(
+ &config.AppUIEnabled,
+ "ui-enabled", "",
+ config.AppUIEnabled,
+ `serve the gowa-ui dashboard at "/" --ui-enabled <bool>`,
+ )
+ rootCmd.PersistentFlags().BoolVarP(
+ &config.AppUIAutoUpdate,
+ "ui-auto-update", "",
+ config.AppUIAutoUpdate,
+ `download the latest gowa-ui release at startup and periodically --ui-auto-update <bool> | disable for air-gapped deployments with a pre-seeded storages/ui cache`,
+ )
+ rootCmd.PersistentFlags().StringVarP(
+ &config.AppUIRepo,
+ "ui-repo", "",
+ config.AppUIRepo,
+ `GitHub repository the dashboard is downloaded from --ui-repo <string> | example: --ui-repo="aldinokemal/gowa-ui"`,
+ )
+ rootCmd.PersistentFlags().StringVarP(
+ &config.AppUIAssetName,
+ "ui-asset-name", "",
+ config.AppUIAssetName,
+ `release asset name to download --ui-asset-name <string>`,
+ )
+ rootCmd.PersistentFlags().DurationVarP(
+ &config.AppUIUpdateInterval,
+ "ui-update-interval", "",
+ config.AppUIUpdateInterval,
+ `how often to check for a newer dashboard release --ui-update-interval <duration> | example: --ui-update-interval=3h`,
+ )
+ rootCmd.PersistentFlags().StringVarP(
+ &config.AppUIAssetSHA256,
+ "ui-asset-sha256", "",
+ config.AppUIAssetSHA256,
+ `supply-chain pin: only serve the dashboard whose sha256 matches --ui-asset-sha256 <hex> (see the release's .sha256 asset)`,
+ )
// Database flags
rootCmd.PersistentFlags().StringVarP(
@@ -580,7 +650,7 @@ func initApp() {
}
//preparing folder if not exist
- err := utils.CreateFolder(config.PathQrCode, config.PathSendItems, config.PathStorages, config.PathMedia)
+ err := utils.CreateFolder(config.PathQrCode, config.PathSendItems, config.PathStorages, config.PathMedia, config.PathUICache)
if err != nil {
logrus.Errorln(err)
}
@@ -623,9 +693,7 @@ func initApp() {
}
// Execute adds all child commands to the root command and sets flags appropriately.
-func Execute(embedIndex embed.FS, embedViews embed.FS) {
- EmbedIndex = embedIndex
- EmbedViews = embedViews
+func Execute() {
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
diff --git a/src/config/settings.go b/src/config/settings.go
index fc9e24a1..3aee1594 100644
--- a/src/config/settings.go
+++ b/src/config/settings.go
@@ -16,6 +16,18 @@ var (
AppBasicAuthCredential []string
AppBasePath = ""
AppTrustedProxies []string // Trusted proxy IP ranges (e.g., "0.0.0.0/0" for all, or specific CIDRs)
+ AppCORSAllowedOrigins []string // CORS allowed origins; empty means "*" (any origin)
+
+ // Web UI (gowa-ui) runtime download settings. The dashboard is a separate
+ // project released as a single HTML file; gowa fetches the latest release
+ // asset and serves it at "/".
+ AppUIEnabled = true
+ AppUIAutoUpdate = true
+ AppUIRepo = "aldinokemal/gowa-ui"
+ AppUIAssetName = "gowa-ui.html"
+ AppUIUpdateInterval = 3 * time.Hour
+ AppUIGithubToken = "" // optional, raises the GitHub API rate limit
+ AppUIAssetSHA256 = "" // optional supply-chain pin: only serve the asset with this sha256
McpPort = "8080"
McpHost = "localhost"
@@ -24,6 +36,7 @@ var (
PathSendItems = "statics/senditems"
PathMedia = "statics/media"
PathStorages = "storages"
+ PathUICache = "storages/ui"
DBURI = "file:storages/whatsapp.db"
DBKeysURI = ""
diff --git a/src/go.mod b/src/go.mod
index f399b182..41780697 100644
--- a/src/go.mod
+++ b/src/go.mod
@@ -10,7 +10,6 @@ require (
github.com/go-ozzo/ozzo-validation/v4 v4.3.0
github.com/gofiber/contrib/v3/websocket v1.2.1
github.com/gofiber/fiber/v3 v3.4.0
- github.com/gofiber/template/html/v2 v2.1.3
github.com/gofiber/utils/v2 v2.1.2
github.com/google/uuid v1.6.0
github.com/lib/pq v1.12.3
@@ -42,8 +41,6 @@ require (
github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/gofiber/schema v1.8.0 // indirect
- github.com/gofiber/template v1.8.3 // indirect
- github.com/gofiber/utils v1.2.0 // indirect
github.com/google/jsonschema-go v0.4.3 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/klauspost/compress v1.19.0 // indirect
diff --git a/src/go.sum b/src/go.sum
index c4afbc5c..93b2f05e 100644
--- a/src/go.sum
+++ b/src/go.sum
@@ -47,12 +47,6 @@ github.com/gofiber/fiber/v3 v3.4.0 h1:F0aND4vwZF7dR7cbvSwFQQEpBU902XHKWxrLsFBkVq
github.com/gofiber/fiber/v3 v3.4.0/go.mod h1:nAhJfdxUIJJph2tPWPmqWf8QDIN2iiqQiQf3lENZpdk=
github.com/gofiber/schema v1.8.0 h1:NGsC9toPHmj8Xg4KpznuXBzNmHG6V5YV0tXKpKMcmis=
github.com/gofiber/schema v1.8.0/go.mod h1:lmbXPQ8hvzXSLkdS2DS7pb4kpunC2Roh7Sj3HMjGfzA=
-github.com/gofiber/template v1.8.3 h1:hzHdvMwMo/T2kouz2pPCA0zGiLCeMnoGsQZBTSYgZxc=
-github.com/gofiber/template v1.8.3/go.mod h1:bs/2n0pSNPOkRa5VJ8zTIvedcI/lEYxzV3+YPXdBvq8=
-github.com/gofiber/template/html/v2 v2.1.3 h1:n1LYBtmr9C0V/k/3qBblXyMxV5B0o/gpb6dFLp8ea+o=
-github.com/gofiber/template/html/v2 v2.1.3/go.mod h1:U5Fxgc5KpyujU9OqKzy6Kn6Qup6Tm7zdsISR+VpnHRE=
-github.com/gofiber/utils v1.2.0 h1:NCaqd+Efg3khhN++eeUUTyBz+byIxAsmIjpl8kKOMIc=
-github.com/gofiber/utils v1.2.0/go.mod h1:poZpsnhBykfnY1Mc0KeEa6mSHrS3dV0+oBWyeQmb2e0=
github.com/gofiber/utils/v2 v2.1.2 h1:/rfkCHvC3XWfOHR04c34KajAhbs5QxmF6cNeJKnkEBI=
github.com/gofiber/utils/v2 v2.1.2/go.mod h1:DdOgEVwQTi8cou/AKWPqhXOR4fHGRVhA/rEWL3IXG7Q=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
diff --git a/src/infrastructure/chatstorage/sqlite_repository.go b/src/infrastructure/chatstorage/sqlite_repository.go
index b75de305..a6006f3b 100644
--- a/src/infrastructure/chatstorage/sqlite_repository.go
+++ b/src/infrastructure/chatstorage/sqlite_repository.go
@@ -2203,16 +2203,53 @@ func (r *SQLiteRepository) StoreSentMessageWithContext(ctx context.Context, mess
normalizedJID := whatsapp.NormalizeJIDFromLID(ctx, jid, client)
chatJID := normalizedJID.String()
- // Get chat name (no pushname available for sent messages) - device scoped
- chatName := r.GetChatNameWithPushNameByDevice(deviceID, normalizedJID, chatJID, normalizedJID.User, "")
+ // Extract media info from the protobuf message if available
+ var mediaType, filename, mediaURL, directPath string
+ var mediaKey, fileSHA256, fileEncSHA256 []byte
+ var fileLength uint64
+ if msg != nil {
+ mediaType, filename, mediaURL, directPath, mediaKey, fileSHA256, fileEncSHA256, fileLength = utils.ExtractMediaInfo(msg)
+ }
- // Check context again before database operations
+ // Store the message BEFORE the chat row. The reverse order left a visible
+ // inconsistency when the context deadline expired between the two writes:
+ // the chat surfaced with a fresh last_message_time while the message
+ // itself was missing. Losing only the chat bump is invisible instead —
+ // the next stored message repairs it.
+ message := &domainChatStorage.Message{
+ ID: messageID,
+ ChatJID: chatJID,
+ DeviceID: deviceID,
+ Sender: senderJID,
+ Content: content,
+ Timestamp: timestamp,
+ IsFromMe: true,
+ MediaType: mediaType,
+ Filename: filename,
+ URL: mediaURL,
+ DirectPath: directPath,
+ MediaKey: mediaKey,
+ FileSHA256: fileSHA256,
+ FileEncSHA256: fileEncSHA256,
+ FileLength: fileLength,
+ }
+ if err := r.StoreMessage(message); err != nil {
+ return fmt.Errorf("failed to store message: %w", err)
+ }
+
+ // The individual writes cannot honor the context (database/sql Exec;
+ // busy_timeout bounds each statement), so enforce the deadline here: once
+ // it has passed, skip the chat bump. Losing it is invisible — the next
+ // stored message repairs it — while the message row above is already safe.
select {
case <-ctx.Done():
return ctx.Err()
default:
}
+ // Get chat name (no pushname available for sent messages) - device scoped
+ chatName := r.GetChatNameWithPushNameByDevice(deviceID, normalizedJID, chatJID, normalizedJID.User, "")
+
// Get existing chat to preserve ephemeral_expiration and archived status (device-scoped)
existingChat, err := r.GetChatByDevice(deviceID, chatJID)
if err != nil {
@@ -2236,41 +2273,7 @@ func (r *SQLiteRepository) StoreSentMessageWithContext(ctx context.Context, mess
return fmt.Errorf("failed to store chat: %w", err)
}
- // Check context one more time before storing message
- select {
- case <-ctx.Done():
- return ctx.Err()
- default:
- }
-
- // Extract media info from the protobuf message if available
- var mediaType, filename, mediaURL, directPath string
- var mediaKey, fileSHA256, fileEncSHA256 []byte
- var fileLength uint64
- if msg != nil {
- mediaType, filename, mediaURL, directPath, mediaKey, fileSHA256, fileEncSHA256, fileLength = utils.ExtractMediaInfo(msg)
- }
-
- // Store the sent message
- message := &domainChatStorage.Message{
- ID: messageID,
- ChatJID: chatJID,
- DeviceID: deviceID,
- Sender: senderJID,
- Content: content,
- Timestamp: timestamp,
- IsFromMe: true,
- MediaType: mediaType,
- Filename: filename,
- URL: mediaURL,
- DirectPath: directPath,
- MediaKey: mediaKey,
- FileSHA256: fileSHA256,
- FileEncSHA256: fileEncSHA256,
- FileLength: fileLength,
- }
-
- return r.StoreMessage(message)
+ return nil
}
// _____________________________________________________________________________________________________________________
diff --git a/src/infrastructure/uiasset/cache.go b/src/infrastructure/uiasset/cache.go
new file mode 100644
index 00000000..5edf2753
--- /dev/null
+++ b/src/infrastructure/uiasset/cache.go
@@ -0,0 +1,103 @@
+package uiasset
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/sirupsen/logrus"
+)
+
+func contentSHA(data []byte) string {
+ sum := sha256.Sum256(data)
+ return hex.EncodeToString(sum[:])
+}
+
+const (
+ cacheFileName = "index.html"
+ metaFileName = "meta.json"
+)
+
+type cacheMeta struct {
+ Tag string `json:"tag"`
+ AssetName string `json:"asset_name"`
+ SHA256 string `json:"sha256"`
+ ETag string `json:"etag"`
+ DownloadedAt time.Time `json:"downloaded_at"`
+}
+
+// LoadCache loads a previously downloaded dashboard from disk, if present.
+// Air-gapped deployments can pre-seed CacheDir with index.html (+ optional
+// meta.json) and disable auto-update.
+func (m *Manager) LoadCache() error {
+ html, err := os.ReadFile(filepath.Join(m.cfg.CacheDir, cacheFileName))
+ if err != nil {
+ return err
+ }
+
+ asset := cachedAsset{html: html, sha256: contentSHA(html)}
+ if metaRaw, metaErr := os.ReadFile(filepath.Join(m.cfg.CacheDir, metaFileName)); metaErr == nil {
+ var meta cacheMeta
+ if json.Unmarshal(metaRaw, &meta) == nil && meta.AssetName == m.cfg.AssetName {
+ asset.tag = meta.Tag
+ asset.etag = meta.ETag
+ }
+ }
+
+ if m.cfg.PinnedSHA256 != "" && !strings.EqualFold(asset.sha256, m.cfg.PinnedSHA256) {
+ return fmt.Errorf("cached dashboard sha256 %s does not match the pinned sha256 %s; refusing to serve",
+ asset.sha256, m.cfg.PinnedSHA256)
+ }
+
+ m.current.Store(&asset)
+ return nil
+}
+
+func (m *Manager) persist(html []byte, tag, sha, etag string) error {
+ if err := os.MkdirAll(m.cfg.CacheDir, 0o755); err != nil {
+ return err
+ }
+ if err := atomicWrite(filepath.Join(m.cfg.CacheDir, cacheFileName), html); err != nil {
+ return err
+ }
+ m.persistMeta(tag, sha, etag)
+ return nil
+}
+
+func (m *Manager) persistMeta(tag, sha, etag string) {
+ meta := cacheMeta{
+ Tag: tag,
+ AssetName: m.cfg.AssetName,
+ SHA256: sha,
+ ETag: etag,
+ DownloadedAt: time.Now().UTC(),
+ }
+ if raw, err := json.MarshalIndent(meta, "", " "); err == nil {
+ if writeErr := atomicWrite(filepath.Join(m.cfg.CacheDir, metaFileName), raw); writeErr != nil {
+ logrus.Warnf("[UI_ASSET] cache metadata write failed (ETag/tag lost on restart): %v", writeErr)
+ }
+ }
+}
+
+func atomicWrite(path string, data []byte) error {
+ tmp, err := os.CreateTemp(filepath.Dir(path), ".tmp-*")
+ if err != nil {
+ return err
+ }
+ tmpName := tmp.Name()
+ if _, err = tmp.Write(data); err != nil {
+ tmp.Close()
+ os.Remove(tmpName)
+ return err
+ }
+ if err = tmp.Close(); err != nil {
+ os.Remove(tmpName)
+ return err
+ }
+ return os.Rename(tmpName, path)
+}
diff --git a/src/infrastructure/uiasset/fallback.go b/src/infrastructure/uiasset/fallback.go
new file mode 100644
index 00000000..00c37681
--- /dev/null
+++ b/src/infrastructure/uiasset/fallback.go
@@ -0,0 +1,29 @@
+package uiasset
+
+import (
+ "fmt"
+)
+
+// FallbackHTML is served at "/" until a dashboard download succeeds.
+func FallbackHTML(version, repo string) []byte {
+ return fmt.Appendf(nil, `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta http-equiv="refresh" content="30">
+<title>gowa %s</title>
+<style>body{font-family:system-ui,sans-serif;display:flex;min-height:100vh;align-items:center;justify-content:center;background:#0a0a0a;color:#e5e5e5}main{max-width:34rem;padding:2rem;text-align:center}code{background:#262626;padding:.15rem .4rem;border-radius:.25rem}</style>
+</head>
+<body>
+<main>
+<h1>gowa %s</h1>
+<p>The API is running, but the dashboard has not been downloaded yet.</p>
+<p>gowa fetches the UI from the latest <code>%s</code> release. If this server
+has no internet access, pre-seed <code>storages/ui/index.html</code> and set
+<code>APP_UI_AUTO_UPDATE=false</code>, or disable the UI with
+<code>APP_UI_ENABLED=false</code>.</p>
+<p>This page refreshes automatically.</p>
+</main>
+</body>
+</html>`, version, version, repo)
+}
diff --git a/src/infrastructure/uiasset/github.go b/src/infrastructure/uiasset/github.go
new file mode 100644
index 00000000..8be1bacc
--- /dev/null
+++ b/src/infrastructure/uiasset/github.go
@@ -0,0 +1,149 @@
+package uiasset
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+
+ "github.com/sirupsen/logrus"
+)
+
+// githubAPIBase is a variable so tests can point it at a local server.
+var githubAPIBase = "https://api.github.com"
+
+// maxAssetBytes bounds the release download so a hostile or misconfigured
+// release cannot exhaust memory: the dashboard is a single HTML file (~1 MB),
+// so 64 MiB is generous headroom. A variable so tests can lower it.
+var maxAssetBytes int64 = 64 << 20
+
+type releaseAsset struct {
+ Name string `json:"name"`
+ Digest string `json:"digest"` // "sha256:<hex>", may be empty
+ BrowserDownloadURL string `json:"browser_download_url"`
+}
+
+type release struct {
+ TagName string `json:"tag_name"`
+ Assets []releaseAsset `json:"assets"`
+}
+
+// EnsureLatest checks the newest GitHub release and downloads the dashboard
+// asset when the cached copy is missing or outdated. It is safe to call
+// concurrently with Content and never leaves a partially written cache.
+func (m *Manager) EnsureLatest(ctx context.Context) error {
+ current := m.current.Load()
+
+ url := fmt.Sprintf("%s/repos/%s/releases/latest", githubAPIBase, m.cfg.Repo)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ if err != nil {
+ return err
+ }
+ req.Header.Set("Accept", "application/vnd.github+json")
+ req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
+ if m.cfg.GithubToken != "" {
+ req.Header.Set("Authorization", "Bearer "+m.cfg.GithubToken)
+ }
+ if current != nil && current.etag != "" {
+ req.Header.Set("If-None-Match", current.etag)
+ }
+
+ resp, err := m.client.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode == http.StatusNotModified {
+ return nil
+ }
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("release lookup returned %s", resp.Status)
+ }
+
+ var rel release
+ if err = json.NewDecoder(resp.Body).Decode(&rel); err != nil {
+ return fmt.Errorf("decode release: %w", err)
+ }
+
+ var asset *releaseAsset
+ for i := range rel.Assets {
+ if rel.Assets[i].Name == m.cfg.AssetName {
+ asset = &rel.Assets[i]
+ break
+ }
+ }
+ if asset == nil {
+ return fmt.Errorf("release %s has no asset named %s", rel.TagName, m.cfg.AssetName)
+ }
+
+ etag := resp.Header.Get("ETag")
+ remoteSHA := strings.TrimPrefix(asset.Digest, "sha256:")
+
+ if m.cfg.PinnedSHA256 != "" && remoteSHA != "" && !strings.EqualFold(remoteSHA, m.cfg.PinnedSHA256) {
+ return fmt.Errorf("release %s asset digest %s does not match the pinned sha256 %s; refusing to download",
+ rel.TagName, remoteSHA, m.cfg.PinnedSHA256)
+ }
+
+ if current != nil && remoteSHA != "" && remoteSHA == current.sha256 {
+ // Same content; just remember the fresher ETag/tag for future checks.
+ m.current.Store(&cachedAsset{html: current.html, sha256: current.sha256, tag: rel.TagName, etag: etag})
+ m.persistMeta(rel.TagName, current.sha256, etag)
+ return nil
+ }
+
+ html, downloadedSHA, err := m.download(ctx, asset.BrowserDownloadURL)
+ if err != nil {
+ return err
+ }
+ if remoteSHA != "" && downloadedSHA != remoteSHA {
+ return fmt.Errorf("digest mismatch: release says %s, downloaded %s", remoteSHA, downloadedSHA)
+ }
+ if m.cfg.PinnedSHA256 != "" && !strings.EqualFold(downloadedSHA, m.cfg.PinnedSHA256) {
+ return fmt.Errorf("downloaded asset sha256 %s does not match the pinned sha256 %s; refusing to serve",
+ downloadedSHA, m.cfg.PinnedSHA256)
+ }
+
+ if err = m.persist(html, rel.TagName, downloadedSHA, etag); err != nil {
+ logrus.Warnf("[UI_ASSET] cache write failed (serving from memory): %v", err)
+ }
+ m.current.Store(&cachedAsset{html: html, sha256: downloadedSHA, tag: rel.TagName, etag: etag})
+ logrus.Infof("[UI_ASSET] dashboard updated to %s (%d bytes)", rel.TagName, len(html))
+ return nil
+}
+
+func (m *Manager) download(ctx context.Context, url string) ([]byte, string, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ if err != nil {
+ return nil, "", err
+ }
+ req.Header.Set("Accept", "application/octet-stream")
+ if m.cfg.GithubToken != "" {
+ req.Header.Set("Authorization", "Bearer "+m.cfg.GithubToken)
+ }
+
+ resp, err := m.client.Do(req)
+ if err != nil {
+ return nil, "", err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return nil, "", fmt.Errorf("asset download returned %s", resp.Status)
+ }
+
+ hasher := sha256.New()
+ // Read one byte past the limit so truncation is detected as an explicit
+ // error instead of a silently short (and wrongly hashed) asset.
+ body, err := io.ReadAll(io.LimitReader(io.TeeReader(resp.Body, hasher), maxAssetBytes+1))
+ if err != nil {
+ return nil, "", err
+ }
+ if int64(len(body)) > maxAssetBytes {
+ return nil, "", fmt.Errorf("asset exceeds the %d MiB download limit; refusing", maxAssetBytes>>20)
+ }
+ return body, hex.EncodeToString(hasher.Sum(nil)), nil
+}
diff --git a/src/infrastructure/uiasset/manager.go b/src/infrastructure/uiasset/manager.go
new file mode 100644
index 00000000..82ff0b7d
--- /dev/null
+++ b/src/infrastructure/uiasset/manager.go
@@ -0,0 +1,83 @@
+// Package uiasset downloads the gowa-ui dashboard (a single self-contained
+// HTML file published as a GitHub release asset) and serves it from an
+// in-memory copy backed by a disk cache. Network failures are never fatal:
+// the manager keeps serving the cached copy, or callers fall back to
+// FallbackHTML until a download succeeds.
+package uiasset
+
+import (
+ "context"
+ "math/rand/v2"
+ "net/http"
+ "sync/atomic"
+ "time"
+
+ "github.com/sirupsen/logrus"
+)
+
+type Config struct {
+ // Repo is the "owner/name" GitHub repository to download from.
+ Repo string
+ // AssetName is the exact release asset filename to match.
+ AssetName string
+ // CacheDir is a writable directory holding index.html + meta.json.
+ CacheDir string
+ // GithubToken optionally authenticates GitHub API calls (rate limits).
+ GithubToken string
+ // Interval between update checks; jittered by ±10%.
+ Interval time.Duration
+ // PinnedSHA256 optionally pins the exact dashboard build (hex sha256).
+ // The release digest alone proves the download matches what GitHub
+ // advertises, not that the publisher is trustworthy; the pin is an
+ // operator-controlled trust anchor independent of the release metadata.
+ PinnedSHA256 string
+}
+
+type cachedAsset struct {
+ html []byte
+ sha256 string
+ tag string
+ etag string // GitHub API ETag for conditional release lookups
+}
+
+type Manager struct {
+ cfg Config
+ current atomic.Pointer[cachedAsset]
+ client *http.Client
+}
+
+func New(cfg Config) *Manager {
+ return &Manager{
+ cfg: cfg,
+ // Default transport honors HTTP(S)_PROXY from the environment.
+ client: &http.Client{Timeout: 5 * time.Minute},
+ }
+}
+
+// Content returns the dashboard HTML and its sha256 (usable as an ETag).
+func (m *Manager) Content() (html []byte, etag string, ok bool) {
+ asset := m.current.Load()
+ if asset == nil || len(asset.html) == 0 {
+ return nil, "", false
+ }
+ return asset.html, asset.sha256, true
+}
+
+// StartAutoUpdate periodically refreshes the dashboard until ctx is canceled.
+func (m *Manager) StartAutoUpdate(ctx context.Context) {
+ interval := m.cfg.Interval
+ if interval <= 0 {
+ interval = 3 * time.Hour
+ }
+ for {
+ jitter := time.Duration((rand.Float64()*0.2 - 0.1) * float64(interval))
+ select {
+ case <-ctx.Done():
+ return
+ case <-time.After(interval + jitter):
+ if err := m.EnsureLatest(ctx); err != nil {
+ logrus.Warnf("[UI_ASSET] update check failed: %v", err)
+ }
+ }
+ }
+}
diff --git a/src/infrastructure/uiasset/manager_test.go b/src/infrastructure/uiasset/manager_test.go
new file mode 100644
index 00000000..ef8cd224
--- /dev/null
+++ b/src/infrastructure/uiasset/manager_test.go
@@ -0,0 +1,251 @@
+package uiasset
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type fakeGithub struct {
+ tag string
+ asset []byte
+ digest bool // include the sha256 digest field
+ etag string
+ lookups int
+ notModked int
+ downloads int
+ badDigest bool
+ server *httptest.Server
+ assetRoute string
+}
+
+func newFakeGithub(t *testing.T, tag string, asset []byte) *fakeGithub {
+ t.Helper()
+ fake := &fakeGithub{tag: tag, asset: asset, digest: true, etag: `W/"rel-1"`, assetRoute: "/dl/gowa-ui.html"}
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/repos/aldinokemal/gowa-ui/releases/latest", func(w http.ResponseWriter, r *http.Request) {
+ fake.lookups++
+ if r.Header.Get("If-None-Match") == fake.etag {
+ fake.notModked++
+ w.WriteHeader(http.StatusNotModified)
+ return
+ }
+ digest := ""
+ if fake.digest {
+ sum := sha256.Sum256(fake.asset)
+ hexSum := hex.EncodeToString(sum[:])
+ if fake.badDigest {
+ hexSum = "deadbeef" + hexSum[8:]
+ }
+ digest = `"digest":"sha256:` + hexSum + `",`
+ }
+ w.Header().Set("ETag", fake.etag)
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprintf(w, `{"tag_name":%q,"assets":[
+ {"name":"other.txt","browser_download_url":"%s/dl/other.txt"},
+ {"name":"gowa-ui.html",%s"browser_download_url":"%s%s"}
+ ]}`, fake.tag, fake.server.URL, digest, fake.server.URL, fake.assetRoute)
+ })
+ mux.HandleFunc("/dl/", func(w http.ResponseWriter, _ *http.Request) {
+ fake.downloads++
+ _, _ = w.Write(fake.asset)
+ })
+
+ fake.server = httptest.NewServer(mux)
+ t.Cleanup(fake.server.Close)
+ return fake
+}
+
+func newTestManager(t *testing.T, fake *fakeGithub) *Manager {
+ t.Helper()
+ previous := githubAPIBase
+ githubAPIBase = fake.server.URL
+ t.Cleanup(func() { githubAPIBase = previous })
+
+ return New(Config{
+ Repo: "aldinokemal/gowa-ui",
+ AssetName: "gowa-ui.html",
+ CacheDir: filepath.Join(t.TempDir(), "ui"),
+ })
+}
+
+func TestEnsureLatestDownloadsAndCaches(t *testing.T) {
+ html := []byte("<html>v1</html>")
+ fake := newFakeGithub(t, "v1.0.0", html)
+ manager := newTestManager(t, fake)
+
+ _, _, ok := manager.Content()
+ assert.False(t, ok)
+
+ require.NoError(t, manager.EnsureLatest(context.Background()))
+
+ served, etag, ok := manager.Content()
+ require.True(t, ok)
+ assert.Equal(t, html, served)
+ assert.Equal(t, contentSHA(html), etag)
+ assert.Equal(t, 1, fake.downloads)
+
+ cached, err := os.ReadFile(filepath.Join(manager.cfg.CacheDir, "index.html"))
+ require.NoError(t, err)
+ assert.Equal(t, html, cached)
+}
+
+func TestEnsureLatestSkipsWhenNotModified(t *testing.T) {
+ fake := newFakeGithub(t, "v1.0.0", []byte("<html>v1</html>"))
+ manager := newTestManager(t, fake)
+
+ require.NoError(t, manager.EnsureLatest(context.Background()))
+ require.NoError(t, manager.EnsureLatest(context.Background()))
+
+ assert.Equal(t, 1, fake.downloads, "304 must not re-download")
+ assert.Equal(t, 1, fake.notModked)
+}
+
+func TestEnsureLatestSkipsWhenDigestMatches(t *testing.T) {
+ html := []byte("<html>v1</html>")
+ fake := newFakeGithub(t, "v1.0.0", html)
+ manager := newTestManager(t, fake)
+
+ require.NoError(t, manager.EnsureLatest(context.Background()))
+
+ // New release ETag but identical asset digest: lookup happens, no download.
+ fake.etag = `W/"rel-2"`
+ fake.tag = "v1.0.1"
+ require.NoError(t, manager.EnsureLatest(context.Background()))
+
+ assert.Equal(t, 1, fake.downloads)
+ served, _, ok := manager.Content()
+ require.True(t, ok)
+ assert.Equal(t, html, served)
+}
+
+func TestEnsureLatestRejectsDigestMismatch(t *testing.T) {
+ fake := newFakeGithub(t, "v1.0.0", []byte("<html>tampered</html>"))
+ fake.badDigest = true
+ manager := newTestManager(t, fake)
+
+ err := manager.EnsureLatest(context.Background())
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "digest mismatch")
+
+ _, _, ok := manager.Content()
+ assert.False(t, ok, "tampered asset must not be served")
+}
+
+func TestEnsureLatestUpgradesToNewRelease(t *testing.T) {
+ fake := newFakeGithub(t, "v1.0.0", []byte("<html>v1</html>"))
+ manager := newTestManager(t, fake)
+ require.NoError(t, manager.EnsureLatest(context.Background()))
+
+ next := []byte("<html>v2</html>")
+ fake.asset = next
+ fake.tag = "v2.0.0"
+ fake.etag = `W/"rel-2"`
+ require.NoError(t, manager.EnsureLatest(context.Background()))
+
+ served, _, ok := manager.Content()
+ require.True(t, ok)
+ assert.Equal(t, next, served)
+ assert.Equal(t, 2, fake.downloads)
+}
+
+func TestLoadCacheServesPreseededFile(t *testing.T) {
+ manager := New(Config{
+ Repo: "aldinokemal/gowa-ui",
+ AssetName: "gowa-ui.html",
+ CacheDir: t.TempDir(),
+ })
+ html := []byte("<html>air-gapped</html>")
+ require.NoError(t, os.WriteFile(filepath.Join(manager.cfg.CacheDir, "index.html"), html, 0o644))
+
+ require.NoError(t, manager.LoadCache())
+
+ served, etag, ok := manager.Content()
+ require.True(t, ok)
+ assert.Equal(t, html, served)
+ assert.Equal(t, contentSHA(html), etag)
+}
+
+func TestLoadCacheMissingIsAnError(t *testing.T) {
+ manager := New(Config{CacheDir: t.TempDir(), AssetName: "gowa-ui.html"})
+ assert.Error(t, manager.LoadCache())
+}
+
+func TestPinnedSHARejectsMismatchedRelease(t *testing.T) {
+ fake := newFakeGithub(t, "v1.0.0", []byte("<html>unaudited build</html>"))
+ manager := newTestManager(t, fake)
+ manager.cfg.PinnedSHA256 = contentSHA([]byte("the build the operator audited"))
+
+ err := manager.EnsureLatest(context.Background())
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "pinned sha256")
+ assert.Equal(t, 0, fake.downloads, "mismatched digest must be rejected before downloading")
+
+ _, _, ok := manager.Content()
+ assert.False(t, ok)
+}
+
+func TestPinnedSHAAcceptsMatchingRelease(t *testing.T) {
+ html := []byte("<html>audited build</html>")
+ fake := newFakeGithub(t, "v1.0.0", html)
+ manager := newTestManager(t, fake)
+ manager.cfg.PinnedSHA256 = contentSHA(html)
+
+ require.NoError(t, manager.EnsureLatest(context.Background()))
+
+ served, _, ok := manager.Content()
+ require.True(t, ok)
+ assert.Equal(t, html, served)
+}
+
+func TestPinnedSHARejectsTamperedCache(t *testing.T) {
+ manager := New(Config{
+ Repo: "aldinokemal/gowa-ui",
+ AssetName: "gowa-ui.html",
+ CacheDir: t.TempDir(),
+ PinnedSHA256: contentSHA([]byte("expected build")),
+ })
+ require.NoError(t, os.WriteFile(
+ filepath.Join(manager.cfg.CacheDir, "index.html"), []byte("<html>tampered</html>"), 0o644))
+
+ err := manager.LoadCache()
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "pinned sha256")
+
+ _, _, ok := manager.Content()
+ assert.False(t, ok)
+}
+
+func TestEnsureLatestRejectsOversizedAsset(t *testing.T) {
+ previous := maxAssetBytes
+ maxAssetBytes = 16
+ t.Cleanup(func() { maxAssetBytes = previous })
+
+ fake := newFakeGithub(t, "v1.0.0", []byte("<html>this asset is larger than the limit</html>"))
+ manager := newTestManager(t, fake)
+
+ err := manager.EnsureLatest(context.Background())
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "download limit")
+
+ _, _, ok := manager.Content()
+ assert.False(t, ok, "oversized asset must not be served")
+ _, statErr := os.Stat(filepath.Join(manager.cfg.CacheDir, "index.html"))
+ assert.True(t, os.IsNotExist(statErr), "oversized asset must not be cached")
+}
+
+func TestFallbackHTMLMentionsRepoAndVersion(t *testing.T) {
+ page := string(FallbackHTML("v9.0.0", "aldinokemal/gowa-ui"))
+ assert.Contains(t, page, "v9.0.0")
+ assert.Contains(t, page, "aldinokemal/gowa-ui")
+}
diff --git a/src/main.go b/src/main.go
index 2441d04a..bd1a2a37 100644
--- a/src/main.go
+++ b/src/main.go
@@ -1,16 +1,9 @@
package main
import (
- "embed"
"github.com/aldinokemal/go-whatsapp-web-multidevice/cmd"
)
-//go:embed views/index.html
-var embedIndex embed.FS
-
-//go:embed views
-var embedViews embed.FS
-
func main() {
- cmd.Execute(embedIndex, embedViews)
+ cmd.Execute()
}
diff --git a/src/ui/rest/app.go b/src/ui/rest/app.go
index 18c9347c..27aec67e 100644
--- a/src/ui/rest/app.go
+++ b/src/ui/rest/app.go
@@ -30,6 +30,29 @@ func InitRestApp(app fiber.Router, service domainApp.IAppUsecase) App {
return App{Service: service}
}
+// InitRestAppInfo registers /app/info outside the device-scoped group so
+// standalone UIs can read server metadata before any device exists.
+func InitRestAppInfo(app fiber.Router) {
+ app.Get("/app/info", AppInfo)
+}
+
+func AppInfo(c fiber.Ctx) error {
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "Fetch app info success",
+ Results: map[string]any{
+ "version": config.AppVersion,
+ "os": config.AppOs,
+ "base_path": config.AppBasePath,
+ "max_file_size": config.WhatsappSettingMaxFileSize,
+ "max_video_size": config.WhatsappSettingMaxVideoSize,
+ "max_image_size": config.WhatsappSettingMaxImageSize,
+ "chatwoot_enabled": config.ChatwootEnabled,
+ },
+ })
+}
+
func (handler *App) Login(c fiber.Ctx) error {
device, err := getDeviceInstance(c)
if err != nil {
diff --git a/src/ui/rest/chat.go b/src/ui/rest/chat.go
index 5a4dd669..5addb1d5 100644
--- a/src/ui/rest/chat.go
+++ b/src/ui/rest/chat.go
@@ -1,6 +1,9 @@
package rest
import (
+ "net/url"
+ "strings"
+
domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
@@ -52,7 +55,16 @@ func (controller *Chat) GetChatMessages(c fiber.Ctx) error {
var request domainChat.GetChatMessagesRequest
// Parse path parameter
- request.ChatJID = c.Params("chat_jid")
+ chatJID, err := chatJIDParam(c)
+ if err != nil {
+ return c.Status(400).JSON(utils.ResponseData{
+ Status: 400,
+ Code: "BAD_REQUEST",
+ Message: "invalid chat_jid path parameter: " + err.Error(),
+ Results: nil,
+ })
+ }
+ request.ChatJID = chatJID
// Parse query parameters
request.Limit = fiber.Query[int](c, "limit", 50)
@@ -89,7 +101,16 @@ func (controller *Chat) PinChat(c fiber.Ctx) error {
var request domainChat.PinChatRequest
// Parse path parameter
- request.ChatJID = c.Params("chat_jid")
+ chatJID, err := chatJIDParam(c)
+ if err != nil {
+ return c.Status(400).JSON(utils.ResponseData{
+ Status: 400,
+ Code: "BAD_REQUEST",
+ Message: "invalid chat_jid path parameter: " + err.Error(),
+ Results: nil,
+ })
+ }
+ request.ChatJID = chatJID
// Parse JSON body
if err := c.Bind().Body(&request); err != nil {
@@ -116,7 +137,16 @@ func (controller *Chat) SetDisappearingTimer(c fiber.Ctx) error {
var request domainChat.SetDisappearingTimerRequest
// Parse path parameter
- request.ChatJID = c.Params("chat_jid")
+ chatJID, err := chatJIDParam(c)
+ if err != nil {
+ return c.Status(400).JSON(utils.ResponseData{
+ Status: 400,
+ Code: "BAD_REQUEST",
+ Message: "invalid chat_jid path parameter: " + err.Error(),
+ Results: nil,
+ })
+ }
+ request.ChatJID = chatJID
// Parse JSON body
if err := c.Bind().Body(&request); err != nil {
@@ -143,7 +173,16 @@ func (controller *Chat) ArchiveChat(c fiber.Ctx) error {
var request domainChat.ArchiveChatRequest
// Parse path parameter
- request.ChatJID = c.Params("chat_jid")
+ chatJID, err := chatJIDParam(c)
+ if err != nil {
+ return c.Status(400).JSON(utils.ResponseData{
+ Status: 400,
+ Code: "BAD_REQUEST",
+ Message: "invalid chat_jid path parameter: " + err.Error(),
+ Results: nil,
+ })
+ }
+ request.ChatJID = chatJID
// Parse JSON body
if err := c.Bind().Body(&request); err != nil {
@@ -165,3 +204,15 @@ func (controller *Chat) ArchiveChat(c fiber.Ctx) error {
Results: response,
})
}
+
+// chatJIDParam returns the chat_jid path parameter with percent-encoding
+// decoded. Fiber does not unescape path params, so URL-encoding clients send
+// "...%40g.us" which would miss every chat-storage lookup. strings.Clone
+// detaches the no-escapes passthrough from fiber's reusable param buffer.
+func chatJIDParam(c fiber.Ctx) (string, error) {
+ decoded, err := url.PathUnescape(c.Params("chat_jid"))
+ if err != nil {
+ return "", err
+ }
+ return strings.Clone(decoded), nil
+}
diff --git a/src/ui/rest/chat_test.go b/src/ui/rest/chat_test.go
new file mode 100644
index 00000000..ec8e704f
--- /dev/null
+++ b/src/ui/rest/chat_test.go
@@ -0,0 +1,78 @@
+package rest
+
+import (
+ "encoding/json"
+ "io"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/gofiber/fiber/v3"
+ "github.com/stretchr/testify/require"
+)
+
+func TestChatJIDParamDecodesPercentEncoding(t *testing.T) {
+ tests := []struct {
+ name string
+ path string
+ want string
+ }{
+ {
+ name: "percent-encoded group JID",
+ path: "/chat/120363151317289139%40g.us/messages",
+ },
+ {
+ name: "raw group JID",
+ path: "/chat/[email protected]/messages",
+ },
+ {
+ name: "percent-encoded user JID",
+ path: "/chat/6289685028129%40s.whatsapp.net/messages",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ app := fiber.New()
+ var got string
+ app.Get("/chat/:chat_jid/messages", func(c fiber.Ctx) error {
+ jid, err := chatJIDParam(c)
+ require.NoError(t, err)
+ got = jid
+ return c.SendStatus(fiber.StatusOK)
+ })
+
+ resp, err := app.Test(httptest.NewRequest("GET", tt.path, nil))
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+ require.Equal(t, tt.want, got)
+ })
+ }
+}
+
+func TestChatJIDParamRejectsMalformedEscape(t *testing.T) {
+ app := fiber.New()
+ // The decode error path responds before the service is touched, so a
+ // zero-value controller is enough to exercise the real handler.
+ controller := &Chat{}
+ app.Get("/chat/:chat_jid/messages", controller.GetChatMessages)
+
+ req := httptest.NewRequest("GET", "/chat/placeholder/messages", nil)
+ // httptest.NewRequest rejects invalid escapes up front, so smuggle the
+ // malformed URI past net/url via the Opaque field.
+ req.URL.Opaque = "/chat/%zz/messages"
+
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusBadRequest, resp.StatusCode)
+
+ body, err := io.ReadAll(resp.Body)
+ require.NoError(t, err)
+ var envelope utils.ResponseData
+ require.NoError(t, json.Unmarshal(body, &envelope), "error must be the JSON envelope, got: %s", body)
+ require.Equal(t, "BAD_REQUEST", envelope.Code)
+ require.Contains(t, envelope.Message, "invalid chat_jid path parameter")
+}
diff --git a/src/ui/rest/middleware/basicauth.go b/src/ui/rest/middleware/basicauth.go
deleted file mode 100644
index 266c2ad0..00000000
--- a/src/ui/rest/middleware/basicauth.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package middleware
-
-import (
- "context"
- "github.com/gofiber/fiber/v3"
-)
-
-type AuthorizationValue string
-
-func BasicAuth() fiber.Handler {
- return func(c fiber.Ctx) error {
- token := string(c.Request().Header.Peek("Authorization"))
- if token != "" {
- ctx := context.WithValue(c.Context(), AuthorizationValue("BASIC_AUTH"), token)
- c.SetContext(ctx)
- }
-
- return c.Next()
- }
-}
diff --git a/src/ui/rest/middleware/websocketauth.go b/src/ui/rest/middleware/websocketauth.go
new file mode 100644
index 00000000..c86f272c
--- /dev/null
+++ b/src/ui/rest/middleware/websocketauth.go
@@ -0,0 +1,26 @@
+package middleware
+
+import (
+ "strings"
+
+ "github.com/gofiber/contrib/v3/websocket"
+ "github.com/gofiber/fiber/v3"
+)
+
+// WebsocketQueryAuth lets browser WebSocket clients authenticate with
+// ?authorization=<base64(user:pass)>, because the browser WebSocket API cannot
+// set an Authorization header and userinfo in WS URLs is rejected per spec.
+// The value is restored into the header before the basic-auth middleware runs.
+func WebsocketQueryAuth() fiber.Handler {
+ return func(c fiber.Ctx) error {
+ if websocket.IsWebSocketUpgrade(c) && len(c.Request().Header.Peek(fiber.HeaderAuthorization)) == 0 {
+ if q := c.Query("authorization"); q != "" {
+ // fasthttp decodes '+' as space; base64 never contains spaces,
+ // so restoring '+' is lossless.
+ token := strings.ReplaceAll(q, " ", "+")
+ c.Request().Header.Set(fiber.HeaderAuthorization, "Basic "+token)
+ }
+ }
+ return c.Next()
+ }
+}
diff --git a/src/usecase/send.go b/src/usecase/send.go
index 276a91f8..1feefe17 100644
--- a/src/usecase/send.go
+++ b/src/usecase/send.go
@@ -68,15 +68,18 @@ func (service serviceSend) wrapSendMessage(ctx context.Context, client *whatsmeo
// Store message asynchronously with timeout.
// Preserve device context (for device_id scoping) but detach from request cancellation.
+ // The budget must survive chat-storage write contention (history sync batches
+ // hold the SQLite writer for a while; busy_timeout is 30s) — with a short
+ // deadline the sent message is silently missing from the chat viewer.
go func() {
- storeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
+ storeCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second)
defer cancel()
if err := service.chatStorageRepo.StoreSentMessageWithContext(storeCtx, ts.ID, senderJID, recipient.String(), content, ts.Timestamp, msg); err != nil {
if errors.Is(err, context.DeadlineExceeded) {
- logrus.Warn("Timeout storing sent message")
+ logrus.Warnf("Timeout storing sent message %s to %s", ts.ID, recipient.String())
} else {
- logrus.Warnf("Failed to store sent message: %v", err)
+ logrus.Warnf("Failed to store sent message %s to %s: %v", ts.ID, recipient.String(), err)
}
}
}()
diff --git a/src/views/AGENTS.md b/src/views/AGENTS.md
deleted file mode 100644
index a2002f21..00000000
--- a/src/views/AGENTS.md
+++ /dev/null
@@ -1,46 +0,0 @@
-# EMBEDDED WEB UI
-
-Generated: 2026-06-06
-
-## OVERVIEW
-
-The UI is embedded into the Go binary and served by Fiber. It uses Vue 3 plain JS modules, Fomantic UI, jQuery modals/toasts, Axios, and DataTables from CDNs.
-
-## STRUCTURE
-
-```text
-views/
-|-- index.html # Imports all components, creates Vue app, manages selected device
-|-- assets/app.css # Local CSS
-|-- assets/gowa.svg # Logo
-`-- components/ # One plain JS module per card/modal
- `-- generic/ # Reused form pieces
-```
-
-## WHERE TO LOOK
-
-| Task | Location | Notes |
-|------|----------|-------|
-| Add card/modal | `components/<Name>.js`, `index.html` | Import, register component, and place tag in the right grid. |
-| Shared recipient fields | `components/generic/FormRecipient.js` | Used by send/message/group components. |
-| Send forms | `components/Send*.js` | Text/link use JSON payloads; media forms append fields to `FormData`. |
-| Reply Message ID UI | `SendMessage.js` and media/link send components | Keep optional `reply_message_id` omitted when blank. |
-| Device selector | `components/DeviceManager.js`, `index.html` | Sets `X-Device-Id` and websocket query param. |
-| Chat UI | `components/ChatList.js`, `components/ChatMessages.js` | Handles null/empty API result cases. |
-
-## CONVENTIONS
-
-- Components export default Vue option objects from plain `.js` files.
-- Templates are inline backtick strings in component modules.
-- Vue delimiters are `[[` and `]]` to avoid conflict with Go templates.
-- API calls go through `window.http`, whose base URL includes `AppBasePath`.
-- The selected device is sent as encoded `X-Device-Id`; websockets use `?device_id=`.
-- Use `showSuccessInfo` and `showErrorInfo` for user feedback.
-- Keep Fomantic UI modal IDs unique across components.
-
-## ANTI-PATTERNS
-
-- Do not add `.vue` single-file components or a frontend build step unless the project explicitly changes direction.
-- Do not call `axios` directly if the request needs base path, auth, or device headers; use `window.http`.
-- Do not add components to `components/` without importing/registering them in `index.html`.
-- Do not assume there is always a selected or logged-in device.
diff --git a/src/views/assets/app.css b/src/views/assets/app.css
deleted file mode 100644
index 653457e6..00000000
--- a/src/views/assets/app.css
+++ /dev/null
@@ -1,393 +0,0 @@
-:root {
- --primary-color: #00ADD8; /* Golang's brand blue */
- --secondary-color: #007d9c; /* Golang's darker blue */
- --tertiary-color: #004d5f; /* Golang's darkest blue */
- --background-color: #f8fbff; /* Light blue background */
- --card-hover-color: #ffffff;
- --text-color: #111B21; /* Keep text readable */
- --gradient-start: #00ADD8;
- --gradient-end: #007d9c;
- --message-background: #FFFFFF;
- --success-blue: #00ADD8;
-}
-
-body {
- background-color: var(--background-color) !important;
- color: var(--text-color) !important;
- font-family: "Helvetica Neue", "Helvetica Neue", Helvetica, Arial, sans-serif !important;
-}
-
-.container {
- padding: 2em 1em !important;
- max-width: 1400px !important;
- margin: 0 auto !important;
-}
-
-.main-header {
- background: var(--primary-color) !important;
- color: white !important;
- padding: 1.5em 2em !important;
- border-radius: 24px !important;
- margin-bottom: 2em !important;
- box-shadow:
- 0 20px 40px rgba(0, 173, 216, 0.2),
- inset 0 0 80px rgba(255, 255, 255, 0.15) !important;
- position: relative;
- overflow: hidden;
- backdrop-filter: blur(10px);
- border: 1px solid rgba(255, 255, 255, 0.2);
- transition: all 0.3s ease-in-out;
-}
-
-.main-header::before {
- content: '';
- position: absolute;
- top: 0;
- left: 0;
- right: 0;
- bottom: 0;
- background:
- radial-gradient(
- circle at top right,
- rgba(255,255,255,0.2) 0%,
- rgba(255,255,255,0) 60%
- ),
- linear-gradient(
- 45deg,
- rgba(255,255,255,0.1) 0%,
- rgba(255,255,255,0) 70%
- );
- opacity: 0.8;
- z-index: 1;
-}
-
-.main-header::after {
- content: '';
- position: absolute;
- top: -50%;
- left: -50%;
- right: -50%;
- bottom: -50%;
- background:
- radial-gradient(
- circle,
- rgba(255,255,255,0.1) 0%,
- transparent 70%
- );
- animation: rotate 20s linear infinite;
- z-index: 0;
-}
-
-@keyframes rotate {
- from { transform: rotate(0deg); }
- to { transform: rotate(360deg); }
-}
-
-.main-header .ui.header {
- position: relative;
- z-index: 2;
- margin: 0 !important;
- font-weight: 700 !important;
- font-size: clamp(1.5em, 3vw, 1.8em) !important;
- text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2) !important;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- gap: 8px;
- letter-spacing: 0.5px;
-}
-
-.main-header .title-container {
- display: flex;
- justify-content: space-between;
- align-items: center;
- width: 100%;
- color: white;
-}
-
-.main-header .title-container img {
- width: 2.2em;
- height: 2.2em;
- background: white;
- padding: 0.2em;
- border-radius: 8px;
- box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
-}
-
-.main-header .title-container span {
- flex: 1;
- text-align: center;
-}
-
-.main-header .title-container img {
- animation: float 4s ease-in-out infinite;
- backdrop-filter: blur(5px);
- transition: all 0.3s ease;
-}
-
-.main-header .title-container img:hover {
- transform: scale(1.1);
-}
-
-.main-header .version-label {
- margin-top: 4px !important;
- background: rgba(255,255,255,0.12);
- color: white;
- font-size: 0.5em;
- padding: 4px 10px;
- border-radius: 12px;
- backdrop-filter: blur(4px);
- border: 1px solid rgba(255, 255, 255, 0.15);
- transition: all 0.25s ease;
- letter-spacing: 0.5px;
- box-shadow: 0 2px 4px rgba(0,0,0,0.1);
-}
-
-.main-header .version-label:hover {
- background: rgba(255,255,255,0.2);
- transform: translateY(-2px);
-}
-
-@media (min-width: 768px) {
- .main-header {
- padding: 2em !important;
- }
-
- .main-header .ui.header {
- flex-direction: column;
- }
-
- .main-header .version-label {
- margin-top: 4px !important;
- }
-}
-
-@keyframes float {
- 0% { transform: translateY(0px) rotate(0deg); }
- 50% { transform: translateY(-8px) rotate(5deg); }
- 100% { transform: translateY(0px) rotate(0deg); }
-}
-
-.ui.header {
- font-weight: 600 !important;
- color: var(--text-color) !important;
-}
-
-.ui.cards > .card {
- box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05) !important;
- transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275) !important;
- border-radius: 16px !important;
- margin: 0.7em !important;
- background-color: var(--message-background) !important;
- border: 1px solid rgba(0, 173, 216, 0.1);
-}
-
-.ui.cards > .card:hover {
- transform: translateY(-8px) !important;
- box-shadow: 0 12px 24px rgba(0, 173, 216, 0.15) !important;
- background-color: var(--card-hover-color) !important;
-}
-
-.ui.horizontal.divider {
- font-size: 1.3em !important;
- color: var(--secondary-color) !important;
- margin: 2.5em 0 !important;
- font-weight: 700 !important;
- text-transform: uppercase;
- letter-spacing: 1px;
-}
-
-.ui.success.message {
- border-radius: 16px !important;
- box-shadow: 0 4px 8px rgba(0, 173, 216, 0.1) !important;
- border: 1px solid rgba(0, 173, 216, 0.2) !important;
- background-color: rgba(230, 248, 255, 0.8) !important;
- color: var(--success-blue) !important;
- animation: slideIn 0.6s cubic-bezier(0.175, 0.885, 0.32, 1.275);
- backdrop-filter: blur(10px);
-}
-
-@keyframes slideIn {
- from { transform: translateX(-30px); opacity: 0; }
- to { transform: translateX(0); opacity: 1; }
-}
-
-.ui.button {
- border-radius: 12px !important;
- transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) !important;
- /* background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%) !important; */
- /* background: var(--primary-color) !important; */
- color: white !important;
- font-weight: 600 !important;
- letter-spacing: 0.5px;
-}
-
-.ui.button:hover {
- transform: translateY(-3px) !important;
- box-shadow: 0 8px 16px rgba(0, 173, 216, 0.2) !important;
- filter: brightness(0.95);
-}
-
-.ui.form input, .ui.form textarea {
- border-radius: 12px !important;
- border: 2px solid rgba(0, 173, 216, 0.1) !important;
- transition: all 0.3s ease;
-}
-
-.ui.form input:focus, .ui.form textarea:focus {
- border-color: var(--primary-color) !important;
- box-shadow: 0 0 0 3px rgba(0, 173, 216, 0.1) !important;
-}
-
-.ui.toast-container {
- padding: 1.5em !important;
-}
-
-.ui.toast {
- border-radius: 16px !important;
- box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1) !important;
- background-color: var(--message-background) !important;
- border: 1px solid rgba(0, 173, 216, 0.1);
-}
-
-.ui.grid {
- margin: -0.7em !important;
-}
-
-.ui.grid > .column {
- padding: 0.7em !important;
-}
-
-@keyframes fadeIn {
- from { opacity: 0; transform: translateY(30px); }
- to { opacity: 1; transform: translateY(0); }
-}
-
-.ui.cards {
- animation: fadeIn 0.6s cubic-bezier(0.175, 0.885, 0.32, 1.275);
-}
-
-.ui.modal {
- border-radius: 20px !important;
- background-color: var(--message-background) !important;
- overflow: hidden;
-}
-
-.ui.modal > .header {
- border-radius: 20px 20px 0 0 !important;
- background: var(--gradient-start) !important;
- color: white !important;
- padding: 1.5em !important;
-}
-
-.ui.modal > .actions {
- border-radius: 0 0 20px 20px !important;
- background-color: rgba(248, 248, 248, 0.8) !important;
- backdrop-filter: blur(10px);
-}
-
-.ui.modal > .actions > .ui.button {
- background: var(--primary-color) !important;
- color: white !important;
- font-weight: 600 !important;
- letter-spacing: 0.5px;
-}
-
-/* Splash Screen Styles */
-#splash-screen {
- position: fixed;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- background: linear-gradient(135deg, #00ADD8 0%, #007d9c 100%);
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- z-index: 9999;
- transition: opacity 0.5s ease-in-out;
- color: white;
- box-sizing: border-box;
- padding: 0;
- margin: 0;
-}
-
-#splash-screen.fade-out {
- opacity: 0;
- pointer-events: none;
-}
-
-.splash-icon {
- width: 5em;
- height: 5em;
- margin: 0;
- animation: bounce 2s infinite, glassShimmer 4s ease-in-out infinite;
- border-radius: 20px;
- display: block;
- object-fit: cover;
- object-position: center;
- position: relative;
- z-index: 2;
- background: white;
- padding: 0.5em;
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
-}
-
-.splash-title {
- font-size: 2em;
- font-weight: bold;
- margin: 20px 0 10px 0;
- text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
- text-align: center;
-}
-
-.splash-spinner {
- margin-top: 20px;
- align-self: center;
-}
-
-#splash-screen > * {
- flex-shrink: 0;
-}
-
-@keyframes bounce {
- 0%, 100% { transform: translateY(0); }
- 50% { transform: translateY(-20px); }
-}
-
-@keyframes glassShimmer {
- 0%, 100% {
- filter: drop-shadow(0 8px 32px rgba(0, 0, 0, 0.15)) brightness(1);
- }
- 50% {
- filter: drop-shadow(0 12px 40px rgba(0, 0, 0, 0.2)) brightness(1.05);
- }
-}
-
-/* Responsive splash icon design */
-@media (max-width: 768px) {
- .splash-icon {
- width: 5em;
- height: 5em;
- border-radius: 20px;
- }
-}
-
-@media (max-width: 480px) {
- .splash-icon {
- width: 4em;
- height: 4em;
- border-radius: 16px;
- }
-}
-
-/* High-DPI/Retina display optimizations */
-@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
- .splash-icon {
- image-rendering: -webkit-optimize-contrast;
- image-rendering: optimize-contrast;
- image-rendering: crisp-edges;
- }
-}
\ No newline at end of file
diff --git a/src/views/components/AccountAvatar.js b/src/views/components/AccountAvatar.js
deleted file mode 100644
index 458e3b65..00000000
--- a/src/views/components/AccountAvatar.js
+++ /dev/null
@@ -1,127 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'AccountAvatar',
- components: {
- FormRecipient
- },
- data() {
- return {
- type: window.TYPEUSER,
- phone: '',
- image: null,
- loading: false,
- is_preview: false,
- is_community: false,
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- },
- isGroupType() {
- return this.type === window.TYPEGROUP;
- }
- },
- watch: {
- type(newType) {
- // Reset is_community when switching to user type (only valid for groups)
- if (newType !== window.TYPEGROUP) {
- this.is_community = false;
- }
- }
- },
- methods: {
- async openModal() {
- this.handleReset();
- $('#modalUserAvatar').modal('show');
- },
- isValidForm() {
- if (!this.phone.trim()) {
- return false;
- }
-
- return true;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
-
- try {
- await this.submitApi();
- showSuccessInfo("Avatar fetched")
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let response = await window.http.get(`/user/avatar?phone=${this.phone_id}&is_preview=${this.is_preview}&is_community=${this.is_community}`)
- this.image = response.data.results.url;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.phone = '';
- this.image = null;
- this.type = window.TYPEUSER;
- }
- },
- template: `
- <div class="olive card" @click="openModal" style="cursor: pointer;">
- <div class="content">
- <a class="ui olive right ribbon label">Account</a>
- <div class="header">Avatar</div>
- <div class="description">
- You can search someone avatar by phone
- </div>
- </div>
- </div>
-
- <!-- Modal UserAvatar -->
- <div class="ui small modal" id="modalUserAvatar">
- <i class="close icon"></i>
- <div class="header">
- Search User Avatar
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone"/>
-
- <div class="field">
- <label>Preview</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="compress" v-model="is_preview">
- <label>Check for small size image</label>
- </div>
- </div>
-
- <div class="field" v-if="isGroupType">
- <label>Community</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="compress" v-model="is_community">
- <label>Check if it's a community group</label>
- </div>
- </div>
-
- <button type="button" class="ui primary button" :class="{'loading': loading, 'disabled': !this.isValidForm() || this.loading}"
- @click.prevent="handleSubmit">
- Search
- </button>
- </form>
-
- <div v-if="image != null" class="center">
- <img :src="image" alt="profile picture" style="padding-top: 10px; max-height: 200px">
- </div>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/AccountBusinessProfile.js b/src/views/components/AccountBusinessProfile.js
deleted file mode 100644
index 35650853..00000000
--- a/src/views/components/AccountBusinessProfile.js
+++ /dev/null
@@ -1,211 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'AccountBusinessProfile',
- components: {
- FormRecipient
- },
- data() {
- return {
- type: window.TYPEUSER,
- phone: '',
- //
- jid: null,
- email: null,
- address: null,
- categories: [],
- profileOptions: {},
- businessHoursTimeZone: null,
- businessHours: [],
- //
- loading: false,
- }
- },
-
- computed: {
- phone_id() {
- return this.phone + this.type;
- }
- },
- methods: {
- async openModal() {
- this.handleReset();
- $('#modalBusinessProfile').modal('show');
- },
- isValidForm() {
- if (!this.phone.trim()) {
- return false;
- }
-
- return true;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
-
- try {
- await this.submitApi();
- showSuccessInfo("Business profile fetched")
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let response = await window.http.get(`/user/business-profile?phone=${this.phone_id}`)
- const results = response.data.results;
- this.jid = results.jid;
- this.email = results.email;
- this.address = results.address;
- this.categories = results.categories || [];
- this.profileOptions = results.profile_options || {};
- this.businessHoursTimeZone = results.business_hours_timezone;
- this.businessHours = results.business_hours || [];
- } catch (error) {
- if (error.response) {
- const message = error.response.data.message;
- if (message.includes('not be a business account')) {
- throw new Error('This number is not a WhatsApp Business account or does not have a public business profile.');
- } else if (message.includes('profile data is corrupted')) {
- throw new Error('The business profile data appears to be corrupted. Please try again later.');
- } else {
- throw new Error(message);
- }
- } else {
- throw new Error('Failed to fetch business profile. Please check the phone number and try again.');
- }
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.phone = '';
- this.jid = null;
- this.email = null;
- this.address = null;
- this.categories = [];
- this.profileOptions = {};
- this.businessHoursTimeZone = null;
- this.businessHours = [];
- this.type = window.TYPEUSER;
- },
- formatBusinessHours(hours) {
- if (!hours || hours.length === 0) return 'Not available';
- return hours.map(h => `${h.day_of_week}: ${h.open_time} - ${h.close_time} (${h.mode})`).join(', ');
- }
- },
- template: `
- <div class="olive card" @click="openModal" style="cursor: pointer;">
- <div class="content">
- <a class="ui olive right ribbon label">Account</a>
- <div class="header">Business Profile</div>
- <div class="description">
- Get detailed business profile information
- </div>
- </div>
- </div>
-
-
- <!-- Modal Business Profile -->
- <div class="ui large modal" id="modalBusinessProfile">
- <i class="close icon"></i>
- <div class="header">
- Business Profile Information
- </div>
- <div class="content">
- <form class="ui form">
- <div class="ui info message">
- <div class="header">
- <i class="info circle icon"></i>
- Business Profile Information
- </div>
- <p>This feature works only with WhatsApp Business accounts that have a public business profile set up.</p>
- </div>
-
- <FormRecipient v-model:type="type" v-model:phone="phone"/>
-
- <button type="button" class="ui primary button" :class="{'loading': loading, 'disabled': !this.isValidForm() || this.loading}"
- @click.prevent="handleSubmit">
- Get Business Profile
- </button>
- </form>
-
- <div v-if="jid" class="ui segment" style="margin-top: 20px;">
- <h4 class="ui header">Business Profile Details</h4>
- <div class="ui list">
- <div class="item">
- <i class="id badge icon"></i>
- <div class="content">
- <div class="header">JID</div>
- <div class="description">{{ jid }}</div>
- </div>
- </div>
- <div class="item" v-if="email">
- <i class="mail icon"></i>
- <div class="content">
- <div class="header">Email</div>
- <div class="description">{{ email }}</div>
- </div>
- </div>
- <div class="item" v-if="address">
- <i class="map marker icon"></i>
- <div class="content">
- <div class="header">Address</div>
- <div class="description">{{ address }}</div>
- </div>
- </div>
- <div class="item" v-if="categories.length > 0">
- <i class="tags icon"></i>
- <div class="content">
- <div class="header">Categories</div>
- <div class="description">
- <div class="ui small labels">
- <div v-for="category in categories" :key="category.id" class="ui label">
- {{ category.name }}
- </div>
- </div>
- </div>
- </div>
- </div>
- <div class="item" v-if="businessHoursTimeZone">
- <i class="clock icon"></i>
- <div class="content">
- <div class="header">Timezone</div>
- <div class="description">{{ businessHoursTimeZone }}</div>
- </div>
- </div>
- <div class="item" v-if="businessHours.length > 0">
- <i class="calendar icon"></i>
- <div class="content">
- <div class="header">Business Hours</div>
- <div class="description">
- <div class="ui tiny segments">
- <div v-for="hours in businessHours" :key="hours.day_of_week" class="ui segment">
- <strong>{{ hours.day_of_week.charAt(0).toUpperCase() + hours.day_of_week.slice(1) }}:</strong>
- {{ hours.open_time }} - {{ hours.close_time }} ({{ hours.mode }})
- </div>
- </div>
- </div>
- </div>
- </div>
- <div class="item" v-if="Object.keys(profileOptions).length > 0">
- <i class="info circle icon"></i>
- <div class="content">
- <div class="header">Profile Options</div>
- <div class="description">
- <div class="ui list">
- <div v-for="(value, key) in profileOptions" :key="key" class="item">
- <strong>{{ key }}:</strong> {{ value }}
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/AccountChangeAvatar.js b/src/views/components/AccountChangeAvatar.js
deleted file mode 100644
index 7c109ccb..00000000
--- a/src/views/components/AccountChangeAvatar.js
+++ /dev/null
@@ -1,113 +0,0 @@
-export default {
- name: 'AccountChangeAvatar',
- data() {
- return {
- loading: false,
- selected_file: null,
- preview_url: null
- }
- },
- methods: {
- openModal() {
- $('#modalChangeAvatar').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- return this.selected_file !== null;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
-
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalChangeAvatar').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let payload = new FormData();
- payload.append('avatar', $("#file_avatar")[0].files[0])
-
- let response = await window.http.post(`/user/avatar`, payload)
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.preview_url = null;
- this.selected_file = null;
- $("#file_avatar").val('');
- },
- handleImageChange(event) {
- const file = event.target.files[0];
- if (file) {
- this.preview_url = URL.createObjectURL(file);
- this.selected_file = file.name;
- }
- }
- },
- template: `
- <div class="olive card" @click="openModal()" style="cursor:pointer;">
- <div class="content">
- <a class="ui olive right ribbon label">Account</a>
- <div class="header">Change Avatar</div>
- <div class="description">
- Update your profile picture
- </div>
- </div>
- </div>
-
- <!-- Modal Change Avatar -->
- <div class="ui small modal" id="modalChangeAvatar">
- <i class="close icon"></i>
- <div class="header">
- Change Avatar
- </div>
- <div class="content" style="max-height: 70vh; overflow-y: auto;">
- <div class="ui warning message">
- <i class="info circle icon"></i>
- Please upload a square image (1:1 aspect ratio) to avoid cropping.
- For best results, use an image at least 400x400 pixels.
- </div>
-
- <form class="ui form">
- <div class="field" style="padding-bottom: 30px">
- <label>Avatar Image</label>
- <input type="file" style="display: none" id="file_avatar" accept="image/png,image/jpg,image/jpeg" @change="handleImageChange"/>
- <label for="file_avatar" class="ui positive medium green left floated button" style="color: white">
- <i class="ui upload icon"></i>
- Upload image
- </label>
- <div v-if="preview_url" style="margin-top: 60px">
- <img :src="preview_url" style="max-width: 100%; max-height: 300px; object-fit: contain" />
- </div>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button"
- :class="{'loading': this.loading, 'disabled': !isValidForm() || loading}"
- @click.prevent="handleSubmit">
- Update Avatar
- <i class="save icon"></i>
- </button>
- </div>
- </div>
- `
-}
diff --git a/src/views/components/AccountChangePushName.js b/src/views/components/AccountChangePushName.js
deleted file mode 100644
index 467ff4a5..00000000
--- a/src/views/components/AccountChangePushName.js
+++ /dev/null
@@ -1,96 +0,0 @@
-export default {
- name: 'AccountChangePushName',
- data() {
- return {
- loading: false,
- push_name: ''
- }
- },
- methods: {
- openModal() {
- $('#modalChangePushName').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- return this.push_name.trim() !== '';
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
-
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalChangePushName').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let payload = {
- push_name: this.push_name
- }
-
- let response = await window.http.post(`/user/pushname`, payload)
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.push_name = '';
- }
- },
- template: `
- <div class="olive card" @click="openModal()" style="cursor:pointer;">
- <div class="content">
- <a class="ui olive right ribbon label">Account</a>
- <div class="header">Change Push Name</div>
- <div class="description">
- Update your WhatsApp display name
- </div>
- </div>
- </div>
-
- <!-- Modal Change Push Name -->
- <div class="ui small modal" id="modalChangePushName">
- <i class="close icon"></i>
- <div class="header">
- Change Push Name
- </div>
- <div class="content" style="max-height: 70vh; overflow-y: auto;">
- <div class="ui info message">
- <i class="info circle icon"></i>
- Your push name is the display name shown to others in WhatsApp.
- </div>
-
- <form class="ui form">
- <div class="field">
- <label>New Push Name</label>
- <input type="text" v-model="push_name" placeholder="Enter your new display name">
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button"
- :class="{'loading': this.loading, 'disabled': !isValidForm() || loading}"
- @click.prevent="handleSubmit">
- Update Push Name
- <i class="save icon"></i>
- </button>
- </div>
- </div>
- `
-}
diff --git a/src/views/components/AccountContact.js b/src/views/components/AccountContact.js
deleted file mode 100644
index 6e2fbf64..00000000
--- a/src/views/components/AccountContact.js
+++ /dev/null
@@ -1,114 +0,0 @@
-export default {
- name: 'AccountContact',
- data() {
- return {
- contacts: []
- }
- },
- methods: {
- async openModal() {
- try {
- this.dtClear()
- await this.submitApi();
- $('#modalContactList').modal('show');
- this.dtRebuild()
- showSuccessInfo("Contacts fetched")
- } catch (err) {
- showErrorInfo(err)
- }
- },
- dtClear() {
- $('#account_contacts_table').DataTable().destroy();
- },
- dtRebuild() {
- $('#account_contacts_table').DataTable({
- "pageLength": 10,
- "reloadData": true,
- }).draw();
- },
- async submitApi() {
- try {
- let response = await window.http.get(`/user/my/contacts`)
- this.contacts = response.data.results.data;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- }
- },
- getPhoneNumber(jid) {
- return jid.split('@')[0];
- },
- exportToCSV() {
- if (!this.contacts || this.contacts.length === 0) {
- showErrorInfo("No contacts to export");
- return;
- }
-
- // Create CSV content with headers
- let csvContent = "Phone Number,Name\n";
-
- // Add each contact as a row
- this.contacts.forEach(contact => {
- const phoneNumber = this.getPhoneNumber(contact.jid);
- // Escape commas and quotes in the name field
- const escapedName = contact.name ? contact.name.replace(/"/g, '""') : "";
- csvContent += `${phoneNumber},"${escapedName}"\n`;
- });
-
- // Create a Blob with the CSV data
- const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
-
- // Create a download link and trigger download
- const url = URL.createObjectURL(blob);
- const link = document.createElement('a');
- link.setAttribute('href', url);
- link.setAttribute('download', 'contacts.csv');
- link.style.visibility = 'hidden';
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
-
- showSuccessInfo("Contacts exported to CSV");
- }
- },
- template: `
- <div class="olive card" @click="openModal" style="cursor: pointer">
- <div class="content">
- <a class="ui olive right ribbon label">Contacts</a>
- <div class="header">My Contacts</div>
- <div class="description">
- Display all your contacts
- </div>
- </div>
- </div>
-
- <!-- Modal Contact List -->
- <div class="ui large modal" id="modalContactList">
- <i class="close icon"></i>
- <div class="header">
- My Contacts
- <button class="ui green right floated button" @click="exportToCSV">
- <i class="download icon"></i> Export to CSV
- </button>
- </div>
- <div class="content">
- <table class="ui celled table" id="account_contacts_table">
- <thead>
- <tr>
- <th>Phone Number</th>
- <th>Name</th>
- </tr>
- </thead>
- <tbody v-if="contacts != null">
- <tr v-for="contact in contacts">
- <td>{{ getPhoneNumber(contact.jid) }}</td>
- <td>{{ contact.name }}</td>
- </tr>
- </tbody>
- </table>
- </div>
- </div>
- `
-}
diff --git a/src/views/components/AccountPrivacy.js b/src/views/components/AccountPrivacy.js
deleted file mode 100644
index fb473684..00000000
--- a/src/views/components/AccountPrivacy.js
+++ /dev/null
@@ -1,58 +0,0 @@
-export default {
- name: 'AccountPrivacy',
- data() {
- return {
- data_privacy: null
- }
- },
- methods: {
- async openModal() {
- try {
- await this.submitApi();
- $('#modalUserPrivacy').modal('show');
- showSuccessInfo("Privacy fetched")
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- try {
- let response = await window.http.get(`/user/my/privacy`)
- this.data_privacy = response.data.results;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- }
- },
- },
- template: `
- <div class="olive card" @click="openModal" style="cursor: pointer">
- <div class="content">
- <a class="ui olive right ribbon label">Account</a>
- <div class="header">My Privacy Setting</div>
- <div class="description">
- Get your privacy settings
- </div>
- </div>
- </div>
-
- <!-- Modal UserPrivacy -->
- <div class="ui small modal" id="modalUserPrivacy">
- <i class="close icon"></i>
- <div class="header">
- My Privacy
- </div>
- <div class="content">
- <ol v-if="data_privacy != null">
- <li>Who can add Group : <b>{{ data_privacy.group_add }}</b></li>
- <li>Who can see my Last Seen : <b>{{ data_privacy.last_seen }}</b></li>
- <li>Who can see my Status : <b>{{ data_privacy.status }}</b></li>
- <li>Who can see my Profile : <b>{{ data_privacy.profile }}</b></li>
- <li>Read Receipts : <b>{{ data_privacy.read_receipts }}</b></li>
- </ol>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/AccountUserCheck.js b/src/views/components/AccountUserCheck.js
deleted file mode 100644
index c417c68c..00000000
--- a/src/views/components/AccountUserCheck.js
+++ /dev/null
@@ -1,95 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'AccountUserCheck',
- components: {
- FormRecipient
- },
- data() {
- return {
- type: window.TYPEUSER,
- phone: '',
- isOnWhatsApp: null,
- loading: false,
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- }
- },
- methods: {
- async openModal() {
- this.handleReset();
- $('#modalUserCheck').modal('show');
- },
- isValidForm() {
- return this.phone.trim() !== '';
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- await this.submitApi();
- showSuccessInfo("Check completed")
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let response = await window.http.get(`/user/check?phone=${this.phone_id}`)
- this.isOnWhatsApp = response.data.results.is_on_whatsapp;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.phone = '';
- this.isOnWhatsApp = null;
- this.type = window.TYPEUSER;
- }
- },
- template: `
- <div class="olive card" @click="openModal" style="cursor: pointer;">
- <div class="content">
- <a class="ui olive right ribbon label">Account</a>
- <div class="header">User Check</div>
- <div class="description">
- Check if a user is on WhatsApp
- </div>
- </div>
- </div>
-
- <div class="ui small modal" id="modalUserCheck">
- <i class="close icon"></i>
- <div class="header">
- Check if User is on WhatsApp
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone"/>
- <button type="button" class="ui primary button" :class="{'loading': loading, 'disabled': !this.isValidForm() || this.loading}"
- @click.prevent="handleSubmit">
- Check
- </button>
- </form>
-
- <div v-if="isOnWhatsApp !== null" class="ui message" :class="isOnWhatsApp ? 'positive' : 'negative'">
- <div class="header">
- <i :class="isOnWhatsApp ? 'check circle icon' : 'times circle icon'"></i>
- {{ isOnWhatsApp ? 'User is on WhatsApp' : 'User is not on WhatsApp' }}
- </div>
- <p>Phone: {{ phone_id }}</p>
- </div>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/AccountUserInfo.js b/src/views/components/AccountUserInfo.js
deleted file mode 100644
index 23f1510e..00000000
--- a/src/views/components/AccountUserInfo.js
+++ /dev/null
@@ -1,161 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'AccountUserInfo',
- components: {
- FormRecipient
- },
- data() {
- return {
- type: window.TYPEUSER,
- phone: '',
- //
- name: null,
- status: null,
- devices: [],
- resolvedPhone: null,
- resolvedLid: null,
- //
- loading: false,
- }
- },
-
- computed: {
- phone_id() {
- return this.phone + this.type;
- }
- },
- methods: {
- async openModal() {
- this.handleReset();
- $('#modalUserInfo').modal('show');
- },
- isValidForm() {
- if (!this.phone.trim()) {
- return false;
- }
-
- return true;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
-
- try {
- await this.submitApi();
- showSuccessInfo("Info fetched")
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let response = await window.http.get(`/user/info?phone=${this.phone_id}`)
- const results = response.data.results;
- const userData = results.data && results.data.length > 0 ? results.data[0] : null;
-
- if (userData) {
- this.name = userData.verified_name;
- this.status = userData.status;
- this.devices = userData.devices || [];
- }
-
- this.resolvedPhone = results.resolved_phone || null;
- this.resolvedLid = results.resolved_lid || null;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.phone = '';
- this.name = null;
- this.status = null;
- this.devices = [];
- this.resolvedPhone = null;
- this.resolvedLid = null;
- this.type = window.TYPEUSER;
- }
- },
- template: `
- <div class="olive card" @click="openModal" style="cursor: pointer;">
- <div class="content">
- <a class="ui olive right ribbon label">Account</a>
- <div class="header">User Info</div>
- <div class="description">
- You can search someone user info by phone or LID
- </div>
- </div>
- </div>
-
-
- <!-- Modal UserInfo -->
- <div class="ui small modal" id="modalUserInfo">
- <i class="close icon"></i>
- <div class="header">
- Search User Information
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone"/>
-
- <button type="button" class="ui primary button" :class="{'loading': loading, 'disabled': !this.isValidForm() || this.loading}"
- @click.prevent="handleSubmit">
- Search
- </button>
- </form>
-
- <div v-if="devices.length > 0 || resolvedPhone || resolvedLid" class="ui segment" style="margin-top: 1em;">
- <div class="ui list">
- <div class="item" v-if="resolvedPhone">
- <i class="phone icon"></i>
- <div class="content">
- <div class="header">Resolved Phone</div>
- <div class="description">{{ resolvedPhone }}</div>
- </div>
- </div>
- <div class="item" v-if="resolvedLid">
- <i class="linkify icon"></i>
- <div class="content">
- <div class="header">Resolved LID</div>
- <div class="description">{{ resolvedLid }}</div>
- </div>
- </div>
- <div class="item" v-if="name">
- <i class="user icon"></i>
- <div class="content">
- <div class="header">Name</div>
- <div class="description">{{ name }}</div>
- </div>
- </div>
- <div class="item" v-if="status">
- <i class="info circle icon"></i>
- <div class="content">
- <div class="header">Status</div>
- <div class="description">{{ status }}</div>
- </div>
- </div>
- <div class="item" v-if="devices.length > 0">
- <i class="mobile alternate icon"></i>
- <div class="content">
- <div class="header">Devices ({{ devices.length }})</div>
- <div class="ui relaxed list">
- <div class="item" v-for="d in devices" :key="d.AD">
- <i class="tablet icon"></i>
- <div class="content">{{ d.Device }} - {{ d.AD }}</div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/AppLogin.js b/src/views/components/AppLogin.js
deleted file mode 100644
index 54b8063e..00000000
--- a/src/views/components/AppLogin.js
+++ /dev/null
@@ -1,125 +0,0 @@
-export default {
- name: 'AppLogin',
- props: {
- loggedIn: {
- type: Boolean,
- default: false,
- },
- },
- data() {
- return {
- login_link: '',
- login_duration_sec: 0,
- countdown_timer: null,
- }
- },
- methods: {
- async openModal() {
- try {
- if (this.loggedIn) throw Error('You are already logged in.');
-
- await this.submitApi();
- $('#modalLogin').modal({
- onApprove: function () {
- return false;
- },
- onHidden: () => {
- this.stopCountdown();
- }
- }).modal('show');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- try {
- // Stop existing countdown before making new request
- this.stopCountdown();
-
- let response = await window.http.get(`app/login`)
- let results = response.data.results;
- this.login_link = results.qr_link;
- this.login_duration_sec = results.qr_duration;
-
- // Start countdown after successful API call
- this.startCountdown();
- } catch (error) {
- if (error.response) {
- throw Error(error.response.data.message)
- }
- throw Error(error.message)
- }
- },
- startCountdown() {
- // Clear any existing timer
- this.stopCountdown();
-
- this.countdown_timer = setInterval(() => {
- if (this.login_duration_sec > 0) {
- this.login_duration_sec--;
- } else {
- // Auto refresh when countdown reaches 0
- this.autoRefresh();
- }
- }, 1000);
- },
- stopCountdown() {
- if (this.countdown_timer) {
- clearInterval(this.countdown_timer);
- this.countdown_timer = null;
- }
- },
- async autoRefresh() {
- try {
- console.log('QR Code expired, auto refreshing...');
- await this.submitApi();
- } catch (error) {
- console.error('Auto refresh failed:', error);
- this.stopCountdown();
- showErrorInfo(error);
- }
- }
- },
- beforeUnmount() {
- // Clean up timer when component is destroyed
- this.stopCountdown();
- },
- template: `
- <div class="green card" @click="openModal" style="cursor: pointer">
- <div class="content">
- <a class="ui teal right ribbon label">App</a>
- <div class="header">Login</div>
- <div class="description">
- Scan your QR code to access all API capabilities.
- </div>
- </div>
- </div>
-
- <!-- Modal Login -->
- <div class="ui small modal" id="modalLogin">
- <i class="close icon"></i>
- <div class="header">
- Login Whatsapp
- </div>
- <div class="image content">
- <div class="ui medium image">
- <img :src="login_link" alt="qrCodeLogin">
- </div>
- <div class="description">
- <div class="ui header">Please scan to connect</div>
- <p>Open Setting > Linked Devices > Link Device</p>
- <div style="padding-top: 50px;">
- <i v-if="login_duration_sec > 0">QR Code expires in {{ login_duration_sec }} seconds (auto-refreshing)</i>
- <i v-else class="ui active inline">Refreshing QR Code...</i>
- </div>
- </div>
- </div>
- <div class="actions">
- <div class="ui approve positive right labeled icon button" @click="submitApi">
- Refresh QR Code
- <i class="refresh icon"></i>
- </div>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/AppLoginWithCode.js b/src/views/components/AppLoginWithCode.js
deleted file mode 100644
index 93685ef0..00000000
--- a/src/views/components/AppLoginWithCode.js
+++ /dev/null
@@ -1,99 +0,0 @@
-export default {
- name: 'AppLoginWithCode',
- props: {
- loggedIn: {
- type: Boolean,
- default: false,
- }
- },
- data: () => {
- return {
- phone: '',
- submitting: false,
- pair_code: null,
- };
- },
- methods: {
- async openModal() {
- try {
- if (this.loggedIn) throw Error('You are already logged in.');
-
- $('#modalLoginWithCode').modal({
- onApprove: function() {
- return false;
- },
- }).modal('show');
- } catch (err) {
- showErrorInfo(err);
- }
- },
- async handleSubmit() {
- if (this.submitting) return;
- try {
- this.submitting = true;
- const { data } = await http.get(`/app/login-with-code`, {
- params: {
- phone: this.phone,
- },
- });
- this.pair_code = data.results.pair_code;
- } catch (err) {
- if (err.response) {
- showErrorInfo(err.response.data.message);
- }else{
- showErrorInfo(err.message);
- }
- } finally {
- this.submitting = false;
- }
- },
- },
- template: `
- <div class="green card" @click="openModal" style="cursor: pointer">
- <div class="content">
- <a class="ui teal right ribbon label">App</a>
- <div class="header">Login with Code</div>
- <div class="description">
- Enter your pairing code to log in and access your devices.
- </div>
- </div>
- </div>
-
- <!-- Modal Login -->
- <div class="ui small modal" id="modalLoginWithCode">
- <i class="close icon"></i>
- <div class="header">
- Getting Pair Code
- </div>
- <div class="content">
- <div class="ui message info">
- <div class="header">How to pair?</div>
- <ol>
- <li>Open your Whatsapp</li>
- <li>Link a device</li>
- <li>Link with pair code</li>
- </ol>
- </div>
-
- <div class="ui form">
- <div class="field">
- <label>Phone</label>
- <input type="text" v-model="phone" placeholder="Type your phone number"
- @keyup.enter="handleSubmit" :disabled="submitting">
- <small>Enter to submit</small>
- </div>
- </div>
-
- <div class="ui grid" v-if="pair_code">
- <div class="ui two column centered grid">
- <div class="column center aligned">
- <div class="header">Pair Code</div>
- <p style="font-size: 32px">{{ pair_code }}</p>
-
- </div>
- </div>
- </div>
- </div>
- </div>
- `,
-};
\ No newline at end of file
diff --git a/src/views/components/AppLogout.js b/src/views/components/AppLogout.js
deleted file mode 100644
index 41956eb1..00000000
--- a/src/views/components/AppLogout.js
+++ /dev/null
@@ -1,39 +0,0 @@
-export default {
- name: 'AppLogout',
- methods: {
- async handleSubmit() {
- try {
- await this.submitApi()
- showSuccessInfo("Logout success")
-
- // fetch devices
- this.$emit('reload-devices')
- } catch (err) {
- showErrorInfo(err)
- }
- },
-
- async submitApi() {
- try {
- await http.get(`app/logout`)
- } catch (error) {
- if (error.response) {
- throw Error(error.response.data.message)
- }
- throw Error(error.message)
- }
-
- }
- },
- template: `
- <div class="green card" @click="handleSubmit" style="cursor: pointer">
- <div class="content">
- <a class="ui teal right ribbon label">App</a>
- <div class="header">Logout</div>
- <div class="description">
- Remove your login session in application
- </div>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/AppReconnect.js b/src/views/components/AppReconnect.js
deleted file mode 100644
index 695f3f14..00000000
--- a/src/views/components/AppReconnect.js
+++ /dev/null
@@ -1,37 +0,0 @@
-export default {
- name: 'AppReconnect',
- methods: {
- async handleSubmit() {
- try {
- await this.submitApi()
- showSuccessInfo("Reconnect success")
-
- // fetch devices
- this.$emit('reload-devices')
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- try {
- await window.http.get(`/app/reconnect`)
- } catch (error) {
- if (error.response) {
- throw Error(error.response.data.message)
- }
- throw Error(error.message)
- }
- }
- },
- template: `
- <div class="green card" @click="handleSubmit" style="cursor: pointer">
- <div class="content">
- <a class="ui teal right ribbon label">App</a>
- <div class="header">Reconnect</div>
- <div class="description">
- Please reconnect to the WhatsApp service if your API doesn't work or if your app is down.
- </div>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/CallReject.js b/src/views/components/CallReject.js
deleted file mode 100644
index 0adfeae6..00000000
--- a/src/views/components/CallReject.js
+++ /dev/null
@@ -1,114 +0,0 @@
-export default {
- name: 'CallReject',
- data() {
- return {
- phone: '',
- call_id: '',
- loading: false,
- }
- },
- computed: {
- caller_jid() {
- const trimmed = this.phone.trim().replace(/\s+/g, '');
- if (trimmed.includes('@')) {
- return trimmed;
- }
- return trimmed + window.TYPEUSER;
- }
- },
- methods: {
- openModal() {
- $('#modalCallReject').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- if (!this.phone.trim()) {
- return false;
- }
- if (!this.call_id.trim()) {
- return false;
- }
- return true;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalCallReject').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- const payload = {
- caller_jid: this.caller_jid,
- call_id: this.call_id.trim(),
- }
- let response = await window.http.post(`/call/reject`, payload)
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.phone = '';
- this.call_id = '';
- },
- },
- template: `
- <div class="red card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui red right ribbon label">Call</a>
- <div class="header">Reject Call</div>
- <div class="description">
- Reject an incoming call by providing the caller JID and call ID from the webhook
- </div>
- </div>
- </div>
-
- <!-- Modal CallReject -->
- <div class="ui small modal" id="modalCallReject">
- <i class="close icon"></i>
- <div class="header">
- Reject Incoming Call
- </div>
- <div class="content">
- <form class="ui form" @submit.prevent>
- <div class="field">
- <label>Caller Phone Number</label>
- <input v-model="phone" type="text" placeholder="e.g. 628912345678"
- aria-label="caller phone number">
- <input :value="caller_jid" disabled aria-label="caller jid">
- </div>
-
- <div class="field">
- <label>Call ID</label>
- <input v-model="call_id" type="text" placeholder="Call ID from webhook event"
- aria-label="call id">
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve negative right labeled icon button" :class="{'loading': this.loading, 'disabled': !isValidForm() || loading}"
- @click="handleSubmit">
- Reject Call
- <i class="phone slash icon"></i>
- </button>
- </div>
- </div>
- `
-}
diff --git a/src/views/components/ChatDisappearingManager.js b/src/views/components/ChatDisappearingManager.js
deleted file mode 100644
index b5465162..00000000
--- a/src/views/components/ChatDisappearingManager.js
+++ /dev/null
@@ -1,127 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'ChatDisappearingManager',
- components: {
- FormRecipient
- },
- data() {
- return {
- type: window.TYPEUSER,
- phone: '',
- timerSeconds: 86400, // Default to 24 hours
- loading: false,
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- },
- timerLabel() {
- const labels = {
- 0: 'Off',
- 86400: '24 hours',
- 604800: '7 days',
- 7776000: '90 days'
- };
- return labels[this.timerSeconds] || 'Unknown';
- }
- },
- methods: {
- isValidForm() {
- const isPhoneValid = this.phone.trim().length > 0;
- return isPhoneValid;
- },
- openModal() {
- $('#modalChatDisappearing').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- const response = await this.submitApi();
- showSuccessInfo(response);
- $('#modalChatDisappearing').modal('hide');
- } catch (err) {
- showErrorInfo(err);
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- const payload = {
- timer_seconds: parseInt(this.timerSeconds)
- };
-
- const response = await window.http.post(`/chat/${this.phone_id}/disappearing`, payload);
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response?.data?.message) {
- throw new Error(error.response.data.message);
- }
- throw error;
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.phone = '';
- this.timerSeconds = 86400;
- },
- },
- template: `
- <div class="purple card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui purple right ribbon label">Chat</a>
- <div class="header">Disappearing Messages</div>
- <div class="description">
- Set auto-delete timer for chat messages
- </div>
- </div>
- </div>
-
- <!-- Modal ChatDisappearing -->
- <div class="ui small modal" id="modalChatDisappearing">
- <i class="close icon"></i>
- <div class="header">
- <i class="clock outline icon"></i> Disappearing Messages
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone" :show-status="false"/>
- <div class="field">
- <label>Timer Duration</label>
- <select class="ui dropdown" v-model="timerSeconds">
- <option :value="0">Off (disabled)</option>
- <option :value="86400">24 hours</option>
- <option :value="604800">7 days</option>
- <option :value="7776000">90 days</option>
- </select>
- </div>
- <div class="ui info message" v-if="timerSeconds > 0">
- <i class="info circle icon"></i>
- Messages will disappear after <strong>{{ timerLabel }}</strong>
- </div>
- <div class="ui warning message" v-else>
- <i class="exclamation triangle icon"></i>
- Disappearing messages will be <strong>disabled</strong>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button"
- :class="{'disabled': !isValidForm() || loading, 'loading': loading}"
- @click.prevent="handleSubmit">
- {{ timerSeconds === 0 ? 'Disable Timer' : 'Set Timer' }}
- <i class="clock icon"></i>
- </button>
- </div>
- </div>
- `
-}
diff --git a/src/views/components/ChatList.js b/src/views/components/ChatList.js
deleted file mode 100644
index 4943d839..00000000
--- a/src/views/components/ChatList.js
+++ /dev/null
@@ -1,239 +0,0 @@
-export default {
- name: 'ChatList',
- data() {
- return {
- chats: [],
- loading: false,
- searchQuery: '',
- includeMediaChats: false,
- archiveFilter: '',
- currentPage: 1,
- pageSize: 10,
- totalChats: 0,
- selectedChatJid: ''
- }
- },
- computed: {
- totalPages() {
- return Math.ceil(this.totalChats / this.pageSize);
- },
- filteredChats() {
- if (!this.searchQuery) return this.chats;
- return this.chats.filter(chat =>
- chat.name?.toLowerCase().includes(this.searchQuery.toLowerCase()) ||
- chat.jid?.toLowerCase().includes(this.searchQuery.toLowerCase())
- );
- }
- },
- methods: {
- openModal() {
- $('#modalChatList').modal('show');
- this.loadChats();
- },
- closeModal() {
- $('#modalChatList').modal('hide');
- },
- async loadChats() {
- this.loading = true;
- try {
- const params = new URLSearchParams({
- offset: (this.currentPage - 1) * this.pageSize,
- limit: this.pageSize
- });
-
- if (this.searchQuery.trim()) {
- params.append('search', this.searchQuery);
- }
-
- if (this.includeMediaChats) {
- params.append('has_media', 'true');
- }
-
- if (this.archiveFilter !== '') {
- params.append('archived', this.archiveFilter);
- }
-
- const response = await window.http.get(`/chats?${params}`);
- this.chats = response.data.results?.data || [];
- this.totalChats = response.data.results?.pagination?.total || 0;
- } catch (error) {
- showErrorInfo(error.response?.data?.message || 'Failed to load chats');
- } finally {
- this.loading = false;
- }
- },
- async searchChats() {
- this.currentPage = 1;
- await this.loadChats();
- },
- nextPage() {
- if (this.currentPage < this.totalPages) {
- this.currentPage++;
- this.loadChats();
- }
- },
- prevPage() {
- if (this.currentPage > 1) {
- this.currentPage--;
- this.loadChats();
- }
- },
- selectChat(jid) {
- this.selectedChatJid = jid;
- // Store the JID for the chat messages component
- localStorage.setItem('selectedChatJid', jid);
-
- // Close the current modal
- $('#modalChatList').modal('hide');
-
- // Directly open ChatMessages modal after ChatList modal closes
- setTimeout(() => {
- // Find the ChatMessages component and call its openModal method
- if (window.ChatMessagesComponent && window.ChatMessagesComponent.openModal) {
- window.ChatMessagesComponent.openModal();
- }
- }, 200);
- },
- formatTimestamp(timestamp) {
- if (!timestamp) return 'N/A';
- return moment(timestamp).format('MMM DD, YYYY HH:mm');
- },
- formatJid(jid) {
- if (!jid) return '';
- if (jid.includes('@g.us')) return 'Group';
- if (jid.includes('@s.whatsapp.net')) return 'Contact';
- return 'Other';
- }
- },
- mounted() {
- // Expose the component globally for other components to access
- window.ChatListComponent = this;
- },
- beforeUnmount() {
- // Clean up global reference
- if (window.ChatListComponent === this) {
- delete window.ChatListComponent;
- }
- },
- template: `
- <div class="purple card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui purple right ribbon label">Chat</a>
- <div class="header">Chat List</div>
- <div class="description">
- View all chats with search and pagination
- </div>
- </div>
- </div>
-
- <!-- Modal ChatList -->
- <div class="ui large modal" id="modalChatList">
- <i class="close icon"></i>
- <div class="header">
- <i class="comments icon"></i>
- Chat List
- </div>
- <div class="content">
- <div class="ui form">
- <div class="fields">
- <div class="eight wide field">
- <label>Search Chats</label>
- <div class="ui icon input">
- <input type="text"
- placeholder="Search by name or JID..."
- v-model="searchQuery"
- @input="searchChats">
- <i class="search icon"></i>
- </div>
- </div>
- <div class="four wide field">
- <label>&nbsp;</label>
- <div class="ui checkbox">
- <input type="checkbox" v-model="includeMediaChats" @change="searchChats">
- <label>Media chats only</label>
- </div>
- </div>
- <div class="four wide field">
- <label>Archive Filter</label>
- <select class="ui dropdown" v-model="archiveFilter" @change="searchChats">
- <option value="">All Chats</option>
- <option value="true">Archived</option>
- <option value="false">Non-Archived</option>
- </select>
- </div>
- </div>
- </div>
-
- <div class="ui divider"></div>
-
- <div v-if="loading" class="ui active centered inline loader"></div>
-
- <div v-else-if="filteredChats.length === 0" class="ui placeholder segment">
- <div class="ui icon header">
- <i class="comments outline icon"></i>
- No chats found
- </div>
- </div>
-
- <div v-else>
- <table class="ui celled striped table">
- <thead>
- <tr>
- <th>Name</th>
- <th>Type</th>
- <th>JID</th>
- <th>Last Message</th>
- <th>Actions</th>
- </tr>
- </thead>
- <tbody>
- <tr v-for="chat in filteredChats" :key="chat.jid">
- <td>
- <div class="ui header">
- <div class="content">
- {{ chat.name || 'Unknown' }}
- </div>
- </div>
- </td>
- <td>
- <div class="ui label" :class="chat.jid?.includes('@g.us') ? 'blue' : 'green'">
- {{ formatJid(chat.jid) }}
- </div>
- </td>
- <td class="collapsing">
- <code>{{ chat.jid }}</code>
- </td>
- <td>
- {{ formatTimestamp(chat.last_message_time) }}
- </td>
- <td class="collapsing">
- <button class="ui small primary button"
- @click="selectChat(chat.jid)">
- <i class="eye icon"></i>
- View Messages
- </button>
- </td>
- </tr>
- </tbody>
- </table>
-
- <!-- Pagination -->
- <div class="ui pagination menu" v-if="totalPages > 1">
- <a class="icon item" @click="prevPage" :class="{ disabled: currentPage === 1 }">
- <i class="left chevron icon"></i>
- </a>
- <div class="item">
- Page {{ currentPage }} of {{ totalPages }}
- </div>
- <a class="icon item" @click="nextPage" :class="{ disabled: currentPage === totalPages }">
- <i class="right chevron icon"></i>
- </a>
- </div>
- </div>
- </div>
- <div class="actions">
- <div class="ui approve button">Close</div>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/ChatMessages.js b/src/views/components/ChatMessages.js
deleted file mode 100644
index 31d28350..00000000
--- a/src/views/components/ChatMessages.js
+++ /dev/null
@@ -1,780 +0,0 @@
-export default {
- name: "ChatMessages",
- data() {
- return {
- jid: "",
- messages: [],
- loading: false,
- searchQuery: "",
- startTime: "",
- endTime: "",
- isFromMe: "",
- onlyMedia: false,
- currentPage: 1,
- pageSize: 20,
- totalMessages: 0,
- // Media download tracking
- downloadedMedia: {}, // messageId -> { file_path, media_type, file_size, status }
- downloadingMedia: new Set(), // Set of messageIds currently downloading
- mediaDownloadErrors: {}, // messageId -> error message
- maxConcurrentDownloads: 3,
- currentDownloads: 0,
- // Composer state
- newMessage: "",
- attachedFile: null,
- sending: false,
- };
- },
- computed: {
- totalPages() {
- return Math.ceil(this.totalMessages / this.pageSize);
- },
- sortedMessages() {
- // Chronological order: oldest at top, newest at bottom (like a chat)
- return [...this.messages].sort(
- (a, b) => new Date(a.timestamp) - new Date(b.timestamp)
- );
- },
- formattedJid() {
- return (
- this.jid.trim() + (this.jid.includes("@") ? "" : "@s.whatsapp.net")
- );
- },
- },
- methods: {
- isValidForm() {
- return this.jid.trim().length > 0;
- },
- openModal() {
- // Check if there's a pre-selected JID from chat list
- const selectedJid = localStorage.getItem("selectedChatJid");
- if (selectedJid) {
- this.jid = selectedJid;
- localStorage.removeItem("selectedChatJid"); // Clean up
-
- this.loadMessages();
- }
-
- $("#modalChatMessages")
- .modal({
- onShow: function () {
- // Initialize accordion after modal is shown
- setTimeout(() => {
- $("#modalChatMessages .ui.accordion").accordion();
- }, 100);
- },
- })
- .modal("show");
- },
- buildQueryParams() {
- const params = new URLSearchParams({
- offset: (this.currentPage - 1) * this.pageSize,
- limit: this.pageSize,
- });
-
- if (this.searchQuery.trim()) {
- params.append("search", this.searchQuery);
- }
-
- if (this.startTime) {
- params.append("start_time", this.startTime);
- }
-
- if (this.endTime) {
- params.append("end_time", this.endTime);
- }
-
- if (this.isFromMe !== "") {
- params.append("is_from_me", this.isFromMe);
- }
-
- if (this.onlyMedia) {
- params.append("media_only", "true");
- }
-
- return params;
- },
- async loadMessages() {
- if (!this.isValidForm()) {
- showErrorInfo("Please enter a valid JID");
- return;
- }
-
- this.loading = true;
- try {
- const params = this.buildQueryParams();
-
- const response = await window.http.get(
- `/chat/${this.formattedJid}/messages?${params}`
- );
- this.messages = response.data.results?.data || [];
- this.totalMessages = response.data.results?.pagination?.total || 0;
-
- if (this.messages.length === 0) {
- showErrorInfo("No messages found for the specified criteria");
- } else {
- // Auto-download media for loaded messages
- this.downloadAllMediaInMessages();
- this.scrollToBottom();
- }
- } catch (error) {
- showErrorInfo(
- error.response?.data?.message || "Failed to load messages"
- );
- } finally {
- this.loading = false;
- }
- },
- async refreshMessages() {
- // Silent reload used after sending: no loader toggle, no error toasts
- if (!this.isValidForm()) return;
- try {
- const params = this.buildQueryParams();
- const response = await window.http.get(
- `/chat/${this.formattedJid}/messages?${params}`
- );
- this.messages = response.data.results?.data || [];
- this.totalMessages = response.data.results?.pagination?.total || 0;
- if (this.messages.length > 0) {
- this.downloadAllMediaInMessages();
- this.scrollToBottom();
- }
- } catch (error) {
- console.error("Failed to refresh messages:", error);
- }
- },
- searchMessages() {
- this.currentPage = 1;
- this.loadMessages();
- },
- nextPage() {
- if (this.currentPage < this.totalPages) {
- this.currentPage++;
- this.loadMessages();
- }
- },
- prevPage() {
- if (this.currentPage > 1) {
- this.currentPage--;
- this.loadMessages();
- }
- },
- handleReset() {
- this.jid = "";
- this.messages = [];
- this.searchQuery = "";
- this.startTime = "";
- this.endTime = "";
- this.isFromMe = "";
- this.onlyMedia = false;
- this.currentPage = 1;
- this.totalMessages = 0;
- // Clear media download state
- this.downloadedMedia = {};
- this.downloadingMedia.clear();
- this.mediaDownloadErrors = {};
- this.currentDownloads = 0;
- // Clear composer state
- this.newMessage = "";
- this.removeAttachment();
- this.sending = false;
- },
- onFileSelected(event) {
- const file = event.target.files[0];
- if (file) this.attachedFile = file;
- },
- removeAttachment() {
- this.attachedFile = null;
- const input = this.$refs.composerFileInput;
- if (input) input.value = "";
- },
- canSend() {
- return (
- this.jid.trim().length > 0 &&
- !this.sending &&
- (this.newMessage.trim().length > 0 || this.attachedFile)
- );
- },
- async sendChatMessage() {
- if (!this.canSend()) return;
- this.sending = true;
- try {
- if (this.attachedFile) {
- const file = this.attachedFile;
- const payload = new FormData();
- payload.append("phone", this.formattedJid);
-
- let endpoint;
- if (file.type.startsWith("image/")) {
- endpoint = "/send/image";
- payload.append("image", file);
- payload.append("compress", "false");
- if (this.newMessage.trim()) {
- payload.append("caption", this.newMessage.trim());
- }
- } else if (file.type.startsWith("video/")) {
- endpoint = "/send/video";
- payload.append("video", file);
- payload.append("compress", "false");
- if (this.newMessage.trim()) {
- payload.append("caption", this.newMessage.trim());
- }
- } else if (file.type.startsWith("audio/")) {
- endpoint = "/send/audio";
- payload.append("audio", file);
- } else {
- endpoint = "/send/file";
- payload.append("file", file);
- if (this.newMessage.trim()) {
- payload.append("caption", this.newMessage.trim());
- }
- }
-
- await window.http.post(endpoint, payload);
- } else {
- await window.http.post("/send/message", {
- phone: this.formattedJid,
- message: this.newMessage.trim(),
- });
- }
-
- this.newMessage = "";
- this.removeAttachment();
- showSuccessInfo("Message sent");
- this.currentPage = 1;
- await this.refreshMessages();
- // The sent message may not be persisted yet on the first refresh;
- // refresh again shortly after so the chat auto-updates.
- setTimeout(() => this.refreshMessages(), 1200);
- } catch (error) {
- showErrorInfo(
- error.response?.data?.message || "Failed to send message"
- );
- } finally {
- this.sending = false;
- }
- },
- formatTimestamp(timestamp) {
- if (!timestamp) return "N/A";
- return moment(timestamp).format("MMM DD, YYYY HH:mm:ss");
- },
- formatMessageType(message) {
- if (message.media_type) return message.media_type.toUpperCase();
- if (message.message_type) return message.message_type.toUpperCase();
- return "TEXT";
- },
- formatSender(message) {
- if (message.is_from_me) return "Me";
- return message.push_name || message.sender_jid || "Unknown";
- },
- getMessageContent(message) {
- if (message.content) return message.content;
- if (message.text) return message.text;
- if (message.caption) return message.caption;
- if (message.media_type) return `[${message.media_type.toUpperCase()}]`;
- return "[No content]";
- },
- getMediaDisplay(message) {
- if (!message.media_type || !message.url || !message.id) {
- return null;
- }
-
- const messageId = message.id;
- const downloadedInfo = this.downloadedMedia[messageId];
- const isDownloaded = this.isMediaDownloaded(messageId);
- const isDownloading = this.isMediaDownloading(messageId);
- const hasError = this.hasMediaDownloadError(messageId);
-
- // Show loading state
- if (isDownloading) {
- return {
- type: 'loading',
- content: `<div class="ui active mini inline loader"></div> Downloading ${message.media_type}...`
- };
- }
-
- // Show error state with retry option
- if (hasError) {
- return {
- type: 'error',
- content: `<div class="ui red message">
- <i class="exclamation triangle icon"></i>
- Failed to download ${message.media_type}
- <span class="ui mini button" style="cursor: pointer; margin-left: 10px;"
- onclick="document.dispatchEvent(new CustomEvent('retryMediaDownload', {detail: '${messageId}'}))">
- <i class="redo icon"></i> Retry
- </span>
- </div>`
- };
- }
-
- // Show downloaded media
- if (isDownloaded && downloadedInfo) {
- const filePath = downloadedInfo.file_path;
- const mediaType = downloadedInfo.media_type;
- const filename = downloadedInfo.filename;
- const fileSize = downloadedInfo.file_size;
-
- switch (mediaType.toLowerCase()) {
- case 'image':
- return {
- type: 'image',
- content: `<div class="ui fluid image">
- <img src="${filePath}" alt="${filename}" style="max-width: 300px; max-height: 300px; border-radius: 4px;"
- onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">
- <div style="display: none;" class="ui placeholder segment">
- <div class="ui icon header">
- <i class="image outline icon"></i>
- Image not available
- </div>
- </div>
- </div>`
- };
-
- case 'video':
- return {
- type: 'video',
- content: `<div class="ui fluid">
- <video controls style="max-width: 300px; max-height: 300px; border-radius: 4px;" preload="metadata">
- <source src="${filePath}" type="video/mp4">
- <source src="${filePath}" type="video/webm">
- <source src="${filePath}" type="video/ogg">
- Your browser does not support the video tag.
- </video>
- </div>`
- };
-
- case 'audio':
- return {
- type: 'audio',
- content: `<div class="ui fluid">
- <audio controls style="width: 100%; max-width: 300px;">
- <source src="${filePath}" type="audio/mpeg">
- <source src="${filePath}" type="audio/ogg">
- <source src="${filePath}" type="audio/wav">
- Your browser does not support the audio tag.
- </audio>
- </div>`
- };
-
- case 'document':
- const sizeText = fileSize ? `(${Math.round(fileSize / 1024)} KB)` : '';
- return {
- type: 'document',
- content: `<div class="ui labeled button">
- <a href="${filePath}" download="${filename}" class="ui button">
- <i class="download icon"></i>
- ${filename} ${sizeText}
- </a>
- <div class="ui basic left pointing label">
- Document
- </div>
- </div>`
- };
-
- case 'sticker':
- return {
- type: 'sticker',
- content: `<div class="ui">
- <img src="${filePath}" alt="Sticker" style="max-width: 150px; max-height: 150px; border-radius: 4px;"
- onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">
- <div style="display: none;" class="ui placeholder segment">
- <div class="ui icon header">
- <i class="smile outline icon"></i>
- Sticker not available
- </div>
- </div>
- </div>`
- };
-
- default:
- return {
- type: 'unknown',
- content: `<div class="ui message">
- <i class="file icon"></i>
- Unknown media type: ${mediaType}
- </div>`
- };
- }
- }
-
- // Default: show media available label
- return {
- type: 'available',
- content: `<div class="ui tiny blue label">
- <i class="linkify icon"></i>
- ${message.media_type.toUpperCase()} Available
- </div>`
- };
- },
- getMessageStyle(message) {
- const baseStyle = {
- maxWidth: "75%",
- minWidth: "140px",
- padding: "0.6em 0.9em",
- borderRadius: "12px",
- boxShadow: "0 1px 1px rgba(0,0,0,0.12)",
- overflowWrap: "break-word",
- wordBreak: "break-word",
- };
-
- if (message.is_from_me) {
- return {
- ...baseStyle,
- backgroundColor: "#d9fdd3",
- borderTopRightRadius: "4px",
- };
- } else {
- return {
- ...baseStyle,
- backgroundColor: "#ffffff",
- borderTopLeftRadius: "4px",
- };
- }
- },
- scrollToBottom() {
- this.$nextTick(() => {
- const container = this.$refs.messagesContainer;
- if (container) {
- container.scrollTop = container.scrollHeight;
- }
- });
- },
- // Media download methods
- isMediaDownloaded(messageId) {
- return this.downloadedMedia[messageId] && this.downloadedMedia[messageId].status === 'completed';
- },
- isMediaDownloading(messageId) {
- return this.downloadingMedia.has(messageId);
- },
- hasMediaDownloadError(messageId) {
- return !!this.mediaDownloadErrors[messageId];
- },
- async downloadMediaForMessage(message) {
- if (!message.media_type || !message.url || !message.id) {
- return;
- }
-
- const messageId = message.id;
-
- // Skip if already downloaded or downloading
- if (this.isMediaDownloaded(messageId) || this.isMediaDownloading(messageId)) {
- return;
- }
-
- // Check concurrent download limit
- if (this.currentDownloads >= this.maxConcurrentDownloads) {
- return;
- }
-
- try {
- this.downloadingMedia.add(messageId);
- this.currentDownloads++;
-
- // Clear any previous error
- if (this.mediaDownloadErrors[messageId]) {
- delete this.mediaDownloadErrors[messageId];
- }
-
- const response = await window.http.get(
- `/message/${messageId}/download?phone=${this.formattedJid}`
- );
-
- if (response.data && response.data.results) {
- this.downloadedMedia[messageId] = {
- file_path: response.data.results.file_path,
- media_type: response.data.results.media_type,
- file_size: response.data.results.file_size,
- filename: response.data.results.filename,
- status: 'completed'
- };
- }
- } catch (error) {
- console.error(`Failed to download media for message ${messageId}:`, error);
- this.mediaDownloadErrors[messageId] = error.response?.data?.message || 'Download failed';
- } finally {
- this.downloadingMedia.delete(messageId);
- this.currentDownloads--;
- }
- },
- async retryMediaDownload(messageId) {
- const message = this.messages.find(m => m.id === messageId);
- if (message) {
- // Clear the error first
- delete this.mediaDownloadErrors[messageId];
- await this.downloadMediaForMessage(message);
- }
- },
- async downloadAllMediaInMessages() {
- const mediaMessages = this.messages.filter(message =>
- message.media_type && message.url && message.id &&
- !this.isMediaDownloaded(message.id) && !this.isMediaDownloading(message.id)
- );
-
- if (mediaMessages.length === 0) {
- return;
- }
-
- // Download in batches to respect concurrency limit
- const downloadQueue = [...mediaMessages];
-
- const processQueue = async () => {
- while (downloadQueue.length > 0 && this.currentDownloads < this.maxConcurrentDownloads) {
- const message = downloadQueue.shift();
- if (message) {
- await this.downloadMediaForMessage(message);
- // Small delay to prevent overwhelming the server
- await new Promise(resolve => setTimeout(resolve, 100));
- }
- }
-
- // If there are still items in queue and we can download more, continue
- if (downloadQueue.length > 0 && this.currentDownloads < this.maxConcurrentDownloads) {
- setTimeout(processQueue, 500); // Wait a bit before checking again
- }
- };
-
- // Start processing
- processQueue();
- },
- backToChatList() {
- // Close current modal
- $('#modalChatMessages').modal('hide');
-
- // Open Chat List modal after a short delay
- setTimeout(() => {
- if (window.ChatListComponent && window.ChatListComponent.openModal) {
- window.ChatListComponent.openModal();
- } else {
- // Fallback: try to find and click the Chat List card
- const chatListCards = document.querySelectorAll('.card .header');
- for (let card of chatListCards) {
- if (card.textContent.includes('Chat List')) {
- card.click();
- break;
- }
- }
- }
- }, 200);
- },
- },
- mounted() {
- // Expose the openModal method globally for ChatList component to call
- window.ChatMessagesComponent = this;
-
- // Handle retry media download events
- this.handleRetryMediaDownload = (event) => {
- const messageId = event.detail;
- this.retryMediaDownload(messageId);
- };
-
- // Listen for retry media download events
- document.addEventListener('retryMediaDownload', this.handleRetryMediaDownload);
- },
- beforeUnmount() {
- // Clean up global reference
- if (window.ChatMessagesComponent === this) {
- delete window.ChatMessagesComponent;
- }
-
- // Clean up event listeners
- if (this.handleRetryMediaDownload) {
- document.removeEventListener('retryMediaDownload', this.handleRetryMediaDownload);
- }
- },
- template: `
- <div class="purple card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui purple right ribbon label">Chat</a>
- <div class="header">Chat Messages</div>
- <div class="description">
- View messages from specific chats with advanced filtering
- </div>
- </div>
- </div>
-
- <!-- Modal ChatMessages -->
- <div class="ui large modal" id="modalChatMessages">
- <i class="close icon"></i>
- <div class="header">
- <i class="comment icon"></i>
- Chat Messages
- </div>
- <div class="content">
- <div class="ui form">
- <div class="field">
- <label>Chat JID</label>
- <input type="text"
- placeholder="Enter phone number or full JID (e.g. 1234567890 or [email protected])"
- v-model="jid">
- </div>
-
- <div class="ui accordion">
- <div class="title">
- <i class="dropdown icon"></i>
- Advanced Filters (Optional)
- </div>
- <div class="content">
- <div class="fields">
- <div class="eight wide field">
- <label>Search Message Content</label>
- <input type="text"
- placeholder="Search in message text..."
- v-model="searchQuery">
- </div>
- <div class="four wide field">
- <label>Sender Filter</label>
- <select class="ui dropdown" v-model="isFromMe">
- <option value="">All messages</option>
- <option value="true">My messages</option>
- <option value="false">Their messages</option>
- </select>
- </div>
- <div class="four wide field">
- <label>&nbsp;</label>
- <div class="ui checkbox">
- <input type="checkbox" v-model="onlyMedia">
- <label>Media only</label>
- </div>
- </div>
- </div>
-
- <div class="fields">
- <div class="eight wide field">
- <label>Start Date/Time</label>
- <input type="datetime-local" v-model="startTime">
- </div>
- <div class="eight wide field">
- <label>End Date/Time</label>
- <input type="datetime-local" v-model="endTime">
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <div class="ui divider"></div>
-
- <div class="actions">
- <button class="ui primary button"
- :class="{'disabled': !isValidForm() || loading}"
- @click="loadMessages">
- <i class="search icon"></i>
- {{ loading ? 'Loading...' : 'Load Messages' }}
- </button>
- <button class="ui button" @click="handleReset">
- <i class="refresh icon"></i>
- Reset
- </button>
- </div>
-
- <div v-if="loading" class="ui active centered inline loader"></div>
-
- <div v-else-if="messages.length === 0 && totalMessages === 0" class="ui placeholder segment">
- <div class="ui icon header">
- <i class="comment outline icon"></i>
- No messages loaded
- </div>
- <p>Enter a JID and click "Load Messages" to view chat history</p>
- </div>
-
- <div v-else-if="messages.length > 0" style="margin-top: 1em;">
- <div style="display: flex; align-items: center; justify-content: space-between; background: #f0f2f5; border-radius: 8px 8px 0 0; padding: 0.65em 1em; border-bottom: 1px solid #e0e0e0;">
- <div style="font-weight: bold; color: #111b21; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
- <i class="comments icon" style="color: #54656f;"></i>
- {{ formattedJid }}
- </div>
- <div style="font-size: 0.85em; color: #667781; white-space: nowrap; margin-left: 1em;">
- {{ messages.length }} of {{ totalMessages }} messages
- </div>
- </div>
-
- <div ref="messagesContainer"
- style="max-height: 400px; overflow-y: auto; overflow-x: hidden; -webkit-overflow-scrolling: touch; scrollbar-width: thin; background: #efeae2; border-radius: 0 0 8px 8px; padding: 1em;">
- <div v-for="message in sortedMessages" :key="message.id"
- style="display: flex; margin-bottom: 0.75em;"
- :style="{ justifyContent: message.is_from_me ? 'flex-end' : 'flex-start' }">
- <div :style="getMessageStyle(message)">
- <div v-if="!message.is_from_me"
- style="font-size: 0.8em; font-weight: bold; color: #d35400; margin-bottom: 0.25em; word-break: break-all;">
- {{ formatSender(message) }}
- </div>
- <div style="white-space: pre-wrap;">{{ getMessageContent(message) }}</div>
- <div v-if="message.media_type && message.url" class="media-container" style="margin-top: 0.5em;">
- <div v-if="getMediaDisplay(message)" v-html="getMediaDisplay(message).content"></div>
- </div>
- <div style="font-size: 0.72em; color: rgba(0,0,0,0.45); margin-top: 0.35em; text-align: right;">
- <span v-if="formatMessageType(message) !== 'TEXT'"
- style="text-transform: uppercase; margin-right: 0.5em; font-weight: bold;">
- {{ formatMessageType(message) }}
- </span>
- <span>{{ formatTimestamp(message.timestamp) }}</span>
- </div>
- <div v-if="message.id"
- :title="message.id"
- style="font-size: 0.65em; color: rgba(0,0,0,0.3); font-family: monospace; word-break: break-all; text-align: right; margin-top: 0.15em;">
- {{ message.id }}
- </div>
- </div>
- </div>
- </div>
-
- <!-- Pagination -->
- <div class="ui pagination menu" v-if="totalPages > 1">
- <a class="icon item" @click="prevPage" :class="{ disabled: currentPage === 1 }">
- <i class="left chevron icon"></i>
- </a>
- <div class="item">
- Page {{ currentPage }} of {{ totalPages }}
- </div>
- <a class="icon item" @click="nextPage" :class="{ disabled: currentPage === totalPages }">
- <i class="right chevron icon"></i>
- </a>
- </div>
- </div>
-
- <!-- Composer -->
- <div v-if="jid.trim().length > 0" style="margin-top: 0.75em;">
- <div v-if="attachedFile"
- style="display: inline-flex; align-items: center; gap: 0.5em; background: #e7f3ff; border: 1px solid #b3d9f7; border-radius: 16px; padding: 0.35em 0.85em; margin-bottom: 0.5em; font-size: 0.9em;">
- <i class="paperclip icon" style="margin: 0; color: #2185d0;"></i>
- <span style="max-width: 260px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
- {{ attachedFile.name }}
- </span>
- <i class="close icon" @click="removeAttachment"
- style="margin: 0; cursor: pointer; color: #999;"
- title="Remove attachment"></i>
- </div>
- <div style="display: flex; align-items: center; gap: 0.5em; background: #f0f2f5; border-radius: 24px; padding: 0.4em 0.5em;">
- <input type="file" ref="composerFileInput" style="display: none;" @change="onFileSelected">
- <button class="ui circular basic icon button"
- style="box-shadow: none; margin: 0;"
- @click="$refs.composerFileInput.click()"
- title="Attach media">
- <i class="paperclip icon" style="color: #54656f;"></i>
- </button>
- <input type="text"
- :placeholder="attachedFile ? 'Add a caption (optional)...' : 'Type a message...'"
- v-model="newMessage"
- @keyup.enter="sendChatMessage"
- style="flex: 1; border: none; outline: none; background: #ffffff; border-radius: 18px; padding: 0.65em 1em; font-size: 1em; min-width: 0;">
- <button class="ui circular primary icon button"
- :class="{ 'disabled': !canSend(), 'loading': sending }"
- style="margin: 0;"
- @click="sendChatMessage"
- title="Send message">
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- </div>
- <div class="actions">
- <button class="ui button" @click="backToChatList">
- <i class="arrow left icon"></i>
- Back to Chat List
- </button>
- <div class="ui approve button">Close</div>
- </div>
- </div>
- `,
-};
diff --git a/src/views/components/ChatPinManager.js b/src/views/components/ChatPinManager.js
deleted file mode 100644
index e20394e5..00000000
--- a/src/views/components/ChatPinManager.js
+++ /dev/null
@@ -1,108 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'ChatPinManager',
- components: {
- FormRecipient
- },
- data() {
- return {
- type: window.TYPEUSER,
- phone: '',
- pinned: true,
- loading: false,
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- },
- },
- methods: {
- isValidForm() {
- const isPhoneValid = this.phone.trim().length > 0;
- return isPhoneValid;
- },
- openModal() {
- $('#modalChatPin').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- const response = await this.submitApi();
- showSuccessInfo(response);
- $('#modalChatPin').modal('hide');
- } catch (err) {
- showErrorInfo(err);
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- const payload = {
- pinned: this.pinned
- };
-
- const response = await window.http.post(`/chat/${this.phone_id}/pin`, payload);
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response?.data?.message) {
- throw new Error(error.response.data.message);
- }
- throw error;
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.phone = '';
- this.pinned = true;
- },
- },
- template: `
- <div class="purple card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui purple right ribbon label">Chat</a>
- <div class="header">Pin Chat</div>
- <div class="description">
- Pin or unpin chats to the top of the list
- </div>
- </div>
- </div>
-
- <!-- Modal ChatPin -->
- <div class="ui small modal" id="modalChatPin">
- <i class="close icon"></i>
- <div class="header">
- Pin Chat
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone" :show-status="false"/>
- <div class="field">
- <label>Action</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="pinned" v-model="pinned">
- <label>Pin chat (uncheck to unpin)</label>
- </div>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button"
- :class="{'disabled': !isValidForm() || loading}"
- @click.prevent="handleSubmit">
- {{ pinned ? 'Pin Chat' : 'Unpin Chat' }}
- <i class="pin icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/DeviceManager.js b/src/views/components/DeviceManager.js
deleted file mode 100644
index c8ae808a..00000000
--- a/src/views/components/DeviceManager.js
+++ /dev/null
@@ -1,277 +0,0 @@
-export default {
- name: 'DeviceManager',
- props: {
- wsBasePath: {
- type: String,
- default: ''
- }
- },
- data() {
- return {
- deviceList: [],
- selectedDeviceId: '',
- deviceIdInput: '',
- isCreatingDevice: false,
- deviceToDelete: { id: '', jid: '', state: '' },
- isDeleting: false,
- webhookUrlInput: '',
- webhookSecretInput: '',
- webhookEventsInput: '',
- webhookInsecureSkipVerify: false
- }
- },
- computed: {
- selectedDevice() {
- if (!this.selectedDeviceId) return null;
- return this.deviceList.find(d => (d.id || d.device) === this.selectedDeviceId) || null;
- },
- isSelectedDeviceLoggedIn() {
- return this.selectedDevice?.state === 'logged_in';
- }
- },
- methods: {
- async fetchDevices() {
- try {
- const res = await window.http.get(`/devices`);
- this.deviceList = res.data.results || [];
- if (!this.selectedDeviceId && this.deviceList.length > 0) {
- const first = this.deviceList[0].id || this.deviceList[0].device;
- this.setDeviceContext(first);
- }
- // Emit devices to parent for other components
- this.$emit('devices-updated', this.deviceList);
- } catch (err) {
- console.error(err);
- }
- },
- setDeviceContext(id) {
- if (!id) {
- showErrorInfo('Device ID is required');
- return;
- }
- this.selectedDeviceId = id;
- this.$emit('device-selected', id);
- showSuccessInfo(`Using device ${id}`);
- },
- async createDevice() {
- try {
- this.isCreatingDevice = true;
- const payload = this.deviceIdInput ? {device_id: this.deviceIdInput} : {};
- if (this.webhookUrlInput) {
- payload.webhook_url = this.webhookUrlInput;
- }
- if (this.webhookSecretInput) {
- payload.webhook_secret = this.webhookSecretInput;
- }
- if (this.webhookEventsInput) {
- payload.webhook_events = this.webhookEventsInput;
- }
- if (this.webhookInsecureSkipVerify) {
- payload.webhook_insecure_skip_verify = this.webhookInsecureSkipVerify;
- }
- const res = await window.http.post('/devices', payload);
- const deviceID = res.data?.results?.id || res.data?.results?.device_id || this.deviceIdInput;
- this.setDeviceContext(deviceID);
- this.deviceIdInput = '';
- this.webhookUrlInput = '';
- this.webhookSecretInput = '';
- this.webhookEventsInput = '';
- this.webhookInsecureSkipVerify = false;
- } catch (err) {
- const msg = err.response?.data?.message || err.message || 'Failed to create device';
- showErrorInfo(msg);
- } finally {
- this.isCreatingDevice = false;
- }
- },
- useDeviceFromInput() {
- if (!this.deviceIdInput) {
- showErrorInfo('Enter a device_id or create one first.');
- return;
- }
- this.setDeviceContext(this.deviceIdInput);
- },
- openDeleteModal(deviceId, jid) {
- const device = this.deviceList.find(d => (d.id || d.device) === deviceId);
- this.deviceToDelete = { id: deviceId, jid: jid || '', state: device?.state || '' };
- $('#deleteDeviceModal').modal({
- closable: false,
- onApprove: () => {
- this.executeDelete();
- return false;
- },
- onDeny: () => {
- this.resetDeleteState();
- }
- }).modal('show');
- },
- resetDeleteState() {
- this.deviceToDelete = { id: '', jid: '', state: '' };
- this.isDeleting = false;
- },
- async executeDelete() {
- const deviceId = this.deviceToDelete.id;
- if (!deviceId) {
- showErrorInfo('No device selected for deletion');
- return;
- }
- try {
- this.isDeleting = true;
-
- // DELETE owns the full purge/logout flow: it logs the device out of
- // WhatsApp and clears its session before removing the slot. Firing a
- // separate /app/logout here would race the DELETE response and could
- // make a removed slot momentarily reappear, so we don't.
- await window.http.delete(`/devices/${encodeURIComponent(deviceId)}`);
- showSuccessInfo(`Device ${deviceId} deleted successfully`);
- $('#deleteDeviceModal').modal('hide');
-
- if (this.selectedDeviceId === deviceId) {
- this.selectedDeviceId = '';
- this.$emit('device-selected', '');
- }
-
- await this.fetchDevices();
- this.resetDeleteState();
- } catch (err) {
- const msg = err.response?.data?.message || err.message || 'Failed to delete device';
- showErrorInfo(msg);
- this.isDeleting = false;
- }
- },
- // Called by parent to refresh devices
- refresh() {
- this.fetchDevices();
- },
- // Called by parent to update device list from websocket
- updateDeviceList(devices) {
- if (Array.isArray(devices)) {
- this.deviceList = devices;
- this.$emit('devices-updated', devices);
- }
- }
- },
- mounted() {
- this.fetchDevices();
- },
- template: `
- <div class="ui stackable grid">
- <div class="ten wide column">
- <div class="ui segment">
- <h3 class="ui header">
- <i class="play icon"></i>
- <div class="content">
- Device setup
- <div class="sub header">Create or select a device_id, then open login.</div>
- </div>
- </h3>
- <div class="ui form">
- <div class="fields">
- <div class="field">
- <label>Device ID (optional)</label>
- <input type="text" v-model="deviceIdInput" placeholder="Leave empty to auto-generate">
- </div>
- </div>
- <div class="fields">
- <div class="field">
- <label>Webhook URL (optional)</label>
- <input type="text" v-model="webhookUrlInput" placeholder="https://your-webhook.com/handler">
- </div>
- <div class="field">
- <label>Webhook Secret (optional)</label>
- <input type="text" v-model="webhookSecretInput" placeholder="secret-key">
- </div>
- </div>
- <div class="fields">
- <div class="field">
- <label>Webhook Events (optional, comma-separated)</label>
- <input type="text" v-model="webhookEventsInput" placeholder="message,message.ack,group.participants">
- </div>
- <div class="field">
- <label>Skip TLS Verify</label>
- <div class="ui checkbox">
- <input type="checkbox" v-model="webhookInsecureSkipVerify">
- <label></label>
- </div>
- </div>
- </div>
- <div class="ui buttons">
- <button class="ui primary button" :class="{loading: isCreatingDevice}" @click="createDevice">
- Create device
- </button>
- <div class="or"></div>
- <button class="ui button" @click="useDeviceFromInput">Use this device</button>
- </div>
- </div>
- <div class="ui divider"></div>
-
- <!-- Device List -->
- <div class="ui relaxed list" v-if="deviceList.length">
- <div class="item" v-for="dev in deviceList" :key="dev.id || dev.device">
- <i class="mobile alternate icon"></i>
- <div class="content">
- <div class="header">{{ dev.id || dev.device }}</div>
- <div class="description">
- <span>State: {{ dev.state || 'unknown' }}</span>
- <span v-if="dev.jid"> · JID: {{ dev.jid }}</span>
- </div>
- </div>
- <div class="right floated content">
- <button class="ui mini button"
- :class="{active: selectedDeviceId === (dev.id || dev.device)}"
- @click="setDeviceContext(dev.id || dev.device)">
- {{ selectedDeviceId === (dev.id || dev.device) ? 'Selected' : 'Use' }}
- </button>
- <button class="ui mini red icon button"
- @click="openDeleteModal(dev.id || dev.device, dev.jid)"
- :class="{loading: isDeleting && deviceToDelete.id === (dev.id || dev.device)}">
- <i class="trash icon" style="margin: 0;"></i>
- </button>
- </div>
- </div>
- </div>
- <div class="ui message" v-else>
- No devices yet. Create one to begin.
- </div>
- </div>
- </div>
- <div class="six wide column">
- <div class="ui warning message">
- <div class="header">How to log in</div>
- <ul class="list">
- <li>Step 1: Create a device to get <code>device_id</code>.</li>
- <li>Step 2: Send <code>X-Device-Id: device_id</code> on REST calls.</li>
- <li>Step 3: Open Login card to pair (QR or code).</li>
- <li>WebSocket URL: <code>{{ wsBasePath }}/ws?device_id=&lt;device_id&gt;</code></li>
- </ul>
- </div>
- </div>
-
- <!-- Delete Device Confirmation Modal -->
- <div class="ui small modal" id="deleteDeviceModal">
- <div class="header">
- <i class="trash alternate icon"></i>
- Confirm Delete Device
- </div>
- <div class="content">
- <p>Are you sure you want to delete this device?</p>
- <div class="ui segment">
- <p><strong>Device ID:</strong> <code>{{ deviceToDelete.id }}</code></p>
- <p v-if="deviceToDelete.jid"><strong>JID:</strong> <code>{{ deviceToDelete.jid }}</code></p>
- </div>
- <div class="ui warning message">
- <div class="header">Warning</div>
- <p>This action will permanently delete the device and all associated data including chats and messages. This cannot be undone.</p>
- </div>
- </div>
- <div class="actions">
- <button class="ui cancel button">Cancel</button>
- <button class="ui red approve button" :class="{loading: isDeleting}">
- <i class="trash icon"></i>
- Delete Device
- </button>
- </div>
- </div>
- </div>
- `
-}
diff --git a/src/views/components/GroupCreate.js b/src/views/components/GroupCreate.js
deleted file mode 100644
index 81fc4d30..00000000
--- a/src/views/components/GroupCreate.js
+++ /dev/null
@@ -1,141 +0,0 @@
-export default {
- name: 'CreateGroup',
- data() {
- return {
- loading: false,
- title: '',
- participants: ['', ''],
- }
- },
- methods: {
- openModal() {
- $('#modalGroupCreate').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- // title must contain at least one non-whitespace char
- if (!String(this.title ?? '').trim()) {
- return false;
- }
-
- // must have at least one valid participant
- if (
- this.participants.length < 1 ||
- this.participants.every(p => this.isEmpty(p))
- ) {
- return false;
- }
-
- return true;
- },
- // Helper: returns true when param is empty/blank
- isEmpty(value) {
- // If the element is an object coming from the picker, use its jid field
- const str = String(value?.jid ?? value).trim();
- return !str;
- },
- handleAddParticipant() {
- this.participants.push('')
- },
- handleDeleteParticipant(index) {
- this.participants.splice(index, 1)
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalGroupCreate').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let response = await window.http.post(`/group`, {
- title: this.title,
- // sanitize participants list
- participants: this.participants
- .filter(p => !this.isEmpty(p))
- .map(p => `${p?.jid ?? p}`)
- })
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.title = '';
- this.participants = ['', ''];
- },
- },
- template: `
- <div class="green card" @click="openModal" style="cursor: pointer">
- <div class="content">
- <a class="ui green right ribbon label">Group</a>
- <div class="header">Create Groups</div>
- <div class="description">
- Add more friends to your group
- </div>
- </div>
- </div>
-
- <!-- Modal AccountGroup -->
- <div class="ui small modal" id="modalGroupCreate">
- <i class="close icon"></i>
- <div class="header">
- Create Group
- </div>
- <div class="content">
- <form class="ui form">
- <div class="field">
- <label>Group Name</label>
- <input v-model="title" type="text"
- placeholder="Group Name..."
- aria-label="Group Name">
- </div>
-
- <div class="field">
- <label>Participants</label>
- <div style="display: flex; flex-direction: column; gap: 5px">
- <div class="ui action input" :key="index" v-for="(participant, index) in participants">
- <input type="number" placeholder="Phone Int Number (6289...)" v-model="participants[index]"
- aria-label="list participant">
- <button class="ui button" @click="handleDeleteParticipant(index)" type="button">
- <i class="minus circle icon"></i>
- </button>
- </div>
- <div class="field" style="display: flex; flex-direction: column; gap: 3px">
- <small>You do not need to include yourself as participant. it will be automatically included.</small>
- <div>
- <button class="mini ui primary button" @click="handleAddParticipant" type="button">
- <i class="plus icon"></i> Option
- </button>
- </div>
- </div>
- </div>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button" :class="{'loading': this.loading, 'disabled': !this.isValidForm() || this.loading}"
- @click.prevent="handleSubmit" type="button">
- Create
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/GroupGetInviteLink.js b/src/views/components/GroupGetInviteLink.js
deleted file mode 100644
index 074e5a76..00000000
--- a/src/views/components/GroupGetInviteLink.js
+++ /dev/null
@@ -1,238 +0,0 @@
-export default {
- name: 'GroupGetInviteLink',
- components: {},
- data() {
- return {
- group_id: '',
- inviteLink: '',
- resetLink: false,
- loading: false,
- copying: false,
- }
- },
- computed: {
- fullGroupID() {
- if (!this.group_id) return '';
- // Ensure suffix
- if (this.group_id.endsWith(window.TYPEGROUP)) {
- return this.group_id;
- }
- return this.group_id + window.TYPEGROUP;
- },
- isValidForm() {
- return this.group_id.trim() !== '';
- },
- displayGroupID() {
- if (!this.group_id) return '';
- // Show the full ID with suffix for clarity
- return this.fullGroupID;
- }
- },
- methods: {
- openModal() {
- this.reset();
- $('#modalGroupGetInviteLink').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- async handleSubmit() {
- if (!this.isValidForm || this.loading) return;
- try {
- await this.getInviteLink();
- if (this.inviteLink) {
- showSuccessInfo('Group invite link fetched successfully!');
- } else {
- showErrorInfo('No invite link received from the server');
- }
- } catch (err) {
- showErrorInfo(err.message || err);
- }
- },
- async getInviteLink() {
- this.loading = true;
- try {
- const response = await window.http.get(`/group/invite-link`, {
- params: {
- group_id: this.fullGroupID,
- reset: this.resetLink
- }
- });
- if (response.data.results && typeof response.data.results.invite_link === 'string') {
- this.inviteLink = response.data.results.invite_link;
- } else if (response.data && typeof response.data.invite_link === 'string') {
- this.inviteLink = response.data.invite_link;
- } else if (typeof response.data.results === 'string') {
- this.inviteLink = response.data.results;
- } else if (typeof response.data === 'string') {
- this.inviteLink = response.data;
- } else {
- this.inviteLink = '';
- }
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message || error.response.data);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- reset() {
- this.group_id = '';
- this.inviteLink = '';
- this.resetLink = false;
- this.loading = false;
- this.copying = false;
- },
- async copyToClipboard() {
- if (this.inviteLink) {
- this.copying = true;
- try {
- // Try modern clipboard API first
- if (navigator.clipboard && navigator.clipboard.writeText) {
- await navigator.clipboard.writeText(this.inviteLink);
- showSuccessInfo('✅ Invite link copied to clipboard!');
- } else {
- // Fallback for older browsers
- this.fallbackCopyToClipboard();
- }
- } catch (err) {
- console.error('Clipboard API failed:', err);
- this.fallbackCopyToClipboard();
- } finally {
- this.copying = false;
- }
- } else {
- showErrorInfo('No invite link to copy');
- }
- },
- fallbackCopyToClipboard() {
- try {
- // Create a temporary input element
- const tempInput = document.createElement('input');
- tempInput.style.position = 'absolute';
- tempInput.style.left = '-9999px';
- tempInput.value = this.inviteLink;
- document.body.appendChild(tempInput);
-
- // Select and copy
- tempInput.select();
- tempInput.setSelectionRange(0, 99999); // For mobile devices
-
- const successful = document.execCommand('copy');
- document.body.removeChild(tempInput);
-
- if (successful) {
- showSuccessInfo('✅ Invite link copied to clipboard!');
- } else {
- showErrorInfo('❌ Failed to copy. Please select and copy manually.');
- }
- } catch (err) {
- console.error('Fallback copy failed:', err);
- showErrorInfo('❌ Failed to copy. Please select and copy manually.');
- }
- },
- closeModal() {
- $('#modalGroupGetInviteLink').modal('hide');
- },
- handleGroupIDInput() {
- // Auto-correct the input if it's just numbers
- const input = this.group_id.trim();
- if (input && !input.includes('@') && !input.includes('g.us')) {
- // If it's just numbers, assume it's a group ID
- this.group_id = input + window.TYPEGROUP;
- }
- }
- },
- template: `
- <div class="green card" @click="openModal" style="cursor: pointer;">
- <div class="content">
- <a class="ui green right ribbon label">Group</a>
- <div class="header">Get Group Invite Link</div>
- <div class="description">
- Get invite link for a group
- </div>
- </div>
- </div>
-
- <!-- Modal -->
- <div class="ui modal" id="modalGroupGetInviteLink">
- <i class="close icon"></i>
- <div class="header">
- <i class="linkify icon"></i>
- Get Group Invite Link
- </div>
- <div class="content">
- <form class="ui form">
- <div class="field">
- <label>Group ID</label>
- <input type="text" v-model="group_id"
- placeholder="Enter group ID (e.g., 120363419080717833)"
- @blur="handleGroupIDInput"
- @input="handleGroupIDInput">
- <div class="ui tiny info message">
- <i class="info circle icon"></i>
- <div class="content">
- <p>You can enter just the numbers (e.g., 120363419080717833) - the @g.us suffix will be added automatically.</p>
- </div>
- </div>
- <div v-if="group_id && displayGroupID !== group_id" class="ui info message">
- <i class="info circle icon"></i>
- <div class="content">
- <div class="header">Auto-corrected Group ID</div>
- <p>Your input: <code>{{ group_id }}</code></p>
- <p>Will use: <code>{{ displayGroupID }}</code></p>
- </div>
- </div>
- </div>
-
- <div class="field">
- <div class="ui checkbox">
- <input type="checkbox" v-model="resetLink" id="resetInviteLink">
- <label for="resetInviteLink">Reset invite link (revoke old link)</label>
- </div>
- </div>
-
- <div class="ui divider"></div>
-
- <div v-if="inviteLink" class="field">
- <label>Invite Link</label>
- <div class="ui action input">
- <input type="text" :value="inviteLink" readonly
- style="font-family: monospace; background-color: #f8f9fa; cursor: text;"
- @click="$event.target.select()"
- @focus="$event.target.select()">
- <button type="button" class="ui blue button" @click="copyToClipboard" :class="{'loading': copying}">
- <i class="copy icon"></i>
- <span v-if="copying">Copying...</span>
- <span v-else>Copy</span>
- </button>
- </div>
- <div class="ui info message">
- <i class="info circle icon"></i>
- <div class="content">
- <div class="header">Invite Link Generated</div>
- <p>Share this link with others to invite them to the group.</p>
- </div>
- </div>
- </div>
-
- <div class="ui divider"></div>
-
- <button type="button" class="ui approve positive right labeled icon button"
- :class="{'loading': loading, 'disabled': !isValidForm || loading}"
- @click.prevent="handleSubmit">
- <span v-if="loading">Fetching...</span>
- <span v-else>Get Invite Link</span>
- <i class="linkify icon"></i>
- </button>
- </form>
- </div>
- <div class="actions">
- <div class="ui approve button" @click="closeModal">Close</div>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/GroupInfo.js b/src/views/components/GroupInfo.js
deleted file mode 100644
index f1a4e282..00000000
--- a/src/views/components/GroupInfo.js
+++ /dev/null
@@ -1,349 +0,0 @@
-export default {
- name: 'GroupInfo',
- components: {},
- data() {
- return {
- group_id: '',
- groupInfo: null,
- loading: false,
- }
- },
- computed: {
- fullGroupID() {
- if (!this.group_id) return '';
- // Ensure suffix
- if (this.group_id.endsWith(window.TYPEGROUP)) {
- return this.group_id;
- }
- return this.group_id + window.TYPEGROUP;
- },
- formattedGroupCreated() {
- if (!this.groupInfo?.GroupCreated) return '';
- return new Date(this.groupInfo.GroupCreated).toLocaleString();
- },
- formattedNameSetAt() {
- if (!this.groupInfo?.NameSetAt) return '';
- return new Date(this.groupInfo.NameSetAt).toLocaleString();
- },
- formattedTopicSetAt() {
- if (!this.groupInfo?.TopicSetAt) return '';
- return new Date(this.groupInfo.TopicSetAt).toLocaleString();
- },
- disappearingTimerText() {
- if (!this.groupInfo?.DisappearingTimer) return '';
- const days = Math.floor(this.groupInfo.DisappearingTimer / (24 * 60 * 60));
- const hours = Math.floor((this.groupInfo.DisappearingTimer % (24 * 60 * 60)) / (60 * 60));
- const minutes = Math.floor((this.groupInfo.DisappearingTimer % (60 * 60)) / 60);
-
- if (days > 0) return `${days} day${days > 1 ? 's' : ''}`;
- if (hours > 0) return `${hours} hour${hours > 1 ? 's' : ''}`;
- if (minutes > 0) return `${minutes} minute${minutes > 1 ? 's' : ''}`;
- return `${this.groupInfo.DisappearingTimer} second${this.groupInfo.DisappearingTimer > 1 ? 's' : ''}`;
- }
- },
- methods: {
- openModal() {
- this.reset();
- $('#modalGroupInfo').modal('show');
- },
- isValidForm() {
- return this.group_id.trim() !== '';
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) return;
- try {
- await this.fetchInfo();
- showSuccessInfo('Group info fetched');
- } catch (err) {
- showErrorInfo(err.message || err);
- }
- },
- async fetchInfo() {
- this.loading = true;
- try {
- const response = await window.http.get('/group/info', {
- params: { group_id: this.fullGroupID }
- });
- this.groupInfo = response.data.results;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- reset() {
- this.group_id = '';
- this.groupInfo = null;
- this.loading = false;
- },
- formatPhoneNumber(phone) {
- if (!phone) return '';
- return phone.replace('@s.whatsapp.net', '');
- },
- getParticipantRole(participant) {
- if (participant.IsSuperAdmin) return 'Super Admin';
- if (participant.IsAdmin) return 'Admin';
- return 'Member';
- },
- getParticipantRoleColor(participant) {
- if (participant.IsSuperAdmin) return 'red';
- if (participant.IsAdmin) return 'orange';
- return 'blue';
- }
- },
- template: `
- <div class="green card" @click="openModal" style="cursor: pointer;">
- <div class="content">
- <a class="ui green right ribbon label">Group</a>
- <div class="header">Group Info</div>
- <div class="description">
- Search detailed information about a group by ID
- </div>
- </div>
- </div>
-
- <!-- Modal -->
- <div class="ui large modal" id="modalGroupInfo">
- <i class="close icon"></i>
- <div class="header">
- <i class="users icon"></i>
- Group Information
- </div>
- <div class="content">
- <form class="ui form">
- <div class="field">
- <label>Group ID</label>
- <div class="ui action input">
- <input v-model="group_id" placeholder="e.g. 1203630...">
- <button type="button" class="ui primary button" :class="{'loading': loading, 'disabled': !isValidForm() || loading}" @click.prevent="handleSubmit">
- <i class="search icon"></i>
- Search
- </button>
- </div>
- <small class="ui grey text">Full ID: {{ fullGroupID }}</small>
- </div>
- </form>
-
- <div v-if="groupInfo" style="margin-top: 2rem;">
- <div class="ui stackable two column grid">
- <!-- Basic Information -->
- <div class="column">
- <div class="ui segment">
- <h3 class="ui header">
- <i class="info circle icon"></i>
- <div class="content">
- Basic Information
- </div>
- </h3>
- <div class="ui relaxed divided list">
- <div class="item">
- <i class="tag icon"></i>
- <div class="content">
- <div class="header">Group Name</div>
- <div class="description">{{ groupInfo.Name || 'No name' }}</div>
- </div>
- </div>
- <div class="item">
- <i class="id card icon"></i>
- <div class="content">
- <div class="header">Group ID</div>
- <div class="description">{{ groupInfo.JID }}</div>
- </div>
- </div>
- <div class="item">
- <i class="comment icon"></i>
- <div class="content">
- <div class="header">Description</div>
- <div class="description">{{ groupInfo.Topic || 'No description' }}</div>
- </div>
- </div>
- <div class="item">
- <i class="calendar icon"></i>
- <div class="content">
- <div class="header">Created</div>
- <div class="description">{{ formattedGroupCreated }}</div>
- </div>
- </div>
- <div class="item">
- <i class="flag icon"></i>
- <div class="content">
- <div class="header">Creator Country</div>
- <div class="description">{{ groupInfo.CreatorCountryCode }}</div>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Group Settings -->
- <div class="column">
- <div class="ui segment">
- <h3 class="ui header">
- <i class="settings icon"></i>
- <div class="content">
- Group Settings
- </div>
- </h3>
- <div class="ui relaxed list">
- <div class="item">
- <div class="content">
- <div class="header">Group Type</div>
- <div class="ui labels">
- <div class="ui label" :class="groupInfo.IsLocked ? 'red' : 'green'">
- <i class="lock icon" v-if="groupInfo.IsLocked"></i>
- <i class="unlock icon" v-else></i>
- {{ groupInfo.IsLocked ? 'Locked' : 'Unlocked' }}
- </div>
- <div class="ui label" :class="groupInfo.IsAnnounce ? 'orange' : 'blue'">
- <i class="bullhorn icon" v-if="groupInfo.IsAnnounce"></i>
- <i class="comments icon" v-else></i>
- {{ groupInfo.IsAnnounce ? 'Announcement' : 'Open Chat' }}
- </div>
- </div>
- </div>
- </div>
- <div class="item">
- <div class="content">
- <div class="header">Privacy Settings</div>
- <div class="ui labels">
- <div class="ui label" :class="groupInfo.IsEphemeral ? 'purple' : 'grey'">
- <i class="hourglass icon" v-if="groupInfo.IsEphemeral"></i>
- <i class="save icon" v-else></i>
- {{ groupInfo.IsEphemeral ? 'Disappearing Messages' : 'Persistent Messages' }}
- </div>
- <div v-if="groupInfo.IsEphemeral" class="ui purple label">
- <i class="clock icon"></i>
- {{ disappearingTimerText }}
- </div>
- </div>
- </div>
- </div>
- <div class="item">
- <div class="content">
- <div class="header">Join Settings</div>
- <div class="ui labels">
- <div class="ui label" :class="groupInfo.IsJoinApprovalRequired ? 'red' : 'green'">
- <i class="user check icon" v-if="groupInfo.IsJoinApprovalRequired"></i>
- <i class="user plus icon" v-else></i>
- {{ groupInfo.IsJoinApprovalRequired ? 'Approval Required' : 'Open Join' }}
- </div>
- <div class="ui label">
- <i class="users icon"></i>
- {{ groupInfo.MemberAddMode }}
- </div>
- </div>
- </div>
- </div>
- <div class="item">
- <div class="content">
- <div class="header">Other Settings</div>
- <div class="ui labels">
- <div v-if="groupInfo.IsIncognito" class="ui grey label">
- <i class="user secret icon"></i>
- Incognito
- </div>
- <div v-if="groupInfo.IsParent" class="ui teal label">
- <i class="sitemap icon"></i>
- Parent Group
- </div>
- <div v-if="groupInfo.IsDefaultSubGroup" class="ui olive label">
- <i class="share icon"></i>
- Default Sub Group
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Participants -->
- <div class="ui segment">
- <h3 class="ui header">
- <i class="users icon"></i>
- <div class="content">
- Participants
- <div class="sub header">{{ groupInfo.Participants ? groupInfo.Participants.length : 0 }} members</div>
- </div>
- </h3>
- <div class="ui relaxed divided list">
- <div v-for="participant in groupInfo.Participants" :key="participant.JID" class="item">
- <div class="right floated content">
- <div class="ui label" :class="getParticipantRoleColor(participant)">
- <i class="user icon"></i>
- {{ getParticipantRole(participant) }}
- </div>
- </div>
- <i class="user circle icon"></i>
- <div class="content">
- <div class="header">{{ formatPhoneNumber(participant.PhoneNumber) }}</div>
- <div class="description">
- JID: {{ participant.JID }}
- <span v-if="participant.LID" class="ui grey text"> • LID: {{ participant.LID }}</span>
- <span v-if="participant.DisplayName" class="ui grey text"> • {{ participant.DisplayName }}</span>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Metadata -->
- <div class="ui segment">
- <h3 class="ui header">
- <i class="info icon"></i>
- <div class="content">
- Metadata
- </div>
- </h3>
- <div class="ui two column stackable grid">
- <div class="column">
- <div class="ui relaxed list">
- <div class="item">
- <div class="content">
- <div class="header">Name Last Changed</div>
- <div class="description">{{ formattedNameSetAt }}</div>
- <div class="description">By: {{ formatPhoneNumber(groupInfo.NameSetBy) }}</div>
- </div>
- </div>
- <div class="item">
- <div class="content">
- <div class="header">Topic Last Changed</div>
- <div class="description">{{ formattedTopicSetAt }}</div>
- <div class="description">By: {{ formatPhoneNumber(groupInfo.TopicSetBy) }}</div>
- </div>
- </div>
- </div>
- </div>
- <div class="column">
- <div class="ui relaxed list">
- <div class="item">
- <div class="content">
- <div class="header">Owner</div>
- <div class="description">{{ formatPhoneNumber(groupInfo.OwnerJID) }}</div>
- </div>
- </div>
- <div class="item">
- <div class="content">
- <div class="header">Participant Version</div>
- <div class="description">{{ groupInfo.ParticipantVersionID }}</div>
- </div>
- </div>
- <div class="item">
- <div class="content">
- <div class="header">Announce Version</div>
- <div class="description">{{ groupInfo.AnnounceVersionID }}</div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/GroupInfoFromLink.js b/src/views/components/GroupInfoFromLink.js
deleted file mode 100644
index 4dc15df6..00000000
--- a/src/views/components/GroupInfoFromLink.js
+++ /dev/null
@@ -1,181 +0,0 @@
-export default {
- name: 'GroupInfoFromLink',
- data() {
- return {
- loading: false,
- link: '',
- groupInfo: null,
- }
- },
- methods: {
- openModal() {
- $('#modalGroupInfoFromLink').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- if (!this.link.trim()) {
- return false;
- }
-
- // should be a valid WhatsApp invitation URL
- try {
- const url = new URL(this.link);
- if (!url.hostname.includes('chat.whatsapp.com') || !url.pathname.includes('/')) {
- return false;
- }
- } catch (error) {
- return false;
- }
-
- return true;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- let response = await this.submitApi()
- this.groupInfo = response.results;
- showSuccessInfo('Group information retrieved successfully');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let response = await window.http.get(`/group/info-from-link`, {
- params: {
- link: this.link,
- }
- })
- return response.data;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.link = '';
- this.groupInfo = null;
- },
- formatDate(dateString) {
- if (!dateString) return 'N/A';
- return moment(dateString).format('YYYY-MM-DD HH:mm');
- },
- closeModal() {
- $('#modalGroupInfoFromLink').modal('hide');
- this.handleReset();
- },
- },
- template: `
- <div class="green card" @click="openModal" style="cursor: pointer">
- <div class="content">
- <a class="ui green right ribbon label">Group</a>
- <div class="header">Group Preview</div>
- <div class="description">
- Get group information from invitation link
- </div>
- </div>
- </div>
-
- <!-- Modal Group Info From Link -->
- <div class="ui small modal" id="modalGroupInfoFromLink">
- <i class="close icon"></i>
- <div class="header">
- Group Information Preview
- </div>
- <div class="content">
- <form class="ui form">
- <div class="field">
- <label>Invitation Link</label>
- <input v-model="link" type="text"
- placeholder="Invitation link..."
- aria-label="Invitation Link">
- </div>
-
- <div v-if="groupInfo" class="ui segment">
- <h4 class="ui header">Group Details</h4>
- <div class="ui relaxed divided list">
- <div class="item">
- <div class="content">
- <div class="header">Group Name</div>
- <div class="description">{{ groupInfo.name || 'N/A' }}</div>
- </div>
- </div>
- <div class="item">
- <div class="content">
- <div class="header">Group ID</div>
- <div class="description">{{ groupInfo.group_id || 'N/A' }}</div>
- </div>
- </div>
- <div class="item">
- <div class="content">
- <div class="header">Topic</div>
- <div class="description">{{ groupInfo.topic || 'No topic set' }}</div>
- </div>
- </div>
- <div class="item">
- <div class="content">
- <div class="header">Description</div>
- <div class="description">{{ groupInfo.description || 'No description' }}</div>
- </div>
- </div>
- <div class="item">
- <div class="content">
- <div class="header">Created At</div>
- <div class="description">{{ formatDate(groupInfo.created_at) }}</div>
- </div>
- </div>
- <div class="item">
- <div class="content">
- <div class="header">Participants</div>
- <div class="description">{{ groupInfo.participant_count || 0 }} members</div>
- </div>
- </div>
- <div class="item">
- <div class="content">
- <div class="header">Group Settings</div>
- <div class="description">
- <div class="ui mini labels">
- <div class="ui label" :class="groupInfo.is_locked ? 'red' : 'green'">
- <i class="lock icon"></i>
- {{ groupInfo.is_locked ? 'Locked' : 'Unlocked' }}
- </div>
- <div class="ui label" :class="groupInfo.is_announce ? 'orange' : 'blue'">
- <i class="bullhorn icon"></i>
- {{ groupInfo.is_announce ? 'Announce Mode' : 'Regular Mode' }}
- </div>
- <div class="ui label" :class="groupInfo.is_ephemeral ? 'purple' : 'grey'">
- <i class="clock icon"></i>
- {{ groupInfo.is_ephemeral ? 'Disappearing Messages' : 'Regular Messages' }}
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui grey button" @click="closeModal">
- Close
- </button>
- <button class="ui approve positive right labeled icon button"
- :class="{'loading': this.loading, 'disabled': !this.isValidForm() || this.loading}"
- @click.prevent="handleSubmit" type="button">
- Get Info
- <i class="info icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/GroupJoinWithLink.js b/src/views/components/GroupJoinWithLink.js
deleted file mode 100644
index 88639af4..00000000
--- a/src/views/components/GroupJoinWithLink.js
+++ /dev/null
@@ -1,100 +0,0 @@
-export default {
- name: 'JoinGroupWithLink',
- data() {
- return {
- loading: false,
- link: '',
- }
- },
- methods: {
- openModal() {
- $('#modalGroupJoinWithLink').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- if (!this.link.trim()) {
- return false;
- }
-
- // should valid URL
- try {
- new URL(this.link);
- } catch (error) {
- return false;
- }
-
- return true;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalGroupJoinWithLink').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let response = await window.http.post(`/group/join-with-link`, {
- link: this.link,
- })
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.link = '';
- },
- },
- template: `
- <div class="green card" @click="openModal" style="cursor: pointer">
- <div class="content">
- <a class="ui green right ribbon label">Group</a>
- <div class="header">Join Groups</div>
- <div class="description">
- Join group with invitation link
- </div>
- </div>
- </div>
-
- <!-- Modal AccountGroup -->
- <div class="ui small modal" id="modalGroupJoinWithLink">
- <i class="close icon"></i>
- <div class="header">
- Join Group With Link
- </div>
- <div class="content">
- <form class="ui form">
- <div class="field">
- <label>Invitation Link</label>
- <input v-model="link" type="text"
- placeholder="Invitation link..."
- aria-label="Invitation Link">
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button" :class="{'loading': this.loading, 'disabled': !this.isValidForm() || this.loading}"
- @click.prevent="handleSubmit" type="button">
- Join
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/GroupList.js b/src/views/components/GroupList.js
deleted file mode 100644
index dfff6731..00000000
--- a/src/views/components/GroupList.js
+++ /dev/null
@@ -1,303 +0,0 @@
-import GroupListParticipants from "./GroupListParticipants.js";
-
-export default {
- name: 'ListGroup',
- components: { GroupListParticipants },
- props: ['connected'],
- data() {
- return {
- groups: [],
- selectedGroupId: null,
- requestedMembers: [],
- loadingRequestedMembers: false,
- processingMember: null,
- }
- },
- computed: {
- currentUserJID() {
- // connected can be array of objects with device/id or may be undefined
- if (!this.connected || this.connected.length === 0) return null;
- return this.connected[0].jid;
- }
- },
- methods: {
- async openModal() {
- try {
- this.dtClear();
- // Reset groups before fetching new data
- this.groups = [];
- await this.submitApi();
- $('#modalGroupList').modal('show');
- // Wait a bit for modal animation to complete before initializing DataTable
- await new Promise(resolve => setTimeout(resolve, 100));
- await this.dtRebuild();
- showSuccessInfo("Groups fetched")
- } catch (err) {
- showErrorInfo(err)
- }
- },
- dtClear() {
- const table = $('#account_groups_table');
- if ($.fn.DataTable.isDataTable(table)) {
- table.DataTable().clear().destroy();
- }
- },
- async dtRebuild() {
- // Wait for Vue to render the new data
- await this.$nextTick();
- // Additional delay to ensure DOM is fully updated after Vue render
- await new Promise(resolve => setTimeout(resolve, 100));
- const table = $('#account_groups_table');
- if ($.fn.DataTable.isDataTable(table)) {
- table.DataTable().destroy();
- }
- table.DataTable({
- pageLength: 100,
- });
- },
- async handleLeaveGroup(group_id) {
- try {
- const ok = confirm("Are you sure to leave this group?");
- if (!ok) return;
-
- await this.leaveGroupApi(group_id);
- this.dtClear()
- await this.submitApi();
- this.dtRebuild()
- showSuccessInfo("Group left")
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async leaveGroupApi(group_id) {
- try {
- let payload = new FormData();
- payload.append("group_id", group_id)
- await window.http.post(`/group/leave`, payload)
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
-
- }
- },
- async submitApi() {
- try {
- let response = await window.http.get(`/user/my/groups`)
- // Ensure groups is always an array, even if null/undefined
- this.groups = response.data.results.data || [];
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- }
- },
- formatDate: function (value) {
- if (!value) return ''
- return moment(value).format('LLL');
- },
- isAdmin(group) {
- // Check if current user is the owner
- const owner = group.OwnerJID.split('@')[0];
- if (owner === this.currentUserJID) {
- return true;
- }
-
- // Check if current user is an admin in participants
- const participant = group.Participants.find(p => p.PhoneNumber === this.currentUserJID);
- return participant && participant.IsAdmin;
- },
- async handleSeeRequestedMember(group_id) {
- this.selectedGroupId = group_id;
- this.loadingRequestedMembers = true;
- this.requestedMembers = [];
-
- try {
- const response = await window.http.get(`/group/participant-requests?group_id=${group_id}`);
- this.requestedMembers = response.data.results || [];
- this.loadingRequestedMembers = false;
- $('#modalRequestedMembers').modal('show');
- } catch (error) {
- this.loadingRequestedMembers = false;
- let errorMessage = "Failed to fetch requested members";
- if (error.response) {
- errorMessage = error.response.data.message || errorMessage;
- }
- showErrorInfo(errorMessage);
- }
- },
- async handleSeeParticipants(group) {
- if (!group || !group.JID) return;
-
- this.selectedGroupId = group.JID;
- $('#modalGroupList').modal('hide');
-
- try {
- await this.$refs.participantsModal.open(group);
- } catch (error) {
- const errorMessage = error?.message || 'Failed to fetch participants';
- showErrorInfo(errorMessage);
- $('#modalGroupList').modal('show');
- }
- },
- handleExportParticipants(group) {
- if (!group || !group.JID) return;
-
- const baseURL = (window.http && window.http.defaults && window.http.defaults.baseURL) ? window.http.defaults.baseURL : '';
- const exportUrl = `${baseURL}/group/participants/export?group_id=${encodeURIComponent(group.JID)}`;
- window.open(exportUrl, '_blank');
- },
- formatJID(jid) {
- return jid ? jid.split('@')[0] : '';
- },
- closeRequestedMembersModal() {
- $('#modalRequestedMembers').modal('hide');
- // open modal again
- this.openModal();
- },
- handleParticipantsClosed() {
- $('#modalGroupList').modal('show');
- },
- async handleProcessRequest(member, action) {
- if (!this.selectedGroupId || !member) return;
-
- const actionText = action === 'approve' ? 'approve' : 'reject';
- const confirmMsg = `Are you sure you want to ${actionText} this member request?`;
- const ok = confirm(confirmMsg);
- if (!ok) return;
-
- try {
- this.processingMember = member.jid;
-
- const payload = {
- group_id: this.selectedGroupId,
- participants: [this.formatJID(member.jid)]
- };
-
- await window.http.post(`/group/participant-requests/${action}`, payload);
-
- // Remove the processed member from the list
- this.requestedMembers = this.requestedMembers.filter(m => m.jid !== member.jid);
-
- showSuccessInfo(`Member request ${actionText}d`);
- this.processingMember = null;
- } catch (error) {
- this.processingMember = null;
- let errorMessage = `Failed to ${actionText} member request`;
- if (error.response) {
- errorMessage = error.response.data.message || errorMessage;
- }
- showErrorInfo(errorMessage);
- }
- }
- },
- template: `
- <div class="green card" @click="openModal" style="cursor: pointer">
- <div class="content">
- <a class="ui green right ribbon label">Group</a>
- <div class="header">List Groups</div>
- <div class="description">
- Display all your groups
- </div>
- </div>
- </div>
-
- <!-- Modal AccountGroup -->
- <div class="ui large modal" id="modalGroupList">
- <i class="close icon"></i>
- <div class="header">
- My Group List
- </div>
- <div class="content">
- <table class="ui celled table" id="account_groups_table">
- <thead>
- <tr>
- <th>Group ID</th>
- <th>Name</th>
- <th>Participants</th>
- <th>Created At</th>
- <th>Action</th>
- </tr>
- </thead>
- <tbody>
- <tr v-for="g in groups" :key="g.JID">
- <td>{{ g.JID.split('@')[0] }}</td>
- <td>{{ g.Name }}</td>
- <td>{{ g.Participants.length }}</td>
- <td>{{ formatDate(g.GroupCreated) }}</td>
- <td>
- <div style="display: flex; gap: 8px; align-items: center;">
- <button class="ui blue tiny button" @click="handleSeeParticipants(g)">Participants</button>
- <button class="ui grey tiny button" @click="handleExportParticipants(g)">Export CSV</button>
- <button v-if="isAdmin(g)" class="ui green tiny button" @click="handleSeeRequestedMember(g.JID)">Requested Members</button>
- <button class="ui red tiny button" @click="handleLeaveGroup(g.JID)">Leave</button>
- </div>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- </div>
-
- <group-list-participants ref="participantsModal" @closed="handleParticipantsClosed"></group-list-participants>
-
- <!-- Requested Members Modal -->
- <div class="ui modal" id="modalRequestedMembers">
- <i class="close icon"></i>
- <div class="header">
- Requested Group Members
- </div>
- <div class="content">
- <div v-if="loadingRequestedMembers" class="ui active centered inline loader"></div>
-
- <div v-else-if="requestedMembers.length === 0" class="ui info message">
- <div class="header">No Requested Members</div>
- <p>There are no pending member requests for this group.</p>
- </div>
-
- <table v-else class="ui celled table">
- <thead>
- <tr>
- <th>User</th>
- <th>Phone Number</th>
- <th>Request Time</th>
- <th>Action</th>
- </tr>
- </thead>
- <tbody>
- <tr v-for="member in requestedMembers" :key="member.jid">
- <td>
- <div class="header">{{ formatJID(member.jid) }}</div>
- <div v-if="member.display_name" class="description">{{ member.display_name }}</div>
- </td>
- <td>{{ member.phone_number || formatJID(member.jid) }}</td>
- <td>{{ formatDate(member.requested_at) }}</td>
- <td>
- <div class="ui mini buttons">
- <button class="ui green button"
- @click="handleProcessRequest(member, 'approve')"
- :disabled="processingMember === member.jid">
- <i v-if="processingMember === member.jid" class="spinner loading icon"></i>
- Approve
- </button>
- <div class="or"></div>
- <button class="ui red button"
- @click="handleProcessRequest(member, 'reject')"
- :disabled="processingMember === member.jid">
- <i v-if="processingMember === member.jid" class="spinner loading icon"></i>
- Reject
- </button>
- </div>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- <div class="actions">
- <div class="ui button" @click="closeRequestedMembersModal">Close</div>
- </div>
- </div>
- `
-}
diff --git a/src/views/components/GroupListParticipants.js b/src/views/components/GroupListParticipants.js
deleted file mode 100644
index 6d281fb9..00000000
--- a/src/views/components/GroupListParticipants.js
+++ /dev/null
@@ -1,144 +0,0 @@
-export default {
- name: 'GroupListParticipants',
- emits: ['closed'],
- data() {
- return {
- selectedGroup: null,
- loading: false,
- participants: [],
- };
- },
- methods: {
- async open(group) {
- if (!group || !group.JID) {
- throw new Error('Invalid group data');
- }
-
- this.selectedGroup = {
- id: group.JID,
- name: group.Name || this.formatJID(group.JID),
- };
- this.loading = true;
- this.participants = [];
-
- try {
- const response = await window.http.get(`/group/participants?group_id=${encodeURIComponent(group.JID)}`);
- const results = response.data.results || {};
- this.participants = results.participants || [];
- if (results.name) {
- this.selectedGroup.name = results.name;
- }
- this.loading = false;
- this.showModal();
- } catch (error) {
- this.loading = false;
- this.selectedGroup = null;
-
- if (error.response && error.response.data && error.response.data.message) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message || 'Failed to fetch participants');
- }
- },
- close() {
- this.hideModal();
- },
- showModal() {
- if (!this.$refs.modal) return;
- $(this.$refs.modal).modal('show');
- },
- hideModal() {
- if (!this.$refs.modal) return;
- $(this.$refs.modal).modal('hide');
- },
- handleHidden() {
- this.selectedGroup = null;
- this.participants = [];
- this.$emit('closed');
- },
- formatJID(jid) {
- if (!jid) return '';
- return jid.split('@')[0];
- },
- formatParticipantPhone(participant) {
- if (!participant) return '';
- if (participant.phone_number) {
- return this.formatJID(participant.phone_number);
- }
- return this.formatJID(participant.jid);
- },
- getParticipantRole(participant) {
- if (!participant) return 'Member';
- if (participant.is_super_admin) return 'Super Admin';
- if (participant.is_admin) return 'Admin';
- return 'Member';
- },
- getParticipantRoleColor(participant) {
- if (!participant) return 'grey';
- if (participant.is_super_admin) return 'red';
- if (participant.is_admin) return 'orange';
- return 'teal';
- },
- },
- mounted() {
- if (!this.$refs.modal) return;
- $(this.$refs.modal).modal({
- autofocus: false,
- observeChanges: true,
- onHidden: () => {
- this.handleHidden();
- },
- });
- },
- template: `
- <div class="ui modal" ref="modal">
- <i class="close icon"></i>
- <div class="header">
- Group Participants
- <div class="sub header" v-if="selectedGroup && selectedGroup.name">{{ selectedGroup.name }}</div>
- </div>
- <div class="content">
- <div v-if="loading" class="ui active centered inline loader"></div>
-
- <div v-else-if="!participants.length" class="ui info message">
- <div class="header">No Participants Found</div>
- <p>Unable to retrieve participants for this group.</p>
- </div>
-
- <table v-else class="ui celled table">
- <thead>
- <tr>
- <th>Participant</th>
- <th>Phone Number</th>
- <th>LID</th>
- <th>Role</th>
- </tr>
- </thead>
- <tbody>
- <tr v-for="participant in participants" :key="participant.jid">
- <td>
- <div class="header">{{ formatJID(participant.jid) }}</div>
- <div v-if="participant.display_name" class="description">{{ participant.display_name }}</div>
- </td>
- <td>
- {{ formatParticipantPhone(participant) }}
- </td>
- <td>
- <span v-if="participant.lid">{{ formatJID(participant.lid) }}</span>
- <span v-else>-</span>
- </td>
- <td>
- <div class="ui tiny label" :class="getParticipantRoleColor(participant)">
- {{ getParticipantRole(participant) }}
- </div>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- <div class="actions">
- <div class="ui button" @click="close">Close</div>
- </div>
- </div>
- `,
-};
diff --git a/src/views/components/GroupManageParticipants.js b/src/views/components/GroupManageParticipants.js
deleted file mode 100644
index 0c2ef45b..00000000
--- a/src/views/components/GroupManageParticipants.js
+++ /dev/null
@@ -1,169 +0,0 @@
-export default {
- name: 'ManageGroupParticipants',
- data() {
- return {
- loading: false,
- group: '',
- action: 'add', // add, remove, promote, demote
- participants: ['', ''],
- };
- },
- computed: {
- group_id() {
- return `${this.group}${window.TYPEGROUP}`;
- },
- },
- methods: {
- openModal() {
- $('#modalGroupAddParticipant').modal({
- onApprove: function() {
- return false;
- },
- }).modal('show');
- },
- isValidForm() {
- if (
- this.participants.length < 1 ||
- this.participants.every(p => this.isEmpty(p))
- ) {
- return false;
- }
-
- return true;
- },
- // Helper to determine if participant value is empty
- isEmpty(value) {
- const str = String(value?.jid ?? value).trim();
- return !str;
- },
- handleAddParticipant() {
- this.participants.push('');
- },
- handleDeleteParticipant(index) {
- this.participants.splice(index, 1);
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
-
- try {
- let response = await this.submitApi();
- showSuccessInfo(response);
- $('#modalGroupAddParticipant').modal('hide');
- } catch (err) {
- showErrorInfo(err);
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- const payload = {
- group_id: this.group_id,
- // convert participant become list of string
- participants: this.participants
- .filter(p => !this.isEmpty(p))
- .map(p => `${p?.jid ?? p}`),
- };
-
- let response;
- switch (this.action) {
- case 'add':
- response = await window.http.post(`/group/participants`, payload);
- break;
- case 'remove':
- response = await window.http.post(`/group/participants/remove`, payload);
- break;
- case 'promote':
- response = await window.http.post(`/group/participants/promote`, payload);
- break;
- case 'demote':
- response = await window.http.post(`/group/participants/demote`, payload);
- break;
- }
-
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.group = '';
- this.action = 'add';
- this.participants = ['', ''];
- },
- },
- template: `
- <div class="green card" @click="openModal" style="cursor: pointer">
- <div class="content">
- <a class="ui green right ribbon label">Group</a>
- <div class="header">Manage Participants</div>
- <div class="description">
- Add/Remove/Promote/Demote Participants
- </div>
- </div>
- </div>
-
- <!-- Modal AccountGroup -->
- <div class="ui small modal" id="modalGroupAddParticipant">
- <i class="close icon"></i>
- <div class="header">
- Manage Participants
- </div>
- <div class="content">
- <form class="ui form">
- <div class="field">
- <label>Group ID</label>
- <input v-model="group" type="text"
- placeholder="12036322888236XXXX..."
- aria-label="Group Name">
- <input :value="group_id" disabled aria-label="whatsapp_id">
- </div>
-
- <div class="field">
- <label>Participants</label>
- <div style="display: flex; flex-direction: column; gap: 5px">
- <div class="ui action input" :key="index" v-for="(participant, index) in participants">
- <input type="number" placeholder="Phone Int Number (6289...)" v-model="participants[index]"
- aria-label="list participant">
- <button class="ui button" @click="handleDeleteParticipant(index)" type="button">
- <i class="minus circle icon"></i>
- </button>
- </div>
- <div class="field" style="display: flex; flex-direction: column; gap: 3px">
- <div>
- <button class="mini ui primary button" @click="handleAddParticipant" type="button">
- <i class="plus icon"></i> Option
- </button>
- </div>
- </div>
- </div>
- </div>
-
- <div class="field">
- <label>Action</label>
- <select v-model="action" class="ui dropdown" aria-label="Action">
- <option value="add">Add to group</option>
- <option value="remove">Remove from group</option>
- <option value="promote">Promote to admin</option>
- <option value="demote">Demote from admin</option>
- </select>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button" :class="{'loading': this.loading, 'disabled': !this.isValidForm() || this.loading}"
- @click.prevent="handleSubmit" type="button">
- Submit
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `,
-};
\ No newline at end of file
diff --git a/src/views/components/GroupSetAnnounce.js b/src/views/components/GroupSetAnnounce.js
deleted file mode 100644
index b5708eab..00000000
--- a/src/views/components/GroupSetAnnounce.js
+++ /dev/null
@@ -1,108 +0,0 @@
-export default {
- name: 'GroupSetAnnounce',
- data() {
- return {
- loading: false,
- groupId: '',
- announce: false,
- }
- },
- methods: {
- openModal() {
- $('#modalGroupSetAnnounce').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- return this.groupId.trim() !== '';
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalGroupSetAnnounce').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let response = await window.http.post(`/group/announce`, {
- group_id: this.groupId,
- announce: this.announce
- })
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.groupId = '';
- this.announce = false;
- },
- },
- template: `
- <div class="green card" @click="openModal" style="cursor: pointer">
- <div class="content">
- <a class="ui green right ribbon label">Group</a>
- <div class="header">Set Group Announce</div>
- <div class="description">
- Enable/disable announce mode for admins only messaging
- </div>
- </div>
- </div>
-
- <!-- Modal Group Set Announce -->
- <div class="ui small modal" id="modalGroupSetAnnounce">
- <i class="close icon"></i>
- <div class="header">
- Set Group Announce Mode
- </div>
- <div class="content">
- <form class="ui form">
- <div class="field">
- <label>Group ID</label>
- <input v-model="groupId" type="text"
- placeholder="[email protected]"
- aria-label="Group ID">
- </div>
-
- <div class="field">
- <label>Announce Mode</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" v-model="announce">
- <label>{{ announce ? 'Enable announce mode (only admins can send messages)' : 'Disable announce mode (all members can send messages)' }}</label>
- </div>
- <div class="ui info message" style="margin-top: 10px;">
- <div class="header">What does this do?</div>
- <ul class="list">
- <li><strong>Announce Mode ON:</strong> Only group admins can send messages to the group</li>
- <li><strong>Announce Mode OFF:</strong> All group members can send messages</li>
- </ul>
- </div>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button"
- :class="{'loading': this.loading, 'disabled': !this.isValidForm() || this.loading}"
- @click.prevent="handleSubmit" type="button">
- {{ announce ? 'Enable Announce Mode' : 'Disable Announce Mode' }}
- <i :class="announce ? 'bullhorn icon' : 'comment icon'"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/GroupSetLocked.js b/src/views/components/GroupSetLocked.js
deleted file mode 100644
index 615df2d0..00000000
--- a/src/views/components/GroupSetLocked.js
+++ /dev/null
@@ -1,108 +0,0 @@
-export default {
- name: 'GroupSetLocked',
- data() {
- return {
- loading: false,
- groupId: '',
- locked: false,
- }
- },
- methods: {
- openModal() {
- $('#modalGroupSetLocked').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- return this.groupId.trim() !== '';
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalGroupSetLocked').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let response = await window.http.post(`/group/locked`, {
- group_id: this.groupId,
- locked: this.locked
- })
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.groupId = '';
- this.locked = false;
- },
- },
- template: `
- <div class="green card" @click="openModal" style="cursor: pointer">
- <div class="content">
- <a class="ui green right ribbon label">Group</a>
- <div class="header">Set Group Locked</div>
- <div class="description">
- Lock/unlock group info editing for admins only
- </div>
- </div>
- </div>
-
- <!-- Modal Group Set Locked -->
- <div class="ui small modal" id="modalGroupSetLocked">
- <i class="close icon"></i>
- <div class="header">
- Set Group Locked Status
- </div>
- <div class="content">
- <form class="ui form">
- <div class="field">
- <label>Group ID</label>
- <input v-model="groupId" type="text"
- placeholder="[email protected]"
- aria-label="Group ID">
- </div>
-
- <div class="field">
- <label>Lock Status</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" v-model="locked">
- <label>{{ locked ? 'Lock group (only admins can edit group info)' : 'Unlock group (all members can edit group info)' }}</label>
- </div>
- <div class="ui info message" style="margin-top: 10px;">
- <div class="header">What does this do?</div>
- <ul class="list">
- <li><strong>Locked:</strong> Only group admins can change group name, description, and photo</li>
- <li><strong>Unlocked:</strong> All group members can change group info</li>
- </ul>
- </div>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button"
- :class="{'loading': this.loading, 'disabled': !this.isValidForm() || this.loading}"
- @click.prevent="handleSubmit" type="button">
- {{ locked ? 'Lock Group' : 'Unlock Group' }}
- <i :class="locked ? 'lock icon' : 'unlock icon'"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/GroupSetName.js b/src/views/components/GroupSetName.js
deleted file mode 100644
index 80f9f4ff..00000000
--- a/src/views/components/GroupSetName.js
+++ /dev/null
@@ -1,102 +0,0 @@
-export default {
- name: 'GroupSetName',
- data() {
- return {
- loading: false,
- groupId: '',
- name: '',
- }
- },
- methods: {
- openModal() {
- $('#modalGroupSetName').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- return this.groupId.trim() !== '' && this.name.trim() !== '' && this.name.length <= 25;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalGroupSetName').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let response = await window.http.post(`/group/name`, {
- group_id: this.groupId,
- name: this.name
- })
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.groupId = '';
- this.name = '';
- },
- },
- template: `
- <div class="green card" @click="openModal" style="cursor: pointer">
- <div class="content">
- <a class="ui green right ribbon label">Group</a>
- <div class="header">Set Group Name</div>
- <div class="description">
- Change the group name/title
- </div>
- </div>
- </div>
-
- <!-- Modal Group Set Name -->
- <div class="ui small modal" id="modalGroupSetName">
- <i class="close icon"></i>
- <div class="header">
- Set Group Name
- </div>
- <div class="content">
- <form class="ui form">
- <div class="field">
- <label>Group ID</label>
- <input v-model="groupId" type="text"
- placeholder="[email protected]"
- aria-label="Group ID">
- </div>
-
- <div class="field">
- <label>Group Name</label>
- <input v-model="name" type="text"
- placeholder="Enter new group name..."
- maxlength="25"
- aria-label="Group Name">
- <small class="text">Maximum 25 characters. Current length: {{ name.length }}/25</small>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button"
- :class="{'loading': this.loading, 'disabled': !this.isValidForm() || this.loading}"
- @click.prevent="handleSubmit" type="button">
- Update Name
- <i class="edit icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/GroupSetPhoto.js b/src/views/components/GroupSetPhoto.js
deleted file mode 100644
index 2a96776b..00000000
--- a/src/views/components/GroupSetPhoto.js
+++ /dev/null
@@ -1,144 +0,0 @@
-export default {
- name: 'GroupSetPhoto',
- data() {
- return {
- loading: false,
- groupId: '',
- photo: null,
- photoFile: null,
- previewUrl: null,
- }
- },
- methods: {
- openModal() {
- $('#modalGroupSetPhoto').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- return this.groupId.trim() !== '';
- },
- handleFileChange(event) {
- const file = event.target.files[0];
- if (file) {
- this.photoFile = file;
- // Create preview
- const reader = new FileReader();
- reader.onload = (e) => {
- this.previewUrl = e.target.result;
- };
- reader.readAsDataURL(file);
- }
- },
- handleRemovePhoto() {
- this.photoFile = null;
- this.previewUrl = null;
- // Reset file input
- const fileInput = document.querySelector('#photoUpload');
- if (fileInput) {
- fileInput.value = '';
- }
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalGroupSetPhoto').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- const formData = new FormData();
- formData.append('group_id', this.groupId);
- if (this.photoFile) {
- formData.append('photo', this.photoFile);
- }
-
- let response = await window.http.post(`/group/photo`, formData, {
- headers: {
- 'Content-Type': 'multipart/form-data'
- }
- })
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.groupId = '';
- this.photoFile = null;
- this.previewUrl = null;
- const fileInput = document.querySelector('#photoUpload');
- if (fileInput) {
- fileInput.value = '';
- }
- },
- },
- template: `
- <div class="green card" @click="openModal" style="cursor: pointer">
- <div class="content">
- <a class="ui green right ribbon label">Group</a>
- <div class="header">Set Group Photo</div>
- <div class="description">
- Update or remove group profile picture
- </div>
- </div>
- </div>
-
- <!-- Modal Group Set Photo -->
- <div class="ui small modal" id="modalGroupSetPhoto">
- <i class="close icon"></i>
- <div class="header">
- Set Group Photo
- </div>
- <div class="content">
- <form class="ui form">
- <div class="field">
- <label>Group ID</label>
- <input v-model="groupId" type="text"
- placeholder="[email protected]"
- aria-label="Group ID">
- </div>
-
- <div class="field">
- <label>Group Photo</label>
- <input type="file" id="photoUpload" accept="image/*" @change="handleFileChange">
- <small class="text">Select a JPEG image for best results. Leave empty to remove current photo.</small>
- </div>
-
- <div class="field" v-if="previewUrl">
- <label>Preview</label>
- <div style="display: flex; align-items: center; gap: 10px;">
- <img :src="previewUrl" alt="Preview" style="width: 100px; height: 100px; object-fit: cover; border-radius: 8px;">
- <button class="ui red button" @click="handleRemovePhoto" type="button">
- <i class="trash icon"></i> Remove
- </button>
- </div>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button"
- :class="{'loading': this.loading, 'disabled': !this.isValidForm() || this.loading}"
- @click.prevent="handleSubmit" type="button">
- Update Photo
- <i class="camera icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/GroupSetTopic.js b/src/views/components/GroupSetTopic.js
deleted file mode 100644
index a01c1452..00000000
--- a/src/views/components/GroupSetTopic.js
+++ /dev/null
@@ -1,103 +0,0 @@
-export default {
- name: 'GroupSetTopic',
- data() {
- return {
- loading: false,
- groupId: '',
- topic: '',
- }
- },
- methods: {
- openModal() {
- $('#modalGroupSetTopic').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- return this.groupId.trim() !== '';
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalGroupSetTopic').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let response = await window.http.post(`/group/topic`, {
- group_id: this.groupId,
- topic: this.topic
- })
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.groupId = '';
- this.topic = '';
- },
- },
- template: `
- <div class="green card" @click="openModal" style="cursor: pointer">
- <div class="content">
- <a class="ui green right ribbon label">Group</a>
- <div class="header">Set Group Topic</div>
- <div class="description">
- Set or remove group description/topic
- </div>
- </div>
- </div>
-
- <!-- Modal Group Set Topic -->
- <div class="ui small modal" id="modalGroupSetTopic">
- <i class="close icon"></i>
- <div class="header">
- Set Group Topic
- </div>
- <div class="content">
- <form class="ui form">
- <div class="field">
- <label>Group ID</label>
- <input v-model="groupId" type="text"
- placeholder="[email protected]"
- aria-label="Group ID">
- </div>
-
- <div class="field">
- <label>Group Topic (Description)</label>
- <textarea v-model="topic"
- placeholder="Enter group description/topic... Leave empty to remove topic."
- rows="4"
- aria-label="Group Topic">
- </textarea>
- <small class="text">This will be displayed as the group description. Leave empty to remove the current topic.</small>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button"
- :class="{'loading': this.loading, 'disabled': !this.isValidForm() || this.loading}"
- @click.prevent="handleSubmit" type="button">
- {{ topic.trim() === '' ? 'Remove Topic' : 'Update Topic' }}
- <i :class="topic.trim() === '' ? 'trash icon' : 'edit icon'"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/MessageDelete.js b/src/views/components/MessageDelete.js
deleted file mode 100644
index 15f1bc98..00000000
--- a/src/views/components/MessageDelete.js
+++ /dev/null
@@ -1,115 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'DeleteMessage',
- components: {
- FormRecipient
- },
- data() {
- return {
- type: window.TYPEUSER,
- phone: '',
- message_id: '',
- loading: false,
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- }
- },
- methods: {
- openModal() {
- $('#modalMessageDelete').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- if (this.type !== window.TYPESTATUS && !this.phone.trim()) {
- return false;
- }
-
- if (!this.message_id.trim()) {
- return false;
- }
-
- return true;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
-
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalMessageDelete').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- const payload = {phone: this.phone_id, message: this.new_message}
-
- let response = await window.http.post(`/message/${this.message_id}/delete`, payload)
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.type = window.TYPEUSER;
- this.phone = '';
- this.message_id = '';
- this.new_message = '';
- this.loading = false;
- },
- },
- template: `
- <div class="red card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui red right ribbon label">Message</a>
- <div class="header">Delete Message</div>
- <div class="description">
- Delete your sent message
- </div>
- </div>
- </div>
-
- <!-- Modal MessageDelete -->
- <div class="ui small modal" id="modalMessageDelete">
- <i class="close icon"></i>
- <div class="header">
- Delete Message
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone"/>
-
- <div class="field">
- <label>Message ID</label>
- <input v-model="message_id" type="text" placeholder="Please enter your message id"
- aria-label="message id">
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button" :class="{'loading': this.loading, 'disabled': !isValidForm() || loading}"
- @click.prevent="handleSubmit">
- Delete
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/MessageReact.js b/src/views/components/MessageReact.js
deleted file mode 100644
index 3aa94a6b..00000000
--- a/src/views/components/MessageReact.js
+++ /dev/null
@@ -1,119 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'ReactMessage',
- components: {
- FormRecipient
- },
- data() {
- return {
- type: window.TYPEUSER,
- phone: '',
- message_id: '',
- emoji: '',
- loading: false,
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- }
- },
- methods: {
- openModal() {
- $('#modalMessageReaction').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- if (this.type !== window.TYPESTATUS && !this.phone.trim()) {
- return false;
- }
-
- if (!this.message_id.trim() || !this.emoji.trim()) {
- return false;
- }
-
- return true;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalMessageReaction').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- const payload = {phone: this.phone_id, emoji: this.emoji}
- let response = await window.http.post(`/message/${this.message_id}/reaction`, payload)
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.phone = '';
- this.message_id = '';
- this.emoji = '';
- this.type = window.TYPEUSER;
- },
- },
- template: `
- <div class="red card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui red right ribbon label">Message</a>
- <div class="header">React Message</div>
- <div class="description">
- any message in private or group chat
- </div>
- </div>
- </div>
-
-
- <!-- Modal MessageReaction -->
- <div class="ui small modal" id="modalMessageReaction">
- <i class="close icon"></i>
- <div class="header">
- React Message
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone"/>
-
- <div class="field">
- <label>Message ID</label>
- <input v-model="message_id" type="text" placeholder="Please enter your message id"
- aria-label="message id">
- </div>
- <div class="field">
- <label>Emoji</label>
- <input v-model="emoji" type="text" placeholder="Please enter emoji"
- aria-label="message id">
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button" :class="{'loading': this.loading, 'disabled': !this.isValidForm() || this.loading}"
- @click="handleSubmit">
- Send
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/MessageRead.js b/src/views/components/MessageRead.js
deleted file mode 100644
index bf0d9672..00000000
--- a/src/views/components/MessageRead.js
+++ /dev/null
@@ -1,114 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'ReadMessage',
- components: {
- FormRecipient
- },
- data() {
- return {
- type: window.TYPEUSER,
- phone: '',
- message_id: '',
- loading: false,
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- }
- },
- methods: {
- openModal() {
- $('#modalMessageRead').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- if (this.type !== window.TYPESTATUS && !this.phone.trim()) {
- return false;
- }
-
- if (!this.message_id.trim()) {
- return false;
- }
-
- return true;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
-
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalMessageRead').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- const payload = {phone: this.phone_id}
-
- let response = await window.http.post(`/message/${this.message_id}/read`, payload)
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.type = window.TYPEUSER;
- this.phone = '';
- this.message_id = '';
- this.loading = false;
- },
- },
- template: `
- <div class="red card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui red right ribbon label">Message</a>
- <div class="header">Mark as Read</div>
- <div class="description">
- Mark a message as read in a chat
- </div>
- </div>
- </div>
-
- <!-- Modal MessageRead -->
- <div class="ui small modal" id="modalMessageRead">
- <i class="close icon"></i>
- <div class="header">
- Mark Message as Read
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone"/>
-
- <div class="field">
- <label>Message ID</label>
- <input v-model="message_id" type="text" placeholder="Please enter the message id to mark as read"
- aria-label="message id">
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button" :class="{'loading': this.loading, 'disabled': !isValidForm() || loading}"
- @click.prevent="handleSubmit">
- Mark as Read
- <i class="check icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/MessageRevoke.js b/src/views/components/MessageRevoke.js
deleted file mode 100644
index 144132aa..00000000
--- a/src/views/components/MessageRevoke.js
+++ /dev/null
@@ -1,111 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'Message',
- components: {
- FormRecipient
- },
- data() {
- return {
- type: window.TYPEUSER,
- phone: '',
- message_id: '',
- loading: false,
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- }
- },
- methods: {
- openModal() {
- $('#modalMessageRevoke').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- if (this.type !== window.TYPESTATUS && !this.phone.trim()) {
- return false;
- }
-
- if (!this.message_id.trim()) {
- return false;
- }
-
- return true;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalMessageRevoke').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- const payload = {phone: this.phone_id}
- let response = await window.http.post(`/message/${this.message_id}/revoke`, payload)
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.phone = '';
- this.message_id = '';
- this.type = window.TYPEUSER;
- },
- },
- template: `
- <div class="red card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui red right ribbon label">Message</a>
- <div class="header">Revoke Message</div>
- <div class="description">
- Revoke your own message, or any member's message in a group where you are admin
- </div>
- </div>
- </div>
-
- <!-- Modal MessageRevoke -->
- <div class="ui small modal" id="modalMessageRevoke">
- <i class="close icon"></i>
- <div class="header">
- Revoke Message
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone"/>
-
- <div class="field">
- <label> Message ID</label>
- <input v-model="message_id" type="text" placeholder="Please enter the message id to revoke"
- aria-label="message id">
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button" :class="{'loading': this.loading, 'disabled': !isValidForm() || loading}"
- @click="handleSubmit">
- Send
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/MessageUpdate.js b/src/views/components/MessageUpdate.js
deleted file mode 100644
index eba8ad2f..00000000
--- a/src/views/components/MessageUpdate.js
+++ /dev/null
@@ -1,120 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'UpdateMessage',
- components: {
- FormRecipient
- },
- data() {
- return {
- type: window.TYPEUSER,
- phone: '',
- message_id: '',
- new_message: '',
- loading: false,
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- }
- },
- methods: {
- openModal() {
- $('#modalMessageUpdate').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- if (this.type !== window.TYPESTATUS && !this.phone.trim()) {
- return false;
- }
-
- if (!this.message_id.trim() || !this.new_message.trim()) {
- return false;
- }
-
- return true;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalMessageUpdate').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- const payload = {phone: this.phone_id, message: this.new_message}
-
- let response = await window.http.post(`/message/${this.message_id}/update`, payload)
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.type = window.TYPEUSER;
- this.phone = '';
- this.message_id = '';
- this.new_message = '';
- this.loading = false;
- },
- },
- template: `
- <div class="red card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui red right ribbon label">Message</a>
- <div class="header">Update Message</div>
- <div class="description">
- Update your sent message
- </div>
- </div>
- </div>
-
- <!-- Modal MessageUpdate -->
- <div class="ui small modal" id="modalMessageUpdate">
- <i class="close icon"></i>
- <div class="header">
- Update Message
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone"/>
-
- <div class="field">
- <label>Message ID</label>
- <input v-model="message_id" type="text" placeholder="Please enter your message id"
- aria-label="message id">
- </div>
- <div class="field">
- <label>New Message</label>
- <textarea v-model="new_message" type="text" placeholder="Hello this is your new message text, you can edit before 15 minutes after sent."
- aria-label="message"></textarea>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button" :class="{'loading': this.loading, 'disabled': !this.isValidForm() || this.loading}"
- @click="handleSubmit">
- Update
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/NewsletterList.js b/src/views/components/NewsletterList.js
deleted file mode 100644
index acdabba1..00000000
--- a/src/views/components/NewsletterList.js
+++ /dev/null
@@ -1,117 +0,0 @@
-export default {
- name: 'ListNewsletter',
- data() {
- return {
- newsletters: []
- }
- },
- methods: {
- async openModal() {
- try {
- this.dtClear()
- await this.submitApi();
- $('#modalNewsletterList').modal('show');
- this.dtRebuild()
- showSuccessInfo("Newsletters fetched")
- } catch (err) {
- showErrorInfo(err)
- }
- },
- dtClear() {
- $('#account_newsletters_table').DataTable().destroy();
- },
- dtRebuild() {
- $('#account_newsletters_table').DataTable({
- "pageLength": 100,
- "reloadData": true,
- }).draw();
- },
- async handleUnfollowNewsletter(newsletter_id) {
- try {
- const ok = confirm("Are you sure to leave this newsletter?");
- if (!ok) return;
-
- await this.unfollowNewsletterApi(newsletter_id);
- this.dtClear()
- await this.submitApi();
- this.dtRebuild()
- showSuccessInfo("Success unfollow newsletter")
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async unfollowNewsletterApi(newsletter_id) {
- try {
- let payload = {
- newsletter_id: newsletter_id
- };
- await window.http.post(`/newsletter/unfollow`, payload)
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
-
- }
- },
- async submitApi() {
- try {
- let response = await window.http.get(`/user/my/newsletters`)
- this.newsletters = response.data.results.data;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- }
- },
- formatDate: function (value) {
- if (!value) return ''
- if (isNaN(value)) return 'Invalid date';
- return moment.unix(value).format('LLL');
- }
- },
- template: `
- <div class="green card" @click="openModal" style="cursor: pointer">
- <div class="content">
- <a class="ui green right ribbon label">Newsletter</a>
- <div class="header">List Newsletters</div>
- <div class="description">
- Display all your newsletters
- </div>
- </div>
- </div>
-
- <!-- Modal AccountNewsletter -->
- <div class="ui small modal" id="modalNewsletterList">
- <i class="close icon"></i>
- <div class="header">
- My Newsletter List
- </div>
- <div class="content">
- <table class="ui celled table" id="account_newsletters_table">
- <thead>
- <tr>
- <th>Newsletter ID</th>
- <th>Name</th>
- <th>Role</th>
- <th>Created At</th>
- <th>Action</th>
- </tr>
- </thead>
- <tbody v-if="newsletters != null">
- <tr v-for="n in newsletters">
- <td>{{ n.id.split('@')[0] }}</td>
- <td>{{ n.thread_metadata?.name?.text || 'N/A' }}</td>
- <td>{{ n.viewer_metadata?.role || 'N/A' }}</td>
- <td>{{ formatDate(n.thread_metadata?.creation_time) }}</td>
- <td>
- <button class="ui red tiny button" @click="handleUnfollowNewsletter(n.id)">Unfollow</button>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/SendAudio.js b/src/views/components/SendAudio.js
deleted file mode 100644
index f9b8f8f5..00000000
--- a/src/views/components/SendAudio.js
+++ /dev/null
@@ -1,193 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'Send',
- components: {
- FormRecipient
- },
- data() {
- return {
- phone: '',
- type: window.TYPEUSER,
- loading: false,
- selectedFileName: null,
- is_forwarded: false,
- reply_message_id: '',
- audio_url: null,
- duration: 0,
- ptt: false,
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- }
- },
- methods: {
- openModal() {
- $('#modalAudioSend').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isShowAttributes() {
- return this.type !== window.TYPESTATUS;
- },
- isValidForm() {
- if (this.type !== window.TYPEUSER && !this.phone.trim()) {
- return false;
- }
-
- if (!this.selectedFileName && !this.audio_url) {
- return false;
- }
-
- return true;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
-
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalAudioSend').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let payload = new FormData();
- payload.append("phone", this.phone_id)
- payload.append("is_forwarded", this.is_forwarded)
- payload.append("ptt", this.ptt)
- const replyMessageID = this.reply_message_id.trim()
- if (this.isShowAttributes() && replyMessageID !== '') {
- payload.append("reply_message_id", replyMessageID)
- }
- if (this.duration && this.duration > 0) {
- payload.append("duration", this.duration)
- }
-
- const fileInput = $("#file_audio");
- if (fileInput.length > 0 && fileInput[0].files.length > 0) {
- const file = fileInput[0].files[0];
- payload.append('audio', file);
- }
- if (this.audio_url) {
- payload.append('audio_url', this.audio_url)
- }
-
- const response = await window.http.post(`/send/audio`, payload)
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.phone = '';
- this.type = window.TYPEUSER;
- this.is_forwarded = false;
- this.reply_message_id = '';
- this.duration = 0;
- this.ptt = false;
- $("#file_audio").val('');
- this.selectedFileName = null;
- this.audio_url = null;
- },
- handleFileChange(event) {
- const file = event.target.files[0];
- if (file) {
- this.selectedFileName = file.name;
- }
- }
- },
- template: `
- <div class="blue card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui blue right ribbon label">Send</a>
- <div class="header">Send Audio</div>
- <div class="description">
- Send audio to user or group
- </div>
- </div>
- </div>
-
- <!-- Modal SendAudio -->
- <div class="ui small modal" id="modalAudioSend">
- <i class="close icon"></i>
- <div class="header">
- Send Audio
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone"/>
- <div class="field" v-if="isShowAttributes()">
- <label>Reply Message ID</label>
- <input v-model="reply_message_id" type="text"
- placeholder="Optional: 57D29F74B7FC62F57D8AC2C840279B5B/3EB0288F008D32FCD0A424"
- aria-label="reply_message_id">
- </div>
- <div class="field">
- <label>Is Forwarded</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="is forwarded" v-model="is_forwarded">
- <label>Mark audio as forwarded</label>
- </div>
- </div>
- <div class="field">
- <label>Voice Note (PTT)</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="ptt" v-model="ptt">
- <label>Send as voice note (required for OGG/Opus files)</label>
- </div>
- </div>
- <div class="field">
- <label>Disappearing Duration (seconds)</label>
- <input v-model.number="duration" type="number" min="0" placeholder="0 (no expiry)" aria-label="duration"/>
- </div>
- <div class="field">
- <label>Audio URL</label>
- <input type="text" v-model="audio_url" placeholder="https://example.com/audio.mp3"
- aria-label="audio_url"/>
- </div>
- <div style="text-align: left; font-weight: bold; margin: 10px 0;">or you can upload audio from your
- device
- </div>
- <div class="field" style="padding-bottom: 30px">
- <label>Audio</label>
- <input type="file" style="display: none" accept="audio/*" id="file_audio"
- @change="handleFileChange"/>
- <label for="file_audio" class="ui positive medium green left floated button" style="color: white">
- <i class="ui upload icon"></i>
- Upload
- </label>
- <div v-if="selectedFileName" style="margin-top: 60px">
- <div class="ui message">
- <i class="file icon"></i>
- Selected file: {{ selectedFileName }}
- </div>
- </div>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button" :class="{'loading': this.loading, 'disabled': !isValidForm() || loading}"
- @click.prevent="handleSubmit">
- Send
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `
-}
diff --git a/src/views/components/SendChatPresence.js b/src/views/components/SendChatPresence.js
deleted file mode 100644
index 7afa17c5..00000000
--- a/src/views/components/SendChatPresence.js
+++ /dev/null
@@ -1,99 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'SendChatPresence',
- components: {
- FormRecipient
- },
- data() {
- return {
- type: window.TYPEUSER,
- phone: '',
- action: 'start',
- loading: false,
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- },
- },
- methods: {
- openModal() {
- $('#modalSendChatPresence').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- async handleSubmit() {
- if (this.loading) {
- return;
- }
-
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let payload = {
- phone: this.phone_id,
- action: this.action
- }
- let response = await window.http.post(`/send/chat-presence`, payload)
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- }
- },
- template: `
- <div class="blue card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui blue right ribbon label">Send</a>
- <div class="header">Send Chat Presence</div>
- <div class="description">
- Send <div class="ui green horizontal label">typing</div> indicators to specific chat
- </div>
- </div>
- </div>
-
- <!-- Modal SendChatPresence -->
- <div class="ui small modal" id="modalSendChatPresence">
- <i class="close icon"></i>
- <div class="header">
- Send Chat Presence
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone" />
- <div class="field">
- <label>Action</label>
- <select v-model="action" class="ui dropdown">
- <option value="start">Start Typing</option>
- <option value="stop">Stop Typing</option>
- </select>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button"
- :class="{'loading': loading, 'disabled': loading}"
- @click.prevent="handleSubmit">
- Send
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/SendContact.js b/src/views/components/SendContact.js
deleted file mode 100644
index a9a76490..00000000
--- a/src/views/components/SendContact.js
+++ /dev/null
@@ -1,147 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'SendContact',
- components: {
- FormRecipient
- },
- data() {
- return {
- type: window.TYPEUSER,
- phone: '',
- card_name: '',
- card_phone: '',
- loading: false,
- is_forwarded: false,
- duration: 0
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- }
- },
- methods: {
- openModal() {
- $('#modalSendContact').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isShowAttributes() {
- return this.type !== window.TYPESTATUS;
- },
- isValidForm() {
- if (this.type !== window.TYPESTATUS && !this.phone.trim()) {
- return false;
- }
-
- if (!this.card_name.trim()) {
- return false;
- }
-
- if (!this.card_phone.trim()) {
- return false;
- }
-
- return true;
- },
- async handleSubmit() {
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalSendContact').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- if (!this.isValidForm()) {
- return;
- }
-
- this.loading = true;
- try {
- const payload = {
- phone: this.phone_id,
- contact_name: this.card_name,
- contact_phone: this.card_phone,
- is_forwarded: this.is_forwarded,
- ...(this.duration && this.duration > 0 ? {duration: this.duration} : {})
- }
- let response = await window.http.post(`/send/contact`, payload)
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.phone = '';
- this.card_name = '';
- this.card_phone = '';
- this.type = window.TYPEUSER;
- this.is_forwarded = false;
- this.duration = 0;
- },
- },
- template: `
- <div class="blue card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui blue right ribbon label">Send</a>
- <div class="header">Send Contact</div>
- <div class="description">
- Send contact to user or group
- </div>
- </div>
- </div>
-
- <!-- Modal SendContact -->
- <div class="ui small modal" id="modalSendContact">
- <i class="close icon"></i>
- <div class="header">
- Send Contact
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone"/>
-
- <div class="field">
- <label>Contact Name</label>
- <input v-model="card_name" type="text" placeholder="Please enter contact name"
- aria-label="contact name">
- </div>
- <div class="field">
- <label>Contact Phone</label>
- <input v-model="card_phone" type="text" placeholder="Please enter contact phone"
- aria-label="contact phone">
- </div>
- <div class="field" v-if="isShowAttributes()">
- <label>Is Forwarded</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="is forwarded" v-model="is_forwarded">
- <label>Mark contact as forwarded</label>
- </div>
- </div>
- <div class="field">
- <label>Disappearing Duration (seconds)</label>
- <input v-model.number="duration" type="number" min="0" placeholder="0 (no expiry)" aria-label="duration"/>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button" :class="{'loading': this.loading, 'disabled': !isValidForm() || loading}"
- @click.prevent="handleSubmit">
- Send
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/SendFile.js b/src/views/components/SendFile.js
deleted file mode 100644
index 3175416f..00000000
--- a/src/views/components/SendFile.js
+++ /dev/null
@@ -1,179 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'SendFile',
- components: {
- FormRecipient
- },
- props: {
- maxFileSize: {
- type: String,
- required: true,
- }
- },
- data() {
- return {
- caption: '',
- reply_message_id: '',
- type: window.TYPEUSER,
- phone: '',
- loading: false,
- selectedFileName: null,
- is_forwarded: false,
- duration: 0
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- }
- },
- methods: {
- openModal() {
- $('#modalSendFile').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isShowAttributes() {
- return this.type !== window.TYPESTATUS;
- },
- isValidForm() {
- if (this.type !== window.TYPESTATUS && !this.phone.trim()) {
- return false;
- }
-
- if (!this.selectedFileName) {
- return false;
- }
-
- return true;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
-
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalSendFile').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let payload = new FormData();
- payload.append("caption", this.caption)
- payload.append("phone", this.phone_id)
- payload.append("is_forwarded", this.is_forwarded)
- const replyMessageID = this.reply_message_id.trim()
- if (this.isShowAttributes() && replyMessageID !== '') {
- payload.append("reply_message_id", replyMessageID)
- }
- if (this.duration && this.duration > 0) {
- payload.append("duration", this.duration)
- }
- payload.append("file", $("#file_file")[0].files[0])
- let response = await window.http.post(`/send/file`, payload)
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.caption = '';
- this.reply_message_id = '';
- this.phone = '';
- this.type = window.TYPEUSER;
- this.selectedFileName = null;
- this.is_forwarded = false;
- this.duration = 0;
- $("#file_file").val('');
- },
- handleFileChange(event) {
- const file = event.target.files[0];
- if (file) {
- this.selectedFileName = file.name;
- }
- }
- },
- template: `
- <div class="blue card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui blue right ribbon label">Send</a>
- <div class="header">Send File</div>
- <div class="description">
- Send any file up to
- <div class="ui blue horizontal label">{{ maxFileSize }}</div>
- </div>
- </div>
- </div>
-
- <!-- Modal SendFile -->
- <div class="ui small modal" id="modalSendFile">
- <i class="close icon"></i>
- <div class="header">
- Send File
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone"/>
-
- <div class="field" v-if="isShowAttributes()">
- <label>Reply Message ID</label>
- <input v-model="reply_message_id" type="text"
- placeholder="Optional: 57D29F74B7FC62F57D8AC2C840279B5B/3EB0288F008D32FCD0A424"
- aria-label="reply_message_id">
- </div>
- <div class="field">
- <label>Caption</label>
- <textarea v-model="caption" placeholder="Type some caption (optional)..."
- aria-label="caption"></textarea>
- </div>
- <div class="field" v-if="isShowAttributes()">
- <label>Is Forwarded</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="is forwarded" v-model="is_forwarded">
- <label>Mark file as forwarded</label>
- </div>
- </div>
- <div class="field">
- <label>Disappearing Duration (seconds)</label>
- <input v-model.number="duration" type="number" min="0" placeholder="0 (no expiry)" aria-label="duration"/>
- </div>
- <div class="field" style="padding-bottom: 30px">
- <label>File</label>
- <input type="file" style="display: none" id="file_file" @change="handleFileChange">
- <label for="file_file" class="ui positive medium green left floated button" style="color: white">
- <i class="ui upload icon"></i>
- Upload file
- </label>
- <div v-if="selectedFileName" style="margin-top: 60px; clear: both;">
- <div class="ui message">
- <i class="file icon"></i>
- Selected file: {{ selectedFileName }}
- </div>
- </div>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button" :class="{'loading': this.loading, 'disabled': !isValidForm() || loading}"
- @click.prevent="handleSubmit">
- Send
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `
-}
diff --git a/src/views/components/SendForward.js b/src/views/components/SendForward.js
deleted file mode 100644
index 18eafc3a..00000000
--- a/src/views/components/SendForward.js
+++ /dev/null
@@ -1,130 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'SendForward',
- components: {
- FormRecipient
- },
- data() {
- return {
- type: window.TYPEUSER,
- phone: '',
- message_id: '',
- force_reupload: false,
- duration: 0,
- loading: false,
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- }
- },
- methods: {
- openModal() {
- $('#modalSendForward').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- if (this.type !== window.TYPESTATUS && !this.phone.trim()) {
- return false;
- }
- if (!this.message_id.trim()) {
- return false;
- }
- return true;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- const response = await this.submitApi();
- showSuccessInfo(response);
- $('#modalSendForward').modal('hide');
- } catch (err) {
- showErrorInfo(err);
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- const payload = {
- phone: this.phone_id,
- force_reupload: this.force_reupload,
- };
- if (this.duration && this.duration > 0) {
- payload.duration = this.duration;
- }
- const response = await window.http.post(`/message/${this.message_id.trim()}/forward`, payload);
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response?.data?.message) {
- throw new Error(error.response.data.message);
- }
- throw error;
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.phone = '';
- this.message_id = '';
- this.force_reupload = false;
- this.duration = 0;
- this.type = window.TYPEUSER;
- },
- },
- template: `
- <div class="red card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui red right ribbon label">Message</a>
- <div class="header">Forward Message</div>
- <div class="description">
- Forward a stored message to another chat by message ID
- </div>
- </div>
- </div>
-
- <div class="ui small modal" id="modalSendForward">
- <i class="close icon"></i>
- <div class="header">
- Forward Message
- </div>
- <div class="content">
- <form class="ui form">
- <div class="field">
- <label>Source Message ID</label>
- <input v-model="message_id" type="text"
- placeholder="57D29F74B7FC62F57D8AC2C840279B5B/3EB0288F008D32FCD0A424"
- aria-label="message id">
- </div>
- <FormRecipient v-model:type="type" v-model:phone="phone"/>
- <div class="field">
- <label>Force Re-upload</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="force reupload" v-model="force_reupload">
- <label>Re-download and re-upload media instead of reusing CDN refs</label>
- </div>
- </div>
- <div class="field">
- <label>Disappearing Duration (seconds)</label>
- <input v-model.number="duration" type="number" min="0" placeholder="0 (no expiry)" aria-label="duration"/>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button"
- :class="{'loading': loading, 'disabled': !isValidForm() || loading}"
- @click.prevent="handleSubmit">
- Forward
- <i class="share icon"></i>
- </button>
- </div>
- </div>
- `
-}
diff --git a/src/views/components/SendImage.js b/src/views/components/SendImage.js
deleted file mode 100644
index 509325ed..00000000
--- a/src/views/components/SendImage.js
+++ /dev/null
@@ -1,227 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'SendImage',
- components: {
- FormRecipient
- },
- data() {
- return {
- phone: '',
- view_once: false,
- compress: false,
- caption: '',
- reply_message_id: '',
- type: window.TYPEUSER,
- loading: false,
- selected_file: null,
- image_url: null,
- preview_url: null,
- is_forwarded: false,
- duration: 0
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- },
- },
- watch: {
- view_once(newValue) {
- // If view_once is set to true, set is_forwarded to false
- if (newValue === true) {
- this.is_forwarded = false;
- this.duration = 0;
- }
- }
- },
- methods: {
- openModal() {
- $('#modalSendImage').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isShowAttributes() {
- return this.type !== window.TYPESTATUS;
- },
- isValidForm() {
- if (this.type !== window.TYPESTATUS && !this.phone.trim()) {
- return false;
- }
-
- if (!this.selected_file && !this.image_url) {
- return false;
- }
-
- return true;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
-
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalSendImage').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let payload = new FormData();
- payload.append("phone", this.phone_id)
- payload.append("view_once", this.view_once)
- payload.append("compress", this.compress)
- payload.append("caption", this.caption)
- payload.append("is_forwarded", this.is_forwarded)
- const replyMessageID = this.reply_message_id.trim()
- if (this.isShowAttributes() && replyMessageID !== '') {
- payload.append("reply_message_id", replyMessageID)
- }
- if (this.duration && this.duration > 0) {
- payload.append("duration", this.duration)
- }
-
- const fileInput = $("#file_image");
- if (fileInput.length > 0 && fileInput[0].files.length > 0) {
- const file = fileInput[0].files[0];
- payload.append('image', file);
- }
- if (this.image_url) {
- payload.append('image_url', this.image_url)
- }
-
- let response = await window.http.post(`/send/image`, payload)
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.view_once = false;
- this.compress = false;
- this.phone = '';
- this.caption = '';
- this.reply_message_id = '';
- this.preview_url = null;
- this.selected_file = null;
- this.image_url = null;
- this.is_forwarded = false;
- this.duration = 0;
- $("#file_image").val('');
- },
- handleImageChange(event) {
- const file = event.target.files[0];
- if (file) {
- this.preview_url = URL.createObjectURL(file);
- // Add small delay to allow DOM update before scrolling
- setTimeout(() => {
- const modalContent = document.querySelector('#modalSendImage .content');
- if (modalContent) {
- modalContent.scrollTop = modalContent.scrollHeight;
- }
- this.selected_file = file.name;
- }, 100);
- }
- }
- },
- template: `
- <div class="blue card" @click="openModal()" style="cursor:pointer;">
- <div class="content">
- <a class="ui blue right ribbon label">Send</a>
- <div class="header">Send Image</div>
- <div class="description">
- Send image with
- <div class="ui blue horizontal label">jpg/jpeg/png</div>
- type
- </div>
- </div>
- </div>
-
- <!-- Modal SendImage -->
- <div class="ui small modal" id="modalSendImage">
- <i class="close icon"></i>
- <div class="header">
- Send Image
- </div>
- <div class="content" style="max-height: 70vh; overflow-y: auto;">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone" :show-status="true"/>
-
- <div class="field" v-if="isShowAttributes()">
- <label>Reply Message ID</label>
- <input v-model="reply_message_id" type="text"
- placeholder="Optional: 57D29F74B7FC62F57D8AC2C840279B5B/3EB0288F008D32FCD0A424"
- aria-label="reply_message_id">
- </div>
- <div class="field">
- <label>Caption</label>
- <textarea v-model="caption" type="text" placeholder="Hello this is image caption"
- aria-label="caption"></textarea>
- </div>
- <div class="field" v-if="isShowAttributes()">
- <label>View Once</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="view once" v-model="view_once">
- <label>Check for enable one time view</label>
- </div>
- </div>
- <div class="field" v-if="isShowAttributes()">
- <label>Compress</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="compress" v-model="compress">
- <label>Check for compressing image to smaller size</label>
- </div>
- </div>
- <div class="field" v-if="isShowAttributes() && !view_once">
- <label>Is Forwarded</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="is forwarded" v-model="is_forwarded">
- <label>Mark image as forwarded</label>
- </div>
- </div>
- <div class="field">
- <label>Disappearing Duration (seconds)</label>
- <input v-model.number="duration" type="number" min="0" placeholder="0 (no expiry)" aria-label="duration"/>
- </div>
- <div class="field">
- <label>Image URL</label>
- <input type="text" v-model="image_url" placeholder="https://example.com/image.jpg"
- aria-label="image_url"/>
- </div>
- <div style="text-align: left; font-weight: bold; margin: 10px 0;">or you can upload image from your device</div>
- <div class="field" style="padding-bottom: 30px">
- <label>Image</label>
- <input type="file" style="display: none" id="file_image" accept="image/png,image/jpg,image/jpeg" @change="handleImageChange"/>
- <label for="file_image" class="ui positive medium green left floated button" style="color: white">
- <i class="ui upload icon"></i>
- Upload image
- </label>
- <div v-if="preview_url" style="margin-top: 60px">
- <img :src="preview_url" style="max-width: 100%; max-height: 300px; object-fit: contain" />
- </div>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button"
- :class="{'loading': this.loading, 'disabled': !isValidForm() || loading}"
- @click.prevent="handleSubmit">
- Send
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `
-}
diff --git a/src/views/components/SendLink.js b/src/views/components/SendLink.js
deleted file mode 100644
index 2c44c52b..00000000
--- a/src/views/components/SendLink.js
+++ /dev/null
@@ -1,155 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'SendLink',
- components: {
- FormRecipient
- },
- data() {
- return {
- type: window.TYPEUSER,
- phone: '',
- link: '',
- caption: '',
- reply_message_id: '',
- loading: false,
- is_forwarded: false,
- duration: 0
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- },
- },
- methods: {
- openModal() {
- $('#modalSendLink').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isShowReplyId() {
- return this.type !== window.TYPESTATUS;
- },
- isValidForm() {
- // Validate phone number is not empty except for status type
- const isPhoneValid = this.type === window.TYPESTATUS || this.phone.trim().length > 0;
-
- // Validate link is not empty and has reasonable length
- const isLinkValid = this.link.trim().length > 0 && this.link.length <= 4096;
-
- // Validate caption is not empty and has reasonable length
- const isCaptionValid = this.caption.trim().length > 0 && this.caption.length <= 4096;
-
- return isPhoneValid && isLinkValid && isCaptionValid
- },
- async handleSubmit() {
- // Add validation check here to prevent submission when form is invalid
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- const response = await this.submitApi();
- showSuccessInfo(response);
- $('#modalSendLink').modal('hide');
- } catch (err) {
- showErrorInfo(err);
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- const payload = {
- phone: this.phone_id,
- link: this.link.trim(),
- caption: this.caption.trim(),
- is_forwarded: this.is_forwarded,
- ...(this.duration && this.duration > 0 ? {duration: this.duration} : {})
- };
- if (this.reply_message_id !== '') {
- payload.reply_message_id = this.reply_message_id;
- }
-
- const response = await window.http.post('/send/link', payload);
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response?.data?.message) {
- throw new Error(error.response.data.message);
- }
- throw error;
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.phone = '';
- this.link = '';
- this.caption = '';
- this.reply_message_id = '';
- this.is_forwarded = false;
- this.duration = 0;
- },
- },
- template: `
- <div class="blue card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui blue right ribbon label">Send</a>
- <div class="header">Send Link</div>
- <div class="description">
- Send link to user or group
- </div>
- </div>
- </div>
-
- <!-- Modal SendLink -->
- <div class="ui small modal" id="modalSendLink">
- <i class="close icon"></i>
- <div class="header">
- Send Link
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone" :show-status="true"/>
- <div class="field" v-if="isShowReplyId()">
- <label>Reply Message ID</label>
- <input v-model="reply_message_id" type="text"
- placeholder="Optional: 57D29F74B7FC62F57D8AC2C840279B5B/3EB0288F008D32FCD0A424"
- aria-label="reply_message_id">
- </div>
- <div class="field">
- <label>Link</label>
- <input v-model="link" type="text" placeholder="https://www.google.com"
- aria-label="link">
- </div>
- <div class="field">
- <label>Caption</label>
- <textarea v-model="caption" placeholder="Hello this is caption"
- aria-label="caption"></textarea>
- </div>
- <div class="field" v-if="isShowReplyId()">
- <label>Is Forwarded</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="is forwarded" v-model="is_forwarded">
- <label>Mark link as forwarded</label>
- </div>
- </div>
- <div class="field">
- <label>Disappearing Duration (seconds)</label>
- <input v-model.number="duration" type="number" min="0" placeholder="0 (no expiry)" aria-label="duration"/>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button"
- :class="{'disabled': !isValidForm() || loading}"
- @click.prevent="handleSubmit">
- Send
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/SendLocation.js b/src/views/components/SendLocation.js
deleted file mode 100644
index 83499a1e..00000000
--- a/src/views/components/SendLocation.js
+++ /dev/null
@@ -1,145 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'SendLocation',
- components: {
- FormRecipient
- },
- data() {
- return {
- type: window.TYPEUSER,
- phone: '',
- latitude: '',
- longitude: '',
- loading: false,
- is_forwarded: false,
- duration: 0
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- },
- isValidForm() {
- // Validate phone number is not empty except for status type
- const isPhoneValid = this.type === window.TYPESTATUS || this.phone.trim().length > 0;
-
- // Validate latitude is between -90 and 90
- const isLatitudeValid = !isNaN(this.latitude) &&
- parseFloat(this.latitude) >= -90 &&
- parseFloat(this.latitude) <= 90;
-
- // Validate longitude is between -180 and 180
- const isLongitudeValid = !isNaN(this.longitude) &&
- parseFloat(this.longitude) >= -180 &&
- parseFloat(this.longitude) <= 180;
-
- return isPhoneValid && isLatitudeValid && isLongitudeValid;
- }
- },
- methods: {
- openModal() {
- $('#modalSendLocation').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isShowAttributes() {
- return this.type !== window.TYPESTATUS;
- },
- async handleSubmit() {
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalSendLocation').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- const payload = {
- phone: this.phone_id,
- latitude: this.latitude,
- longitude: this.longitude,
- is_forwarded: this.is_forwarded,
- ...(this.duration && this.duration > 0 ? {duration: this.duration} : {})
- };
-
- const response = await window.http.post(`/send/location`, payload);
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.phone = '';
- this.latitude = '';
- this.longitude = '';
- this.type = window.TYPEUSER;
- this.is_forwarded = false;
- this.duration = 0;
- },
- },
- template: `
- <div class="blue card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui blue right ribbon label">Send</a>
- <div class="header">Send Location</div>
- <div class="description">
- Send location to user or group
- </div>
- </div>
- </div>
-
- <!-- Modal SendLocation -->
- <div class="ui small modal" id="modalSendLocation">
- <i class="close icon"></i>
- <div class="header">
- Send Location
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone"/>
-
- <div class="field">
- <label>Location Latitude</label>
- <input v-model="latitude" type="text" placeholder="Please enter latitude (-90 to 90)"
- aria-label="latitude">
- </div>
- <div class="field">
- <label>Location Longitude</label>
- <input v-model="longitude" type="text" placeholder="Please enter longitude (-180 to 180)"
- aria-label="longitude">
- </div>
- <div class="field" v-if="isShowAttributes()">
- <label>Is Forwarded</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="is forwarded" v-model="is_forwarded">
- <label>Mark location as forwarded</label>
- </div>
- </div>
- <div class="field">
- <label>Disappearing Duration (seconds)</label>
- <input v-model.number="duration" type="number" min="0" placeholder="0 (no expiry)" aria-label="duration"/>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button" :class="{'loading': this.loading}"
- @click="handleSubmit" :disabled="!isValidForm">
- Send
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/SendMessage.js b/src/views/components/SendMessage.js
deleted file mode 100644
index 7e9aeb77..00000000
--- a/src/views/components/SendMessage.js
+++ /dev/null
@@ -1,164 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'SendMessage',
- components: {
- FormRecipient
- },
- data() {
- return {
- type: window.TYPEUSER,
- phone: '',
- text: '',
- reply_message_id: '',
- is_forwarded: false,
- mention_everyone: false,
- duration: 0,
- loading: false,
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- },
- },
- methods: {
- openModal() {
- $('#modalSendMessage').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isShowReplyId() {
- return this.type !== window.TYPESTATUS;
- },
- isGroup() {
- return this.type === window.TYPEGROUP;
- },
- isValidForm() {
- // Validate phone number is not empty except for status type
- const isPhoneValid = this.type === window.TYPESTATUS || this.phone.trim().length > 0;
-
- // Validate message is not empty and has reasonable length
- const isMessageValid = this.text.trim().length > 0 && this.text.length <= 4096;
-
- return isPhoneValid && isMessageValid
- },
- async handleSubmit() {
- // Add validation check here to prevent submission when form is invalid
- if (!this.isValidForm() || this.loading) {
- return;
- }
- try {
- const response = await this.submitApi();
- showSuccessInfo(response);
- $('#modalSendMessage').modal('hide');
- } catch (err) {
- showErrorInfo(err);
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- const payload = {
- phone: this.phone_id,
- message: this.text.trim(),
- is_forwarded: this.is_forwarded
- };
- if (this.reply_message_id !== '') {
- payload.reply_message_id = this.reply_message_id;
- }
-
- if (this.duration && this.duration > 0) {
- payload.duration = this.duration;
- }
-
- // Add mentions if mention_everyone is checked (only for groups)
- if (this.mention_everyone && this.type === window.TYPEGROUP) {
- payload.mentions = ["@everyone"];
- }
-
- const response = await window.http.post('/send/message', payload);
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response?.data?.message) {
- throw new Error(error.response.data.message);
- }
- throw error;
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.phone = '';
- this.text = '';
- this.reply_message_id = '';
- this.is_forwarded = false;
- this.mention_everyone = false;
- this.duration = 0;
- },
- },
- template: `
- <div class="blue card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui blue right ribbon label">Send</a>
- <div class="header">Send Message</div>
- <div class="description">
- Send any message to user or group
- </div>
- </div>
- </div>
-
- <!-- Modal SendMessage -->
- <div class="ui small modal" id="modalSendMessage">
- <i class="close icon"></i>
- <div class="header">
- Send Message
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone" :show-status="true"/>
- <div class="field" v-if="isShowReplyId()">
- <label>Reply Message ID</label>
- <input v-model="reply_message_id" type="text"
- placeholder="Optional: 57D29F74B7FC62F57D8AC2C840279B5B/3EB0288F008D32FCD0A424"
- aria-label="reply_message_id">
- </div>
- <div class="field">
- <label>Message</label>
- <textarea v-model="text" placeholder="Hello this is message text"
- aria-label="message"></textarea>
- </div>
- <div class="field" v-if="isShowReplyId()">
- <label>Is Forwarded</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="is forwarded" v-model="is_forwarded">
- <label>Mark message as forwarded</label>
- </div>
- </div>
- <div class="field" v-if="isGroup()">
- <label>Mention Everyone</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="mention everyone" v-model="mention_everyone">
- <label>Mention all group participants (@everyone)</label>
- </div>
- </div>
- <div class="field">
- <label>Disappearing Duration (seconds)</label>
- <input v-model.number="duration" type="number" min="0" placeholder="0 (no expiry)" aria-label="duration"/>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button"
- :class="{'disabled': !isValidForm() || loading}"
- @click.prevent="handleSubmit">
- Send
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/SendPoll.js b/src/views/components/SendPoll.js
deleted file mode 100644
index 664635cf..00000000
--- a/src/views/components/SendPoll.js
+++ /dev/null
@@ -1,168 +0,0 @@
-// export Vue Component
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'SendPoll',
- components: {
- FormRecipient
- },
- data() {
- return {
- phone: '',
- type: window.TYPEUSER,
- loading: false,
- question: '',
- options: ['', ''],
- max_answer: 1,
- duration: 0,
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- }
- },
- methods: {
- openModal() {
- $('#modalSendPoll').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isValidForm() {
- if (this.type !== window.TYPESTATUS && !this.phone.trim()) {
- return false;
- }
-
- if (!this.question.trim()) {
- return false;
- }
-
- if (this.options.some(option => option.trim() === '')) {
- return false;
- }
-
- if (this.max_answer < 1 || this.max_answer > this.options.length) {
- return false;
- }
-
- return true;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
-
- try {
- let response = await this.submitApi()
- window.showSuccessInfo(response)
- $('#modalSendPoll').modal('hide');
- } catch (err) {
- window.showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- const payload = {
- phone: this.phone_id,
- question: this.question,
- options: this.options,
- max_answer: this.max_answer,
- ...(this.duration && this.duration > 0 ? {duration: this.duration} : {})
- }
- const response = await window.http.post(`/send/poll`, payload)
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.phone = '';
- this.type = window.TYPEUSER;
- this.question = '';
- this.options = ['', ''];
- this.max_answer = 1;
- this.duration = 0;
- },
- addOption() {
- this.options.push('')
- },
- deleteOption(index) {
- this.options.splice(index, 1)
- }
- },
- template: `
- <div class="blue card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui blue right ribbon label">Send</a>
- <div class="header">Send Poll</div>
- <div class="description">
- Send a poll/vote with multiple options
- </div>
- </div>
- </div>
-
- <!-- Modal SendPoll -->
- <div class="ui small modal" id="modalSendPoll">
- <i class="close icon"></i>
- <div class="header">
- Send Poll
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone"/>
-
- <div class="field">
- <label>Question</label>
- <input v-model="question" type="text" placeholder="Please enter question"
- aria-label="poll question">
- </div>
- <div class="field">
- <label>Options</label>
- <div style="display: flex; flex-direction: column; gap: 5px">
- <div class="ui action input" :key="index" v-for="(option, index) in options">
- <input type="text" placeholder="Option..." v-model="options[index]"
- aria-label="poll option">
- <button class="ui button" @click="deleteOption(index)" type="button">
- <i class="minus circle icon"></i>
- </button>
- </div>
- <div class="field">
- <button class="mini ui primary button" @click="addOption" type="button">
- <i class="plus icon"></i> Option
- </button>
- </div>
- </div>
- </div>
- <div class="field">
- <label>Max Answers Allowed</label>
- <input v-model.number="max_answer" type="number" placeholder="Maximum answers per user"
- aria-label="poll max answers" min="1" max="50">
- <div class="ui pointing label">
- How many options each user can select
- </div>
- </div>
- <div class="field">
- <label>Disappearing Duration (seconds)</label>
- <input v-model.number="duration" type="number" min="0" placeholder="0 (no expiry)" aria-label="duration"/>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button" :class="{'loading': this.loading, 'disabled': !isValidForm() || loading}"
- @click.prevent="handleSubmit">
- Send
- <i class="send icon"></i>
- </button>
- </div>
- </div>
-`
-}
\ No newline at end of file
diff --git a/src/views/components/SendPresence.js b/src/views/components/SendPresence.js
deleted file mode 100644
index 1e57764a..00000000
--- a/src/views/components/SendPresence.js
+++ /dev/null
@@ -1,86 +0,0 @@
-export default {
- name: 'SendPresence',
- data() {
- return {
- type: 'available',
- loading: false,
- }
- },
- methods: {
- openModal() {
- $('#modalSendPresence').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- async handleSubmit() {
- if (this.loading) {
- return;
- }
-
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalSendPresence').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let payload = {
- type: this.type
- }
- let response = await window.http.post(`/send/presence`, payload)
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- }
- },
- template: `
- <div class="blue card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui blue right ribbon label">Send</a>
- <div class="header">Send Presence</div>
- <div class="description">
- Set <div class="ui green horizontal label">available</div> or <div class="ui grey horizontal label">unavailable</div>
- </div>
- </div>
- </div>
-
- <!-- Modal SendPresence -->
- <div class="ui small modal" id="modalSendPresence">
- <i class="close icon"></i>
- <div class="header">
- Send Presence
- </div>
- <div class="content">
- <form class="ui form">
- <div class="field">
- <label>Presence Status</label>
- <select v-model="type" class="ui dropdown">
- <option value="available">Available</option>
- <option value="unavailable">Unavailable</option>
- </select>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button"
- :class="{'loading': loading, 'disabled': loading}"
- @click.prevent="handleSubmit">
- Send
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/SendSticker.js b/src/views/components/SendSticker.js
deleted file mode 100644
index cae0c61f..00000000
--- a/src/views/components/SendSticker.js
+++ /dev/null
@@ -1,190 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'SendSticker',
- components: {
- FormRecipient
- },
- data() {
- return {
- phone: '',
- type: window.TYPEUSER,
- loading: false,
- selected_file: null,
- sticker_url: null,
- preview_url: null,
- is_forwarded: false,
- duration: 0
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- },
- },
- methods: {
- openModal() {
- $('#modalSendSticker').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isShowAttributes() {
- return this.type !== window.TYPESTATUS;
- },
- isValidForm() {
- if (this.type !== window.TYPESTATUS && !this.phone.trim()) {
- return false;
- }
-
- if (!this.selected_file && !this.sticker_url) {
- return false;
- }
-
- return true;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
-
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalSendSticker').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let payload = new FormData();
- payload.append("phone", this.phone_id)
- payload.append("is_forwarded", this.is_forwarded)
- if (this.duration && this.duration > 0) {
- payload.append("duration", this.duration)
- }
-
- const fileInput = $("#file_sticker");
- if (fileInput.length > 0 && fileInput[0].files.length > 0) {
- const file = fileInput[0].files[0];
- payload.append('sticker', file);
- }
- if (this.sticker_url) {
- payload.append('sticker_url', this.sticker_url)
- }
-
- let response = await window.http.post(`/send/sticker`, payload)
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.phone = '';
- this.preview_url = null;
- this.selected_file = null;
- this.sticker_url = null;
- this.is_forwarded = false;
- this.duration = 0;
- $("#file_sticker").val('');
- },
- handleStickerChange(event) {
- const file = event.target.files[0];
- if (file) {
- this.preview_url = URL.createObjectURL(file);
- // Add small delay to allow DOM update before scrolling
- setTimeout(() => {
- const modalContent = document.querySelector('#modalSendSticker .content');
- if (modalContent) {
- modalContent.scrollTop = modalContent.scrollHeight;
- }
- this.selected_file = file.name;
- }, 100);
- }
- }
- },
- template: `
- <div class="blue card" @click="openModal()" style="cursor:pointer;">
- <div class="content">
- <a class="ui blue right ribbon label">Send</a>
- <div class="header">Send Sticker</div>
- <div class="description">
- Send sticker with automatic conversion to WebP format
- <div class="ui blue horizontal label">jpg/jpeg/png/webp/gif</div>
- </div>
- </div>
- </div>
-
- <!-- Modal SendSticker -->
- <div class="ui small modal" id="modalSendSticker">
- <i class="close icon"></i>
- <div class="header">
- Send Sticker
- </div>
- <div class="content" style="max-height: 70vh; overflow-y: auto;">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone" :show-status="true"/>
-
- <div class="ui info message">
- <div class="header">Sticker Information</div>
- <ul class="list">
- <li>Images will be automatically converted to WebP sticker format</li>
- <li>Maximum sticker size is 512x512 pixels (automatic resizing)</li>
- <li>Supports JPG, JPEG, PNG, WebP, and GIF formats</li>
- <li>Transparent backgrounds are preserved for PNG images</li>
- </ul>
- </div>
-
- <div class="field" v-if="isShowAttributes()">
- <label>Is Forwarded</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="is forwarded" v-model="is_forwarded">
- <label>Mark sticker as forwarded</label>
- </div>
- </div>
- <div class="field">
- <label>Disappearing Duration (seconds)</label>
- <input v-model.number="duration" type="number" min="0" placeholder="0 (no expiry)" aria-label="duration"/>
- </div>
- <div class="field">
- <label>Sticker URL</label>
- <input type="text" v-model="sticker_url" placeholder="https://example.com/sticker.png"
- aria-label="sticker_url"/>
- </div>
- <div style="text-align: left; font-weight: bold; margin: 10px 0;">or you can upload sticker from your device</div>
- <div class="field" style="padding-bottom: 30px">
- <label>Sticker Image</label>
- <input type="file" style="display: none" id="file_sticker" accept="image/png,image/jpg,image/jpeg,image/webp,image/gif" @change="handleStickerChange"/>
- <label for="file_sticker" class="ui positive medium blue left floated button" style="color: white">
- <i class="ui upload icon"></i>
- Upload sticker
- </label>
- <div v-if="preview_url" style="margin-top: 60px">
- <div class="ui segment">
- <img :src="preview_url" style="max-width: 100%; max-height: 300px; object-fit: contain" />
- <div class="ui top attached label">Preview (will be converted to WebP sticker)</div>
- </div>
- </div>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button"
- :class="{'loading': this.loading, 'disabled': !isValidForm() || loading}"
- @click.prevent="handleSubmit">
- Send
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/components/SendVideo.js b/src/views/components/SendVideo.js
deleted file mode 100644
index 895f7bb0..00000000
--- a/src/views/components/SendVideo.js
+++ /dev/null
@@ -1,248 +0,0 @@
-import FormRecipient from "./generic/FormRecipient.js";
-
-export default {
- name: 'SendVideo',
- components: {
- FormRecipient
- },
- props: {
- maxVideoSize: {
- type: String,
- required: true,
- }
- },
- data() {
- return {
- caption: '',
- reply_message_id: '',
- view_once: false,
- compress: false,
- gif_playback: false,
- type: window.TYPEUSER,
- phone: '',
- loading: false,
- video_url: null,
- selectedFileName: null,
- is_forwarded: false,
- duration: 0
- }
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- },
- },
- watch: {
- view_once(newValue) {
- // If view_once is set to true, set is_forwarded to false
- if (newValue === true) {
- this.is_forwarded = false;
- this.duration = 0;
- }
- }
- },
- methods: {
- openModal() {
- $('#modalSendVideo').modal({
- onApprove: function () {
- return false;
- }
- }).modal('show');
- },
- isShowAttributes() {
- return this.type !== window.TYPESTATUS;
- },
- isValidForm() {
- let isValid = true;
-
- if (this.type !== window.TYPESTATUS && !this.phone.trim()) {
- isValid = false;
- }
-
- const fileInput = $("#file_video")[0];
- const hasFile = fileInput && fileInput.files && fileInput.files[0];
-
- if (!hasFile && !this.video_url) {
- isValid = false;
- }
-
- if (hasFile) {
- const videoFile = fileInput.files[0];
- if (!videoFile.type.startsWith('video/')) {
- isValid = false;
- }
- }
-
- return isValid;
- },
- async handleSubmit() {
- if (!this.isValidForm() || this.loading) {
- return;
- }
-
- try {
- let response = await this.submitApi()
- showSuccessInfo(response)
- $('#modalSendVideo').modal('hide');
- } catch (err) {
- showErrorInfo(err)
- }
- },
- async submitApi() {
- this.loading = true;
- try {
- let payload = new FormData();
- payload.append("phone", this.phone_id)
- payload.append("caption", this.caption.trim())
- payload.append("view_once", this.view_once)
- payload.append("compress", this.compress)
- payload.append("gif_playback", this.gif_playback)
- payload.append("is_forwarded", this.is_forwarded)
- const replyMessageID = this.reply_message_id.trim()
- if (this.isShowAttributes() && replyMessageID !== '') {
- payload.append("reply_message_id", replyMessageID)
- }
- if (this.duration && this.duration > 0) {
- payload.append("duration", this.duration)
- }
-
- const fileInput = $("#file_video")[0];
- if (fileInput && fileInput.files && fileInput.files[0]) {
- payload.append('video', fileInput.files[0])
- }
- if (this.video_url) {
- payload.append('video_url', this.video_url)
- }
-
- let response = await window.http.post(`/send/video`, payload)
- this.handleReset();
- return response.data.message;
- } catch (error) {
- if (error.response) {
- throw new Error(error.response.data.message);
- }
- throw new Error(error.message);
- } finally {
- this.loading = false;
- }
- },
- handleReset() {
- this.caption = '';
- this.reply_message_id = '';
- this.view_once = false;
- this.compress = false;
- this.gif_playback = false;
- this.phone = '';
- this.selectedFileName = null;
- this.video_url = null;
- this.is_forwarded = false;
- this.duration = 0;
- $("#file_video").val('');
- },
- handleFileChange(event) {
- const file = event.target.files[0];
- if (file) {
- this.selectedFileName = file.name;
- }
- }
- },
- template: `
- <div class="blue card" @click="openModal()" style="cursor: pointer">
- <div class="content">
- <a class="ui blue right ribbon label">Send</a>
- <div class="header">Send Video</div>
- <div class="description">
- Send video
- <div class="ui blue horizontal label">mp4</div>
- up to
- <div class="ui blue horizontal label">{{ maxVideoSize }}</div>
- </div>
- </div>
- </div>
-
- <!-- Modal SendVideo -->
- <div class="ui small modal" id="modalSendVideo">
- <i class="close icon"></i>
- <div class="header">
- Send Video
- </div>
- <div class="content">
- <form class="ui form">
- <FormRecipient v-model:type="type" v-model:phone="phone" :show-status="true"/>
-
- <div class="field" v-if="isShowAttributes()">
- <label>Reply Message ID</label>
- <input v-model="reply_message_id" type="text"
- placeholder="Optional: 57D29F74B7FC62F57D8AC2C840279B5B/3EB0288F008D32FCD0A424"
- aria-label="reply_message_id">
- </div>
- <div class="field">
- <label>Caption</label>
- <textarea v-model="caption" placeholder="Type some caption (optional)..."
- aria-label="caption"></textarea>
- </div>
- <div class="field" v-if="isShowAttributes()">
- <label>View Once</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="view once" v-model="view_once">
- <label>Check for enable one time view</label>
- </div>
- </div>
- <div class="field" v-if="isShowAttributes()">
- <label>Compress</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="compress" v-model="compress">
- <label>Check for compressing video to smaller size</label>
- </div>
- </div>
- <div class="field" v-if="isShowAttributes()">
- <label>GIF Playback</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="gif playback" v-model="gif_playback">
- <label>Display video as GIF (looping, silent, autoplay)</label>
- </div>
- </div>
- <div class="field" v-if="isShowAttributes() && !view_once">
- <label>Is Forwarded</label>
- <div class="ui toggle checkbox">
- <input type="checkbox" aria-label="is forwarded" v-model="is_forwarded">
- <label>Mark video as forwarded</label>
- </div>
- </div>
- <div class="field">
- <label>Disappearing Duration (seconds)</label>
- <input v-model.number="duration" type="number" min="0" placeholder="0 (no expiry)" aria-label="duration"/>
- </div>
- <div class="field">
- <label>Video URL</label>
- <input type="text" v-model="video_url" placeholder="https://example.com/sample.mp4"
- aria-label="video_url" />
- </div>
- <div style="text-align: left; font-weight: bold; margin: 10px 0;" v-if="!video_url">or you can upload video from your device</div>
- <div class="field" style="padding-bottom: 30px" v-if="!video_url">
- <label>Video</label>
- <input type="file" style="display: none" accept="video/*" id="file_video" @change="handleFileChange">
- <label for="file_video" class="ui positive medium green left floated button" style="color: white">
- <i class="ui upload icon"></i>
- Upload video
- </label>
- <div v-if="selectedFileName" style="margin-top: 60px">
- <div class="ui message">
- <i class="file icon"></i>
- Selected file: {{ selectedFileName }}
- </div>
- </div>
- </div>
- </form>
- </div>
- <div class="actions">
- <button class="ui approve positive right labeled icon button"
- :class="{'loading': loading, 'disabled': !isValidForm() || loading}"
- @click.prevent="handleSubmit">
- Send
- <i class="send icon"></i>
- </button>
- </div>
- </div>
- `
-}
diff --git a/src/views/components/generic/FormRecipient.js b/src/views/components/generic/FormRecipient.js
deleted file mode 100644
index 6dfdab5a..00000000
--- a/src/views/components/generic/FormRecipient.js
+++ /dev/null
@@ -1,72 +0,0 @@
-export default {
- name: 'FormRecipient',
- props: {
- type: {
- type: String,
- required: true
- },
- phone: {
- type: String,
- required: true
- },
- showStatus: {
- type: Boolean,
- default: false
- }
- },
- data() {
- return {
- recipientTypes: []
- };
- },
- computed: {
- phone_id() {
- return this.phone + this.type;
- },
- showPhoneInput() {
- return this.type !== window.TYPESTATUS;
- },
- filteredRecipientTypes() {
- return this.recipientTypes.filter(type => {
- if (!this.showStatus && type.value === window.TYPESTATUS) {
- return false;
- }
- return true;
- });
- }
- },
- mounted() {
- this.recipientTypes = [
- { value: window.TYPEUSER, text: 'Private Message' },
- { value: window.TYPEGROUP, text: 'Group Message' },
- { value: window.TYPENEWSLETTER, text: 'Newsletter' },
- { value: window.TYPELID, text: 'LID (Linked ID)' },
- { value: window.TYPESTATUS, text: 'Status' }
- ];
- },
- methods: {
- updateType(event) {
- this.$emit('update:type', event.target.value);
- if (event.target.value === window.TYPESTATUS) {
- this.$emit('update:phone', '');
- }
- },
- updatePhone(event) {
- this.$emit('update:phone', event.target.value);
- }
- },
- template: `
- <div class="field">
- <label>Type</label>
- <select name="type" @change="updateType" class="ui dropdown">
- <option v-for="type in filteredRecipientTypes" :value="type.value">{{ type.text }}</option>
- </select>
- </div>
-
- <div v-if="showPhoneInput" class="field">
- <label>Phone / Group ID</label>
- <input :value="phone" aria-label="wa identifier" @input="updatePhone">
- <input :value="phone_id" disabled aria-label="whatsapp_id">
- </div>
- `
-}
\ No newline at end of file
diff --git a/src/views/index.html b/src/views/index.html
deleted file mode 100644
index c13c1265..00000000
--- a/src/views/index.html
+++ /dev/null
@@ -1,462 +0,0 @@
-<!doctype html>
-<html lang="en">
-<head>
- <!-- Required meta tags -->
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel="icon" href="{{ .AppBasePath }}/assets/gowa.svg" type="image/svg+xml" sizes="any">
- <!-- Bootstrap CSS -->
- <link rel="stylesheet" type="text/css"
- href="https://cdnjs.cloudflare.com/ajax/libs/fomantic-ui/2.8.8/semantic.min.css">
- <link rel="stylesheet" href="https://cdn.datatables.net/1.11.4/css/dataTables.semanticui.min.css">
- <link rel="stylesheet" href="{{ .AppBasePath }}/assets/app.css">
- <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
- <script src="https://cdn.datatables.net/1.11.4/js/jquery.dataTables.min.js"></script>
- <script src="https://cdn.datatables.net/1.11.4/js/dataTables.semanticui.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/fomantic-ui/2.8.8/semantic.min.js"></script>
- <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
- <script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
- <title>WhatsApp API {{ .AppVersion }}</title>
-</head>
-<body>
-<div id="splash-screen">
- <!-- Clean squircle logo without background wrapper -->
- <img src="{{ .AppBasePath }}/assets/gowa.svg" alt="GoWA Logo" class="splash-icon" id="main-logo">
-
- <h2 class="splash-title">WhatsApp API</h2>
- <div class="ui active large inline loader splash-spinner"></div>
-</div>
-
-<div class="ui container" id="app" style="display: none;">
- <div class="main-header">
- <h1 class="ui header center aligned">
- <div class="title-container">
- <img src="{{ .AppBasePath }}/assets/gowa.svg" alt="GoWA Logo">
-
- <span>WhatsApp API</span>
-
- <div class="version-label">
- {{ .AppVersion }}
- </div>
- </div>
- </h1>
- </div>
-
- <div class="ui info message" v-if="selectedDeviceId">
- <div class="header">
- <i class="linkify icon"></i>
- Device context active
- </div>
- <p>
- Using device: <b>[[ selectedDeviceId ]]</b>.
- REST/WebSocket send <code>X-Device-Id</code> (or <code>?device_id=</code> for WS).
- </p>
- </div>
-
- <device-manager
- ref="deviceManager"
- ws-base-path="{{ .AppBasePath }}"
- @device-selected="handleDeviceSelected"
- @devices-updated="handleDevicesUpdated">
- </device-manager>
-
- <div class="ui horizontal divider">
- App
- </div>
-
- <div class="ui warning message" v-if="!selectedDeviceId">
- <div class="header">Device required</div>
- <p>Select or create a device above. Provide <code>X-Device-Id</code> on REST calls.</p>
- </div>
-
- <div class="ui three column stackable grid cards" :class="{disabled: !selectedDeviceId}">
- <app-login :logged-in="isSelectedDeviceLoggedIn"></app-login>
- <app-logout @reload-devices="handleReloadDevice"></app-logout>
- <app-reconnect @reload-devices="handleReloadDevice"></app-reconnect>
- <app-login-with-code :logged-in="isSelectedDeviceLoggedIn"></app-login-with-code>
- </div>
-
- <div class="ui horizontal divider">
- Send
- </div>
-
- <div class="ui three column doubling grid cards">
- <send-message></send-message>
- <send-image></send-image>
- <send-file max-file-size="{{ .MaxFileSize }}"></send-file>
-
- <send-video max-video-size="{{ .MaxVideoSize }}"></send-video>
- <send-sticker></send-sticker>
- <send-contact></send-contact>
-
- <send-location></send-location>
- <send-audio></send-audio>
- <send-poll></send-poll>
-
- <send-presence></send-presence>
-
- <send-chat-presence></send-chat-presence>
- <send-link></send-link>
- </div>
-
- <div class="ui horizontal divider">
- Message
- </div>
-
- <div class="ui three column doubling grid cards">
- <message-delete></message-delete>
- <message-revoke></message-revoke>
- <message-react></message-react>
- <message-update></message-update>
- <message-read></message-read>
- <send-forward></send-forward>
- </div>
-
- <div class="ui horizontal divider">
- Call
- </div>
-
- <div class="ui three column doubling grid cards">
- <call-reject></call-reject>
- </div>
-
- <div class="ui horizontal divider">
- Group
- </div>
-
- <div class="ui three column doubling grid cards">
- <group-list :connected="connected_devices"></group-list>
- <group-create></group-create>
- <group-join-with-link></group-join-with-link>
- <group-info-from-link></group-info-from-link>
- <group-add-participants></group-add-participants>
- <group-set-photo></group-set-photo>
- <group-set-name></group-set-name>
- <group-set-locked></group-set-locked>
- <group-set-announce></group-set-announce>
- <group-set-topic></group-set-topic>
- <group-get-invite-link></group-get-invite-link>
- <group-info></group-info>
- </div>
-
- <div class="ui horizontal divider">
- Newsletter
- </div>
-
- <div class="ui three column doubling grid cards">
- <newsletter-list></newsletter-list>
- </div>
-
- <div class="ui horizontal divider">
- Account
- </div>
-
- <div class="ui three column doubling grid cards">
- <account-avatar></account-avatar>
- <account-change-avatar></account-change-avatar>
- <account-change-push-name></account-change-push-name>
- <account-user-info></account-user-info>
- <account-business-profile></account-business-profile>
- <account-privacy></account-privacy>
- <account-contact></account-contact>
- <account-user-check></account-user-check>
- </div>
-
- <div class="ui horizontal divider">
- Chat Management
- </div>
-
- <div class="ui three column doubling grid cards">
- <chat-pin-manager></chat-pin-manager>
- <chat-disappearing-manager></chat-disappearing-manager>
- <chat-list></chat-list>
- <chat-messages></chat-messages>
- </div>
-
-</div>
-<script>
- window.TYPEGROUP = "@g.us";
- window.TYPEUSER = "@s.whatsapp.net";
- window.TYPENEWSLETTER = "@newsletter";
- window.TYPELID = "@lid";
- window.TYPESTATUS = "status@broadcast";
- window.showErrorInfo = (message) => {
- $('body').toast({
- position: 'bottom right',
- title: 'Error',
- message: message,
- showProgress: 'bottom',
- classProgress: 'red'
- });
- }
- window.showSuccessInfo = (message) => {
- $('body').toast({
- position: 'bottom right',
- title: 'Success',
- message: message,
- showProgress: 'bottom',
- classProgress: 'green'
- });
- }
-
-
- const baseHost = `${window.location.protocol}//${window.location.hostname}${window.location.port ? ':' + window.location.port : ''}`;
- const DEVICE_ID_HEADER = 'X-Device-Id';
- window.http = axios.create({
- baseURL: `${baseHost}{{ .AppBasePath }}`
- });
- {{ if isEnableBasicAuth .BasicAuthToken }}
- window.http.defaults.headers.common['Authorization'] = "{{ .BasicAuthToken }}";
- {{ end }}
-</script>
-<script type="module">
- import AppLogin from "{{ .AppBasePath }}/components/AppLogin.js";
- import AppLoginWithCode from "{{ .AppBasePath }}/components/AppLoginWithCode.js";
- import AppLogout from "{{ .AppBasePath }}/components/AppLogout.js";
- import AppReconnect from "{{ .AppBasePath }}/components/AppReconnect.js";
- import SendMessage from "{{ .AppBasePath }}/components/SendMessage.js";
- import SendImage from "{{ .AppBasePath }}/components/SendImage.js";
- import SendFile from "{{ .AppBasePath }}/components/SendFile.js";
- import SendVideo from "{{ .AppBasePath }}/components/SendVideo.js";
- import SendSticker from "{{ .AppBasePath }}/components/SendSticker.js";
- import SendLink from "{{ .AppBasePath }}/components/SendLink.js";
- import SendContact from "{{ .AppBasePath }}/components/SendContact.js";
- import SendLocation from "{{ .AppBasePath }}/components/SendLocation.js";
- import SendAudio from "{{ .AppBasePath }}/components/SendAudio.js";
- import SendPoll from "{{ .AppBasePath }}/components/SendPoll.js";
- import SendPresence from "{{ .AppBasePath }}/components/SendPresence.js";
- import SendChatPresence from "{{ .AppBasePath }}/components/SendChatPresence.js";
- import MessageDelete from "{{ .AppBasePath }}/components/MessageDelete.js";
- import MessageUpdate from "{{ .AppBasePath }}/components/MessageUpdate.js";
- import MessageReact from "{{ .AppBasePath }}/components/MessageReact.js";
- import MessageRevoke from "{{ .AppBasePath }}/components/MessageRevoke.js";
- import MessageRead from "{{ .AppBasePath }}/components/MessageRead.js";
- import SendForward from "{{ .AppBasePath }}/components/SendForward.js";
- import GroupList from "{{ .AppBasePath }}/components/GroupList.js";
- import GroupCreate from "{{ .AppBasePath }}/components/GroupCreate.js";
- import GroupJoinWithLink from "{{ .AppBasePath }}/components/GroupJoinWithLink.js";
- import GroupInfoFromLink from "{{ .AppBasePath }}/components/GroupInfoFromLink.js";
- import GroupAddParticipants from "{{ .AppBasePath }}/components/GroupManageParticipants.js";
- import GroupSetPhoto from "{{ .AppBasePath }}/components/GroupSetPhoto.js";
- import GroupSetName from "{{ .AppBasePath }}/components/GroupSetName.js";
- import GroupSetLocked from "{{ .AppBasePath }}/components/GroupSetLocked.js";
- import GroupSetAnnounce from "{{ .AppBasePath }}/components/GroupSetAnnounce.js";
- import GroupSetTopic from "{{ .AppBasePath }}/components/GroupSetTopic.js";
- import GroupGetInviteLink from "{{ .AppBasePath }}/components/GroupGetInviteLink.js";
- import GroupInfo from "{{ .AppBasePath }}/components/GroupInfo.js";
- import NewsletterList from "{{ .AppBasePath }}/components/NewsletterList.js";
- import AccountAvatar from "{{ .AppBasePath }}/components/AccountAvatar.js";
- import AccountChangeAvatar from "{{ .AppBasePath }}/components/AccountChangeAvatar.js";
- import AccountChangePushName from "{{ .AppBasePath }}/components/AccountChangePushName.js";
- import AccountUserInfo from "{{ .AppBasePath }}/components/AccountUserInfo.js";
- import AccountPrivacy from "{{ .AppBasePath }}/components/AccountPrivacy.js";
- import AccountContact from "{{ .AppBasePath }}/components/AccountContact.js";
- import AccountUserCheck from "{{ .AppBasePath }}/components/AccountUserCheck.js";
- import AccountBusinessProfile from "{{ .AppBasePath }}/components/AccountBusinessProfile.js";
- import ChatPinManager from "{{ .AppBasePath }}/components/ChatPinManager.js";
- import ChatDisappearingManager from "{{ .AppBasePath }}/components/ChatDisappearingManager.js";
- import ChatList from "{{ .AppBasePath }}/components/ChatList.js";
- import ChatMessages from "{{ .AppBasePath }}/components/ChatMessages.js";
- import DeviceManager from "{{ .AppBasePath }}/components/DeviceManager.js";
- import CallReject from "{{ .AppBasePath }}/components/CallReject.js";
-
- const showErrorInfo = (message) => {
- $('body').toast({
- position: 'bottom right',
- title: 'Error',
- message: message,
- showProgress: 'bottom',
- classProgress: 'red'
- });
- }
- const showSuccessInfo = (message) => {
- $('body').toast({
- position: 'bottom right',
- title: 'Success',
- message: message,
- showProgress: 'bottom',
- classProgress: 'green'
- });
- }
-
- Vue.createApp({
- components: {
- AppLogin, AppLoginWithCode, AppLogout, AppReconnect,
- SendMessage, SendImage, SendFile, SendVideo, SendSticker, SendLink, SendContact, SendLocation, SendAudio, SendPoll, SendPresence, SendChatPresence,
- MessageDelete, MessageUpdate, MessageReact, MessageRevoke, MessageRead, SendForward,
- GroupList, GroupCreate, GroupJoinWithLink, GroupInfoFromLink, GroupAddParticipants, GroupSetPhoto, GroupSetName, GroupSetLocked, GroupSetAnnounce, GroupSetTopic, GroupGetInviteLink, GroupInfo,
- NewsletterList,
- AccountAvatar, AccountUserInfo, AccountPrivacy, AccountChangeAvatar, AccountContact, AccountChangePushName, AccountUserCheck, AccountBusinessProfile,
- ChatPinManager, ChatDisappearingManager, ChatList, ChatMessages,
- CallReject,
- DeviceManager
- },
- delimiters: ['[[', ']]'],
- data() {
- return {
- app_ws: null,
- connected_devices: null,
- deviceList: [],
- selectedDeviceId: '',
- }
- },
- computed: {
- selectedDevice() {
- if (!this.selectedDeviceId) return null;
- return this.deviceList.find(d => (d.id || d.device) === this.selectedDeviceId) || null;
- },
- isSelectedDeviceLoggedIn() {
- return this.selectedDevice?.state === 'logged_in';
- },
- },
- methods: {
- applyDeviceHeader(id) {
- if (id) {
- window.http.defaults.headers.common[DEVICE_ID_HEADER] = encodeURIComponent(id);
- } else {
- delete window.http.defaults.headers.common[DEVICE_ID_HEADER];
- if (this.app_ws) {
- this.app_ws.close();
- this.app_ws = null;
- }
- }
- },
- constructWebSocketURL() {
- if (!this.selectedDeviceId) return '';
- const protocol = location.protocol === 'https:' ? 'wss://' : 'ws://';
- const basePath = '{{ .AppBasePath }}';
- const deviceQuery = encodeURIComponent(this.selectedDeviceId);
- const pathPrefix = basePath || '';
- return `${protocol}${location.host}${pathPrefix}/ws?device_id=${deviceQuery}`;
- },
- handleReloadDevice() {
- if (this.$refs.deviceManager) {
- this.$refs.deviceManager.refresh();
- }
- if (this.app_ws) {
- this.app_ws.send(JSON.stringify({"code": "FETCH_DEVICES"}));
- }
- },
- handleDeviceSelected(id) {
- this.selectedDeviceId = id;
- this.applyDeviceHeader(id);
- if (id) {
- this.connectWebSocket();
- }
- },
- handleDevicesUpdated(devices) {
- this.deviceList = devices;
- this.connected_devices = devices;
- },
- connectWebSocket() {
- if (!this.selectedDeviceId) {
- return;
- }
-
- if (this.app_ws) {
- this.app_ws.close();
- this.app_ws = null;
- }
-
- const wsURL = this.constructWebSocketURL();
- if (!wsURL) {
- return;
- }
-
- this.app_ws = new WebSocket(wsURL);
-
- this.app_ws.onopen = (evt) => {
- this.handleReloadDevice();
- };
-
- this.app_ws.onerror = (error) => {
- console.error('WebSocket error:', error);
- // Only show error notification if the device is logged in
- if (this.isSelectedDeviceLoggedIn) {
- showErrorInfo('Connection error occurred. Please refresh or re-select the device.');
- }
- };
-
- 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.handleReloadDevice()
- break;
- case 'LIST_DEVICES':
- this.connected_devices = message.result
- break;
- case 'DEVICE_REMOVED': {
- const removedId = message.result?.device_id;
- const devices = message.result?.devices;
- showSuccessInfo('✅ ' + (message.message || 'Device removed'));
-
- if (Array.isArray(devices)) {
- this.deviceList = devices;
- this.connected_devices = devices;
-
- if (removedId && this.selectedDeviceId === removedId) {
- this.selectedDeviceId = '';
- this.applyDeviceHeader('');
- }
-
- if (!this.selectedDeviceId && this.deviceList.length > 0) {
- const first = this.deviceList[0].id || this.deviceList[0].device;
- this.setDeviceContext(first);
- }
- } else {
- this.handleReloadDevice();
- }
- break;
- }
- case 'PASSKEY_REQUEST':
- showSuccessInfo('Passkey linking requested. Complete the WebAuthn assertion via the REST API (GET /app/passkey).')
- break;
- case 'PASSKEY_CONFIRMATION':
- if (message.result?.skip_handoff_ux) {
- showSuccessInfo(message.message)
- } else if (window.confirm('Does this passkey pairing code match the one on your phone? ' + (message.result?.code || ''))) {
- window.http.post('app/passkey/confirm')
- .then(() => showSuccessInfo('Passkey pairing confirmed'))
- .catch(err => showErrorInfo(err?.response?.data?.message || 'Passkey confirmation failed'))
- }
- break;
- case 'PASSKEY_ERROR':
- showErrorInfo(message.message)
- break;
- case 'DEVICE_LOGGED_OUT': {
- // Logout keeps the slot: refresh the list (device is now
- // disconnected) but keep the current selection so the user
- // can re-pair it under the same id.
- const devices = message.result?.devices;
- showSuccessInfo('✅ ' + (message.message || 'Device logged out'));
- if (Array.isArray(devices)) {
- this.deviceList = devices;
- this.connected_devices = devices;
- } else {
- this.handleReloadDevice();
- }
- break;
- }
- default:
- console.log(message)
- }
- };
- },
- },
- mounted() {
- // Show app container and hide splash once initial data fetched
- setTimeout(() => {
- document.getElementById('app').style.display = 'block';
- document.getElementById('splash-screen').classList.add('fade-out');
- }, 800);
- },
- }).mount('#app')
-</script>
-</body>
-</html>