commit 584abdb00ea886a3b6549302615c2a44c3ca3fb3 Author: Adrian Victor Date: Sun Jul 12 22:04:52 2026 -0300 initial diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..97aca2e --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.env +node_modules \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..a9ede1b --- /dev/null +++ b/index.js @@ -0,0 +1,21 @@ +import express from "express"; +import path from "path"; +import { fileURLToPath } from "url"; + +const app = express(); +const PORT = process.env.PORT || 3100; + +// Resolve __dirname in ES modules +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +// Serve static assets from the public folder +app.use(express.static(path.join(__dirname, "public"))); + +// Start static file server +app.listen(PORT, () => { + console.log(`==================================================`); + console.log(` Pandora Chat Static Server is running!`); + console.log(` URL: http://localhost:${PORT}`); + console.log(`==================================================`); +}); \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..021eac5 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1036 @@ +{ + "name": "pandora", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "pandora", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "axios": "^1.18.1", + "dotenv": "^17.4.2", + "express": "^5.2.1" + } + }, + "node_modules/accepts": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", + "license": "MIT", + "dependencies": { + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/axios": { + "version": "1.18.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.18.1.tgz", + "integrity": "sha512-3nTvFlvpn9Zu/RkHUqtc7/+al4UpRW5az71ap5zccp6e8RAYEzhMTecX8Dz1wWDYrPpUoB1HAQEGEAEvUr7S9g==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.16.0", + "form-data": "^4.0.5", + "https-proxy-agent": "^5.0.1", + "proxy-from-env": "^2.1.0" + } + }, + "node_modules/body-parser": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz", + "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==", + "license": "MIT", + "dependencies": { + "bytes": "^3.1.2", + "content-type": "^2.0.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.2", + "on-finished": "^2.4.1", + "qs": "^6.15.2", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/body-parser/node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/content-disposition": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz", + "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/dotenv": { + "version": "17.4.2", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz", + "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", + "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.2.1", + "content-disposition": "^1.0.0", + "content-type": "^1.0.5", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.7", + "qs": "^6.14.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.0.1", + "vary": "^1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/finalhandler": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" + }, + "engines": { + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/follow-redirects": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", + "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.4", + "mime-types": "^2.1.35" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/form-data/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/form-data/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", + "license": "MIT" + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", + "integrity": "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/merge-descriptors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/mime-db": { + "version": "1.54.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", + "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "license": "MIT", + "dependencies": { + "mime-db": "^1.54.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", + "integrity": "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "license": "MIT", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/proxy-from-env": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz", + "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, + "node_modules/qs": { + "version": "6.15.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz", + "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==", + "license": "BSD-3-Clause", + "dependencies": { + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", + "license": "MIT", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.7.0", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/send": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-static": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", + "license": "MIT", + "dependencies": { + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/type-is": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", + "license": "MIT", + "dependencies": { + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" + }, + "engines": { + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/type-is/node_modules/content-type": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.0.0.tgz", + "integrity": "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "license": "ISC" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..c71df44 --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "pandora", + "version": "1.0.0", + "type": "module", + "main": "index.js", + "scripts": { + "start": "node index.js", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "description": "", + "dependencies": { + "axios": "^1.18.1", + "dotenv": "^17.4.2", + "express": "^5.2.1" + } +} diff --git a/public/app.js b/public/app.js new file mode 100644 index 0000000..8e2ebfb --- /dev/null +++ b/public/app.js @@ -0,0 +1,263 @@ +import { config } from "./config.js"; +import { waha } from "./waha.js"; +import { ui, elements } from "./ui.js"; +import { websocket } from "./websocket.js"; +import { compensateMessageOrdering, formatTime } from "./utils.js"; + +let chatsState = []; +let activeChatState = null; + +// Initialize app when DOM is ready +document.addEventListener('DOMContentLoaded', () => { + setupEventListeners(); + fetchChats(); + checkWahaStatus(); + initWebSocket(); +}); + +function setupEventListeners() { + elements.refreshChatsBtn.addEventListener('click', () => { + elements.refreshChatsBtn.classList.add('spinning'); + fetchChats().finally(() => { + setTimeout(() => { + elements.refreshChatsBtn.classList.remove('spinning'); + }, 600); + }); + }); + + elements.chatSearch.addEventListener('input', (e) => { + const query = e.target.value.toLowerCase(); + const filtered = chatsState.filter(chat => + chat.name.toLowerCase().includes(query) + ); + ui.renderChatList(filtered, activeChatState, selectChat); + }); + + elements.messageForm.addEventListener('submit', (e) => { + e.preventDefault(); + sendMessage(); + }); + + elements.backToSidebarBtn.addEventListener('click', () => { + elements.sidebar.classList.remove('hidden'); + elements.activeChatContainer.classList.add('hidden'); + }); + + elements.settingsIconBtn.addEventListener('click', openSettings); + elements.closeSettingsBtn.addEventListener('click', () => ui.toggleModal(false)); + elements.cancelSettingsBtn.addEventListener('click', () => ui.toggleModal(false)); + elements.saveSettingsBtn.addEventListener('click', saveSettings); +} + +function initWebSocket() { + websocket.connect((data) => { + console.log('[WS] Received event:', data.event, data); + const ev = data.event; + if (ev === 'message' || ev === 'message.any' || ev === 'message.ack') { + handleIncomingMessage(data.payload); + } + }); +} + +function normalizeChatId(raw) { + if (!raw) return null; + if (typeof raw === 'object') { + return raw._serialized || raw.user || JSON.stringify(raw); + } + return raw; +} + +function handleIncomingMessage(msg) { + if (!msg) return; + + console.log('[WS] handleIncomingMessage payload:', msg); + + const rawChatId = msg.chatId || msg.from || (msg.chat && msg.chat.id); + const msgChatId = normalizeChatId(rawChatId); + if (!msgChatId) { + console.warn('[WS] Could not resolve chatId from payload:', msg); + return; + } + + console.log('[WS] Resolved msgChatId:', msgChatId, '| activeChatState:', activeChatState?.id); + + if (activeChatState && activeChatState.id === msgChatId) { + const msgId = normalizeChatId(msg.id) || msg.id; + const exists = document.getElementById(msgId); + if (!exists) { + ui.appendSingleMessage({ ...msg, chatId: msgChatId }, activeChatState.name); + ui.scrollToBottom(); + } + } + + const chatIndex = chatsState.findIndex(c => c.id === msgChatId); + if (chatIndex !== -1) { + const chat = chatsState[chatIndex]; + chat.lastMessage = msg.body || msg.text || 'Media message'; + chat.timestamp = msg.timestamp ? (msg.timestamp * 1000) : Date.now(); + + if (!msg.fromMe && (!activeChatState || activeChatState.id !== msgChatId)) { + chat.unreadCount = (chat.unreadCount || 0) + 1; + } + + chatsState.sort((a, b) => { + const tA = new Date(a.timestamp).getTime(); + const tB = new Date(b.timestamp).getTime(); + return tB - tA; + }); + + ui.renderChatList(chatsState, activeChatState, selectChat); + } else { + fetchChats(); + } +} + +async function fetchChats() { + const userInfo = await waha.getMyInfo(); + elements.loggedUserName.textContent = userInfo.pushName; + elements.userIcon.innerText = userInfo.pushName[0]; + elements.chatsLoader.classList.remove('hidden'); + try { + chatsState = await waha.getChats(); + ui.renderChatList(chatsState, activeChatState, selectChat); + } catch (error) { + console.error('Failed to load chats:', error); + elements.chatList.innerHTML = ` +
  • +

    Connection to WAHA failed.

    +

    + Ensure WAHA server is running and CORS is enabled, or click Settings to configure. +

    +
  • + `; + } finally { + elements.chatsLoader.classList.add('hidden'); + } +} + +async function selectChat(chat) { + activeChatState = chat; + + chat.unreadCount = 0; + + ui.renderChatList(chatsState, activeChatState, selectChat); + + ui.toggleChatState(true); + elements.activeChatName.textContent = chat.name; + elements.activeChatAvatar.textContent = chat.name ? chat.name.substring(0, 1).toUpperCase() : '?'; + + elements.messagesContainer.innerHTML = '
    Loading messages...
    '; + + if (window.innerWidth <= 768) { + elements.sidebar.classList.add('hidden'); + } + + try { + const rawMessages = await waha.getChatMessages(chat.id); + const processedMessages = compensateMessageOrdering(rawMessages); + ui.renderMessages(processedMessages, chat.name); + } catch (error) { + console.error('Failed to load messages:', error); + elements.messagesContainer.innerHTML = '
    Error loading messages
    '; + } +} + +async function sendMessage() { + const text = elements.messageInput.value.trim(); + if (!text || !activeChatState) return; + + elements.messageInput.value = ''; + + const tempMsg = { + id: 'temp-' + Date.now(), + body: text, + fromMe: true, + sender: 'me', + timestamp: new Date().toISOString(), + status: 'sending' + }; + + ui.appendSingleMessage(tempMsg, activeChatState.name); + ui.scrollToBottom(); + + try { + try { + await waha.startTyping(activeChatState.id); + const delay = Math.min(4000, Math.max(1000, text.length * 50)); + await new Promise(resolve => setTimeout(resolve, delay)); + } catch (e) { + console.warn('Presence start failed:', e); + } + + try { + await waha.stopTyping(activeChatState.id); + } catch (e) { + console.warn('Presence stop failed:', e); + } + + try { + if (!activeChatState.id.endsWith('@lid')) { + await waha.readChat(activeChatState.id); + } + } catch (e) { + console.warn('readChat failed (non-fatal):', e.message); + } + + const responseData = await waha.sendTextMessage(activeChatState.id, text); + + const tempBubble = document.getElementById(tempMsg.id); + if (tempBubble) { + if (responseData && responseData.id) { + tempBubble.id = responseData.id; + } + const meta = tempBubble.querySelector('.message-meta'); + meta.innerHTML = `${formatTime(new Date())}`; + lucide.createIcons(); + } + + activeChatState.lastMessage = text; + activeChatState.timestamp = new Date(); + + chatsState.sort((a, b) => { + const tA = new Date(a.timestamp).getTime(); + const tB = new Date(b.timestamp).getTime(); + return tB - tA; + }); + ui.renderChatList(chatsState, activeChatState, selectChat); + } catch (error) { + console.error('Failed to send message:', error); + const tempBubble = document.getElementById(tempMsg.id); + if (tempBubble) { + const meta = tempBubble.querySelector('.message-meta'); + meta.innerHTML = `Failed to send`; + } + } +} + +function openSettings() { + elements.inputWahaUrl.value = config.wahaUrl; + elements.inputSession.value = config.session; + elements.inputApiKey.value = config.apiKey; + ui.toggleModal(true); +} + +function saveSettings() { + config.save( + elements.inputWahaUrl.value, + elements.inputSession.value, + elements.inputApiKey.value + ); + ui.toggleModal(false); + fetchChats(); + checkWahaStatus(); + initWebSocket(); +} + +async function checkWahaStatus() { + try { + const data = await waha.getVersion(); + ui.updateConnectionStatus(true, `WAHA Connected: v${data.version || 'OK'}`); + } catch (e) { + ui.updateConnectionStatus(false, 'WAHA Server Offline'); + } +} diff --git a/public/config.js b/public/config.js new file mode 100644 index 0000000..a571dbb --- /dev/null +++ b/public/config.js @@ -0,0 +1,17 @@ +// Client Configuration State & Storage Manager + +export const config = { + wahaUrl: localStorage.getItem('waha_url') || 'http://inspiran.beetal-castor.ts.net:3100', + session: localStorage.getItem('waha_session') || 'session_01kxc62bk5fs8vh4v127k88a7j', + apiKey: localStorage.getItem('waha_api_key') || '', + + save(url, session, apiKey) { + this.wahaUrl = url.trim().replace(/\/$/, ""); + this.session = session.trim(); + this.apiKey = apiKey.trim(); + + localStorage.setItem('waha_url', this.wahaUrl); + localStorage.setItem('waha_session', this.session); + localStorage.setItem('waha_api_key', this.apiKey); + } +}; diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..eb79442 --- /dev/null +++ b/public/index.html @@ -0,0 +1,147 @@ + + + + + + Pandora + + + + + + + +
    + + + + +
    + +
    +
    +
    + +
    +

    Welcome to Pandora Chat

    +

    Select a contact from the sidebar to view the conversation or start a new chat. Your chats are synced directly with the WAHA API backend.

    +
    +
    + + + +
    +
    + + + + + + + + diff --git a/public/style.css b/public/style.css new file mode 100644 index 0000000..820ea63 --- /dev/null +++ b/public/style.css @@ -0,0 +1,769 @@ +:root { + --bg-main: #090d16; + --sidebar-bg: rgba(17, 24, 39, 0.75); + --chat-bg: rgba(15, 23, 42, 0.6); + --border-color: rgba(255, 255, 255, 0.08); + --border-hover: rgba(255, 255, 255, 0.15); + --text-primary: #f8fafc; + --text-secondary: #94a3b8; + --text-muted: #64748b; + --accent: #6366f1; + --accent-gradient: linear-gradient(135deg, #6366f1 0%, #a855f7 100%); + --accent-hover: #4f46e5; + --online-color: #10b981; + --bubble-incoming: rgba(30, 41, 59, 0.85); + --bubble-outgoing: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%); + --input-bg: rgba(15, 23, 42, 0.8); + --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05); + --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); + --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.3), 0 4px 6px -2px rgba(0, 0, 0, 0.1); + --glass-blur: blur(20px); +} + +* { + margin: 0; + padding: 0; + box-sizing: border-box; + font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; +} + +body { + background-color: var(--bg-main); + color: var(--text-primary); + height: 100vh; + overflow: hidden; + background-image: + radial-gradient(at 0% 0%, rgba(99, 102, 241, 0.12) 0px, transparent 50%), + radial-gradient(at 100% 100%, rgba(168, 85, 247, 0.12) 0px, transparent 50%); +} + +.app-container { + display: flex; + width: 100vw; + height: 100vh; + overflow: hidden; + backdrop-filter: var(--glass-blur); +} + +/* Sidebar Styling */ +.sidebar { + width: 380px; + background-color: var(--sidebar-bg); + border-right: 1px solid var(--border-color); + display: flex; + flex-direction: column; + flex-shrink: 0; + transition: all 0.3s ease; +} + +.sidebar-header { + padding: 20px; + display: flex; + justify-content: space-between; + align-items: center; + border-bottom: 1px solid var(--border-color); +} + +.user-profile { + display: flex; + align-items: center; + gap: 12px; +} + +.avatar { + width: 44px; + height: 44px; + border-radius: 12px; + display: flex; + align-items: center; + justify-content: center; + font-weight: 700; + font-size: 1.1rem; + color: white; + background: var(--accent-gradient); + box-shadow: var(--shadow-md); + position: relative; + border: 1px solid rgba(255, 255, 255, 0.1); +} + +.user-avatar { + background: linear-gradient(135deg, #10b981 0%, #059669 100%); +} + +.user-info h3 { + font-size: 0.95rem; + font-weight: 600; + color: var(--text-primary); +} + +.status-indicator { + font-size: 0.75rem; + color: var(--text-secondary); + display: flex; + align-items: center; + gap: 4px; +} + +.status-indicator::before { + content: ''; + display: inline-block; + width: 6px; + height: 6px; + border-radius: 50%; + background-color: var(--online-color); +} + +.header-actions { + display: flex; + gap: 8px; +} + +.icon-btn { + width: 38px; + height: 38px; + border-radius: 10px; + border: 1px solid var(--border-color); + background: rgba(255, 255, 255, 0.03); + color: var(--text-secondary); + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); +} + +.icon-btn:hover { + background: rgba(255, 255, 255, 0.08); + color: var(--text-primary); + border-color: var(--border-hover); + transform: translateY(-1px); +} + +.icon-btn:active { + transform: translateY(0); +} + +/* Search Bar */ +.search-container { + padding: 16px 20px; +} + +.search-wrapper { + position: relative; + display: flex; + align-items: center; +} + +.search-icon { + position: absolute; + left: 14px; + color: var(--text-muted); + width: 18px; + height: 18px; + pointer-events: none; +} + +#chat-search { + width: 100%; + padding: 12px 14px 12px 42px; + border-radius: 10px; + border: 1px solid var(--border-color); + background: rgba(15, 23, 42, 0.6); + color: var(--text-primary); + font-size: 0.9rem; + transition: all 0.25s ease; +} + +#chat-search:focus { + outline: none; + border-color: var(--accent); + background: rgba(15, 23, 42, 0.9); + box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2); +} + +/* Chat List container */ +.chat-list-container { + flex: 1; + display: flex; + flex-direction: column; + overflow-y: auto; + padding: 0 10px 10px 10px; +} + +.chat-list-header { + display: flex; + justify-content: space-between; + align-items: center; + padding: 10px 10px 14px 10px; + font-size: 0.8rem; + text-transform: uppercase; + letter-spacing: 0.05em; + color: var(--text-muted); + font-weight: 700; +} + +.badge { + background: var(--accent-gradient); + color: white; + font-size: 0.75rem; + padding: 2px 8px; + border-radius: 12px; + font-weight: 600; +} + +.chat-list { + list-style: none; + display: flex; + flex-direction: column; + gap: 4px; +} + +.chat-item { + display: flex; + align-items: center; + gap: 12px; + padding: 12px; + border-radius: 12px; + cursor: pointer; + transition: all 0.2s ease; + border: 1px solid transparent; +} + +.chat-item:hover { + background: rgba(255, 255, 255, 0.04); +} + +.chat-item.active { + background: rgba(99, 102, 241, 0.15); + border-color: rgba(99, 102, 241, 0.25); +} + +.chat-item-info { + flex: 1; + min-width: 0; +} + +.chat-item-meta { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 4px; +} + +.chat-item-name { + font-size: 0.95rem; + font-weight: 600; + color: var(--text-primary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.chat-item-time { + font-size: 0.75rem; + color: var(--text-muted); + flex-shrink: 0; +} + +.chat-item-preview { + display: flex; + justify-content: space-between; + align-items: center; + gap: 8px; +} + +.chat-item-msg { + font-size: 0.82rem; + color: var(--text-secondary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + flex: 1; +} + +.chat-item .unread-badge { + background: var(--accent); + color: white; + font-size: 0.7rem; + min-width: 18px; + height: 18px; + border-radius: 9px; + display: flex; + align-items: center; + justify-content: center; + font-weight: 700; + padding: 0 4px; +} + +.loading-chats { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 12px; + padding: 40px 20px; + color: var(--text-secondary); + font-size: 0.9rem; +} + +.spinner { + width: 24px; + height: 24px; + border: 2px solid rgba(255, 255, 255, 0.1); + border-top-color: var(--accent); + border-radius: 50%; + animation: spin 0.8s linear infinite; +} + +@keyframes spin { + to { transform: rotate(360deg); } +} + +/* Sidebar Footer */ +.sidebar-footer { + padding: 14px 20px; + border-top: 1px solid var(--border-color); + background: rgba(10, 15, 26, 0.4); +} + +.api-status-badge { + display: flex; + align-items: center; + gap: 8px; + font-size: 0.75rem; + color: var(--text-secondary); +} + +.pulse-dot { + width: 8px; + height: 8px; + background-color: var(--online-color); + border-radius: 50%; + box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); + animation: pulse 1.8s infinite; +} + +@keyframes pulse { + 0% { + transform: scale(0.95); + box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7); + } + 70% { + transform: scale(1); + box-shadow: 0 0 0 6px rgba(16, 185, 129, 0); + } + 100% { + transform: scale(0.95); + box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); + } +} + +/* Main Chat Area */ +.chat-area { + flex: 1; + background-color: var(--chat-bg); + display: flex; + flex-direction: column; + position: relative; +} + +/* Empty State */ +.no-chat-state { + display: flex; + flex: 1; + align-items: center; + justify-content: center; + padding: 40px; + text-align: center; + background: radial-gradient(circle at center, rgba(30, 41, 59, 0.2) 0%, transparent 70%); +} + +.empty-state-content { + max-width: 420px; +} + +.empty-state-icon { + width: 80px; + height: 80px; + border-radius: 24px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid var(--border-color); + display: flex; + align-items: center; + justify-content: center; + margin: 0 auto 24px auto; + color: var(--accent); + font-size: 2rem; +} + +.empty-state-content h2 { + font-size: 1.5rem; + font-weight: 700; + margin-bottom: 12px; + color: var(--text-primary); +} + +.empty-state-content p { + font-size: 0.9rem; + color: var(--text-secondary); + line-height: 1.6; +} + +/* Active Chat Interface */ +.active-chat-container { + display: flex; + flex-direction: column; + height: 100%; +} + +.chat-header { + padding: 16px 24px; + border-bottom: 1px solid var(--border-color); + display: flex; + justify-content: space-between; + align-items: center; + background: rgba(15, 23, 42, 0.3); +} + +.active-contact-info { + display: flex; + align-items: center; + gap: 14px; +} + +.active-avatar { + width: 42px; + height: 42px; + border-radius: 12px; +} + +.active-contact-info h3 { + font-size: 1rem; + font-weight: 600; + margin-bottom: 2px; +} + +.contact-status { + font-size: 0.75rem; + color: var(--text-secondary); +} + +.chat-actions { + display: flex; + gap: 8px; +} + +.back-btn { + display: none; +} + +/* Messages Area */ +.messages-container { + flex: 1; + overflow-y: auto; + padding: 24px; + display: flex; + flex-direction: column; + gap: 16px; + background-image: + radial-gradient(circle at 10% 20%, rgba(99, 102, 241, 0.03) 0%, transparent 40%), + radial-gradient(circle at 90% 80%, rgba(168, 85, 247, 0.03) 0%, transparent 40%); +} + +.message-group { + display: flex; + flex-direction: column; + max-width: 65%; + gap: 4px; +} + +.message-group.incoming { + align-self: flex-start; +} + +.message-group.outgoing { + align-self: flex-end; +} + +.message-sender { + font-size: 0.75rem; + font-weight: 600; + color: var(--text-muted); + margin-left: 12px; + margin-bottom: 2px; +} + +.message-bubble { + padding: 12px 16px; + border-radius: 18px; + font-size: 0.92rem; + line-height: 1.5; + position: relative; + word-break: break-word; + box-shadow: var(--shadow-sm); +} + +.message-group.incoming .message-bubble { + background-color: var(--bubble-incoming); + color: var(--text-primary); + border-top-left-radius: 4px; + border: 1px solid var(--border-color); +} + +.message-group.outgoing .message-bubble { + background: var(--bubble-outgoing); + color: white; + border-top-right-radius: 4px; +} + +.message-meta { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 4px; + font-size: 0.7rem; + color: rgba(255, 255, 255, 0.65); + margin-top: 4px; +} + +.message-group.incoming .message-meta { + color: var(--text-muted); +} + +/* Chat Input Panel */ +.chat-input-panel { + padding: 20px 24px; + background: var(--input-bg); + border-top: 1px solid var(--border-color); + display: flex; + align-items: center; + gap: 16px; +} + +.input-actions-left { + display: flex; + gap: 8px; +} + +.input-form { + flex: 1; + display: flex; + gap: 12px; + align-items: center; +} + +#message-input { + flex: 1; + padding: 12px 18px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid var(--border-color); + border-radius: 12px; + color: var(--text-primary); + font-size: 0.95rem; + transition: all 0.2s ease; +} + +#message-input:focus { + outline: none; + border-color: var(--accent); + background: rgba(255, 255, 255, 0.06); + box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1); +} + +.send-btn { + width: 44px; + height: 44px; + border-radius: 12px; + background: var(--accent-gradient); + border: none; + color: white; + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + box-shadow: var(--shadow-md); + transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); +} + +.send-btn:hover { + transform: scale(1.05) translateY(-1px); + box-shadow: 0 6px 20px rgba(99, 102, 241, 0.4); +} + +.send-btn:active { + transform: scale(0.98) translateY(0); +} + +.send-btn i { + width: 18px; + height: 18px; +} + +/* Scrollbars styling */ +::-webkit-scrollbar { + width: 6px; + height: 6px; +} + +::-webkit-scrollbar-track { + background: transparent; +} + +::-webkit-scrollbar-thumb { + background: rgba(255, 255, 255, 0.08); + border-radius: 10px; +} + +::-webkit-scrollbar-thumb:hover { + background: rgba(255, 255, 255, 0.16); +} + +/* Helper classes */ +.hidden { + display: none !important; +} + +/* Responsive design */ +@media (max-width: 768px) { + .app-container { + position: relative; + } + + .sidebar { + width: 100%; + position: absolute; + left: 0; + top: 0; + height: 100%; + z-index: 10; + } + + .sidebar.hidden { + transform: translateX(-100%); + display: flex !important; /* overrides standard .hidden */ + } + + .chat-area { + width: 100%; + } + + .back-btn { + display: flex; + margin-right: 8px; + } +} + +/* Modal Styling */ +.modal-overlay { + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + background: rgba(0, 0, 0, 0.6); + backdrop-filter: blur(8px); + display: flex; + align-items: center; + justify-content: center; + z-index: 100; + transition: all 0.3s ease; +} + +.modal-content { + background: rgba(30, 41, 59, 0.85); + border: 1px solid var(--border-color); + border-radius: 16px; + width: 90%; + max-width: 480px; + padding: 24px; + box-shadow: var(--shadow-lg); + backdrop-filter: var(--glass-blur); +} + +.modal-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 20px; +} + +.modal-header h2 { + font-size: 1.2rem; + font-weight: 600; +} + +.modal-body { + display: flex; + flex-direction: column; + gap: 16px; +} + +.form-group { + display: flex; + flex-direction: column; + gap: 6px; +} + +.form-group label { + font-size: 0.82rem; + color: var(--text-secondary); + font-weight: 500; +} + +.form-group input { + padding: 10px 12px; + border-radius: 8px; + border: 1px solid var(--border-color); + background: rgba(15, 23, 42, 0.5); + color: var(--text-primary); + font-size: 0.9rem; +} + +.form-group input:focus { + outline: none; + border-color: var(--accent); +} + +.settings-warning { + font-size: 0.75rem; + color: var(--text-muted); + line-height: 1.4; +} + +.modal-footer { + display: flex; + justify-content: flex-end; + gap: 12px; + margin-top: 24px; +} + +.btn { + padding: 10px 18px; + border-radius: 8px; + font-size: 0.9rem; + font-weight: 500; + cursor: pointer; + border: none; + transition: all 0.2s ease; +} + +.primary-btn { + background: var(--accent-gradient); + color: white; +} + +.primary-btn:hover { + transform: translateY(-1px); + box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3); +} + +.secondary-btn { + background: rgba(255, 255, 255, 0.05); + color: var(--text-primary); + border: 1px solid var(--border-color); +} + +.secondary-btn:hover { + background: rgba(255, 255, 255, 0.1); +} + diff --git a/public/ui.js b/public/ui.js new file mode 100644 index 0000000..70f9e39 --- /dev/null +++ b/public/ui.js @@ -0,0 +1,198 @@ +import { formatTime } from "./utils.js"; + +// DOM Selector Cache +export const elements = { + chatList: document.getElementById('chat-list'), + chatsLoader: document.getElementById('chats-loader'), + chatCountBadge: document.getElementById('chat-count'), + chatSearch: document.getElementById('chat-search'), + refreshChatsBtn: document.getElementById('refresh-chats-btn'), + backendStatusText: document.getElementById('backend-status-text'), + apiStatusIndicator: document.querySelector('.pulse-dot'), + noChatState: document.getElementById('no-chat-state'), + activeChatContainer: document.getElementById('active-chat-container'), + activeChatName: document.getElementById('active-chat-name'), + activeChatAvatar: document.getElementById('active-chat-avatar'), + messagesContainer: document.getElementById('messages-container'), + messageForm: document.getElementById('message-form'), + messageInput: document.getElementById('message-input'), + backToSidebarBtn: document.getElementById('back-to-sidebar'), + sidebar: document.querySelector('.sidebar'), + settingsModal: document.getElementById('settings-modal'), + settingsIconBtn: document.querySelector('.header-actions button[title="Settings"]'), + closeSettingsBtn: document.getElementById('close-settings'), + cancelSettingsBtn: document.getElementById('cancel-settings'), + saveSettingsBtn: document.getElementById('save-settings'), + inputWahaUrl: document.getElementById('settings-waha-url'), + inputSession: document.getElementById('settings-session'), + inputApiKey: document.getElementById('settings-api-key'), + loggedUserName: document.getElementById('pandora-username'), + userIcon: document.getElementById('pandora-user-icon') +}; + +export const ui = { + /** + * Show or hide Settings connection modal + */ + toggleModal(show) { + if (show) { + elements.settingsModal.classList.remove('hidden'); + } else { + elements.settingsModal.classList.add('hidden'); + } + }, + + /** + * Switch view state when a contact chat is opened or closed + */ + toggleChatState(hasActive) { + if (hasActive) { + elements.noChatState.classList.add('hidden'); + elements.activeChatContainer.classList.remove('hidden'); + } else { + elements.noChatState.classList.remove('hidden'); + elements.activeChatContainer.classList.add('hidden'); + } + }, + + /** + * Scroll message list automatically to bottom + */ + scrollToBottom() { + elements.messagesContainer.scrollTop = elements.messagesContainer.scrollHeight; + }, + + /** + * Update connection status badge in sidebar footer + */ + updateConnectionStatus(isConnected, text) { + elements.backendStatusText.textContent = text; + if (isConnected) { + elements.apiStatusIndicator.style.backgroundColor = 'var(--online-color)'; + elements.apiStatusIndicator.style.animation = 'pulse 1.8s infinite'; + } else { + elements.apiStatusIndicator.style.backgroundColor = '#ef4444'; + elements.apiStatusIndicator.style.animation = 'none'; + } + }, + + /** + * Render sidebar contact chats list + */ + renderChatList(chats, activeChat, onChatSelect) { + elements.chatList.innerHTML = ''; + elements.chatCountBadge.textContent = chats.length; + + if (chats.length === 0) { + elements.chatList.innerHTML = `
  • No chats found
  • `; + return; + } + + chats.forEach(chat => { + const li = document.createElement('li'); + li.className = `chat-item ${activeChat && activeChat.id === chat.id ? 'active' : ''}`; + li.dataset.id = chat.id; + + const initials = chat.name ? chat.name.substring(0, 1).toUpperCase() : '?'; + const hasUnread = chat.unreadCount && chat.unreadCount > 0; + const timeStr = formatTime(chat.timestamp || new Date()); + + li.innerHTML = ` +
    ${initials}
    +
    +
    + ${chat.name} + ${timeStr} +
    +
    + ${chat.lastMessage || 'No messages yet'} + ${hasUnread ? `${chat.unreadCount}` : ''} +
    +
    + `; + + li.addEventListener('click', () => onChatSelect(chat)); + elements.chatList.appendChild(li); + }); + }, + + /** + * Render chat message log inside chat view container + */ + renderMessages(messages, activeChatName) { + elements.messagesContainer.innerHTML = ''; + + if (messages.length === 0) { + elements.messagesContainer.innerHTML = '
    No messages. Say hello!
    '; + return; + } + + messages.forEach(msg => { + const isOutgoing = msg.fromMe || msg.sender === 'me'; + const groupDiv = document.createElement('div'); + groupDiv.className = `message-group ${isOutgoing ? 'outgoing' : 'incoming'}`; + groupDiv.id = msg.id; + + const senderName = isOutgoing ? 'Me' : (msg.senderName || activeChatName); + const timeStr = formatTime(msg.timestamp || new Date()); + + let statusCheck = ''; + if (isOutgoing) { + if (msg.status === 'read') { + statusCheck = ''; + } else if (msg.status === 'delivered') { + statusCheck = ''; + } else { + statusCheck = ''; + } + } + + groupDiv.innerHTML = ` + ${!isOutgoing ? `${senderName}` : ''} +
    + ${msg.body || msg.text} +
    + ${timeStr} + ${statusCheck} +
    +
    + `; + + elements.messagesContainer.appendChild(groupDiv); + }); + + lucide.createIcons(); + this.scrollToBottom(); + }, + + /** + * Append a single message (used for optimistic updates immediately upon sending) + */ + appendSingleMessage(msg, activeChatName) { + if (elements.messagesContainer.querySelector('.loading-chats')) { + elements.messagesContainer.innerHTML = ''; + } + + const isOutgoing = msg.fromMe || msg.sender === 'me'; + const groupDiv = document.createElement('div'); + groupDiv.className = `message-group ${isOutgoing ? 'outgoing' : 'incoming'}`; + groupDiv.id = msg.id; + + const senderName = isOutgoing ? 'Me' : activeChatName; + const timeStr = formatTime(msg.timestamp || new Date()); + + groupDiv.innerHTML = ` + ${!isOutgoing ? `${senderName}` : ''} +
    + ${msg.body || msg.text} +
    + ${timeStr} + +
    +
    + `; + + elements.messagesContainer.appendChild(groupDiv); + lucide.createIcons(); + } +}; diff --git a/public/utils.js b/public/utils.js new file mode 100644 index 0000000..4f2ca61 --- /dev/null +++ b/public/utils.js @@ -0,0 +1,81 @@ +// Helper utilities and algorithms + +/** + * Format timestamps (supports Unix epoch seconds/ms, strings and ISO dates) + * @param {string|number|Date} dateVal + * @returns {string} Formatted HH:MM AM/PM string + */ +export function formatTime(dateVal) { + if (!dateVal) return ''; + let date; + if (typeof dateVal === 'number') { + date = new Date(dateVal < 10000000000 ? dateVal * 1000 : dateVal); + } else if (typeof dateVal === 'string' && /^\d+$/.test(dateVal)) { + const num = parseInt(dateVal, 10); + date = new Date(num < 10000000000 ? num * 1000 : num); + } else { + date = new Date(dateVal); + } + + let hours = date.getHours(); + let minutes = date.getMinutes(); + const ampm = hours >= 12 ? 'PM' : 'AM'; + hours = hours % 12; + hours = hours ? hours : 12; + minutes = minutes < 10 ? '0' + minutes : minutes; + return `${hours}:${minutes} ${ampm}`; +} + +/** + * Adjust outgoing messages backdated behind incoming messages due to clock drift. + * Uses a 30-second sliding bubble-sort window. + * @param {Array} messages List of raw messages from WAHA + * @returns {Array} Compensated chronological message array + */ +export function compensateMessageOrdering(messages) { + if (!Array.isArray(messages)) return []; + + // Convert timestamps to numeric milliseconds for stable comparison + const msgs = messages.map(m => { + let t = m.timestamp; + if (typeof t === 'number') { + if (t < 10000000000) t = t * 1000; + } else { + t = new Date(t).getTime(); + } + return { ...m, _time: t }; + }); + + // Initial chronological sort + msgs.sort((a, b) => a._time - b._time); + + // Apply drift bubble adjustments + let changed = true; + while (changed) { + changed = false; + for (let i = 0; i < msgs.length - 1; i++) { + const current = msgs[i]; + const next = msgs[i + 1]; + const timeDiff = next._time - current._time; + + // Swap if an outgoing message is sorted before an incoming message within a 30-sec window + if (current.fromMe && !next.fromMe && timeDiff >= 0 && timeDiff <= 30000) { + msgs[i] = next; + msgs[i + 1] = current; + + // Advance the outgoing message's timestamp to be exactly 1 second after the incoming one + current._time = next._time + 1000; + if (typeof current.timestamp === 'number') { + current.timestamp = Math.floor(current._time / 1000); + } else { + current.timestamp = new Date(current._time).toISOString(); + } + + changed = true; + } + } + } + + // Clean up temporary property + return msgs.map(({ _time, ...m }) => m); +} diff --git a/public/waha.js b/public/waha.js new file mode 100644 index 0000000..1413bc0 --- /dev/null +++ b/public/waha.js @@ -0,0 +1,92 @@ +import { config } from "./config.js"; + +async function request(path, options = {}) { + const url = `${config.wahaUrl}${path}`; + const headers = { + 'Content-Type': 'application/json', + 'accept': '*/*', + ...options.headers + }; + if (config.apiKey) { + headers['X-Api-Key'] = config.apiKey; + } + + console.log(`[WAHA] ${options.method || 'GET'} ${url}`, options.body ? JSON.parse(options.body) : ''); + + const response = await fetch(url, { ...options, headers }); + if (!response.ok) { + let errorDetail = ''; + try { + const errBody = await response.json(); + errorDetail = JSON.stringify(errBody); + console.error(`[WAHA] Error response body:`, errBody); + } catch (_) { + errorDetail = await response.text().catch(() => ''); + } + throw new Error(`WAHA API returned ${response.status}: ${response.statusText} — ${errorDetail}`); + } + return response.json(); +} + +export const waha = { + async getVersion() { + return request('/api/version'); + }, + + async getChats() { + const data = await request(`/api/${config.session}/chats`); + return data.map(chat => { + let chatId = chat.id; + if (chatId && typeof chatId === "object") { + chatId = chatId._serialized || chatId.user || JSON.stringify(chatId); + } + return { + id: chatId || chat.chatId || chat.name, + name: chat.name || "Unknown Contact", + unreadCount: chat.unreadCount || 0, + lastMessage: chat.lastMessage?.body || chat.lastMessageText || "Click to open chat", + timestamp: chat.lastMessage?.timestamp || new Date() + }; + }); + }, + + async getChatMessages(chatId) { + return request(`/api/${config.session}/chats/${chatId}/messages?downloadMedia=false&limit=40`); + }, + + async readChat(chatId) { + return request('/api/sendSeen', { + method: 'POST', + body: JSON.stringify({ chatId, session: config.session }) + }); + }, + + async getMyInfo() { + return request(`/api/sessions/${config.session}/me`); + }, + + async startTyping(chatId) { + return request('/api/startTyping', { + method: 'POST', + body: JSON.stringify({ chatId, session: config.session }) + }); + }, + + async stopTyping(chatId) { + return request('/api/stopTyping', { + method: 'POST', + body: JSON.stringify({ chatId, session: config.session }) + }); + }, + + async sendTextMessage(chatId, text) { + return request('/api/sendText', { + method: 'POST', + body: JSON.stringify({ + chatId, + text, + session: config.session + }) + }); + } +}; diff --git a/public/websocket.js b/public/websocket.js new file mode 100644 index 0000000..ab0f073 --- /dev/null +++ b/public/websocket.js @@ -0,0 +1,93 @@ +import { config } from "./config.js"; + +let socket = null; +let reconnectTimer = null; +let currentOnMessageCallback = null; + +export const websocket = { + connect(onMessageCallback) { + currentOnMessageCallback = onMessageCallback; + + this.disconnect(false); + + const httpUrl = config.wahaUrl; + if (!httpUrl) { + console.warn('[WS] Config wahaUrl is empty. Cannot connect.'); + return; + } + + let wsUrl = httpUrl.replace(/^http:/i, 'ws:').replace(/^https:/i, 'wss:'); + wsUrl = wsUrl.replace(/\/$/, '') + '/ws'; + + const apiKey = config.apiKey; + const session = config.session; + const events = ['session.status', 'message', 'message.any']; + + const queryParams = new URLSearchParams(); + if (apiKey) { + queryParams.append('x-api-key', apiKey); + } + queryParams.append('session', session); + events.forEach(event => queryParams.append('events', event)); + + const fullWsUrl = `${wsUrl}?${queryParams.toString()}`; + console.log('[WS] Connecting to:', fullWsUrl); + + try { + socket = new WebSocket(fullWsUrl); + + socket.onopen = () => { + console.log('[WS] Connection successfully established'); + if (reconnectTimer) { + clearTimeout(reconnectTimer); + reconnectTimer = null; + } + }; + + socket.onmessage = (event) => { + try { + const data = JSON.parse(event.data); + if (currentOnMessageCallback) { + currentOnMessageCallback(data); + } + } catch (e) { + console.error('[WS] Failed to parse message JSON:', e); + } + }; + + socket.onerror = (error) => { + console.error('[WS] WebSocket Error occurred:', error); + }; + + socket.onclose = (event) => { + console.log(`[WS] Connection closed (code: ${event.code}). Reconnecting in 5 seconds...`); + socket = null; + + reconnectTimer = setTimeout(() => { + this.connect(currentOnMessageCallback); + }, 5000); + }; + } catch (e) { + console.error('[WS] Failed to initialize WebSocket client:', e); + } + }, + + disconnect(clearCallback = true) { + if (reconnectTimer) { + clearTimeout(reconnectTimer); + reconnectTimer = null; + } + if (clearCallback) { + currentOnMessageCallback = null; + } + if (socket) { + socket.onclose = null; + socket.onerror = null; + socket.onopen = null; + socket.onmessage = null; + socket.close(); + socket = null; + console.log('[WS] Connection closed explicitly'); + } + } +}; diff --git a/wahaService.js b/wahaService.js new file mode 100644 index 0000000..39394a2 --- /dev/null +++ b/wahaService.js @@ -0,0 +1,77 @@ +import axios from "axios"; + +const session = "session_01kxc62bk5fs8vh4v127k88a7j"; +const wahaBaseUrl = "http://inspiran.beetal-castor.ts.net:3100"; +const apiKey = process.env.WAHA_API_KEY; + +const client = axios.create({ + baseURL: wahaBaseUrl, + headers: { + "X-API-KEY": apiKey, + "Content-Type": "application/json" + } +}); + +export const wahaService = { + getConfigStatus() { + return { + wahaBaseUrl, + session, + hasApiKey: !!apiKey + }; + }, + + async getChats() { + const response = await client.get(`/api/${session}/chats`, { timeout: 5000 }); + + if (!Array.isArray(response.data)) { + throw new Error("Invalid chats response format from WAHA API"); + } + + return response.data.map(chat => { + let chatId = chat.id; + if (chatId && typeof chatId === "object") { + chatId = chatId._serialized || chatId.user || JSON.stringify(chatId); + } + return { + id: chatId || chat.chatId || chat.name, + name: chat.name || "Unknown Contact", + unreadCount: chat.unreadCount || 0, + lastMessage: chat.lastMessage?.body || chat.lastMessageText || "Click to open chat", + timestamp: chat.lastMessage?.timestamp || new Date() + }; + }); + }, + + async getChatMessages(chatId) { + const response = await client.get(`/api/${session}/chats/${chatId}/messages?downloadMedia=false&merge=true&limit=10`); + return response.data; + }, + + async getMyInfo(chatId) { + const response = await client.get(`/api/${session}/me`); + return response.data; + }, + + async startTyping(chatId) { + await client.post("/api/startTyping", { + chatId, + session + }, { timeout: 3000 }); + }, + + async stopTyping(chatId) { + await client.post("/api/stopTyping", { + chatId, + session + }, { timeout: 2000 }); + }, + + async sendTextMessage(chatId, text) { + const response = await client.post("/api/sendText", { + chatId, + text + }); + return response.data; + } +};