init project evolution api
5
.dockerignore
Normal file
@ -0,0 +1,5 @@
|
||||
.git
|
||||
*Dockerfile*
|
||||
*docker-compose*
|
||||
node_modules
|
||||
dist
|
2
.eslintignore
Normal file
@ -0,0 +1,2 @@
|
||||
/node-modules
|
||||
/dist
|
42
.eslintrc.js
Normal file
@ -0,0 +1,42 @@
|
||||
module.exports = {
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: {
|
||||
sourceType: 'CommonJS',
|
||||
},
|
||||
plugins: ['@typescript-eslint/eslint-plugin'],
|
||||
extends: [
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:prettier/recommended',
|
||||
'plugin:prettier/recommended'
|
||||
],
|
||||
globals: {
|
||||
Atomics: 'readonly',
|
||||
SharedArrayBuffer: 'readonly',
|
||||
},
|
||||
root: true,
|
||||
env: {
|
||||
node: true,
|
||||
jest: true,
|
||||
},
|
||||
ignorePatterns: ['.eslintrc.js'],
|
||||
rules: {
|
||||
'@typescript-eslint/interface-name-prefix': 'off',
|
||||
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||
'@typescript-eslint/explicit-module-boundary-types': 'off',
|
||||
'@typescript-eslint/no-explicit-any': 'off',
|
||||
'@typescript-eslint/no-empty-function': 'off',
|
||||
'@typescript-eslint/no-non-null-assertion': 'off',
|
||||
'@typescript-eslint/no-unused-vars': 'off',
|
||||
'@typescript-eslint/ban-types': [
|
||||
'error',
|
||||
{
|
||||
extendDefaults: true,
|
||||
types: {
|
||||
'{}': false,
|
||||
Object: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
'prettier/prettier': ['error', { endOfLine: 'auto' }],
|
||||
},
|
||||
};
|
32
.gitignore
vendored
Normal file
@ -0,0 +1,32 @@
|
||||
# compiled output
|
||||
/dist
|
||||
/node_modules
|
||||
|
||||
# Logs
|
||||
logs/**.json
|
||||
*.log
|
||||
npm-debug.log*
|
||||
pnpm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# Package
|
||||
/yarn.lock
|
||||
/package-lock.json
|
||||
|
||||
# IDE - VSCode
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
|
||||
# Prisma
|
||||
/prisma/migrations
|
||||
|
||||
# Project related
|
||||
/instances/*
|
||||
!/instances/.gitkeep
|
||||
/test/
|
||||
/src/env.yml
|
9
.prettierrc.js
Normal file
@ -0,0 +1,9 @@
|
||||
module.exports = {
|
||||
semi: true,
|
||||
trailingComma: 'all',
|
||||
singleQuote: true,
|
||||
printWidth: 90,
|
||||
tabWidth: 2,
|
||||
bracketSameLine: true,
|
||||
bracketSpacing: true
|
||||
}
|
11
.vscode/settings.json
vendored
Normal file
@ -0,0 +1,11 @@
|
||||
{
|
||||
"editor.fontSize": 13,
|
||||
"editor.fontLigatures": true,
|
||||
"editor.letterSpacing": 0.5,
|
||||
"editor.smoothScrolling": true,
|
||||
"editor.tabSize": 2,
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.eslint": true,
|
||||
"source.fixAll": true
|
||||
}
|
||||
}
|
80
Docker/.env
Normal file
@ -0,0 +1,80 @@
|
||||
CORS_ORIGIN='*' # Or separate by commas - ex.: 'yourdomain1.com, yourdomain2.com'
|
||||
CORS_METHODS='POST,GET,PUT,DELETE'
|
||||
CORS_CREDENTIALS=true
|
||||
|
||||
# Determine the logs to be displayed
|
||||
LOG_LEVEL='ERROR,WARN,DEBUG,INFO,LOG,VERBOSE,DARK'
|
||||
LOG_COLOR=true
|
||||
|
||||
# Determine how long the instance should be deleted from memory in case of no connection.
|
||||
# Default time: 5 minutes
|
||||
# If you don't even want an expiration, enter the value false
|
||||
DEL_INSTANCE=5
|
||||
|
||||
# Temporary data storage
|
||||
STORE_CLEANING_INTERVAL=7200 # seconds ===2h
|
||||
STORE_MESSAGE=true
|
||||
STORE_CONTACTS=false
|
||||
STORE_CHATS=false
|
||||
|
||||
# Permanent data storage
|
||||
DATABASE_ENABLED=false
|
||||
DATABASE_CONNECTION_URI='<uri>'
|
||||
DATABASE_CONNECTION_DB_PREFIX_NAME='evolution'
|
||||
DATABASE_SAVE_DATA_INSTANCE=false
|
||||
DATABASE_SAVE_DATA_OLD_MESSAGE=false
|
||||
DATABASE_SAVE_DATA_NEW_MESSAGE=true
|
||||
DATABASE_SAVE_MESSAGE_UPDATE=true
|
||||
DATABASE_SAVE_DATA_CONTACTS=true
|
||||
DATABASE_SAVE_DATA_CHATS=true
|
||||
|
||||
REDIS_ENABLED=true
|
||||
REDIS_URI='<uri>/1'
|
||||
REDIS_PREFIX_KEY='evolution'
|
||||
|
||||
# Webhook Settings
|
||||
## Define a global webhook that will listen for enabled events from all instances
|
||||
WEBHOOK_GLOBAL_URL='<url>'
|
||||
WEBHOOK_GLOBAL_ENABLED=false
|
||||
WEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS=false
|
||||
## Set the events you want to hear
|
||||
WEBHOOK_EVENTS_STATUS_INSTANCE=true
|
||||
WEBHOOK_EVENTS_APPLICATION_STARTUP=true
|
||||
WEBHOOK_EVENTS_QRCODE_UPDATED=true
|
||||
WEBHOOK_EVENTS_MESSAGES_SET=true
|
||||
WEBHOOK_EVENTS_MESSAGES_UPDATE=true
|
||||
WEBHOOK_EVENTS_MESSAGES_UPSERT=true
|
||||
WEBHOOK_EVENTS_SEND_MESSAGE=true
|
||||
WEBHOOK_EVENTS_CONTACTS_SET=true
|
||||
WEBHOOK_EVENTS_CONTACTS_UPSERT=true
|
||||
WEBHOOK_EVENTS_CONTACTS_UPDATE=true
|
||||
WEBHOOK_EVENTS_PRESENCE_UPDATE=true
|
||||
WEBHOOK_EVENTS_CHATS_SET=true
|
||||
WEBHOOK_EVENTS_CHATS_UPSERT=true
|
||||
WEBHOOK_EVENTS_CHATS_UPDATE=true
|
||||
WEBHOOK_EVENTS_CONNECTION_UPDATE=true
|
||||
WEBHOOK_EVENTS_GROUPS_UPSERT=false
|
||||
WEBHOOK_EVENTS_GROUPS_UPDATE=false
|
||||
WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE=false
|
||||
## This event fires every time a new token is requested via the refresh route
|
||||
WEBHOOK_EVENTS_NEW_JWT_TOKEN=true
|
||||
|
||||
CONFIG_SESSION_PHONE_CLIENT='Evolution API'
|
||||
CONFIG_SESSION_PHONE_NAME='Chrome'
|
||||
|
||||
# Set qrcode display limit
|
||||
QRCODE_LIMIT=6
|
||||
|
||||
# Defines an authentication type for the api
|
||||
AUTHENTICATION_TYPE='jwt' # or 'apikey'
|
||||
## Define a global apikey to access all instances.
|
||||
### OBS: This key must be inserted in the request header to create an instance.
|
||||
AUTHENTICATION_API_KEY='t8OOEeISKzpmc3jjcMqBWYSaJsafdefer'
|
||||
## Set the secret key to encrypt and decrypt your token and its expiration time
|
||||
AUTHENTICATION_JWT_EXPIRIN_IN=3600 # seconds - 3600s ===1h | zero (0) - never expires
|
||||
AUTHENTICATION_JWT_SECRET='L0YWtjb2w554WFqPG'
|
||||
|
||||
AUTHENTICATION_INSTANCE_NAME='evolution'
|
||||
AUTHENTICATION_INSTANCE_WEBHOOK_URL='<url>'
|
||||
AUTHENTICATION_INSTANCE_MODE='container' # or 'server'
|
||||
AUTHENTICATION_INSTANCE_WEBHOOK_BY_EVENTS=false
|
89
Dockerfile
Normal file
@ -0,0 +1,89 @@
|
||||
FROM node:16.18-alpine
|
||||
|
||||
RUN apk update && apk upgrade && \
|
||||
apk add --no-cache git
|
||||
|
||||
WORKDIR /evolution
|
||||
|
||||
COPY ./package.json .
|
||||
|
||||
ENV DOCKER_ENV=true
|
||||
|
||||
ENV TZ=America/Sao_Paulo
|
||||
|
||||
ENV CORS_ORIGIN="*"
|
||||
ENV CORS_METHODS="POST,GET,PUT,DELETE"
|
||||
ENV CORS_CREDENTIALS=true
|
||||
|
||||
ENV LOG_LEVEL="ERROR,WARN,DEBUG,INFO,LOG,VERBOSE,DARK"
|
||||
ENV LOG_COLOR=true
|
||||
|
||||
ENV DEL_INSTANCE=false
|
||||
|
||||
ENV STORE_CLEANING_INTERVAL=7200
|
||||
ENV STORE_MESSAGE=true
|
||||
ENV STORE_CONTACTS=true
|
||||
ENV STORE_CHATS=true
|
||||
|
||||
ENV DATABASE_ENABLED=$DATABASE_ENABLED
|
||||
ENV DATABASE_CONNECTION_URI=$DATABASE_CONNECTION_URI
|
||||
ENV DATABASE_CONNECTION_DB_PREFIX_NAME=$DATABASE_CONNECTION_DB_PREFIX_NAME
|
||||
ENV DATABASE_SAVE_DATA_INSTANCE=false
|
||||
ENV DATABASE_SAVE_DATA_OLD_MESSAGE=false
|
||||
ENV DATABASE_SAVE_DATA_NEW_MESSAGE=true
|
||||
ENV DATABASE_SAVE_MESSAGE_UPDATE=false
|
||||
ENV DATABASE_SAVE_DATA_CONTACTS=true
|
||||
ENV DATABASE_SAVE_DATA_CHATS=true
|
||||
|
||||
ENV REDIS_ENABLED=$REDIS_ENABLED
|
||||
ENV REDIS_URI=$REDIS_URI
|
||||
|
||||
ENV WEBHOOK_GLOBAL_URL=$WEBHOOK_GLOBAL_URL
|
||||
ENV WEBHOOK_GLOBAL_ENABLED=true
|
||||
ENV WEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS=$WEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS
|
||||
|
||||
ENV WEBHOOK_EVENTS_STATUS_INSTANCE=true
|
||||
ENV WEBHOOK_EVENTS_APPLICATION_STARTUP=true
|
||||
ENV WEBHOOK_EVENTS_QRCODE_UPDATED=true
|
||||
ENV WEBHOOK_EVENTS_MESSAGES_SET=true
|
||||
ENV WEBHOOK_EVENTS_MESSAGES_UPDATE=true
|
||||
ENV WEBHOOK_EVENTS_MESSAGES_UPSERT=true
|
||||
ENV WEBHOOK_EVENTS_SEND_MESSAGE=true
|
||||
ENV WEBHOOK_EVENTS_CONTACTS_SET=true
|
||||
ENV WEBHOOK_EVENTS_CONTACTS_UPSERT=true
|
||||
ENV WEBHOOK_EVENTS_CONTACTS_UPDATE=true
|
||||
ENV WEBHOOK_EVENTS_PRESENCE_UPDATE=true
|
||||
ENV WEBHOOK_EVENTS_CHATS_SET=true
|
||||
ENV WEBHOOK_EVENTS_CHATS_UPSERT=true
|
||||
ENV WEBHOOK_EVENTS_CHATS_UPDATE=true
|
||||
ENV WEBHOOK_EVENTS_CONNECTION_UPDATE=true
|
||||
ENV WEBHOOK_EVENTS_GROUPS_UPSERT=true
|
||||
ENV WEBHOOK_EVENTS_GROUPS_UPDATE=true
|
||||
ENV WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE=true
|
||||
|
||||
ENV WEBHOOK_EVENTS_NEW_JWT_TOKEN=true
|
||||
|
||||
ENV CONFIG_SESSION_PHONE_CLIENT="Evolution API"
|
||||
ENV CONFIG_SESSION_PHONE_NAME="Chrome"
|
||||
|
||||
ENV QRCODE_LIMIT=30
|
||||
|
||||
ENV AUTHENTICATION_TYPE="apikey"
|
||||
|
||||
ENV AUTHENTICATION_API_KEY=$AUTHENTICATION_API_KEY
|
||||
|
||||
ENV AUTHENTICATION_JWT_EXPIRIN_IN=0
|
||||
ENV AUTHENTICATION_JWT_SECRET="L0YWtjb2w554WFqPG"
|
||||
|
||||
ENV AUTHENTICATION_INSTANCE_NAME=$AUTHENTICATION_INSTANCE_NAME
|
||||
ENV AUTHENTICATION_INSTANCE_WEBHOOK_URL=$AUTHENTICATION_INSTANCE_WEBHOOK_URL
|
||||
ENV AUTHENTICATION_INSTANCE_MODE=$AUTHENTICATION_INSTANCE_MODE
|
||||
ENV AUTHENTICATION_INSTANCE_WEBHOOK_BY_EVENTS=$AUTHENTICATION_INSTANCE_WEBHOOK_BY_EVENTS
|
||||
|
||||
RUN npm install
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN npm run build
|
||||
|
||||
CMD [ "node", "./dist/src/main.js" ]
|
674
LICENSE
Normal file
@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
267
README.md
Normal file
@ -0,0 +1,267 @@
|
||||
<h1 align="center">Evolution Api</h1>
|
||||
<!--
|
||||
</br>
|
||||
<hr style="height: 5px;background: #007500;margin: 20px 0;box-shadow: 0px 3px 5px 0px rgb(204 204 204);">-->
|
||||
|
||||
<!-- <div align="center"> -->
|
||||
|
||||
<!-- [](#)
|
||||
[](#)
|
||||
[](./LICENSE)
|
||||
[](https://app.picpay.com/user/davidsongomes1998) -->
|
||||
|
||||
<!-- </div> -->
|
||||
|
||||
<!-- <div align="center"><img src="./public/images/cover.png"></div>-> -->
|
||||
|
||||
## WhatsApp-Api-NodeJs
|
||||
|
||||
This project is based on the [CodeChat](https://github.com/code-chat-br/whatsapp-api). The original project is an implementation of [Baileys](https://github.com/adiwajshing/Baileys), serving as a Restful API service that controls WhatsApp functions.</br>
|
||||
The code allows the creation of multiservice chats, service bots, or any other system that utilizes WhatsApp. The documentation provides instructions on how to set up and use the project, as well as additional information about its features and configuration options.
|
||||
|
||||
## Infrastructure
|
||||
|
||||
### Nvm installation
|
||||
|
||||
```sh
|
||||
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
|
||||
# or
|
||||
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
|
||||
```
|
||||
>
|
||||
> After finishing, restart the terminal to load the new information.
|
||||
>
|
||||
|
||||
### Docker installation \[optional\]
|
||||
|
||||
```sh
|
||||
curl -fsSL https://get.docker.com -o get-docker.sh
|
||||
|
||||
sudo sh get-docker.sh
|
||||
|
||||
sudo usermod -aG docker ${USER}
|
||||
```
|
||||
### Nodejs installation
|
||||
|
||||
```sh
|
||||
nvm install 16.17.0
|
||||
```
|
||||
|
||||
### pm2 installation
|
||||
```sh
|
||||
npm i -g pm2
|
||||
```
|
||||
|
||||
```sh
|
||||
docker --version
|
||||
|
||||
node --version
|
||||
```
|
||||
## MongoDb [optional]
|
||||
|
||||
After installing docker and docker-compose, up the container.
|
||||
- [compose from mongodb](./mongodb/docker-compose.yaml)
|
||||
|
||||
In the same directory where the file is located, run the following command:
|
||||
```sh
|
||||
bash docker.sh
|
||||
```
|
||||
Using the database is optional.
|
||||
|
||||
## Application startup
|
||||
|
||||
Cloning the Repository
|
||||
```
|
||||
git clone https://github.com/code-chat-br/whatsapp-api.git
|
||||
```
|
||||
|
||||
Go to the project directory and install all dependencies.</br>
|
||||
```sh
|
||||
cd whatsapp-api
|
||||
|
||||
npm i
|
||||
```
|
||||
|
||||
Finally, run the command below to start the application:
|
||||
```sh
|
||||
# Under development
|
||||
npm run start
|
||||
|
||||
# In production
|
||||
npm run start:prod
|
||||
|
||||
# pm2
|
||||
pm2 start 'npm run start:prod' --name ApiCodechat
|
||||
```
|
||||
## Authentication
|
||||
|
||||
You can define two authentication **types** for the routes in the **[env file](./src/dev-env.yml)**.
|
||||
Authentications must be inserted in the request header.
|
||||
|
||||
1. **apikey**
|
||||
|
||||
2. **jwt:** A JWT is a standard for authentication and information exchange defined with a signature.
|
||||
|
||||
> Authentications are generated at instance creation time.
|
||||
|
||||
**Note:** There is also the possibility to define a global api key, which can access and control all instances.
|
||||
|
||||
### Connection
|
||||
|
||||
#### Create an instance
|
||||
|
||||
##### HTTP
|
||||
|
||||
> *NOTE:* This key must be inserted in the request header to create an instance.
|
||||
|
||||
```http
|
||||
POST /instance/create HTTP/1.1
|
||||
Host: localhost:8080
|
||||
Content-Type: application/json
|
||||
apikey: t8OOEeISKzpmc3jjcMqBWYSaJH2PIxns
|
||||
|
||||
{
|
||||
"instanceName": "codechat"
|
||||
}
|
||||
```
|
||||
##### cURL
|
||||
|
||||
```bash
|
||||
curl --location --request POST 'http://localhost:8080/instance/create' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--header 'apikey: t8OOEeISKzpmc3jjcMqBWYSaJH2PIxns' \
|
||||
--data-raw '{
|
||||
"instanceName": "codechat"
|
||||
}'
|
||||
```
|
||||
### Response
|
||||
|
||||
```ts
|
||||
{
|
||||
"instance": {
|
||||
"instanceName": "codechat",
|
||||
"status": "created"
|
||||
},
|
||||
"hash": {
|
||||
"jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. [...]"
|
||||
|
||||
// or
|
||||
// "apikey": "88513847-1B0E-4188-8D76-4A2750C9B6C3"
|
||||
}
|
||||
}
|
||||
```
|
||||
#### Connection with qrcode
|
||||
|
||||
##### HTTP
|
||||
|
||||
```http
|
||||
GET /instance/connect/codechat HTTP/1.1
|
||||
Host: localhost:8080
|
||||
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. [...]
|
||||
```
|
||||
```http
|
||||
GET /instance/connect/codechat HTTP/1.1
|
||||
Host: localhost:8080
|
||||
apikey: 88513847-1B0E-4188-8D76-4A2750C9B6C3
|
||||
```
|
||||
##### cURL
|
||||
|
||||
```bash
|
||||
curl --location --request GET 'http://localhost:8080/instance/connect/codechat' \
|
||||
--header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. [...]'
|
||||
```
|
||||
```bash
|
||||
curl --location --request GET 'http://localhost:8080/instance/connect/codechat' \
|
||||
--header 'apikey: 88513847-1B0E-4188-8D76-4A2750C9B6C3'
|
||||
```
|
||||
|
||||
### Response
|
||||
|
||||
```ts
|
||||
{
|
||||
"code": "2@nXSUgRJSBY6T0XJmiFKZ0 [...] ,XsgJhJHYa+0MPpXANdPHHt6Ke/I7O2QyXT/Lsge0uSg=",
|
||||
"base64": "data:image/png;base64,iVBORw0KGgoAAAANSUhE [...] LkMtqAAAAABJRU5ErkJggg=="
|
||||
}
|
||||
```
|
||||
|
||||
### App in Docker
|
||||
- [docker run](./docker.sh)
|
||||
- [docker-compose](./docker-compose.yml)
|
||||
- [env for docker](./Docker/.env)
|
||||
- [DockerHub-codechat/api](https://hub.docker.com/r/codechat/api)
|
||||
|
||||
After building the application, in the same directory as the files above, run the following command:
|
||||
```sh
|
||||
docker-compose up
|
||||
```
|
||||
## Send Messages
|
||||
| | |
|
||||
|-----|---|
|
||||
| Send Text | ✔ |
|
||||
| Send Buttons | ✔ |
|
||||
| Send Template | ❌ |
|
||||
| Send Media: audio - video - image - document - gif <br></br>base64: ```true``` | ✔ |
|
||||
| Send Media File | ❌ |
|
||||
| Send Audio type WhatsApp | ✔ |
|
||||
| Send Location | ✔ |
|
||||
| Send List | ✔ |
|
||||
| Send Link Preview | ✔ |
|
||||
| Send Contact | ✔ |
|
||||
| Send Reaction - emoji | ✔ |
|
||||
| Send Poll Message | ✔ |
|
||||
|
||||
## Postman collections
|
||||
- [Postman Json](./postman.json)
|
||||
|
||||
## Webhook Events
|
||||
|
||||
| Name | Event | TypeData | Description |
|
||||
|------|-------|-----------|------------|
|
||||
| APPLICATION_STARTUP | application.startup | json | Notifies you when a application startup |
|
||||
| QRCODE_UPDATED | qrcode.updated | json | Sends the base64 of the qrcode for reading |
|
||||
| CONNECTION_UPDATE | connection.update | json | Informs the status of the connection with whatsapp |
|
||||
| MESSAGES_SET | message.set | json | Sends a list of all your messages uploaded on whatsapp</br>This event occurs only once |
|
||||
| MESSAGES_UPSERT | message.upsert | json | Notifies you when a message is received |
|
||||
| MESSAGES_UPDATE | message.update | json | Tells you when a message is updated |
|
||||
| SEND_MESSAGE | send.message | json | Notifies when a message is sent |
|
||||
| CONTACTS_SET | contacts.set | json | Performs initial loading of all contacts</br>This event occurs only once |
|
||||
| CONTACTS_UPSERT | contacts.upsert | json | Reloads all contacts with additional information</br>This event occurs only once |
|
||||
| CONTACTS_UPDATE | contacts.update | json | Informs you when the chat is updated |
|
||||
| PRESENCE_UPDATE | presence.update | json | Informs if the user is online, if he is performing some action like writing or recording and his last seen</br>'unavailable' | 'available' | 'composing' | 'recording' | 'paused' |
|
||||
| CHATS_SET | chats.set | json | Send a list of all loaded chats |
|
||||
| CHATS_UPDATE | chats.update | json | Informs you when the chat is updated |
|
||||
| CHATS_UPSERT | chats.upsert | json | Sends any new chat information |
|
||||
| GROUPS_UPSERT | groups.upsert | JSON | Notifies when a group is created |
|
||||
| GROUPS_UPDATE | groups.update | JSON | Notifies when a group has its information updated |
|
||||
| GROUP_PARTICIPANTS_UPDATE | group-participants.update | JSON | Notifies when an action occurs involving a participant</br>'add' | 'remove' | 'promote' | 'demote' |
|
||||
| NEW_TOKEN | new.jwt | JSON | Notifies when the token (jwt) is updated
|
||||
|
||||
## Env File
|
||||
|
||||
See additional settings that can be applied through the **env** file by clicking **[here](./src/dev-env.yml)**.
|
||||
|
||||
> **⚠️Attention⚠️:** rename the **dev-env.yml** file to **env.yml**.
|
||||
|
||||
## SSL
|
||||
|
||||
To install the SSL certificate, follow the **[instructions](https://certbot.eff.org/instructions?ws=other&os=ubuntufocal)** below.
|
||||
|
||||
# Note
|
||||
|
||||
This code is in no way affiliated with WhatsApp. Use at your own discretion. Don't spam this.
|
||||
|
||||
This code was produced based on the baileys library and it is still under development.
|
||||
|
||||
# Donate to the project.
|
||||
|
||||
#### Pix: 2b526ada-4ef4-4db4-bbeb-f60da2421fce
|
||||
|
||||
#### PicPay
|
||||
|
||||
<div align="center">
|
||||
<a href="https://app.picpay.com/user/davidsongomes1998" target="_blank" rel="noopener noreferrer">
|
||||
<img src="./public/images/picpay-image.png" style="width: 50% !important;">
|
||||
</a>
|
||||
</div>
|
||||
|
||||
</br>
|
0
instances/.gitkeep
Normal file
28
mongodb/docker-compose.yaml
Normal file
@ -0,0 +1,28 @@
|
||||
|
||||
version: '3.8'
|
||||
|
||||
networks:
|
||||
api-net:
|
||||
driver: bridge
|
||||
|
||||
services:
|
||||
mongodb:
|
||||
container_name: mongodb
|
||||
|
||||
# This image already has a single replica set
|
||||
image: mongo
|
||||
|
||||
restart: always
|
||||
volumes:
|
||||
# sudo mkdir -p /data/mongodb
|
||||
- /data/mongodb:/data/db
|
||||
ports:
|
||||
- 26712:27017
|
||||
environment:
|
||||
MONGO_INITDB_ROOT_USERNAME: root
|
||||
# Set a password to access the bank
|
||||
MONGO_INITDB_ROOT_PASSWORD: <password>
|
||||
networks:
|
||||
- api-net
|
||||
expose:
|
||||
- 26712
|
90
package.json
Normal file
@ -0,0 +1,90 @@
|
||||
{
|
||||
"name": "evolution-api",
|
||||
"version": "1.2.0",
|
||||
"description": "Rest api for communication with WhatsApp",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"start": "ts-node --files --transpile-only ./src/main.ts",
|
||||
"start:prod": "bash start.sh",
|
||||
"dev:server": "clear && tsnd --files --transpile-only --respawn --ignore-watch node_modules ./src/main.ts",
|
||||
"test": "clear && tsnd --files --transpile-only --respawn --ignore-watch node_modules ./test/all.test.ts"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/DavidsonGomes/evolution-api.git"
|
||||
},
|
||||
"keywords": [
|
||||
"chat",
|
||||
"communication",
|
||||
"message",
|
||||
"send message",
|
||||
"whatsapp",
|
||||
"js-whatsapp",
|
||||
"whatsapp-api",
|
||||
"whatsapp-web",
|
||||
"whatsapp",
|
||||
"whatsapp-chat",
|
||||
"whatsapp-group",
|
||||
"automation",
|
||||
"multi-device",
|
||||
"bot"
|
||||
],
|
||||
"author": {
|
||||
"name": "Davidson Gomes",
|
||||
"email": "contato@agenciadgcode.com"
|
||||
},
|
||||
"license": "GPL-3.0",
|
||||
"bugs": {
|
||||
"url": "https://github.com/DavidsonGomes/evolution-api/issues"
|
||||
},
|
||||
"homepage": "https://github.com/DavidsonGomes/evolution-api#readme",
|
||||
"dependencies": {
|
||||
"@adiwajshing/keyed-db": "^0.2.4",
|
||||
"@evolution/base": "github:WhiskeySockets/Baileys",
|
||||
"@hapi/boom": "^10.0.1",
|
||||
"axios": "^1.3.5",
|
||||
"class-validator": "^0.13.2",
|
||||
"compression": "^1.7.4",
|
||||
"cors": "^2.8.5",
|
||||
"cross-env": "^7.0.3",
|
||||
"dayjs": "^1.11.7",
|
||||
"eventemitter2": "^6.4.9",
|
||||
"express": "^4.18.2",
|
||||
"express-async-errors": "^3.1.1",
|
||||
"hbs": "^4.2.0",
|
||||
"jimp": "^0.16.13",
|
||||
"join": "^3.0.0",
|
||||
"js-yaml": "^4.1.0",
|
||||
"jsonschema": "^1.4.1",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
"link-preview-js": "^3.0.4",
|
||||
"mongoose": "^6.10.5",
|
||||
"node-cache": "^5.1.2",
|
||||
"node-mime-types": "^1.1.0",
|
||||
"pino": "^8.11.0",
|
||||
"qrcode": "^1.5.1",
|
||||
"qrcode-terminal": "^0.12.0",
|
||||
"redis": "^4.6.5",
|
||||
"uuid": "^9.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/compression": "^1.7.2",
|
||||
"@types/cors": "^2.8.13",
|
||||
"@types/express": "^4.17.17",
|
||||
"@types/js-yaml": "^4.0.5",
|
||||
"@types/jsonwebtoken": "^8.5.9",
|
||||
"@types/node": "^18.15.11",
|
||||
"@types/qrcode": "^1.5.0",
|
||||
"@types/qrcode-terminal": "^0.12.0",
|
||||
"@types/uuid": "^8.3.4",
|
||||
"@typescript-eslint/eslint-plugin": "^5.57.1",
|
||||
"@typescript-eslint/parser": "^5.57.1",
|
||||
"eslint": "^8.38.0",
|
||||
"eslint-config-prettier": "^8.8.0",
|
||||
"eslint-plugin-prettier": "^4.2.1",
|
||||
"prettier": "^2.8.7",
|
||||
"ts-node-dev": "^2.0.0",
|
||||
"typescript": "^4.9.5"
|
||||
}
|
||||
}
|
2045
postman.json
Normal file
BIN
public/images/atendai-logo.png
Normal file
After Width: | Height: | Size: 25 KiB |
BIN
public/images/code.png
Normal file
After Width: | Height: | Size: 14 KiB |
BIN
public/images/codechat-logo.png
Normal file
After Width: | Height: | Size: 120 KiB |
BIN
public/images/cover.png
Normal file
After Width: | Height: | Size: 108 KiB |
BIN
public/images/n8n-codechat-wapi.png
Normal file
After Width: | Height: | Size: 36 KiB |
BIN
public/images/picpay-image.png
Normal file
After Width: | Height: | Size: 65 KiB |
BIN
public/images/video-cover.png
Normal file
After Width: | Height: | Size: 8.7 KiB |
255
src/config/env.config.ts
Normal file
@ -0,0 +1,255 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import { load } from 'js-yaml';
|
||||
import { join } from 'path';
|
||||
import { SRC_DIR } from './path.config';
|
||||
|
||||
export type HttpServer = { TYPE: 'http' | 'https'; PORT: number };
|
||||
|
||||
export type HttpMethods = 'POST' | 'GET' | 'PUT' | 'DELETE';
|
||||
export type Cors = {
|
||||
ORIGIN: string[];
|
||||
METHODS: HttpMethods[];
|
||||
CREDENTIALS: boolean;
|
||||
};
|
||||
|
||||
export type LogLevel = 'ERROR' | 'WARN' | 'DEBUG' | 'INFO' | 'LOG' | 'VERBOSE' | 'DARK';
|
||||
export type Log = {
|
||||
LEVEL: LogLevel[];
|
||||
COLOR: boolean;
|
||||
};
|
||||
|
||||
export type SaveData = {
|
||||
INSTANCE: boolean;
|
||||
OLD_MESSAGE: boolean;
|
||||
NEW_MESSAGE: boolean;
|
||||
MESSAGE_UPDATE: boolean;
|
||||
CONTACTS: boolean;
|
||||
CHATS: boolean;
|
||||
};
|
||||
|
||||
export type StoreConf = {
|
||||
CLEANING_INTERVAL: number;
|
||||
MESSAGES: boolean;
|
||||
CONTACTS: boolean;
|
||||
CHATS: boolean;
|
||||
};
|
||||
|
||||
export type DBConnection = {
|
||||
URI: string;
|
||||
DB_PREFIX_NAME: string;
|
||||
};
|
||||
export type Database = {
|
||||
CONNECTION: DBConnection;
|
||||
ENABLED: boolean;
|
||||
SAVE_DATA: SaveData;
|
||||
};
|
||||
|
||||
export type Redis = {
|
||||
ENABLED: boolean;
|
||||
URI: string;
|
||||
PREFIX_KEY: string;
|
||||
};
|
||||
|
||||
export type EventsWebhook = {
|
||||
APPLICATION_STARTUP: boolean;
|
||||
QRCODE_UPDATED: boolean;
|
||||
MESSAGES_SET: boolean;
|
||||
MESSAGES_UPSERT: boolean;
|
||||
MESSAGES_UPDATE: boolean;
|
||||
SEND_MESSAGE: boolean;
|
||||
CONTACTS_SET: boolean;
|
||||
CONTACTS_UPDATE: boolean;
|
||||
CONTACTS_UPSERT: boolean;
|
||||
PRESENCE_UPDATE: boolean;
|
||||
CHATS_SET: boolean;
|
||||
CHATS_UPDATE: boolean;
|
||||
CHATS_DELETE: boolean;
|
||||
CHATS_UPSERT: boolean;
|
||||
CONNECTION_UPDATE: boolean;
|
||||
GROUPS_UPSERT: boolean;
|
||||
GROUP_UPDATE: boolean;
|
||||
GROUP_PARTICIPANTS_UPDATE: boolean;
|
||||
NEW_JWT_TOKEN: boolean;
|
||||
};
|
||||
|
||||
export type ApiKey = { KEY: string };
|
||||
export type Jwt = { EXPIRIN_IN: number; SECRET: string };
|
||||
export type Instance = {
|
||||
NAME: string;
|
||||
WEBHOOK_URL: string;
|
||||
MODE: string;
|
||||
WEBHOOK_BY_EVENTS: boolean;
|
||||
};
|
||||
export type Auth = {
|
||||
API_KEY: ApiKey;
|
||||
JWT: Jwt;
|
||||
TYPE: 'jwt' | 'apikey';
|
||||
INSTANCE: Instance;
|
||||
};
|
||||
|
||||
export type DelInstance = number | boolean;
|
||||
|
||||
export type GlobalWebhook = {
|
||||
URL: string;
|
||||
ENABLED: boolean;
|
||||
WEBHOOK_BY_EVENTS: boolean;
|
||||
};
|
||||
export type SslConf = { PRIVKEY: string; FULLCHAIN: string };
|
||||
export type Webhook = { GLOBAL?: GlobalWebhook; EVENTS: EventsWebhook };
|
||||
export type ConfigSessionPhone = { CLIENT: string; NAME: string };
|
||||
export type QrCode = { LIMIT: number };
|
||||
export type Production = boolean;
|
||||
|
||||
export interface Env {
|
||||
SERVER: HttpServer;
|
||||
CORS: Cors;
|
||||
SSL_CONF: SslConf;
|
||||
STORE: StoreConf;
|
||||
DATABASE: Database;
|
||||
REDIS: Redis;
|
||||
LOG: Log;
|
||||
DEL_INSTANCE: DelInstance;
|
||||
WEBHOOK: Webhook;
|
||||
CONFIG_SESSION_PHONE: ConfigSessionPhone;
|
||||
QRCODE: QrCode;
|
||||
AUTHENTICATION: Auth;
|
||||
PRODUCTION?: Production;
|
||||
}
|
||||
|
||||
export type Key = keyof Env;
|
||||
|
||||
export class ConfigService {
|
||||
constructor() {
|
||||
this.loadEnv();
|
||||
}
|
||||
|
||||
private env: Env;
|
||||
|
||||
public get<T = any>(key: Key) {
|
||||
return this.env[key] as T;
|
||||
}
|
||||
|
||||
private loadEnv() {
|
||||
this.env = !(process.env?.DOCKER_ENV === 'true') ? this.envYaml() : this.envProcess();
|
||||
this.env.PRODUCTION = process.env?.NODE_ENV === 'PROD';
|
||||
if (process.env?.DOCKER_ENV === 'true') {
|
||||
this.env.SERVER.TYPE = 'http';
|
||||
this.env.SERVER.PORT = Number.parseInt(process.env?.SERVER_PORT ?? '8080');
|
||||
}
|
||||
}
|
||||
|
||||
private envYaml(): Env {
|
||||
return load(readFileSync(join(SRC_DIR, 'env.yml'), { encoding: 'utf-8' })) as Env;
|
||||
}
|
||||
|
||||
private envProcess(): Env {
|
||||
return {
|
||||
SERVER: {
|
||||
TYPE: process.env.SERVER_TYPE as 'http' | 'https',
|
||||
PORT: Number.parseInt(process.env.SERVER_PORT),
|
||||
},
|
||||
CORS: {
|
||||
ORIGIN: process.env.CORS_ORIGIN.split(','),
|
||||
METHODS: process.env.CORS_METHODS.split(',') as HttpMethods[],
|
||||
CREDENTIALS: process.env?.CORS_CREDENTIALS === 'true',
|
||||
},
|
||||
SSL_CONF: {
|
||||
PRIVKEY: process.env?.SSL_CONF_PRIVKEY,
|
||||
FULLCHAIN: process.env?.SSL_CONF_FULLCHAIN,
|
||||
},
|
||||
STORE: {
|
||||
CLEANING_INTERVAL: Number.isInteger(process.env?.STORE_CLEANING_TERMINAL)
|
||||
? Number.parseInt(process.env.STORE_CLEANING_TERMINAL)
|
||||
: undefined,
|
||||
MESSAGES: process.env?.STORE_MESSAGE === 'true',
|
||||
CONTACTS: process.env?.STORE_CONTACTS === 'true',
|
||||
CHATS: process.env?.STORE_CHATS === 'true',
|
||||
},
|
||||
DATABASE: {
|
||||
CONNECTION: {
|
||||
URI: process.env.DATABASE_CONNECTION_URI,
|
||||
DB_PREFIX_NAME: process.env.DATABASE_CONNECTION_DB_PREFIX_NAME,
|
||||
},
|
||||
ENABLED: process.env?.DATABASE_ENABLED === 'true',
|
||||
SAVE_DATA: {
|
||||
INSTANCE: process.env?.DATABASE_SAVE_DATA_INSTANCE === 'true',
|
||||
OLD_MESSAGE: process.env?.DATABASE_SAVE_DATA_OLD_MESSAGE === 'true',
|
||||
NEW_MESSAGE: process.env?.DATABASE_SAVE_DATA_NEW_MESSAGE === 'true',
|
||||
MESSAGE_UPDATE: process.env?.DATABASE_SAVE_MESSAGE_UPDATE === 'true',
|
||||
CONTACTS: process.env?.DATABASE_SAVE_DATA_CONTACTS === 'true',
|
||||
CHATS: process.env?.DATABASE_SAVE_DATA_CHATS === 'true',
|
||||
},
|
||||
},
|
||||
REDIS: {
|
||||
ENABLED: process.env?.REDIS_ENABLED === 'true',
|
||||
URI: process.env.REDIS_URI,
|
||||
PREFIX_KEY: process.env.REDIS_PREFIX_KEY,
|
||||
},
|
||||
LOG: {
|
||||
LEVEL: process.env?.LOG_LEVEL.split(',') as LogLevel[],
|
||||
COLOR: process.env?.LOG_COLOR === 'true',
|
||||
},
|
||||
DEL_INSTANCE:
|
||||
typeof process.env?.DEL_INSTANCE === 'boolean'
|
||||
? process.env.DEL_INSTANCE === 'true'
|
||||
: Number.parseInt(process.env.DEL_INSTANCE),
|
||||
WEBHOOK: {
|
||||
GLOBAL: {
|
||||
URL: process.env?.WEBHOOK_GLOBAL_URL,
|
||||
ENABLED: process.env?.WEBHOOK_GLOBAL_ENABLED === 'true',
|
||||
WEBHOOK_BY_EVENTS: process.env?.WEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS === 'true',
|
||||
},
|
||||
EVENTS: {
|
||||
APPLICATION_STARTUP: process.env?.WEBHOOK_EVENTS_APPLICATION_STARTUP === 'true',
|
||||
QRCODE_UPDATED: process.env?.WEBHOOK_EVENTS_QRCODE_UPDATED === 'true',
|
||||
MESSAGES_SET: process.env?.WEBHOOK_EVENTS_MESSAGES_SET === 'true',
|
||||
MESSAGES_UPSERT: process.env?.WEBHOOK_EVENTS_MESSAGES_UPSERT === 'true',
|
||||
MESSAGES_UPDATE: process.env?.WEBHOOK_EVENTS_MESSAGES_UPDATE === 'true',
|
||||
SEND_MESSAGE: process.env?.WEBHOOK_EVENTS_SEND_MESSAGE === 'true',
|
||||
CONTACTS_SET: process.env?.WEBHOOK_EVENTS_CONTACTS_SET === 'true',
|
||||
CONTACTS_UPDATE: process.env?.WEBHOOK_EVENTS_CONTACTS_UPDATE === 'true',
|
||||
CONTACTS_UPSERT: process.env?.WEBHOOK_EVENTS_CONTACTS_UPSERT === 'true',
|
||||
PRESENCE_UPDATE: process.env?.WEBHOOK_EVENTS_PRESENCE_UPDATE === 'true',
|
||||
CHATS_SET: process.env?.WEBHOOK_EVENTS_CHATS_SET === 'true',
|
||||
CHATS_UPDATE: process.env?.WEBHOOK_EVENTS_CHATS_UPDATE === 'true',
|
||||
CHATS_UPSERT: process.env?.WEBHOOK_EVENTS_CHATS_UPSERT === 'true',
|
||||
CHATS_DELETE: process.env?.WEBHOOK_EVENTS_CHATS_DELETE === 'true',
|
||||
CONNECTION_UPDATE: process.env?.WEBHOOK_EVENTS_CONNECTION_UPDATE === 'true',
|
||||
GROUPS_UPSERT: process.env?.WEBHOOK_EVENTS_GROUPS_UPSERT === 'true',
|
||||
GROUP_UPDATE: process.env?.WEBHOOK_EVENTS_GROUPS_UPDATE === 'true',
|
||||
GROUP_PARTICIPANTS_UPDATE:
|
||||
process.env?.WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE === 'true',
|
||||
NEW_JWT_TOKEN: process.env?.WEBHOOK_EVENTS_NEW_JWT_TOKEN === 'true',
|
||||
},
|
||||
},
|
||||
CONFIG_SESSION_PHONE: {
|
||||
CLIENT: process.env?.CONFIG_SESSION_PHONE_CLIENT,
|
||||
NAME: process.env?.CONFIG_SESSION_PHONE_NAME,
|
||||
},
|
||||
QRCODE: {
|
||||
LIMIT: Number.parseInt(process.env.QRCODE_LIMIT),
|
||||
},
|
||||
AUTHENTICATION: {
|
||||
TYPE: process.env.AUTHENTICATION_TYPE as 'jwt',
|
||||
API_KEY: {
|
||||
KEY: process.env.AUTHENTICATION_API_KEY,
|
||||
},
|
||||
JWT: {
|
||||
EXPIRIN_IN: Number.isInteger(process.env?.AUTHENTICATION_JWT_EXPIRIN_IN)
|
||||
? Number.parseInt(process.env.AUTHENTICATION_JWT_EXPIRIN_IN)
|
||||
: 3600,
|
||||
SECRET: process.env.AUTHENTICATION_JWT_SECRET,
|
||||
},
|
||||
INSTANCE: {
|
||||
NAME: process.env.AUTHENTICATION_INSTANCE_NAME,
|
||||
WEBHOOK_URL: process.env.AUTHENTICATION_INSTANCE_WEBHOOK_URL,
|
||||
MODE: process.env.AUTHENTICATION_INSTANCE_MODE,
|
||||
WEBHOOK_BY_EVENTS:
|
||||
process.env.AUTHENTICATION_INSTANCE_WEBHOOK_BY_EVENTS === 'true',
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export const configService = new ConfigService();
|
21
src/config/error.config.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import { Logger } from './logger.config';
|
||||
|
||||
export function onUnexpectedError() {
|
||||
process.on('uncaughtException', (error, origin) => {
|
||||
const logger = new Logger('uncaughtException');
|
||||
logger.error({
|
||||
origin,
|
||||
stderr: process.stderr.fd,
|
||||
error,
|
||||
});
|
||||
});
|
||||
|
||||
process.on('unhandledRejection', (error, origin) => {
|
||||
const logger = new Logger('unhandledRejection');
|
||||
logger.error({
|
||||
origin,
|
||||
stderr: process.stderr.fd,
|
||||
error,
|
||||
});
|
||||
});
|
||||
}
|
7
src/config/event.config.ts
Normal file
@ -0,0 +1,7 @@
|
||||
import EventEmitter2 from 'eventemitter2';
|
||||
|
||||
export const eventEmitter = new EventEmitter2({
|
||||
delimiter: '.',
|
||||
newListener: false,
|
||||
ignoreErrors: false,
|
||||
});
|
137
src/config/logger.config.ts
Normal file
@ -0,0 +1,137 @@
|
||||
import { configService, Log } from './env.config';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
const formatDateLog = (timestamp: number) =>
|
||||
dayjs(timestamp)
|
||||
.toDate()
|
||||
.toString()
|
||||
.replace(/\sGMT.+/, '');
|
||||
|
||||
enum Color {
|
||||
LOG = '\x1b[32m',
|
||||
INFO = '\x1b[34m',
|
||||
WARN = '\x1b[33m',
|
||||
ERROR = '\x1b[31m',
|
||||
DEBUG = '\x1b[36m',
|
||||
VERBOSE = '\x1b[37m',
|
||||
DARK = '\x1b[30m',
|
||||
}
|
||||
|
||||
enum Command {
|
||||
RESET = '\x1b[0m',
|
||||
BRIGHT = '\x1b[1m',
|
||||
UNDERSCORE = '\x1b[4m',
|
||||
}
|
||||
|
||||
enum Level {
|
||||
LOG = Color.LOG + '%s' + Command.RESET,
|
||||
DARK = Color.DARK + '%s' + Command.RESET,
|
||||
INFO = Color.INFO + '%s' + Command.RESET,
|
||||
WARN = Color.WARN + '%s' + Command.RESET,
|
||||
ERROR = Color.ERROR + '%s' + Command.RESET,
|
||||
DEBUG = Color.DEBUG + '%s' + Command.RESET,
|
||||
VERBOSE = Color.VERBOSE + '%s' + Command.RESET,
|
||||
}
|
||||
|
||||
enum Type {
|
||||
LOG = 'LOG',
|
||||
WARN = 'WARN',
|
||||
INFO = 'INFO',
|
||||
DARK = 'DARK',
|
||||
ERROR = 'ERROR',
|
||||
DEBUG = 'DEBUG',
|
||||
VERBOSE = 'VERBOSE',
|
||||
}
|
||||
|
||||
enum Background {
|
||||
LOG = '\x1b[42m',
|
||||
INFO = '\x1b[44m',
|
||||
WARN = '\x1b[43m',
|
||||
DARK = '\x1b[40m',
|
||||
ERROR = '\x1b[41m',
|
||||
DEBUG = '\x1b[46m',
|
||||
VERBOSE = '\x1b[47m',
|
||||
}
|
||||
|
||||
export class Logger {
|
||||
private readonly configService = configService;
|
||||
constructor(private context = 'Logger') {}
|
||||
|
||||
public setContext(value: string) {
|
||||
this.context = value;
|
||||
}
|
||||
|
||||
private console(value: any, type: Type) {
|
||||
const types: Type[] = [];
|
||||
|
||||
this.configService.get<Log>('LOG').LEVEL.forEach((level) => types.push(Type[level]));
|
||||
|
||||
const typeValue = typeof value;
|
||||
|
||||
if (types.includes(type)) {
|
||||
if (configService.get<Log>('LOG').COLOR) {
|
||||
console.log(
|
||||
/*Command.UNDERSCORE +*/ Command.BRIGHT + Level[type],
|
||||
'[Evolution API]',
|
||||
Command.BRIGHT + Color[type],
|
||||
process.pid.toString(),
|
||||
Command.RESET,
|
||||
Command.BRIGHT + Color[type],
|
||||
'-',
|
||||
Command.BRIGHT + Color.VERBOSE,
|
||||
`${formatDateLog(Date.now())} `,
|
||||
Command.RESET,
|
||||
Color[type] + Background[type] + Command.BRIGHT,
|
||||
`${type} ` + Command.RESET,
|
||||
Color.WARN + Command.BRIGHT,
|
||||
`[${this.context}]` + Command.RESET,
|
||||
Color[type] + Command.BRIGHT,
|
||||
`[${typeValue}]` + Command.RESET,
|
||||
Color[type],
|
||||
typeValue !== 'object' ? value : '',
|
||||
Command.RESET,
|
||||
);
|
||||
typeValue === 'object' ? console.log(/*Level.DARK,*/ value, '\n') : '';
|
||||
} else {
|
||||
console.log(
|
||||
'[Evolution API]',
|
||||
process.pid.toString(),
|
||||
'-',
|
||||
`${formatDateLog(Date.now())} `,
|
||||
`${type} `,
|
||||
`[${this.context}]`,
|
||||
`[${typeValue}]`,
|
||||
value,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public log(value: any) {
|
||||
this.console(value, Type.LOG);
|
||||
}
|
||||
|
||||
public info(value: any) {
|
||||
this.console(value, Type.INFO);
|
||||
}
|
||||
|
||||
public warn(value: any) {
|
||||
this.console(value, Type.WARN);
|
||||
}
|
||||
|
||||
public error(value: any) {
|
||||
this.console(value, Type.ERROR);
|
||||
}
|
||||
|
||||
public verbose(value: any) {
|
||||
this.console(value, Type.VERBOSE);
|
||||
}
|
||||
|
||||
public debug(value: any) {
|
||||
this.console(value, Type.DEBUG);
|
||||
}
|
||||
|
||||
public dark(value: any) {
|
||||
this.console(value, Type.DARK);
|
||||
}
|
||||
}
|
6
src/config/path.config.ts
Normal file
@ -0,0 +1,6 @@
|
||||
import { join } from 'path';
|
||||
|
||||
export const ROOT_DIR = process.cwd();
|
||||
export const INSTANCE_DIR = join(ROOT_DIR, 'instances');
|
||||
export const SRC_DIR = join(ROOT_DIR, 'src');
|
||||
export const AUTH_DIR = join(ROOT_DIR, 'store', 'auth');
|
14
src/db/db.connect.ts
Normal file
@ -0,0 +1,14 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { configService, Database } from '../config/env.config';
|
||||
import { Logger } from '../config/logger.config';
|
||||
|
||||
const logger = new Logger('Db Connection');
|
||||
|
||||
export const db = configService.get<Database>('DATABASE');
|
||||
export const dbserver = db.ENABLED
|
||||
? mongoose.createConnection(db.CONNECTION.URI, {
|
||||
dbName: db.CONNECTION.DB_PREFIX_NAME + '-whatsapp-api',
|
||||
})
|
||||
: null;
|
||||
|
||||
db.ENABLED ? logger.info('ON - dbName: ' + dbserver['$dbName']) : null;
|
75
src/db/redis.client.ts
Normal file
@ -0,0 +1,75 @@
|
||||
import { createClient, RedisClientType } from '@redis/client';
|
||||
import { Logger } from '../config/logger.config';
|
||||
import { BufferJSON } from '@evolution/base';
|
||||
import { Redis } from '../config/env.config';
|
||||
|
||||
export class RedisCache {
|
||||
constructor(private readonly redisEnv: Partial<Redis>, private instanceName?: string) {
|
||||
this.client = createClient({ url: this.redisEnv.URI });
|
||||
|
||||
this.client.connect();
|
||||
}
|
||||
|
||||
public set reference(reference: string) {
|
||||
this.instanceName = reference;
|
||||
}
|
||||
|
||||
private readonly logger = new Logger(RedisCache.name);
|
||||
private client: RedisClientType;
|
||||
|
||||
public async instanceKeys(): Promise<string[]> {
|
||||
try {
|
||||
return await this.client.sendCommand(['keys', this.redisEnv.PREFIX_KEY + ':*']);
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
public async writeData(field: string, data: any) {
|
||||
try {
|
||||
const json = JSON.stringify(data, BufferJSON.replacer);
|
||||
return await this.client.hSet(
|
||||
this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
|
||||
field,
|
||||
json,
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
public async readData(field: string) {
|
||||
try {
|
||||
const data = await this.client.hGet(
|
||||
this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
|
||||
field,
|
||||
);
|
||||
if (data) {
|
||||
return JSON.parse(data, BufferJSON.reviver);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
public async removeData(field: string) {
|
||||
try {
|
||||
return await this.client.hDel(
|
||||
this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
|
||||
field,
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
public async delAll(hash?: string) {
|
||||
try {
|
||||
return await this.client.del(
|
||||
hash || this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
}
|
||||
}
|
||||
}
|
132
src/dev-env.yml
Normal file
@ -0,0 +1,132 @@
|
||||
# ⚠️
|
||||
# ⚠️ ALL SETTINGS DEFINED IN THIS FILE ARE APPLIED TO ALL INSTANCES.
|
||||
# ⚠️
|
||||
|
||||
# ⚠️ RENAME THIS FILE TO env.yml
|
||||
|
||||
# Choose the server type for the application
|
||||
SERVER:
|
||||
TYPE: http # https
|
||||
PORT: 8083 # 443
|
||||
|
||||
CORS:
|
||||
ORIGIN:
|
||||
- '*'
|
||||
# - yourdomain.com
|
||||
METHODS:
|
||||
- POST
|
||||
- GET
|
||||
- PUT
|
||||
- DELETE
|
||||
CREDENTIALS: true
|
||||
|
||||
# Install ssl certificate and replace string <domain> with domain name
|
||||
# Access: https://certbot.eff.org/instructions?ws=other&os=ubuntufocal
|
||||
SSL_CONF:
|
||||
PRIVKEY: /etc/letsencrypt/live/<domain>/privkey.pem
|
||||
FULLCHAIN: /etc/letsencrypt/live/<domain>/fullchain.pem
|
||||
|
||||
# Determine the logs to be displayed
|
||||
LOG:
|
||||
LEVEL:
|
||||
- ERROR
|
||||
- WARN
|
||||
- DEBUG
|
||||
- INFO
|
||||
- LOG
|
||||
- VERBOSE
|
||||
- DARK
|
||||
COLOR: true
|
||||
|
||||
# Determine how long the instance should be deleted from memory in case of no connection.
|
||||
# Default time: 5 minutes
|
||||
# If you don't even want an expiration, enter the value false
|
||||
DEL_INSTANCE: false # or false
|
||||
|
||||
# Temporary data storage
|
||||
STORE:
|
||||
CLEANING_INTERVAL: 7200 # seconds === 2h
|
||||
MESSAGE: true
|
||||
CONTACTS: true
|
||||
CHATS: true
|
||||
|
||||
# Permanent data storage
|
||||
DATABASE:
|
||||
ENABLED: true
|
||||
CONNECTION:
|
||||
URI: 'mongodb://root:root@localhost:27017/?authSource=admin&readPreference=primary&ssl=false&directConnection=true'
|
||||
DB_PREFIX_NAME: evolution
|
||||
# Choose the data you want to save in the application's database or store
|
||||
SAVE_DATA:
|
||||
INSTANCE: true
|
||||
OLD_MESSAGE: false
|
||||
NEW_MESSAGE: true
|
||||
MESSAGE_UPDATE: true
|
||||
CONTACTS: true
|
||||
CHATS: true
|
||||
|
||||
REDIS:
|
||||
ENABLED: true
|
||||
URI: 'redis://localhost:6379/1'
|
||||
PREFIX_KEY: 'evolution'
|
||||
|
||||
# Webhook Settings
|
||||
WEBHOOK:
|
||||
# Define a global webhook that will listen for enabled events from all instances
|
||||
GLOBAL:
|
||||
URL: <url>
|
||||
ENABLED: true
|
||||
# With this option activated, you work with a url per webhook event, respecting the global url and the name of each event
|
||||
WEBHOOK_BY_EVENTS: true
|
||||
# Automatically maps webhook paths
|
||||
# Set the events you want to hear
|
||||
EVENTS:
|
||||
APPLICATION_STARTUP: true
|
||||
QRCODE_UPDATED: true
|
||||
MESSAGES_SET: true
|
||||
MESSAGES_UPSERT: true
|
||||
MESSAGES_UPDATE: true
|
||||
SEND_MESSAGE: true
|
||||
CONTACTS_SET: true
|
||||
CONTACTS_UPSERT: true
|
||||
CONTACTS_UPDATE: true
|
||||
PRESENCE_UPDATE: true
|
||||
CHATS_SET: true
|
||||
CHATS_UPSERT: true
|
||||
CHATS_UPDATE: true
|
||||
CHATS_DELETE: true
|
||||
GROUPS_UPSERT: true
|
||||
GROUP_UPDATE: true
|
||||
GROUP_PARTICIPANTS_UPDATE: true
|
||||
CONNECTION_UPDATE: true
|
||||
# This event fires every time a new token is requested via the refresh route
|
||||
NEW_JWT_TOKEN: true
|
||||
|
||||
CONFIG_SESSION_PHONE:
|
||||
# Name that will be displayed on smartphone connection
|
||||
CLIENT: 'Evolution API'
|
||||
NAME: Chrome # firefox | edge | opera | safari
|
||||
|
||||
# Set qrcode display limit
|
||||
QRCODE:
|
||||
LIMIT: 30
|
||||
|
||||
# Defines an authentication type for the api
|
||||
AUTHENTICATION:
|
||||
TYPE: apikey # or jwt apikey
|
||||
# Define a global apikey to access all instances
|
||||
API_KEY:
|
||||
# OBS: This key must be inserted in the request header to create an instance.
|
||||
KEY: B6D711FC-DE4D-4FD5-9365-44120E713976
|
||||
# Set the secret key to encrypt and decrypt your token and its expiration time.
|
||||
JWT:
|
||||
EXPIRIN_IN: 0 # seconds - 3600s === 1h | zero (0) - never expires
|
||||
SECRET: L=0YWt]b2w[WF>#>:&E`
|
||||
# Set the instance name and webhook url to create an instance in init the application
|
||||
INSTANCE:
|
||||
# With this option activated, you work with a url per webhook event, respecting the local url and the name of each event
|
||||
WEBHOOK_BY_EVENTS: false
|
||||
MODE: server # container or server
|
||||
# if you are using container mode, set the container name and the webhook url to default instance
|
||||
NAME: evolution
|
||||
WEBHOOK_URL: <url>
|
11
src/exceptions/400.exception.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { HttpStatus } from '../whatsapp/routers/index.router';
|
||||
|
||||
export class BadRequestException {
|
||||
constructor(...objectError: any[]) {
|
||||
throw {
|
||||
status: HttpStatus.BAD_REQUEST,
|
||||
error: 'Bad Request',
|
||||
message: objectError.length > 0 ? objectError : undefined,
|
||||
};
|
||||
}
|
||||
}
|
11
src/exceptions/401.exception.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { HttpStatus } from '../whatsapp/routers/index.router';
|
||||
|
||||
export class UnauthorizedException {
|
||||
constructor(...objectError: any[]) {
|
||||
throw {
|
||||
status: HttpStatus.UNAUTHORIZED,
|
||||
error: 'Unauthorized',
|
||||
message: objectError.length > 0 ? objectError : undefined,
|
||||
};
|
||||
}
|
||||
}
|
11
src/exceptions/403.exception.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { HttpStatus } from '../whatsapp/routers/index.router';
|
||||
|
||||
export class ForbiddenException {
|
||||
constructor(...objectError: any[]) {
|
||||
throw {
|
||||
status: HttpStatus.FORBIDDEN,
|
||||
error: 'Forbidden',
|
||||
message: objectError.length > 0 ? objectError : undefined,
|
||||
};
|
||||
}
|
||||
}
|
11
src/exceptions/404.exception.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { HttpStatus } from '../whatsapp/routers/index.router';
|
||||
|
||||
export class NotFoundException {
|
||||
constructor(...objectError: any[]) {
|
||||
throw {
|
||||
status: HttpStatus.NOT_FOUND,
|
||||
error: 'Not Found',
|
||||
message: objectError.length > 0 ? objectError : undefined,
|
||||
};
|
||||
}
|
||||
}
|
11
src/exceptions/500.exception.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import { HttpStatus } from '../whatsapp/routers/index.router';
|
||||
|
||||
export class InternalServerErrorException {
|
||||
constructor(...objectError: any[]) {
|
||||
throw {
|
||||
status: HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
error: 'Internal Server Error',
|
||||
message: objectError.length > 0 ? objectError : undefined,
|
||||
};
|
||||
}
|
||||
}
|
5
src/exceptions/index.ts
Normal file
@ -0,0 +1,5 @@
|
||||
export * from './400.exception';
|
||||
export * from './401.exception';
|
||||
export * from './403.exception';
|
||||
export * from './404.exception';
|
||||
export * from './500.exception';
|
79
src/main.ts
Normal file
@ -0,0 +1,79 @@
|
||||
import compression from 'compression';
|
||||
import { configService, Cors, HttpServer } from './config/env.config';
|
||||
import cors from 'cors';
|
||||
import express, { json, NextFunction, Request, Response, urlencoded } from 'express';
|
||||
import { join } from 'path';
|
||||
import { onUnexpectedError } from './config/error.config';
|
||||
import { Logger } from './config/logger.config';
|
||||
import { ROOT_DIR } from './config/path.config';
|
||||
import { waMonitor } from './whatsapp/whatsapp.module';
|
||||
import { HttpStatus, router } from './whatsapp/routers/index.router';
|
||||
import 'express-async-errors';
|
||||
import { ServerUP } from './utils/server-up';
|
||||
|
||||
function initWA() {
|
||||
waMonitor.loadInstance();
|
||||
}
|
||||
|
||||
function bootstrap() {
|
||||
initWA();
|
||||
|
||||
const logger = new Logger('SERVER');
|
||||
const app = express();
|
||||
|
||||
app.use(
|
||||
cors({
|
||||
origin(requestOrigin, callback) {
|
||||
const { ORIGIN } = configService.get<Cors>('CORS');
|
||||
!requestOrigin ? (requestOrigin = '*') : undefined;
|
||||
if (ORIGIN.indexOf(requestOrigin) !== -1) {
|
||||
return callback(null, true);
|
||||
}
|
||||
return callback(new Error('Not allowed by CORS'));
|
||||
},
|
||||
methods: [...configService.get<Cors>('CORS').METHODS],
|
||||
credentials: configService.get<Cors>('CORS').CREDENTIALS,
|
||||
}),
|
||||
urlencoded({ extended: true, limit: '50mb' }),
|
||||
json({ limit: '50mb' }),
|
||||
compression(),
|
||||
);
|
||||
|
||||
app.set('view engine', 'hbs');
|
||||
app.set('views', join(ROOT_DIR, 'views'));
|
||||
app.use(express.static(join(ROOT_DIR, 'public')));
|
||||
|
||||
app.use('/', router);
|
||||
|
||||
app.use(
|
||||
(err: Error, req: Request, res: Response, next: NextFunction) => {
|
||||
if (err) {
|
||||
return res.status(err['status'] || 500).json(err);
|
||||
}
|
||||
},
|
||||
(req: Request, res: Response, next: NextFunction) => {
|
||||
const { method, url } = req;
|
||||
|
||||
res.status(HttpStatus.NOT_FOUND).json({
|
||||
status: HttpStatus.NOT_FOUND,
|
||||
message: `Cannot ${method.toUpperCase()} ${url}`,
|
||||
error: 'Not Found',
|
||||
});
|
||||
|
||||
next();
|
||||
},
|
||||
);
|
||||
|
||||
const httpServer = configService.get<HttpServer>('SERVER');
|
||||
|
||||
ServerUP.app = app;
|
||||
const server = ServerUP[httpServer.TYPE];
|
||||
|
||||
server.listen(httpServer.PORT, () =>
|
||||
logger.log(httpServer.TYPE.toUpperCase() + ' - ON: ' + httpServer.PORT),
|
||||
);
|
||||
|
||||
onUnexpectedError();
|
||||
}
|
||||
|
||||
bootstrap();
|
28
src/utils/server-up.ts
Normal file
@ -0,0 +1,28 @@
|
||||
import { Express } from 'express';
|
||||
import { readFileSync } from 'fs';
|
||||
import { configService, SslConf } from '../config/env.config';
|
||||
import * as https from 'https';
|
||||
import * as http from 'http';
|
||||
|
||||
export class ServerUP {
|
||||
static #app: Express;
|
||||
|
||||
static set app(e: Express) {
|
||||
this.#app = e;
|
||||
}
|
||||
|
||||
static get https() {
|
||||
const { FULLCHAIN, PRIVKEY } = configService.get<SslConf>('SSL_CONF');
|
||||
return https.createServer(
|
||||
{
|
||||
cert: readFileSync(FULLCHAIN),
|
||||
key: readFileSync(PRIVKEY),
|
||||
},
|
||||
ServerUP.#app,
|
||||
);
|
||||
}
|
||||
|
||||
static get http() {
|
||||
return http.createServer(ServerUP.#app);
|
||||
}
|
||||
}
|
92
src/utils/use-multi-file-auth-state-db.ts
Normal file
@ -0,0 +1,92 @@
|
||||
import {
|
||||
AuthenticationCreds,
|
||||
AuthenticationState,
|
||||
BufferJSON,
|
||||
initAuthCreds,
|
||||
proto,
|
||||
SignalDataTypeMap,
|
||||
} from '@evolution/base';
|
||||
import { configService, Database } from '../config/env.config';
|
||||
import { Logger } from '../config/logger.config';
|
||||
import { dbserver } from '../db/db.connect';
|
||||
|
||||
export async function useMultiFileAuthStateDb(
|
||||
coll: string,
|
||||
): Promise<{ state: AuthenticationState; saveCreds: () => Promise<void> }> {
|
||||
const logger = new Logger(useMultiFileAuthStateDb.name);
|
||||
|
||||
const client = dbserver.getClient();
|
||||
|
||||
const collection = client
|
||||
.db(configService.get<Database>('DATABASE').CONNECTION.DB_PREFIX_NAME + '-instances')
|
||||
.collection(coll);
|
||||
|
||||
const writeData = async (data: any, key: string): Promise<any> => {
|
||||
try {
|
||||
await client.connect();
|
||||
return await collection.replaceOne(
|
||||
{ _id: key },
|
||||
JSON.parse(JSON.stringify(data, BufferJSON.replacer)),
|
||||
{ upsert: true },
|
||||
);
|
||||
} catch {}
|
||||
};
|
||||
|
||||
const readData = async (key: string): Promise<any> => {
|
||||
try {
|
||||
await client.connect();
|
||||
const data = await collection.findOne({ _id: key });
|
||||
const creds = JSON.stringify(data);
|
||||
return JSON.parse(creds, BufferJSON.reviver);
|
||||
} catch {}
|
||||
};
|
||||
|
||||
const removeData = async (key: string) => {
|
||||
try {
|
||||
await client.connect();
|
||||
return await collection.deleteOne({ _id: key });
|
||||
} catch {}
|
||||
};
|
||||
|
||||
const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds();
|
||||
|
||||
return {
|
||||
state: {
|
||||
creds,
|
||||
keys: {
|
||||
get: async (type, ids: string[]) => {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
const data: { [_: string]: SignalDataTypeMap[type] } = {};
|
||||
await Promise.all(
|
||||
ids.map(async (id) => {
|
||||
let value = await readData(`${type}-${id}`);
|
||||
if (type === 'app-state-sync-key' && value) {
|
||||
value = proto.Message.AppStateSyncKeyData.fromObject(value);
|
||||
}
|
||||
|
||||
data[id] = value;
|
||||
}),
|
||||
);
|
||||
|
||||
return data;
|
||||
},
|
||||
set: async (data: any) => {
|
||||
const tasks: Promise<void>[] = [];
|
||||
for (const category in data) {
|
||||
for (const id in data[category]) {
|
||||
const value = data[category][id];
|
||||
const key = `${category}-${id}`;
|
||||
tasks.push(value ? writeData(value, key) : removeData(key));
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(tasks);
|
||||
},
|
||||
},
|
||||
},
|
||||
saveCreds: async () => {
|
||||
return writeData(creds, 'creds');
|
||||
},
|
||||
};
|
||||
}
|
89
src/utils/use-multi-file-auth-state-redis-db.ts
Normal file
@ -0,0 +1,89 @@
|
||||
import {
|
||||
AuthenticationCreds,
|
||||
AuthenticationState,
|
||||
initAuthCreds,
|
||||
proto,
|
||||
SignalDataTypeMap,
|
||||
} from '@evolution/base';
|
||||
import { RedisCache } from '../db/redis.client';
|
||||
import { Logger } from '../config/logger.config';
|
||||
import { Redis } from '../config/env.config';
|
||||
|
||||
export async function useMultiFileAuthStateRedisDb(
|
||||
redisEnv: Partial<Redis>,
|
||||
instanceName: string,
|
||||
): Promise<{
|
||||
state: AuthenticationState;
|
||||
saveCreds: () => Promise<void>;
|
||||
}> {
|
||||
const logger = new Logger(useMultiFileAuthStateRedisDb.name);
|
||||
|
||||
const cache = new RedisCache(redisEnv, instanceName);
|
||||
|
||||
const writeData = async (data: any, key: string): Promise<any> => {
|
||||
try {
|
||||
return await cache.writeData(key, data);
|
||||
} catch (error) {
|
||||
return logger.error({ localError: 'writeData', error });
|
||||
}
|
||||
};
|
||||
|
||||
const readData = async (key: string): Promise<any> => {
|
||||
try {
|
||||
return await cache.readData(key);
|
||||
} catch (error) {
|
||||
logger.error({ readData: 'writeData', error });
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
const removeData = async (key: string) => {
|
||||
try {
|
||||
return await cache.removeData(key);
|
||||
} catch (error) {
|
||||
logger.error({ readData: 'removeData', error });
|
||||
}
|
||||
};
|
||||
|
||||
const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds();
|
||||
|
||||
return {
|
||||
state: {
|
||||
creds,
|
||||
keys: {
|
||||
get: async (type, ids: string[]) => {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
const data: { [_: string]: SignalDataTypeMap[type] } = {};
|
||||
await Promise.all(
|
||||
ids.map(async (id) => {
|
||||
let value = await readData(`${type}-${id}`);
|
||||
if (type === 'app-state-sync-key' && value) {
|
||||
value = proto.Message.AppStateSyncKeyData.fromObject(value);
|
||||
}
|
||||
|
||||
data[id] = value;
|
||||
}),
|
||||
);
|
||||
|
||||
return data;
|
||||
},
|
||||
set: async (data: any) => {
|
||||
const tasks: Promise<void>[] = [];
|
||||
for (const category in data) {
|
||||
for (const id in data[category]) {
|
||||
const value = data[category][id];
|
||||
const key = `${category}-${id}`;
|
||||
tasks.push(value ? await writeData(value, key) : await removeData(key));
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(tasks);
|
||||
},
|
||||
},
|
||||
},
|
||||
saveCreds: async () => {
|
||||
return await writeData(creds, 'creds');
|
||||
},
|
||||
};
|
||||
}
|
674
src/validate/validate.schema.ts
Normal file
@ -0,0 +1,674 @@
|
||||
import { JSONSchema7, JSONSchema7Definition } from 'json-schema';
|
||||
import { v4 } from 'uuid';
|
||||
|
||||
const isNotEmpty = (...propertyNames: string[]): JSONSchema7 => {
|
||||
const properties = {};
|
||||
propertyNames.forEach(
|
||||
(property) =>
|
||||
(properties[property] = {
|
||||
minLength: 1,
|
||||
description: `The "${property}" cannot be empty`,
|
||||
}),
|
||||
);
|
||||
return {
|
||||
if: {
|
||||
propertyNames: {
|
||||
enum: [...propertyNames],
|
||||
},
|
||||
},
|
||||
then: { properties },
|
||||
};
|
||||
};
|
||||
|
||||
// Instance Schema
|
||||
export const instanceNameSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
instanceName: { type: 'string' },
|
||||
webhook: { type: 'string' },
|
||||
},
|
||||
...isNotEmpty('instanceName'),
|
||||
};
|
||||
|
||||
export const oldTokenSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
oldToken: { type: 'string' },
|
||||
},
|
||||
required: ['oldToken'],
|
||||
...isNotEmpty('oldToken'),
|
||||
};
|
||||
|
||||
const quotedOptionsSchema: JSONSchema7 = {
|
||||
properties: {
|
||||
key: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
remoteJid: { type: 'string' },
|
||||
fromMe: { type: 'boolean', enum: [true, false] },
|
||||
},
|
||||
required: ['id', 'remoteJid', 'fromMe'],
|
||||
...isNotEmpty('id', 'remoteJid'),
|
||||
},
|
||||
message: { type: 'object' },
|
||||
},
|
||||
};
|
||||
|
||||
const mentionsOptionsSchema: JSONSchema7 = {
|
||||
properties: {
|
||||
everyOne: { type: 'boolean', enum: [true, false] },
|
||||
mentioned: {
|
||||
type: 'array',
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
items: {
|
||||
type: 'string',
|
||||
pattern: '^\\d+',
|
||||
description: '"mentioned" must be an array of numeric strings',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// Send Message Schema
|
||||
const optionsSchema: JSONSchema7 = {
|
||||
properties: {
|
||||
delay: {
|
||||
type: 'integer',
|
||||
description: 'Enter a value in milliseconds',
|
||||
},
|
||||
presence: {
|
||||
type: 'string',
|
||||
enum: ['unavailable', 'available', 'composing', 'recording', 'paused'],
|
||||
},
|
||||
quoted: { ...quotedOptionsSchema },
|
||||
mentions: { ...mentionsOptionsSchema },
|
||||
},
|
||||
};
|
||||
|
||||
const numberDefinition: JSONSchema7Definition = {
|
||||
type: 'string',
|
||||
pattern: '^\\d+[\\.@\\w-]+',
|
||||
description: 'Invalid format',
|
||||
};
|
||||
|
||||
export const textMessageSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
number: { ...numberDefinition },
|
||||
options: { ...optionsSchema },
|
||||
textMessage: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
text: { type: 'string' },
|
||||
},
|
||||
required: ['text'],
|
||||
...isNotEmpty('text'),
|
||||
},
|
||||
},
|
||||
required: ['textMessage', 'number'],
|
||||
};
|
||||
|
||||
export const linkPreviewSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
number: { ...numberDefinition },
|
||||
options: { ...optionsSchema },
|
||||
linkPreview: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
text: { type: 'string' },
|
||||
},
|
||||
required: ['text'],
|
||||
...isNotEmpty('text'),
|
||||
},
|
||||
},
|
||||
required: ['linkPreview', 'number'],
|
||||
};
|
||||
|
||||
export const pollMessageSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
number: { ...numberDefinition },
|
||||
options: { ...optionsSchema },
|
||||
pollMessage: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string' },
|
||||
selectableCount: { type: 'integer', minimum: 0, maximum: 10 },
|
||||
values: {
|
||||
type: 'array',
|
||||
minItems: 2,
|
||||
maxItems: 10,
|
||||
uniqueItems: true,
|
||||
items: {
|
||||
type: 'string',
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ['name', 'selectableCount', 'values'],
|
||||
...isNotEmpty('name', 'selectableCount', 'values'),
|
||||
},
|
||||
},
|
||||
required: ['pollMessage', 'number'],
|
||||
};
|
||||
|
||||
export const mediaMessageSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
number: { ...numberDefinition },
|
||||
options: { ...optionsSchema },
|
||||
mediaMessage: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
mediatype: { type: 'string', enum: ['image', 'document', 'video', 'audio'] },
|
||||
media: { type: 'string' },
|
||||
fileName: { type: 'string' },
|
||||
caption: { type: 'string' },
|
||||
},
|
||||
required: ['mediatype', 'media'],
|
||||
...isNotEmpty('fileName', 'caption', 'media'),
|
||||
},
|
||||
},
|
||||
required: ['mediaMessage', 'number'],
|
||||
};
|
||||
|
||||
export const audioMessageSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
number: { ...numberDefinition },
|
||||
options: { ...optionsSchema },
|
||||
audioMessage: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
audio: { type: 'string' },
|
||||
},
|
||||
required: ['audio'],
|
||||
...isNotEmpty('audio'),
|
||||
},
|
||||
},
|
||||
required: ['audioMessage', 'number'],
|
||||
};
|
||||
|
||||
export const buttonMessageSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
number: { ...numberDefinition },
|
||||
options: { ...optionsSchema },
|
||||
buttonMessage: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string' },
|
||||
description: { type: 'string' },
|
||||
footerText: { type: 'string' },
|
||||
buttons: {
|
||||
type: 'array',
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
buttonText: { type: 'string' },
|
||||
buttonId: { type: 'string' },
|
||||
},
|
||||
required: ['buttonText', 'buttonId'],
|
||||
...isNotEmpty('buttonText', 'buttonId'),
|
||||
},
|
||||
},
|
||||
mediaMessage: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
media: { type: 'string' },
|
||||
fileName: { type: 'string' },
|
||||
mediatype: { type: 'string', enum: ['image', 'document', 'video'] },
|
||||
},
|
||||
required: ['media', 'mediatype'],
|
||||
...isNotEmpty('media', 'fileName'),
|
||||
},
|
||||
},
|
||||
required: ['title', 'buttons'],
|
||||
...isNotEmpty('title', 'description'),
|
||||
},
|
||||
},
|
||||
required: ['number', 'buttonMessage'],
|
||||
};
|
||||
|
||||
export const locationMessageSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
number: { ...numberDefinition },
|
||||
options: { ...optionsSchema },
|
||||
locationMessage: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
latitude: { type: 'number' },
|
||||
longitude: { type: 'number' },
|
||||
name: { type: 'string' },
|
||||
address: { type: 'string' },
|
||||
},
|
||||
required: ['latitude', 'longitude'],
|
||||
...isNotEmpty('name', 'addresss'),
|
||||
},
|
||||
},
|
||||
required: ['number', 'locationMessage'],
|
||||
};
|
||||
|
||||
export const listMessageSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
number: { ...numberDefinition },
|
||||
options: { ...optionsSchema },
|
||||
listMessage: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string' },
|
||||
description: { type: 'string' },
|
||||
footerText: { type: 'string' },
|
||||
buttonText: { type: 'string' },
|
||||
sections: {
|
||||
type: 'array',
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string' },
|
||||
rows: {
|
||||
type: 'array',
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
title: { type: 'string' },
|
||||
description: { type: 'string' },
|
||||
rowId: { type: 'string' },
|
||||
},
|
||||
required: ['title', 'description', 'rowId'],
|
||||
...isNotEmpty('title', 'description', 'rowId'),
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ['title', 'rows'],
|
||||
...isNotEmpty('title'),
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ['title', 'description', 'buttonText', 'sections'],
|
||||
...isNotEmpty('title', 'description', 'buttonText', 'footerText'),
|
||||
},
|
||||
},
|
||||
required: ['number', 'listMessage'],
|
||||
};
|
||||
|
||||
export const contactMessageSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
number: { ...numberDefinition },
|
||||
options: { ...optionsSchema },
|
||||
contactMessage: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
fullName: { type: 'string' },
|
||||
wuid: {
|
||||
type: 'string',
|
||||
minLength: 10,
|
||||
pattern: '\\d+',
|
||||
description: '"wuid" must be a numeric string',
|
||||
},
|
||||
phoneNumber: { type: 'string', minLength: 10 },
|
||||
},
|
||||
required: ['fullName', 'wuid', 'phoneNumber'],
|
||||
...isNotEmpty('fullName'),
|
||||
},
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
},
|
||||
},
|
||||
required: ['number', 'contactMessage'],
|
||||
};
|
||||
|
||||
export const reactionMessageSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
reactionMessage: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
key: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
remoteJid: { type: 'string' },
|
||||
fromMe: { type: 'boolean', enum: [true, false] },
|
||||
},
|
||||
required: ['id', 'remoteJid', 'fromMe'],
|
||||
...isNotEmpty('id', 'remoteJid'),
|
||||
},
|
||||
reaction: { type: 'string' },
|
||||
},
|
||||
required: ['key', 'reaction'],
|
||||
...isNotEmpty('reaction'),
|
||||
},
|
||||
},
|
||||
required: ['reactionMessage'],
|
||||
};
|
||||
|
||||
// Chat Schema
|
||||
export const whatsappNumberSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
numbers: {
|
||||
type: 'array',
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
items: {
|
||||
type: 'string',
|
||||
pattern: '^\\d+',
|
||||
description: '"numbers" must be an array of numeric strings',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const readMessageSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
readMessages: {
|
||||
type: 'array',
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
items: {
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
fromMe: { type: 'boolean', enum: [true, false] },
|
||||
remoteJid: { type: 'string' },
|
||||
},
|
||||
required: ['id', 'fromMe', 'remoteJid'],
|
||||
...isNotEmpty('id', 'remoteJid'),
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ['readMessages'],
|
||||
};
|
||||
|
||||
export const archiveChatSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
lastMessage: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
key: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
remoteJid: { type: 'string' },
|
||||
fromMe: { type: 'boolean', enum: [true, false] },
|
||||
},
|
||||
required: ['id', 'fromMe', 'remoteJid'],
|
||||
...isNotEmpty('id', 'remoteJid'),
|
||||
},
|
||||
messageTimestamp: { type: 'integer', minLength: 1 },
|
||||
},
|
||||
required: ['key'],
|
||||
...isNotEmpty('messageTimestamp'),
|
||||
},
|
||||
archive: { type: 'boolean', enum: [true, false] },
|
||||
},
|
||||
required: ['lastMessage', 'archive'],
|
||||
};
|
||||
|
||||
export const deleteMessageSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
id: { type: 'string' },
|
||||
fromMe: { type: 'boolean', enum: [true, false] },
|
||||
remoteJid: { type: 'string' },
|
||||
participant: { type: 'string' },
|
||||
},
|
||||
required: ['id', 'fromMe', 'remoteJid'],
|
||||
...isNotEmpty('id', 'remoteJid', 'participant'),
|
||||
};
|
||||
|
||||
export const contactValidateSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
where: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
_id: { type: 'string', minLength: 1 },
|
||||
pushName: { type: 'string', minLength: 1 },
|
||||
id: { type: 'string', minLength: 1 },
|
||||
},
|
||||
...isNotEmpty('_id', 'id', 'pushName'),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const profileNameSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string' },
|
||||
},
|
||||
...isNotEmpty('name'),
|
||||
};
|
||||
|
||||
export const profileStatusSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
status: { type: 'string' },
|
||||
},
|
||||
...isNotEmpty('status'),
|
||||
};
|
||||
|
||||
export const profilePictureSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
number: { type: 'string' },
|
||||
picture: { type: 'string' },
|
||||
},
|
||||
};
|
||||
|
||||
export const messageValidateSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
where: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
_id: { type: 'string', minLength: 1 },
|
||||
key: {
|
||||
type: 'object',
|
||||
if: {
|
||||
propertyNames: {
|
||||
enum: ['fromMe', 'remoteJid', 'id'],
|
||||
},
|
||||
},
|
||||
then: {
|
||||
properties: {
|
||||
remoteJid: {
|
||||
type: 'string',
|
||||
minLength: 1,
|
||||
description: 'The property cannot be empty',
|
||||
},
|
||||
id: {
|
||||
type: 'string',
|
||||
minLength: 1,
|
||||
description: 'The property cannot be empty',
|
||||
},
|
||||
fromMe: { type: 'boolean', enum: [true, false] },
|
||||
},
|
||||
},
|
||||
},
|
||||
message: { type: 'object' },
|
||||
},
|
||||
...isNotEmpty('_id'),
|
||||
},
|
||||
limit: { type: 'integer' },
|
||||
},
|
||||
};
|
||||
|
||||
export const messageUpSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
where: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
_id: { type: 'string' },
|
||||
remoteJid: { type: 'string' },
|
||||
id: { type: 'string' },
|
||||
fromMe: { type: 'boolean', enum: [true, false] },
|
||||
participant: { type: 'string' },
|
||||
status: {
|
||||
type: 'string',
|
||||
enum: ['ERROR', 'PENDING', 'SERVER_ACK', 'DELIVERY_ACK', 'READ', 'PLAYED'],
|
||||
},
|
||||
},
|
||||
...isNotEmpty('_id', 'remoteJid', 'id', 'status'),
|
||||
},
|
||||
limit: { type: 'integer' },
|
||||
},
|
||||
};
|
||||
|
||||
// Group Schema
|
||||
export const createGroupSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
subject: { type: 'string' },
|
||||
description: { type: 'string' },
|
||||
profilePicture: { type: 'string' },
|
||||
participants: {
|
||||
type: 'array',
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
items: {
|
||||
type: 'string',
|
||||
minLength: 10,
|
||||
pattern: '\\d+',
|
||||
description: '"participants" must be an array of numeric strings',
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ['subject', 'participants'],
|
||||
...isNotEmpty('subject', 'description', 'profilePicture'),
|
||||
};
|
||||
|
||||
export const groupJidSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
groupJid: { type: 'string', pattern: '^[\\d-]+@g.us$' },
|
||||
},
|
||||
required: ['groupJid'],
|
||||
...isNotEmpty('groupJid'),
|
||||
};
|
||||
|
||||
export const groupInviteSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
inviteCode: { type: 'string', pattern: '^[a-zA-Z0-9]{22}$' },
|
||||
},
|
||||
required: ['inviteCode'],
|
||||
...isNotEmpty('inviteCode'),
|
||||
};
|
||||
|
||||
export const updateParticipantsSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
groupJid: { type: 'string' },
|
||||
action: {
|
||||
type: 'string',
|
||||
enum: ['add', 'remove', 'promote', 'demote'],
|
||||
},
|
||||
participants: {
|
||||
type: 'array',
|
||||
minItems: 1,
|
||||
uniqueItems: true,
|
||||
items: {
|
||||
type: 'string',
|
||||
minLength: 10,
|
||||
pattern: '\\d+',
|
||||
description: '"participants" must be an array of numeric strings',
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ['groupJid', 'action', 'participants'],
|
||||
...isNotEmpty('groupJid', 'action'),
|
||||
};
|
||||
|
||||
export const updateSettingsSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
groupJid: { type: 'string' },
|
||||
action: {
|
||||
type: 'string',
|
||||
enum: ['announcement', 'not_announcement', 'locked', 'unlocked'],
|
||||
},
|
||||
},
|
||||
required: ['groupJid', 'action'],
|
||||
...isNotEmpty('groupJid', 'action'),
|
||||
};
|
||||
|
||||
export const toggleEphemeralSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
groupJid: { type: 'string' },
|
||||
expiration: {
|
||||
type: 'number',
|
||||
enum: [0, 86400, 604800, 7776000],
|
||||
},
|
||||
},
|
||||
required: ['groupJid', 'expiration'],
|
||||
...isNotEmpty('groupJid', 'expiration'),
|
||||
};
|
||||
|
||||
export const updateGroupPicture: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
groupJid: { type: 'string' },
|
||||
image: { type: 'string' },
|
||||
},
|
||||
required: ['groupJid', 'image'],
|
||||
...isNotEmpty('groupJid', 'image'),
|
||||
};
|
||||
|
||||
// Webhook Schema
|
||||
export const webhookSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
url: { type: 'string' },
|
||||
enabled: { type: 'boolean', enum: [true, false] },
|
||||
},
|
||||
required: ['url', 'enabled'],
|
||||
...isNotEmpty('url'),
|
||||
};
|
58
src/whatsapp/abstract/abstract.repository.ts
Normal file
@ -0,0 +1,58 @@
|
||||
import { existsSync, mkdirSync, writeFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { ConfigService, Database } from '../../config/env.config';
|
||||
import { ROOT_DIR } from '../../config/path.config';
|
||||
|
||||
export type IInsert = { insertCount: number };
|
||||
|
||||
export interface IRepository {
|
||||
insert(data: any, saveDb?: boolean): Promise<IInsert>;
|
||||
find(query: any): Promise<any>;
|
||||
delete(query: any, force?: boolean): Promise<any>;
|
||||
|
||||
dbSettings: Database;
|
||||
readonly storePath: string;
|
||||
}
|
||||
|
||||
type WriteStore<U> = {
|
||||
path: string;
|
||||
fileName: string;
|
||||
data: U;
|
||||
};
|
||||
|
||||
export abstract class Repository implements IRepository {
|
||||
constructor(configService: ConfigService) {
|
||||
this.dbSettings = configService.get<Database>('DATABASE');
|
||||
}
|
||||
|
||||
dbSettings: Database;
|
||||
readonly storePath = join(ROOT_DIR, 'store');
|
||||
|
||||
public writeStore = <T = any>(create: WriteStore<T>) => {
|
||||
if (!existsSync(create.path)) {
|
||||
mkdirSync(create.path, { recursive: true });
|
||||
}
|
||||
try {
|
||||
writeFileSync(
|
||||
join(create.path, create.fileName + '.json'),
|
||||
JSON.stringify({ ...create.data }),
|
||||
{ encoding: 'utf-8' },
|
||||
);
|
||||
|
||||
return { message: 'create - success' };
|
||||
} finally {
|
||||
create.data = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
public insert(data: any, saveDb = false): Promise<IInsert> {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
public find(query: any): Promise<any> {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
|
||||
delete(query: any, force?: boolean): Promise<any> {
|
||||
throw new Error('Method not implemented.');
|
||||
}
|
||||
}
|
153
src/whatsapp/abstract/abstract.router.ts
Normal file
@ -0,0 +1,153 @@
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
import { JSONSchema7 } from 'json-schema';
|
||||
import { Request } from 'express';
|
||||
import { validate } from 'jsonschema';
|
||||
import { BadRequestException } from '../../exceptions';
|
||||
import 'express-async-errors';
|
||||
import { Logger } from '../../config/logger.config';
|
||||
import { GroupInvite, GroupJid } from '../dto/group.dto';
|
||||
|
||||
type DataValidate<T> = {
|
||||
request: Request;
|
||||
schema: JSONSchema7;
|
||||
ClassRef: any;
|
||||
execute: (instance: InstanceDto, data: T) => Promise<any>;
|
||||
};
|
||||
|
||||
const logger = new Logger('Validate');
|
||||
|
||||
export abstract class RouterBroker {
|
||||
constructor() {}
|
||||
public routerPath(path: string, param = true) {
|
||||
// const route = param ? '/:instanceName/' + path : '/' + path;
|
||||
let route = '/' + path;
|
||||
param ? (route += '/:instanceName') : null;
|
||||
|
||||
return route;
|
||||
}
|
||||
|
||||
public async dataValidate<T>(args: DataValidate<T>) {
|
||||
const { request, schema, ClassRef, execute } = args;
|
||||
|
||||
const ref = new ClassRef();
|
||||
const body = request.body;
|
||||
const instance = request.params as unknown as InstanceDto;
|
||||
|
||||
if (request?.query && Object.keys(request.query).length > 0) {
|
||||
Object.assign(instance, request.query);
|
||||
}
|
||||
|
||||
if (request.originalUrl.includes('/instance/create')) {
|
||||
Object.assign(instance, body);
|
||||
}
|
||||
|
||||
Object.assign(ref, body);
|
||||
|
||||
const v = schema ? validate(ref, schema) : { valid: true, errors: [] };
|
||||
|
||||
if (!v.valid) {
|
||||
const message: any[] = v.errors.map(({ property, stack, schema }) => {
|
||||
let message: string;
|
||||
if (schema['description']) {
|
||||
message = schema['description'];
|
||||
} else {
|
||||
message = stack.replace('instance.', '');
|
||||
}
|
||||
return {
|
||||
property: property.replace('instance.', ''),
|
||||
message,
|
||||
};
|
||||
});
|
||||
logger.error([...message]);
|
||||
throw new BadRequestException(...message);
|
||||
}
|
||||
|
||||
return await execute(instance, ref);
|
||||
}
|
||||
|
||||
public async groupValidate<T>(args: DataValidate<T>) {
|
||||
const { request, ClassRef, schema, execute } = args;
|
||||
|
||||
const groupJid = request.query as unknown as GroupJid;
|
||||
|
||||
if (!groupJid?.groupJid) {
|
||||
throw new BadRequestException(
|
||||
'The group id needs to be informed in the query',
|
||||
'ex: "groupJid=120362@g.us"',
|
||||
);
|
||||
}
|
||||
|
||||
const instance = request.params as unknown as InstanceDto;
|
||||
const body = request.body;
|
||||
|
||||
const ref = new ClassRef();
|
||||
|
||||
Object.assign(body, groupJid);
|
||||
Object.assign(ref, body);
|
||||
|
||||
const v = validate(ref, schema);
|
||||
|
||||
if (!v.valid) {
|
||||
const message: any[] = v.errors.map(({ property, stack, schema }) => {
|
||||
let message: string;
|
||||
if (schema['description']) {
|
||||
message = schema['description'];
|
||||
} else {
|
||||
message = stack.replace('instance.', '');
|
||||
}
|
||||
return {
|
||||
property: property.replace('instance.', ''),
|
||||
message,
|
||||
};
|
||||
});
|
||||
logger.error([...message]);
|
||||
throw new BadRequestException(...message);
|
||||
}
|
||||
|
||||
return await execute(instance, ref);
|
||||
}
|
||||
|
||||
public async inviteCodeValidate<T>(args: DataValidate<T>) {
|
||||
const { request, ClassRef, schema, execute } = args;
|
||||
|
||||
const inviteCode = request.query as unknown as GroupInvite;
|
||||
|
||||
if (!inviteCode?.inviteCode) {
|
||||
throw new BadRequestException(
|
||||
'The group invite code id needs to be informed in the query',
|
||||
'ex: "inviteCode=F1EX5QZxO181L3TMVP31gY" (Obtained from group join link)',
|
||||
);
|
||||
}
|
||||
|
||||
const instance = request.params as unknown as InstanceDto;
|
||||
const body = request.body;
|
||||
|
||||
const ref = new ClassRef();
|
||||
|
||||
Object.assign(body, inviteCode);
|
||||
Object.assign(ref, body);
|
||||
|
||||
const v = validate(ref, schema);
|
||||
|
||||
console.log(v, '@checkei aqui');
|
||||
|
||||
if (!v.valid) {
|
||||
const message: any[] = v.errors.map(({ property, stack, schema }) => {
|
||||
let message: string;
|
||||
if (schema['description']) {
|
||||
message = schema['description'];
|
||||
} else {
|
||||
message = stack.replace('instance.', '');
|
||||
}
|
||||
return {
|
||||
property: property.replace('instance.', ''),
|
||||
message,
|
||||
};
|
||||
});
|
||||
logger.error([...message]);
|
||||
throw new BadRequestException(...message);
|
||||
}
|
||||
|
||||
return await execute(instance, ref);
|
||||
}
|
||||
}
|
101
src/whatsapp/controllers/chat.controller.ts
Normal file
@ -0,0 +1,101 @@
|
||||
import { proto } from '@evolution/base';
|
||||
import {
|
||||
ArchiveChatDto,
|
||||
DeleteMessage,
|
||||
NumberDto,
|
||||
ProfileNameDto,
|
||||
ProfilePictureDto,
|
||||
ProfileStatusDto,
|
||||
ReadMessageDto,
|
||||
WhatsAppNumberDto,
|
||||
} from '../dto/chat.dto';
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
import { ContactQuery } from '../repository/contact.repository';
|
||||
import { MessageQuery } from '../repository/message.repository';
|
||||
import { MessageUpQuery } from '../repository/messageUp.repository';
|
||||
import { WAMonitoringService } from '../services/monitor.service';
|
||||
|
||||
export class ChatController {
|
||||
constructor(private readonly waMonitor: WAMonitoringService) {}
|
||||
|
||||
public async whatsappNumber({ instanceName }: InstanceDto, data: WhatsAppNumberDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].whatsappNumber(data);
|
||||
}
|
||||
|
||||
public async readMessage({ instanceName }: InstanceDto, data: ReadMessageDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].markMessageAsRead(data);
|
||||
}
|
||||
|
||||
public async archiveChat({ instanceName }: InstanceDto, data: ArchiveChatDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].archiveChat(data);
|
||||
}
|
||||
|
||||
public async deleteMessage({ instanceName }: InstanceDto, data: DeleteMessage) {
|
||||
return await this.waMonitor.waInstances[instanceName].deleteMessage(data);
|
||||
}
|
||||
|
||||
public async fetchProfilePicture({ instanceName }: InstanceDto, data: NumberDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].profilePicture(data.number);
|
||||
}
|
||||
|
||||
public async fetchContacts({ instanceName }: InstanceDto, query: ContactQuery) {
|
||||
return await this.waMonitor.waInstances[instanceName].fetchContacts(query);
|
||||
}
|
||||
|
||||
public async getBase64FromMediaMessage(
|
||||
{ instanceName }: InstanceDto,
|
||||
message: proto.IWebMessageInfo,
|
||||
) {
|
||||
return await this.waMonitor.waInstances[instanceName].getBase64FromMediaMessage(
|
||||
message,
|
||||
);
|
||||
}
|
||||
|
||||
public async fetchMessages({ instanceName }: InstanceDto, query: MessageQuery) {
|
||||
return await this.waMonitor.waInstances[instanceName].fetchMessages(query);
|
||||
}
|
||||
|
||||
public async fetchStatusMessage({ instanceName }: InstanceDto, query: MessageUpQuery) {
|
||||
return await this.waMonitor.waInstances[instanceName].fetchStatusMessage(query);
|
||||
}
|
||||
|
||||
public async fetchChats({ instanceName }: InstanceDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].fetchChats();
|
||||
}
|
||||
|
||||
public async getBusinessProfile(
|
||||
{ instanceName }: InstanceDto,
|
||||
data: ProfilePictureDto,
|
||||
) {
|
||||
return await this.waMonitor.waInstances[instanceName].getBusinessProfile(data.number);
|
||||
}
|
||||
|
||||
public async updateProfileName({ instanceName }: InstanceDto, data: ProfileNameDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].updateProfileName(data.name);
|
||||
}
|
||||
|
||||
public async updateProfileStatus(
|
||||
{ instanceName }: InstanceDto,
|
||||
data: ProfileStatusDto,
|
||||
) {
|
||||
return await this.waMonitor.waInstances[instanceName].updateProfileStatus(
|
||||
data.status,
|
||||
);
|
||||
}
|
||||
|
||||
public async updateProfilePicture(
|
||||
{ instanceName }: InstanceDto,
|
||||
data: ProfilePictureDto,
|
||||
) {
|
||||
return await this.waMonitor.waInstances[instanceName].updateProfilePicture(
|
||||
data.picture,
|
||||
);
|
||||
}
|
||||
|
||||
public async removeProfilePicture(
|
||||
{ instanceName }: InstanceDto,
|
||||
data: ProfilePictureDto,
|
||||
) {
|
||||
return await this.waMonitor.waInstances[instanceName].removeProfilePicture();
|
||||
}
|
||||
}
|
72
src/whatsapp/controllers/group.controller.ts
Normal file
@ -0,0 +1,72 @@
|
||||
import {
|
||||
CreateGroupDto,
|
||||
GroupInvite,
|
||||
GroupJid,
|
||||
GroupPictureDto,
|
||||
GroupToggleEphemeralDto,
|
||||
GroupUpdateParticipantDto,
|
||||
GroupUpdateSettingDto,
|
||||
} from '../dto/group.dto';
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
import { WAMonitoringService } from '../services/monitor.service';
|
||||
|
||||
export class GroupController {
|
||||
constructor(private readonly waMonitor: WAMonitoringService) {}
|
||||
|
||||
public async createGroup(instance: InstanceDto, create: CreateGroupDto) {
|
||||
return await this.waMonitor.waInstances[instance.instanceName].createGroup(create);
|
||||
}
|
||||
|
||||
public async updateGroupPicture(instance: InstanceDto, update: GroupPictureDto) {
|
||||
return await this.waMonitor.waInstances[instance.instanceName].updateGroupPicture(
|
||||
update,
|
||||
);
|
||||
}
|
||||
|
||||
public async findGroupInfo(instance: InstanceDto, groupJid: GroupJid) {
|
||||
return await this.waMonitor.waInstances[instance.instanceName].findGroup(groupJid);
|
||||
}
|
||||
|
||||
public async inviteCode(instance: InstanceDto, groupJid: GroupJid) {
|
||||
return await this.waMonitor.waInstances[instance.instanceName].inviteCode(groupJid);
|
||||
}
|
||||
|
||||
public async inviteInfo(instance: InstanceDto, inviteCode: GroupInvite) {
|
||||
return await this.waMonitor.waInstances[instance.instanceName].inviteInfo(inviteCode);
|
||||
}
|
||||
|
||||
public async revokeInviteCode(instance: InstanceDto, groupJid: GroupJid) {
|
||||
return await this.waMonitor.waInstances[instance.instanceName].revokeInviteCode(
|
||||
groupJid,
|
||||
);
|
||||
}
|
||||
|
||||
public async findParticipants(instance: InstanceDto, groupJid: GroupJid) {
|
||||
return await this.waMonitor.waInstances[instance.instanceName].findParticipants(
|
||||
groupJid,
|
||||
);
|
||||
}
|
||||
|
||||
public async updateGParticipate(
|
||||
instance: InstanceDto,
|
||||
update: GroupUpdateParticipantDto,
|
||||
) {
|
||||
return await this.waMonitor.waInstances[instance.instanceName].updateGParticipant(
|
||||
update,
|
||||
);
|
||||
}
|
||||
|
||||
public async updateGSetting(instance: InstanceDto, update: GroupUpdateSettingDto) {
|
||||
return await this.waMonitor.waInstances[instance.instanceName].updateGSetting(update);
|
||||
}
|
||||
|
||||
public async toggleEphemeral(instance: InstanceDto, update: GroupToggleEphemeralDto) {
|
||||
return await this.waMonitor.waInstances[instance.instanceName].toggleEphemeral(
|
||||
update,
|
||||
);
|
||||
}
|
||||
|
||||
public async leaveGroup(instance: InstanceDto, groupJid: GroupJid) {
|
||||
return await this.waMonitor.waInstances[instance.instanceName].leaveGroup(groupJid);
|
||||
}
|
||||
}
|
166
src/whatsapp/controllers/instance.controller.ts
Normal file
@ -0,0 +1,166 @@
|
||||
import { delay } from '@evolution/base';
|
||||
import EventEmitter2 from 'eventemitter2';
|
||||
import { Auth, ConfigService } from '../../config/env.config';
|
||||
import { BadRequestException, InternalServerErrorException } from '../../exceptions';
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
import { RepositoryBroker } from '../repository/repository.manager';
|
||||
import { AuthService, OldToken } from '../services/auth.service';
|
||||
import { WAMonitoringService } from '../services/monitor.service';
|
||||
import { WAStartupService } from '../services/whatsapp.service';
|
||||
import { WebhookService } from '../services/webhook.service';
|
||||
import { Logger } from '../../config/logger.config';
|
||||
|
||||
export class InstanceController {
|
||||
constructor(
|
||||
private readonly waMonitor: WAMonitoringService,
|
||||
private readonly configService: ConfigService,
|
||||
private readonly repository: RepositoryBroker,
|
||||
private readonly eventEmitter: EventEmitter2,
|
||||
private readonly authService: AuthService,
|
||||
private readonly webhookService: WebhookService,
|
||||
) {}
|
||||
|
||||
private readonly logger = new Logger(InstanceController.name);
|
||||
|
||||
public async createInstance({ instanceName, webhook }: InstanceDto) {
|
||||
//verifica se modo da instancia é container
|
||||
const mode = this.configService.get<Auth>('AUTHENTICATION').INSTANCE.MODE;
|
||||
|
||||
if (mode === 'container') {
|
||||
//verifica se ja existe uma instancia criada com qualquer nome
|
||||
if (Object.keys(this.waMonitor.waInstances).length > 0) {
|
||||
throw new BadRequestException([
|
||||
'Instance already created',
|
||||
'Only one instance can be created',
|
||||
]);
|
||||
}
|
||||
|
||||
const instance = new WAStartupService(
|
||||
this.configService,
|
||||
this.eventEmitter,
|
||||
this.repository,
|
||||
);
|
||||
instance.instanceName = instanceName;
|
||||
this.waMonitor.waInstances[instance.instanceName] = instance;
|
||||
this.waMonitor.delInstanceTime(instance.instanceName);
|
||||
|
||||
const hash = await this.authService.generateHash({
|
||||
instanceName: instance.instanceName,
|
||||
});
|
||||
|
||||
if (webhook) {
|
||||
try {
|
||||
this.webhookService.create(instance, { enabled: true, url: webhook });
|
||||
} catch (error) {
|
||||
this.logger.log(error);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
instance: {
|
||||
instanceName: instance.instanceName,
|
||||
status: 'created',
|
||||
},
|
||||
hash,
|
||||
webhook,
|
||||
};
|
||||
} else {
|
||||
const instance = new WAStartupService(
|
||||
this.configService,
|
||||
this.eventEmitter,
|
||||
this.repository,
|
||||
);
|
||||
instance.instanceName = instanceName;
|
||||
this.waMonitor.waInstances[instance.instanceName] = instance;
|
||||
this.waMonitor.delInstanceTime(instance.instanceName);
|
||||
|
||||
const hash = await this.authService.generateHash({
|
||||
instanceName: instance.instanceName,
|
||||
});
|
||||
|
||||
if (webhook) {
|
||||
try {
|
||||
this.webhookService.create(instance, { enabled: true, url: webhook });
|
||||
} catch (error) {
|
||||
this.logger.log(error);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
instance: {
|
||||
instanceName: instance.instanceName,
|
||||
status: 'created',
|
||||
},
|
||||
hash,
|
||||
webhook,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public async connectToWhatsapp({ instanceName }: InstanceDto) {
|
||||
try {
|
||||
const instance = this.waMonitor.waInstances[instanceName];
|
||||
const state = instance.connectionStatus?.state;
|
||||
|
||||
switch (state) {
|
||||
case 'close':
|
||||
await instance.connectToWhatsapp();
|
||||
await delay(2000);
|
||||
return instance.qrCode;
|
||||
case 'connecting':
|
||||
return instance.qrCode;
|
||||
default:
|
||||
return await this.connectionState({ instanceName });
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.log(error);
|
||||
}
|
||||
}
|
||||
|
||||
public async connectionState({ instanceName }: InstanceDto) {
|
||||
return this.waMonitor.waInstances[instanceName].connectionStatus;
|
||||
}
|
||||
|
||||
public async fetchInstances({ instanceName }: InstanceDto) {
|
||||
if (instanceName) {
|
||||
return this.waMonitor.instanceInfo(instanceName);
|
||||
}
|
||||
|
||||
return this.waMonitor.instanceInfo();
|
||||
}
|
||||
|
||||
public async logout({ instanceName }: InstanceDto) {
|
||||
try {
|
||||
await this.waMonitor.waInstances[instanceName]?.client?.logout(
|
||||
'Log out instance: ' + instanceName,
|
||||
);
|
||||
|
||||
this.waMonitor.waInstances[instanceName]?.client?.ws?.close();
|
||||
this.waMonitor.waInstances[instanceName]?.client?.end(undefined);
|
||||
|
||||
return { error: false, message: 'Instance logged out' };
|
||||
} catch (error) {
|
||||
throw new InternalServerErrorException(error.toString());
|
||||
}
|
||||
}
|
||||
|
||||
public async deleteInstance({ instanceName }: InstanceDto) {
|
||||
const stateConn = await this.connectionState({ instanceName });
|
||||
if (stateConn.state === 'open') {
|
||||
throw new BadRequestException([
|
||||
'Deletion failed',
|
||||
'The instance needs to be disconnected',
|
||||
]);
|
||||
}
|
||||
try {
|
||||
delete this.waMonitor.waInstances[instanceName];
|
||||
return { error: false, message: 'Instance deleted' };
|
||||
} catch (error) {
|
||||
throw new BadRequestException(error.toString());
|
||||
}
|
||||
}
|
||||
|
||||
public async refreshToken(_: InstanceDto, oldToken: OldToken) {
|
||||
return await this.authService.refreshToken(oldToken);
|
||||
}
|
||||
}
|
78
src/whatsapp/controllers/sendMessage.controller.ts
Normal file
@ -0,0 +1,78 @@
|
||||
import { isBase64, isURL } from 'class-validator';
|
||||
import { BadRequestException } from '../../exceptions';
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
import {
|
||||
SendAudioDto,
|
||||
SendButtonDto,
|
||||
SendContactDto,
|
||||
SendLinkPreviewDto,
|
||||
SendListDto,
|
||||
SendLocationDto,
|
||||
SendMediaDto,
|
||||
SendPollDto,
|
||||
SendReactionDto,
|
||||
SendTextDto,
|
||||
} from '../dto/sendMessage.dto';
|
||||
import { WAMonitoringService } from '../services/monitor.service';
|
||||
|
||||
export class SendMessageController {
|
||||
constructor(private readonly waMonitor: WAMonitoringService) {}
|
||||
|
||||
public async sendText({ instanceName }: InstanceDto, data: SendTextDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].textMessage(data);
|
||||
}
|
||||
|
||||
public async sendMedia({ instanceName }: InstanceDto, data: SendMediaDto) {
|
||||
if (isBase64(data?.mediaMessage?.media) && !data?.mediaMessage?.fileName) {
|
||||
throw new BadRequestException('For bse64 the file name must be informed.');
|
||||
}
|
||||
if (isURL(data?.mediaMessage?.media) || isBase64(data?.mediaMessage?.media)) {
|
||||
return await this.waMonitor.waInstances[instanceName].mediaMessage(data);
|
||||
}
|
||||
throw new BadRequestException('Owned media must be a url or base64');
|
||||
}
|
||||
|
||||
public async sendWhatsAppAudio({ instanceName }: InstanceDto, data: SendAudioDto) {
|
||||
if (isURL(data.audioMessage.audio) || isBase64(data.audioMessage.audio)) {
|
||||
return await this.waMonitor.waInstances[instanceName].audioWhatsapp(data);
|
||||
}
|
||||
throw new BadRequestException('Owned media must be a url or base64');
|
||||
}
|
||||
|
||||
public async sendButtons({ instanceName }: InstanceDto, data: SendButtonDto) {
|
||||
if (
|
||||
isBase64(data.buttonMessage.mediaMessage?.media) &&
|
||||
!data.buttonMessage.mediaMessage?.fileName
|
||||
) {
|
||||
throw new BadRequestException('For bse64 the file name must be informed.');
|
||||
}
|
||||
return await this.waMonitor.waInstances[instanceName].buttonMessage(data);
|
||||
}
|
||||
|
||||
public async sendLocation({ instanceName }: InstanceDto, data: SendLocationDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].locationMessage(data);
|
||||
}
|
||||
|
||||
public async sendList({ instanceName }: InstanceDto, data: SendListDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].listMessage(data);
|
||||
}
|
||||
|
||||
public async sendContact({ instanceName }: InstanceDto, data: SendContactDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].contactMessage(data);
|
||||
}
|
||||
|
||||
public async sendReaction({ instanceName }: InstanceDto, data: SendReactionDto) {
|
||||
if (!data.reactionMessage.reaction.match(/[^\(\)\w\sà-ú"-\+]+/)) {
|
||||
throw new BadRequestException('"reaction" must be an emoji');
|
||||
}
|
||||
return await this.waMonitor.waInstances[instanceName].reactionMessage(data);
|
||||
}
|
||||
|
||||
public async sendPoll({ instanceName }: InstanceDto, data: SendPollDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].pollMessage(data);
|
||||
}
|
||||
|
||||
public async sendLinkPreview({ instanceName }: InstanceDto, data: SendLinkPreviewDto) {
|
||||
return await this.waMonitor.waInstances[instanceName].linkPreview(data);
|
||||
}
|
||||
}
|
28
src/whatsapp/controllers/views.controller.ts
Normal file
@ -0,0 +1,28 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { Auth, ConfigService } from '../../config/env.config';
|
||||
import { BadRequestException } from '../../exceptions';
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
import { HttpStatus } from '../routers/index.router';
|
||||
import { WAMonitoringService } from '../services/monitor.service';
|
||||
|
||||
export class ViewsController {
|
||||
constructor(
|
||||
private readonly waMonit: WAMonitoringService,
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
public async qrcode(request: Request, response: Response) {
|
||||
try {
|
||||
const param = request.params as unknown as InstanceDto;
|
||||
const instance = this.waMonit.waInstances[param.instanceName];
|
||||
if (instance.connectionStatus.state === 'open') {
|
||||
throw new BadRequestException('The instance is already connected');
|
||||
}
|
||||
const type = this.configService.get<Auth>('AUTHENTICATION').TYPE;
|
||||
|
||||
return response.status(HttpStatus.OK).render('qrcode', { type, ...param });
|
||||
} catch (error) {
|
||||
console.log('ERROR: ', error);
|
||||
}
|
||||
}
|
||||
}
|
20
src/whatsapp/controllers/webhook.controller.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { isURL } from 'class-validator';
|
||||
import { BadRequestException } from '../../exceptions';
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
import { WebhookDto } from '../dto/webhook.dto';
|
||||
import { WebhookService } from '../services/webhook.service';
|
||||
|
||||
export class WebhookController {
|
||||
constructor(private readonly webhookService: WebhookService) {}
|
||||
|
||||
public async createWebhook(instance: InstanceDto, data: WebhookDto) {
|
||||
if (!isURL(data.url, { require_tld: false })) {
|
||||
throw new BadRequestException('Invalid "url" property');
|
||||
}
|
||||
return this.webhookService.create(instance, data);
|
||||
}
|
||||
|
||||
public async findWebhook(instance: InstanceDto) {
|
||||
return this.webhookService.find(instance);
|
||||
}
|
||||
}
|
55
src/whatsapp/dto/chat.dto.ts
Normal file
@ -0,0 +1,55 @@
|
||||
export class OnWhatsAppDto {
|
||||
constructor(
|
||||
public readonly jid: string,
|
||||
public readonly exists: boolean,
|
||||
public readonly name?: string,
|
||||
) {}
|
||||
}
|
||||
|
||||
export class WhatsAppNumberDto {
|
||||
numbers: string[];
|
||||
}
|
||||
|
||||
export class NumberDto {
|
||||
number: string;
|
||||
}
|
||||
|
||||
export class ProfileNameDto {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export class ProfileStatusDto {
|
||||
status: string;
|
||||
}
|
||||
|
||||
export class ProfilePictureDto {
|
||||
number?: string;
|
||||
// url or base64
|
||||
picture?: string;
|
||||
}
|
||||
|
||||
class Key {
|
||||
id: string;
|
||||
fromMe: boolean;
|
||||
remoteJid: string;
|
||||
}
|
||||
export class ReadMessageDto {
|
||||
readMessages: Key[];
|
||||
}
|
||||
|
||||
class LastMessage {
|
||||
key: Key;
|
||||
messageTimestamp?: number;
|
||||
}
|
||||
|
||||
export class ArchiveChatDto {
|
||||
lastMessage: LastMessage;
|
||||
archive: boolean;
|
||||
}
|
||||
|
||||
export class DeleteMessage {
|
||||
id: string;
|
||||
fromMe: boolean;
|
||||
remoteJid: string;
|
||||
participant?: string;
|
||||
}
|
31
src/whatsapp/dto/group.dto.ts
Normal file
@ -0,0 +1,31 @@
|
||||
export class CreateGroupDto {
|
||||
subject: string;
|
||||
description?: string;
|
||||
participants: string[];
|
||||
}
|
||||
|
||||
export class GroupPictureDto {
|
||||
groupJid: string;
|
||||
image: string;
|
||||
}
|
||||
|
||||
export class GroupJid {
|
||||
groupJid: string;
|
||||
}
|
||||
|
||||
export class GroupInvite {
|
||||
inviteCode: string;
|
||||
}
|
||||
|
||||
export class GroupUpdateParticipantDto extends GroupJid {
|
||||
action: 'add' | 'remove' | 'promote' | 'demote';
|
||||
participants: string[];
|
||||
}
|
||||
|
||||
export class GroupUpdateSettingDto extends GroupJid {
|
||||
action: 'announcement' | 'not_announcement' | 'unlocked' | 'locked';
|
||||
}
|
||||
|
||||
export class GroupToggleEphemeralDto extends GroupJid {
|
||||
expiration: 0 | 86400 | 604800 | 7776000;
|
||||
}
|
4
src/whatsapp/dto/instance.dto.ts
Normal file
@ -0,0 +1,4 @@
|
||||
export class InstanceDto {
|
||||
instanceName: string;
|
||||
webhook?: string;
|
||||
}
|
133
src/whatsapp/dto/sendMessage.dto.ts
Normal file
@ -0,0 +1,133 @@
|
||||
import { proto, WAPresence } from '@evolution/base';
|
||||
|
||||
export class Quoted {
|
||||
key: proto.IMessageKey;
|
||||
message: proto.IMessage;
|
||||
}
|
||||
|
||||
export class Mentions {
|
||||
everyOne: boolean;
|
||||
mentioned: string[];
|
||||
}
|
||||
|
||||
export class Options {
|
||||
delay?: number;
|
||||
presence?: WAPresence;
|
||||
quoted?: Quoted;
|
||||
mentions?: Mentions;
|
||||
}
|
||||
class OptionsMessage {
|
||||
options: Options;
|
||||
}
|
||||
|
||||
export class Metadata extends OptionsMessage {
|
||||
number: string;
|
||||
}
|
||||
|
||||
class TextMessage {
|
||||
text: string;
|
||||
}
|
||||
|
||||
class linkPreviewMessage {
|
||||
text: string;
|
||||
}
|
||||
|
||||
class PollMessage {
|
||||
name: string;
|
||||
selectableCount: number;
|
||||
values: string[];
|
||||
messageSecret?: Uint8Array;
|
||||
}
|
||||
export class SendTextDto extends Metadata {
|
||||
textMessage: TextMessage;
|
||||
}
|
||||
|
||||
export class SendLinkPreviewDto extends Metadata {
|
||||
linkPreview: linkPreviewMessage;
|
||||
}
|
||||
|
||||
export class SendPollDto extends Metadata {
|
||||
pollMessage: PollMessage;
|
||||
}
|
||||
|
||||
export type MediaType = 'image' | 'document' | 'video' | 'audio';
|
||||
export class MediaMessage {
|
||||
mediatype: MediaType;
|
||||
caption?: string;
|
||||
// for document
|
||||
fileName?: string;
|
||||
// url or base64
|
||||
media: string;
|
||||
}
|
||||
export class SendMediaDto extends Metadata {
|
||||
mediaMessage: MediaMessage;
|
||||
}
|
||||
|
||||
class Audio {
|
||||
audio: string;
|
||||
}
|
||||
export class SendAudioDto extends Metadata {
|
||||
audioMessage: Audio;
|
||||
}
|
||||
|
||||
class Button {
|
||||
buttonText: string;
|
||||
buttonId: string;
|
||||
}
|
||||
class ButtonMessage {
|
||||
title: string;
|
||||
description: string;
|
||||
footerText?: string;
|
||||
buttons: Button[];
|
||||
mediaMessage?: MediaMessage;
|
||||
}
|
||||
export class SendButtonDto extends Metadata {
|
||||
buttonMessage: ButtonMessage;
|
||||
}
|
||||
|
||||
class LocationMessage {
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
name?: string;
|
||||
address?: string;
|
||||
}
|
||||
export class SendLocationDto extends Metadata {
|
||||
locationMessage: LocationMessage;
|
||||
}
|
||||
|
||||
class Row {
|
||||
title: string;
|
||||
description: string;
|
||||
rowId: string;
|
||||
}
|
||||
class Section {
|
||||
title: string;
|
||||
rows: Row[];
|
||||
}
|
||||
class ListMessage {
|
||||
title: string;
|
||||
description: string;
|
||||
footerText?: string;
|
||||
buttonText: string;
|
||||
sections: Section[];
|
||||
}
|
||||
export class SendListDto extends Metadata {
|
||||
listMessage: ListMessage;
|
||||
}
|
||||
|
||||
export class ContactMessage {
|
||||
fullName: string;
|
||||
wuid: string;
|
||||
phoneNumber: string;
|
||||
}
|
||||
export class SendContactDto extends Metadata {
|
||||
contactMessage: ContactMessage[];
|
||||
}
|
||||
|
||||
class ReactionMessage {
|
||||
key: proto.IMessageKey;
|
||||
reaction: string;
|
||||
}
|
||||
export class SendReactionDto {
|
||||
reactionMessage: ReactionMessage;
|
||||
}
|
4
src/whatsapp/dto/webhook.dto.ts
Normal file
@ -0,0 +1,4 @@
|
||||
export class WebhookDto {
|
||||
enabled?: boolean;
|
||||
url?: string;
|
||||
}
|
94
src/whatsapp/guards/auth.guard.ts
Normal file
@ -0,0 +1,94 @@
|
||||
import { isJWT } from 'class-validator';
|
||||
import { NextFunction, Request, Response } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { Auth, configService } from '../../config/env.config';
|
||||
import { Logger } from '../../config/logger.config';
|
||||
import { name } from '../../../package.json';
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
import { JwtPayload } from '../services/auth.service';
|
||||
import { ForbiddenException, UnauthorizedException } from '../../exceptions';
|
||||
import { repository } from '../whatsapp.module';
|
||||
|
||||
const logger = new Logger('GUARD');
|
||||
|
||||
async function jwtGuard(req: Request, res: Response, next: NextFunction) {
|
||||
const key = req.get('apikey');
|
||||
|
||||
if (key && configService.get<Auth>('AUTHENTICATION').API_KEY.KEY !== key) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
|
||||
if (configService.get<Auth>('AUTHENTICATION').API_KEY.KEY === key) {
|
||||
return next();
|
||||
}
|
||||
|
||||
if (
|
||||
(req.originalUrl.includes('/instance/create') ||
|
||||
req.originalUrl.includes('/instance/fetchInstances')) &&
|
||||
!key
|
||||
) {
|
||||
throw new ForbiddenException(
|
||||
'Missing global api key',
|
||||
'The global api key must be set',
|
||||
);
|
||||
}
|
||||
|
||||
const jwtOpts = configService.get<Auth>('AUTHENTICATION').JWT;
|
||||
try {
|
||||
const [bearer, token] = req.get('authorization').split(' ');
|
||||
|
||||
if (bearer.toLowerCase() !== 'bearer') {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
|
||||
if (!isJWT(token)) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
|
||||
const param = req.params as unknown as InstanceDto;
|
||||
const decode = jwt.verify(token, jwtOpts.SECRET, {
|
||||
ignoreExpiration: jwtOpts.EXPIRIN_IN === 0,
|
||||
}) as JwtPayload;
|
||||
|
||||
if (param.instanceName !== decode.instanceName || name !== decode.apiName) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
|
||||
return next();
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
}
|
||||
|
||||
async function apikey(req: Request, res: Response, next: NextFunction) {
|
||||
const env = configService.get<Auth>('AUTHENTICATION').API_KEY;
|
||||
const key = req.get('apikey');
|
||||
|
||||
if (env.KEY === key) {
|
||||
return next();
|
||||
}
|
||||
|
||||
if (
|
||||
(req.originalUrl.includes('/instance/create') ||
|
||||
req.originalUrl.includes('/instance/fetchInstances')) &&
|
||||
!key
|
||||
) {
|
||||
throw new ForbiddenException(
|
||||
'Missing global api key',
|
||||
'The global api key must be set',
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const param = req.params as unknown as InstanceDto;
|
||||
const instanceKey = await repository.auth.find(param.instanceName);
|
||||
if (instanceKey.apikey === key) {
|
||||
return next();
|
||||
}
|
||||
} catch (error) {}
|
||||
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
|
||||
export const authGuard = { jwt: jwtGuard, apikey };
|
63
src/whatsapp/guards/instance.guard.ts
Normal file
@ -0,0 +1,63 @@
|
||||
import { NextFunction, Request, Response } from 'express';
|
||||
import { existsSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { INSTANCE_DIR } from '../../config/path.config';
|
||||
import { db, dbserver } from '../../db/db.connect';
|
||||
import {
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
NotFoundException,
|
||||
} from '../../exceptions';
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
import { waMonitor } from '../whatsapp.module';
|
||||
|
||||
async function getInstance(instanceName: string) {
|
||||
const exists = waMonitor.waInstances[instanceName];
|
||||
|
||||
if (db.ENABLED) {
|
||||
const collection = dbserver
|
||||
.getClient()
|
||||
.db(db.CONNECTION.DB_PREFIX_NAME + '-instances')
|
||||
.collection(instanceName);
|
||||
return exists || (await collection.find({}).toArray()).length > 0;
|
||||
}
|
||||
|
||||
return exists || existsSync(join(INSTANCE_DIR, instanceName));
|
||||
}
|
||||
|
||||
export async function instanceExistsGuard(req: Request, _: Response, next: NextFunction) {
|
||||
if (
|
||||
req.originalUrl.includes('/instance/create') ||
|
||||
req.originalUrl.includes('/instance/fetchInstances')
|
||||
) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const param = req.params as unknown as InstanceDto;
|
||||
if (!param?.instanceName) {
|
||||
throw new BadRequestException('"instanceName" not provided.');
|
||||
}
|
||||
|
||||
if (!(await getInstance(param.instanceName))) {
|
||||
throw new NotFoundException(`The "${param.instanceName}" instance does not exist`);
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
||||
|
||||
export async function instanceLoggedGuard(req: Request, _: Response, next: NextFunction) {
|
||||
if (req.originalUrl.includes('/instance/create')) {
|
||||
const instance = req.body as InstanceDto;
|
||||
if (await getInstance(instance.instanceName)) {
|
||||
throw new ForbiddenException(
|
||||
`This name "${instance.instanceName}" is already in use.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (waMonitor.waInstances[instance.instanceName]) {
|
||||
delete waMonitor.waInstances[instance.instanceName];
|
||||
}
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
17
src/whatsapp/models/auth.model.ts
Normal file
@ -0,0 +1,17 @@
|
||||
import { Schema } from 'mongoose';
|
||||
import { dbserver } from '../../db/db.connect';
|
||||
|
||||
export class AuthRaw {
|
||||
_id?: string;
|
||||
jwt?: string;
|
||||
apikey?: string;
|
||||
}
|
||||
|
||||
const authSchema = new Schema<AuthRaw>({
|
||||
_id: { type: String, _id: true },
|
||||
jwt: { type: String, minlength: 1 },
|
||||
apikey: { type: String, minlength: 1 },
|
||||
});
|
||||
|
||||
export const AuthModel = dbserver?.model(AuthRaw.name, authSchema, 'authentication');
|
||||
export type IAuthModel = typeof AuthModel;
|
18
src/whatsapp/models/chat.model.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import { Schema } from 'mongoose';
|
||||
import { dbserver } from '../../db/db.connect';
|
||||
|
||||
export class ChatRaw {
|
||||
_id?: string;
|
||||
id?: string;
|
||||
owner: string;
|
||||
lastMsgTimestamp?: number;
|
||||
}
|
||||
|
||||
const chatSchema = new Schema<ChatRaw>({
|
||||
_id: { type: String, _id: true },
|
||||
id: { type: String, required: true, minlength: 1 },
|
||||
owner: { type: String, required: true, minlength: 1 },
|
||||
});
|
||||
|
||||
export const ChatModel = dbserver?.model(ChatRaw.name, chatSchema, 'chats');
|
||||
export type IChatModel = typeof ChatModel;
|
21
src/whatsapp/models/contact.model.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import { Schema } from 'mongoose';
|
||||
import { dbserver } from '../../db/db.connect';
|
||||
|
||||
export class ContactRaw {
|
||||
_id?: string;
|
||||
pushName?: string;
|
||||
id?: string;
|
||||
profilePictureUrl?: string;
|
||||
owner: string;
|
||||
}
|
||||
|
||||
const contactSchema = new Schema<ContactRaw>({
|
||||
_id: { type: String, _id: true },
|
||||
pushName: { type: String, minlength: 1 },
|
||||
id: { type: String, required: true, minlength: 1 },
|
||||
profilePictureUrl: { type: String, minlength: 1 },
|
||||
owner: { type: String, required: true, minlength: 1 },
|
||||
});
|
||||
|
||||
export const ContactModel = dbserver?.model(ContactRaw.name, contactSchema, 'contacts');
|
||||
export type IContactModel = typeof ContactModel;
|
5
src/whatsapp/models/index.ts
Normal file
@ -0,0 +1,5 @@
|
||||
export * from './chat.model';
|
||||
export * from './contact.model';
|
||||
export * from './message.model';
|
||||
export * from './auth.model';
|
||||
export * from './webhook.model';
|
71
src/whatsapp/models/message.model.ts
Normal file
@ -0,0 +1,71 @@
|
||||
import { Schema } from 'mongoose';
|
||||
import { dbserver } from '../../db/db.connect';
|
||||
import { wa } from '../types/wa.types';
|
||||
|
||||
class Key {
|
||||
id?: string;
|
||||
remoteJid?: string;
|
||||
fromMe?: boolean;
|
||||
participant?: string;
|
||||
}
|
||||
|
||||
export class MessageRaw {
|
||||
_id?: string;
|
||||
key?: Key;
|
||||
pushName?: string;
|
||||
participant?: string;
|
||||
message?: object;
|
||||
messageType?: string;
|
||||
messageTimestamp?: number | Long.Long;
|
||||
owner: string;
|
||||
source?: 'android' | 'web' | 'ios';
|
||||
}
|
||||
|
||||
const messageSchema = new Schema<MessageRaw>({
|
||||
_id: { type: String, _id: true },
|
||||
key: {
|
||||
id: { type: String, required: true, minlength: 1 },
|
||||
remoteJid: { type: String, required: true, minlength: 1 },
|
||||
fromMe: { type: Boolean, required: true },
|
||||
participant: { type: String, minlength: 1 },
|
||||
},
|
||||
pushName: { type: String },
|
||||
participant: { type: String },
|
||||
messageType: { type: String },
|
||||
message: { type: Object },
|
||||
source: { type: String, minlength: 3, enum: ['android', 'web', 'ios'] },
|
||||
messageTimestamp: { type: Number, required: true },
|
||||
owner: { type: String, required: true, minlength: 1 },
|
||||
});
|
||||
|
||||
export const MessageModel = dbserver?.model(MessageRaw.name, messageSchema, 'messages');
|
||||
export type IMessageModel = typeof MessageModel;
|
||||
|
||||
export class MessageUpdateRaw {
|
||||
_id?: string;
|
||||
remoteJid?: string;
|
||||
id?: string;
|
||||
fromMe?: boolean;
|
||||
participant?: string;
|
||||
datetime?: number;
|
||||
status?: wa.StatusMessage;
|
||||
owner: string;
|
||||
}
|
||||
|
||||
const messageUpdateSchema = new Schema<MessageUpdateRaw>({
|
||||
_id: { type: String, _id: true },
|
||||
remoteJid: { type: String, required: true, min: 1 },
|
||||
id: { type: String, required: true, min: 1 },
|
||||
fromMe: { type: Boolean, required: true },
|
||||
participant: { type: String, min: 1 },
|
||||
datetime: { type: Number, required: true, min: 1 },
|
||||
status: { type: String, required: true },
|
||||
owner: { type: String, required: true, min: 1 },
|
||||
});
|
||||
|
||||
export const MessageUpModel = dbserver?.model(
|
||||
MessageUpdateRaw.name,
|
||||
messageUpdateSchema,
|
||||
'messageUpdate',
|
||||
);
|
||||
export type IMessageUpModel = typeof MessageUpModel;
|
17
src/whatsapp/models/webhook.model.ts
Normal file
@ -0,0 +1,17 @@
|
||||
import { Schema } from 'mongoose';
|
||||
import { dbserver } from '../../db/db.connect';
|
||||
|
||||
export class WebhookRaw {
|
||||
_id?: string;
|
||||
url?: string;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
const webhookSchema = new Schema<WebhookRaw>({
|
||||
_id: { type: String, _id: true },
|
||||
url: { type: String, required: true },
|
||||
enabled: { type: Boolean, required: true },
|
||||
});
|
||||
|
||||
export const WebhookModel = dbserver?.model(WebhookRaw.name, webhookSchema, 'webhook');
|
||||
export type IWebhookModel = typeof WebhookModel;
|
57
src/whatsapp/repository/auth.repository.ts
Normal file
@ -0,0 +1,57 @@
|
||||
import { join } from 'path';
|
||||
import { Auth, ConfigService } from '../../config/env.config';
|
||||
import { IInsert, Repository } from '../abstract/abstract.repository';
|
||||
import { IAuthModel, AuthRaw } from '../models';
|
||||
import { readFileSync } from 'fs';
|
||||
import { AUTH_DIR } from '../../config/path.config';
|
||||
|
||||
export class AuthRepository extends Repository {
|
||||
constructor(
|
||||
private readonly authModel: IAuthModel,
|
||||
readonly configService: ConfigService,
|
||||
) {
|
||||
super(configService);
|
||||
this.auth = configService.get<Auth>('AUTHENTICATION');
|
||||
}
|
||||
|
||||
private readonly auth: Auth;
|
||||
|
||||
public async create(data: AuthRaw, instance: string): Promise<IInsert> {
|
||||
try {
|
||||
if (this.dbSettings.ENABLED) {
|
||||
const insert = await this.authModel.replaceOne(
|
||||
{ _id: instance },
|
||||
{ ...data },
|
||||
{ upsert: true },
|
||||
);
|
||||
return { insertCount: insert.modifiedCount };
|
||||
}
|
||||
|
||||
this.writeStore<AuthRaw>({
|
||||
path: join(AUTH_DIR, this.auth.TYPE),
|
||||
fileName: instance,
|
||||
data,
|
||||
});
|
||||
|
||||
return { insertCount: 1 };
|
||||
} catch (error) {
|
||||
return { error } as any;
|
||||
}
|
||||
}
|
||||
|
||||
public async find(instance: string): Promise<AuthRaw> {
|
||||
try {
|
||||
if (this.dbSettings.ENABLED) {
|
||||
return await this.authModel.findOne({ _id: instance });
|
||||
}
|
||||
|
||||
return JSON.parse(
|
||||
readFileSync(join(AUTH_DIR, this.auth.TYPE, instance + '.json'), {
|
||||
encoding: 'utf-8',
|
||||
}),
|
||||
) as AuthRaw;
|
||||
} catch (error) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
}
|
89
src/whatsapp/repository/chat.repository.ts
Normal file
@ -0,0 +1,89 @@
|
||||
import { join } from 'path';
|
||||
import { ConfigService } from '../../config/env.config';
|
||||
import { IInsert, Repository } from '../abstract/abstract.repository';
|
||||
import { opendirSync, readFileSync, rmSync } from 'fs';
|
||||
import { ChatRaw, IChatModel } from '../models';
|
||||
|
||||
export class ChatQuery {
|
||||
where: ChatRaw;
|
||||
}
|
||||
|
||||
export class ChatRepository extends Repository {
|
||||
constructor(
|
||||
private readonly chatModel: IChatModel,
|
||||
private readonly configService: ConfigService,
|
||||
) {
|
||||
super(configService);
|
||||
}
|
||||
|
||||
public async insert(data: ChatRaw[], saveDb = false): Promise<IInsert> {
|
||||
if (data.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (this.dbSettings.ENABLED && saveDb) {
|
||||
const insert = await this.chatModel.insertMany([...data]);
|
||||
return { insertCount: insert.length };
|
||||
}
|
||||
|
||||
data.forEach((chat) => {
|
||||
this.writeStore<ChatRaw>({
|
||||
path: join(this.storePath, 'chats', chat.owner),
|
||||
fileName: chat.id,
|
||||
data: chat,
|
||||
});
|
||||
});
|
||||
|
||||
return { insertCount: data.length };
|
||||
} catch (error) {
|
||||
return error;
|
||||
} finally {
|
||||
data = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
public async find(query: ChatQuery): Promise<ChatRaw[]> {
|
||||
try {
|
||||
if (this.dbSettings.ENABLED) {
|
||||
return await this.chatModel.find({ owner: query.where.owner });
|
||||
}
|
||||
|
||||
const chats: ChatRaw[] = [];
|
||||
const openDir = opendirSync(join(this.storePath, 'chats', query.where.owner));
|
||||
for await (const dirent of openDir) {
|
||||
if (dirent.isFile()) {
|
||||
chats.push(
|
||||
JSON.parse(
|
||||
readFileSync(
|
||||
join(this.storePath, 'chats', query.where.owner, dirent.name),
|
||||
{ encoding: 'utf-8' },
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return chats;
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
public async delete(query: ChatQuery) {
|
||||
try {
|
||||
if (this.dbSettings.ENABLED) {
|
||||
return await this.chatModel.deleteOne({ ...query.where });
|
||||
}
|
||||
|
||||
rmSync(join(this.storePath, 'chats', query.where.owner, query.where.id + '.josn'), {
|
||||
force: true,
|
||||
recursive: true,
|
||||
});
|
||||
|
||||
return { deleted: { chatId: query.where.id } };
|
||||
} catch (error) {
|
||||
return { error: error?.toString() };
|
||||
}
|
||||
}
|
||||
}
|
88
src/whatsapp/repository/contact.repository.ts
Normal file
@ -0,0 +1,88 @@
|
||||
import { opendirSync, readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { ConfigService } from '../../config/env.config';
|
||||
import { ContactRaw, IContactModel } from '../models';
|
||||
import { IInsert, Repository } from '../abstract/abstract.repository';
|
||||
|
||||
export class ContactQuery {
|
||||
where: ContactRaw;
|
||||
}
|
||||
|
||||
export class ContactRepository extends Repository {
|
||||
constructor(
|
||||
private readonly contactModel: IContactModel,
|
||||
private readonly configService: ConfigService,
|
||||
) {
|
||||
super(configService);
|
||||
}
|
||||
|
||||
public async insert(data: ContactRaw[], saveDb = false): Promise<IInsert> {
|
||||
if (data.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (this.dbSettings.ENABLED && saveDb) {
|
||||
const insert = await this.contactModel.insertMany([...data]);
|
||||
return { insertCount: insert.length };
|
||||
}
|
||||
|
||||
data.forEach((contact) => {
|
||||
this.writeStore({
|
||||
path: join(this.storePath, 'contacts', contact.owner),
|
||||
fileName: contact.id,
|
||||
data: contact,
|
||||
});
|
||||
});
|
||||
|
||||
return { insertCount: data.length };
|
||||
} catch (error) {
|
||||
return error;
|
||||
} finally {
|
||||
data = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
public async find(query: ContactQuery): Promise<ContactRaw[]> {
|
||||
try {
|
||||
if (this.dbSettings.ENABLED) {
|
||||
return await this.contactModel.find({ ...query.where });
|
||||
}
|
||||
const contacts: ContactRaw[] = [];
|
||||
if (query?.where?.id) {
|
||||
contacts.push(
|
||||
JSON.parse(
|
||||
readFileSync(
|
||||
join(
|
||||
this.storePath,
|
||||
'contacts',
|
||||
query.where.owner,
|
||||
query.where.id + '.json',
|
||||
),
|
||||
{ encoding: 'utf-8' },
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
const openDir = opendirSync(join(this.storePath, 'contacts', query.where.owner), {
|
||||
encoding: 'utf-8',
|
||||
});
|
||||
for await (const dirent of openDir) {
|
||||
if (dirent.isFile()) {
|
||||
contacts.push(
|
||||
JSON.parse(
|
||||
readFileSync(
|
||||
join(this.storePath, 'contacts', query.where.owner, dirent.name),
|
||||
{ encoding: 'utf-8' },
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return contacts;
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
129
src/whatsapp/repository/message.repository.ts
Normal file
@ -0,0 +1,129 @@
|
||||
import { ConfigService } from '../../config/env.config';
|
||||
import { join } from 'path';
|
||||
import { IMessageModel, MessageRaw } from '../models';
|
||||
import { IInsert, Repository } from '../abstract/abstract.repository';
|
||||
import { opendirSync, readFileSync } from 'fs';
|
||||
|
||||
export class MessageQuery {
|
||||
where: MessageRaw;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export class MessageRepository extends Repository {
|
||||
constructor(
|
||||
private readonly messageModel: IMessageModel,
|
||||
private readonly configService: ConfigService,
|
||||
) {
|
||||
super(configService);
|
||||
}
|
||||
|
||||
public async insert(data: MessageRaw[], saveDb = false): Promise<IInsert> {
|
||||
if (!Array.isArray(data) || data.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (this.dbSettings.ENABLED && saveDb) {
|
||||
const cleanedData = data.map((obj) => {
|
||||
const cleanedObj = { ...obj };
|
||||
if ('extendedTextMessage' in obj.message) {
|
||||
const extendedTextMessage = obj.message.extendedTextMessage as {
|
||||
contextInfo?: {
|
||||
mentionedJid?: any;
|
||||
};
|
||||
};
|
||||
|
||||
if (typeof extendedTextMessage === 'object' && extendedTextMessage !== null) {
|
||||
if ('contextInfo' in extendedTextMessage) {
|
||||
delete extendedTextMessage.contextInfo?.mentionedJid;
|
||||
extendedTextMessage.contextInfo = {};
|
||||
}
|
||||
}
|
||||
}
|
||||
return cleanedObj;
|
||||
});
|
||||
|
||||
const insert = await this.messageModel.insertMany([...cleanedData]);
|
||||
return { insertCount: insert.length };
|
||||
}
|
||||
|
||||
if (saveDb) {
|
||||
data.forEach((msg) =>
|
||||
this.writeStore<MessageRaw>({
|
||||
path: join(this.storePath, 'messages', msg.owner),
|
||||
fileName: msg.key.id,
|
||||
data: msg,
|
||||
}),
|
||||
);
|
||||
|
||||
return { insertCount: data.length };
|
||||
}
|
||||
|
||||
return { insertCount: 0 };
|
||||
} catch (error) {
|
||||
console.log('ERROR: ', error);
|
||||
return error;
|
||||
} finally {
|
||||
data = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
public async find(query: MessageQuery) {
|
||||
try {
|
||||
if (this.dbSettings.ENABLED) {
|
||||
if (query?.where?.key) {
|
||||
for (const [k, v] of Object.entries(query.where.key)) {
|
||||
query.where['key.' + k] = v;
|
||||
}
|
||||
delete query?.where?.key;
|
||||
}
|
||||
return await this.messageModel
|
||||
.find({ ...query.where })
|
||||
.sort({ messageTimestamp: -1 })
|
||||
.limit(query?.limit ?? 0);
|
||||
}
|
||||
|
||||
const messages: MessageRaw[] = [];
|
||||
if (query?.where?.key?.id) {
|
||||
messages.push(
|
||||
JSON.parse(
|
||||
readFileSync(
|
||||
join(
|
||||
this.storePath,
|
||||
'messages',
|
||||
query.where.owner,
|
||||
query.where.key.id + '.json',
|
||||
),
|
||||
{ encoding: 'utf-8' },
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
const openDir = opendirSync(join(this.storePath, 'messages', query.where.owner), {
|
||||
encoding: 'utf-8',
|
||||
});
|
||||
|
||||
for await (const dirent of openDir) {
|
||||
if (dirent.isFile()) {
|
||||
messages.push(
|
||||
JSON.parse(
|
||||
readFileSync(
|
||||
join(this.storePath, 'messages', query.where.owner, dirent.name),
|
||||
{ encoding: 'utf-8' },
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return messages
|
||||
.sort((x, y) => {
|
||||
return (y.messageTimestamp as number) - (x.messageTimestamp as number);
|
||||
})
|
||||
.splice(0, query?.limit ?? messages.length);
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
96
src/whatsapp/repository/messageUp.repository.ts
Normal file
@ -0,0 +1,96 @@
|
||||
import { ConfigService } from '../../config/env.config';
|
||||
import { IMessageUpModel, MessageUpdateRaw } from '../models';
|
||||
import { IInsert, Repository } from '../abstract/abstract.repository';
|
||||
import { join } from 'path';
|
||||
import { opendirSync, readFileSync } from 'fs';
|
||||
|
||||
export class MessageUpQuery {
|
||||
where: MessageUpdateRaw;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export class MessageUpRepository extends Repository {
|
||||
constructor(
|
||||
private readonly messageUpModel: IMessageUpModel,
|
||||
private readonly configService: ConfigService,
|
||||
) {
|
||||
super(configService);
|
||||
}
|
||||
|
||||
public async insert(data: MessageUpdateRaw[], saveDb?: boolean): Promise<IInsert> {
|
||||
if (data.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (this.dbSettings.ENABLED && saveDb) {
|
||||
const insert = await this.messageUpModel.insertMany([...data]);
|
||||
return { insertCount: insert.length };
|
||||
}
|
||||
|
||||
data.forEach((update) => {
|
||||
this.writeStore<MessageUpdateRaw>({
|
||||
path: join(this.storePath, 'message-up', update.owner),
|
||||
fileName: update.id,
|
||||
data: update,
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
public async find(query: MessageUpQuery) {
|
||||
try {
|
||||
if (this.dbSettings.ENABLED) {
|
||||
return await this.messageUpModel
|
||||
.find({ ...query.where })
|
||||
.sort({ datetime: -1 })
|
||||
.limit(query?.limit ?? 0);
|
||||
}
|
||||
|
||||
const messageUpdate: MessageUpdateRaw[] = [];
|
||||
if (query?.where?.id) {
|
||||
messageUpdate.push(
|
||||
JSON.parse(
|
||||
readFileSync(
|
||||
join(
|
||||
this.storePath,
|
||||
'message-up',
|
||||
query.where.owner,
|
||||
query.where.id + '.json',
|
||||
),
|
||||
{ encoding: 'utf-8' },
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
const openDir = opendirSync(
|
||||
join(this.storePath, 'message-up', query.where.owner),
|
||||
{ encoding: 'utf-8' },
|
||||
);
|
||||
|
||||
for await (const dirent of openDir) {
|
||||
if (dirent.isFile()) {
|
||||
messageUpdate.push(
|
||||
JSON.parse(
|
||||
readFileSync(
|
||||
join(this.storePath, 'message-up', query.where.owner, dirent.name),
|
||||
{ encoding: 'utf-8' },
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return messageUpdate
|
||||
.sort((x, y) => {
|
||||
return y.datetime - x.datetime;
|
||||
})
|
||||
.splice(0, query?.limit ?? messageUpdate.length);
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
27
src/whatsapp/repository/repository.manager.ts
Normal file
@ -0,0 +1,27 @@
|
||||
import { MessageRepository } from './message.repository';
|
||||
import { ChatRepository } from './chat.repository';
|
||||
import { ContactRepository } from './contact.repository';
|
||||
import { MessageUpRepository } from './messageUp.repository';
|
||||
import { MongoClient } from 'mongodb';
|
||||
import { WebhookRepository } from './webhook.repository';
|
||||
import { AuthRepository } from './auth.repository';
|
||||
|
||||
export class RepositoryBroker {
|
||||
constructor(
|
||||
public readonly message: MessageRepository,
|
||||
public readonly chat: ChatRepository,
|
||||
public readonly contact: ContactRepository,
|
||||
public readonly messageUpdate: MessageUpRepository,
|
||||
public readonly webhook: WebhookRepository,
|
||||
public readonly auth: AuthRepository,
|
||||
dbServer?: MongoClient,
|
||||
) {
|
||||
this.dbClient = dbServer;
|
||||
}
|
||||
|
||||
private dbClient?: MongoClient;
|
||||
|
||||
public get dbServer() {
|
||||
return this.dbClient;
|
||||
}
|
||||
}
|
53
src/whatsapp/repository/webhook.repository.ts
Normal file
@ -0,0 +1,53 @@
|
||||
import { IInsert, Repository } from '../abstract/abstract.repository';
|
||||
import { ConfigService } from '../../config/env.config';
|
||||
import { join } from 'path';
|
||||
import { readFileSync } from 'fs';
|
||||
import { IWebhookModel, WebhookRaw } from '../models';
|
||||
|
||||
export class WebhookRepository extends Repository {
|
||||
constructor(
|
||||
private readonly webhookModel: IWebhookModel,
|
||||
private readonly configService: ConfigService,
|
||||
) {
|
||||
super(configService);
|
||||
}
|
||||
|
||||
public async create(data: WebhookRaw, instance: string): Promise<IInsert> {
|
||||
try {
|
||||
if (this.dbSettings.ENABLED) {
|
||||
const insert = await this.webhookModel.replaceOne(
|
||||
{ _id: instance },
|
||||
{ ...data },
|
||||
{ upsert: true },
|
||||
);
|
||||
return { insertCount: insert.modifiedCount };
|
||||
}
|
||||
|
||||
this.writeStore<WebhookRaw>({
|
||||
path: join(this.storePath, 'webhook'),
|
||||
fileName: instance,
|
||||
data,
|
||||
});
|
||||
|
||||
return { insertCount: 1 };
|
||||
} catch (error) {
|
||||
return error;
|
||||
}
|
||||
}
|
||||
|
||||
public async find(instance: string): Promise<WebhookRaw> {
|
||||
try {
|
||||
if (this.dbSettings.ENABLED) {
|
||||
return await this.webhookModel.findOne({ _id: instance });
|
||||
}
|
||||
|
||||
return JSON.parse(
|
||||
readFileSync(join(this.storePath, 'webhook', instance + '.json'), {
|
||||
encoding: 'utf-8',
|
||||
}),
|
||||
) as WebhookRaw;
|
||||
} catch (error) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
}
|
198
src/whatsapp/routers/chat.router.ts
Normal file
@ -0,0 +1,198 @@
|
||||
import { RequestHandler, Router } from 'express';
|
||||
import {
|
||||
archiveChatSchema,
|
||||
contactValidateSchema,
|
||||
deleteMessageSchema,
|
||||
messageUpSchema,
|
||||
messageValidateSchema,
|
||||
profileNameSchema,
|
||||
profilePictureSchema,
|
||||
profileStatusSchema,
|
||||
readMessageSchema,
|
||||
whatsappNumberSchema,
|
||||
} from '../../validate/validate.schema';
|
||||
import {
|
||||
ArchiveChatDto,
|
||||
DeleteMessage,
|
||||
NumberDto,
|
||||
ProfileNameDto,
|
||||
ProfilePictureDto,
|
||||
ProfileStatusDto,
|
||||
ReadMessageDto,
|
||||
WhatsAppNumberDto,
|
||||
} from '../dto/chat.dto';
|
||||
import { ContactQuery } from '../repository/contact.repository';
|
||||
import { MessageQuery } from '../repository/message.repository';
|
||||
import { chatController } from '../whatsapp.module';
|
||||
import { RouterBroker } from '../abstract/abstract.router';
|
||||
import { HttpStatus } from './index.router';
|
||||
import { MessageUpQuery } from '../repository/messageUp.repository';
|
||||
import { proto } from '@evolution/base';
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
|
||||
export class ChatRouter extends RouterBroker {
|
||||
constructor(...guards: RequestHandler[]) {
|
||||
super();
|
||||
this.router
|
||||
.post(this.routerPath('whatsappNumbers'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<WhatsAppNumberDto>({
|
||||
request: req,
|
||||
schema: whatsappNumberSchema,
|
||||
ClassRef: WhatsAppNumberDto,
|
||||
execute: (instance, data) => chatController.whatsappNumber(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.put(this.routerPath('markMessageAsRead'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<ReadMessageDto>({
|
||||
request: req,
|
||||
schema: readMessageSchema,
|
||||
ClassRef: ReadMessageDto,
|
||||
execute: (instance, data) => chatController.readMessage(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.put(this.routerPath('archiveChat'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<ArchiveChatDto>({
|
||||
request: req,
|
||||
schema: archiveChatSchema,
|
||||
ClassRef: ArchiveChatDto,
|
||||
execute: (instance, data) => chatController.archiveChat(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.delete(
|
||||
this.routerPath('deleteMessageForEveryone'),
|
||||
...guards,
|
||||
async (req, res) => {
|
||||
const response = await this.dataValidate<DeleteMessage>({
|
||||
request: req,
|
||||
schema: deleteMessageSchema,
|
||||
ClassRef: DeleteMessage,
|
||||
execute: (instance, data) => chatController.deleteMessage(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
},
|
||||
)
|
||||
.post(this.routerPath('fetchProfilePictureUrl'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<NumberDto>({
|
||||
request: req,
|
||||
schema: profilePictureSchema,
|
||||
ClassRef: NumberDto,
|
||||
execute: (instance, data) => chatController.fetchProfilePicture(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.post(this.routerPath('findContacts'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<ContactQuery>({
|
||||
request: req,
|
||||
schema: contactValidateSchema,
|
||||
ClassRef: ContactQuery,
|
||||
execute: (instance, data) => chatController.fetchContacts(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.post(this.routerPath('getBase64FromMediaMessage'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<proto.IWebMessageInfo>({
|
||||
request: req,
|
||||
schema: null,
|
||||
ClassRef: Object,
|
||||
execute: (instance, data) =>
|
||||
chatController.getBase64FromMediaMessage(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.post(this.routerPath('findMessages'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<MessageQuery>({
|
||||
request: req,
|
||||
schema: messageValidateSchema,
|
||||
ClassRef: MessageQuery,
|
||||
execute: (instance, data) => chatController.fetchMessages(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.post(this.routerPath('findStatusMessage'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<MessageUpQuery>({
|
||||
request: req,
|
||||
schema: messageUpSchema,
|
||||
ClassRef: MessageUpQuery,
|
||||
execute: (instance, data) => chatController.fetchStatusMessage(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.get(this.routerPath('findChats'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<InstanceDto>({
|
||||
request: req,
|
||||
schema: null,
|
||||
ClassRef: InstanceDto,
|
||||
execute: (instance) => chatController.fetchChats(instance),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
// Profile routes
|
||||
.post(this.routerPath('getBusinessProfile'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<ProfilePictureDto>({
|
||||
request: req,
|
||||
schema: profilePictureSchema,
|
||||
ClassRef: ProfilePictureDto,
|
||||
execute: (instance, data) => chatController.getBusinessProfile(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.post(this.routerPath('updateProfileName'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<ProfileNameDto>({
|
||||
request: req,
|
||||
schema: profileNameSchema,
|
||||
ClassRef: ProfileNameDto,
|
||||
execute: (instance, data) => chatController.updateProfileName(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.post(this.routerPath('updateProfileStatus'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<ProfileStatusDto>({
|
||||
request: req,
|
||||
schema: profileStatusSchema,
|
||||
ClassRef: ProfileStatusDto,
|
||||
execute: (instance, data) => chatController.updateProfileStatus(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.put(this.routerPath('updateProfilePicture'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<ProfilePictureDto>({
|
||||
request: req,
|
||||
schema: profilePictureSchema,
|
||||
ClassRef: ProfilePictureDto,
|
||||
execute: (instance, data) =>
|
||||
chatController.updateProfilePicture(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.delete(this.routerPath('removeProfilePicture'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<ProfilePictureDto>({
|
||||
request: req,
|
||||
schema: profilePictureSchema,
|
||||
ClassRef: ProfilePictureDto,
|
||||
execute: (instance, data) =>
|
||||
chatController.removeProfilePicture(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
});
|
||||
}
|
||||
|
||||
public readonly router = Router();
|
||||
}
|
141
src/whatsapp/routers/group.router.ts
Normal file
@ -0,0 +1,141 @@
|
||||
import { RequestHandler, Router } from 'express';
|
||||
import {
|
||||
createGroupSchema,
|
||||
groupJidSchema,
|
||||
updateParticipantsSchema,
|
||||
updateSettingsSchema,
|
||||
toggleEphemeralSchema,
|
||||
updateGroupPicture,
|
||||
groupInviteSchema,
|
||||
} from '../../validate/validate.schema';
|
||||
import { RouterBroker } from '../abstract/abstract.router';
|
||||
import {
|
||||
CreateGroupDto,
|
||||
GroupInvite,
|
||||
GroupJid,
|
||||
GroupPictureDto,
|
||||
GroupUpdateParticipantDto,
|
||||
GroupUpdateSettingDto,
|
||||
GroupToggleEphemeralDto,
|
||||
} from '../dto/group.dto';
|
||||
import { groupController } from '../whatsapp.module';
|
||||
import { HttpStatus } from './index.router';
|
||||
|
||||
export class GroupRouter extends RouterBroker {
|
||||
constructor(...guards: RequestHandler[]) {
|
||||
super();
|
||||
this.router
|
||||
.post(this.routerPath('create'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<CreateGroupDto>({
|
||||
request: req,
|
||||
schema: createGroupSchema,
|
||||
ClassRef: CreateGroupDto,
|
||||
execute: (instance, data) => groupController.createGroup(instance, data),
|
||||
});
|
||||
|
||||
res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.put(this.routerPath('updateGroupPicture'), ...guards, async (req, res) => {
|
||||
const response = await this.groupValidate<GroupPictureDto>({
|
||||
request: req,
|
||||
schema: updateGroupPicture,
|
||||
ClassRef: GroupPictureDto,
|
||||
execute: (instance, data) => groupController.updateGroupPicture(instance, data),
|
||||
});
|
||||
|
||||
res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.get(this.routerPath('findGroupInfos'), ...guards, async (req, res) => {
|
||||
const response = await this.groupValidate<GroupJid>({
|
||||
request: req,
|
||||
schema: groupJidSchema,
|
||||
ClassRef: GroupJid,
|
||||
execute: (instance, data) => groupController.findGroupInfo(instance, data),
|
||||
});
|
||||
|
||||
res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.get(this.routerPath('participants'), ...guards, async (req, res) => {
|
||||
const response = await this.groupValidate<GroupJid>({
|
||||
request: req,
|
||||
schema: groupJidSchema,
|
||||
ClassRef: GroupJid,
|
||||
execute: (instance, data) => groupController.findParticipants(instance, data),
|
||||
});
|
||||
|
||||
res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.get(this.routerPath('inviteCode'), ...guards, async (req, res) => {
|
||||
const response = await this.groupValidate<GroupJid>({
|
||||
request: req,
|
||||
schema: groupJidSchema,
|
||||
ClassRef: GroupJid,
|
||||
execute: (instance, data) => groupController.inviteCode(instance, data),
|
||||
});
|
||||
|
||||
res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.get(this.routerPath('inviteInfo'), ...guards, async (req, res) => {
|
||||
const response = await this.inviteCodeValidate<GroupInvite>({
|
||||
request: req,
|
||||
schema: groupInviteSchema,
|
||||
ClassRef: GroupInvite,
|
||||
execute: (instance, data) => groupController.inviteInfo(instance, data),
|
||||
});
|
||||
|
||||
res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.put(this.routerPath('revokeInviteCode'), ...guards, async (req, res) => {
|
||||
const response = await this.groupValidate<GroupJid>({
|
||||
request: req,
|
||||
schema: groupJidSchema,
|
||||
ClassRef: GroupJid,
|
||||
execute: (instance, data) => groupController.revokeInviteCode(instance, data),
|
||||
});
|
||||
|
||||
res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.put(this.routerPath('updateParticipant'), ...guards, async (req, res) => {
|
||||
const response = await this.groupValidate<GroupUpdateParticipantDto>({
|
||||
request: req,
|
||||
schema: updateParticipantsSchema,
|
||||
ClassRef: GroupUpdateParticipantDto,
|
||||
execute: (instance, data) => groupController.updateGParticipate(instance, data),
|
||||
});
|
||||
|
||||
res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.put(this.routerPath('updateSetting'), ...guards, async (req, res) => {
|
||||
const response = await this.groupValidate<GroupUpdateSettingDto>({
|
||||
request: req,
|
||||
schema: updateSettingsSchema,
|
||||
ClassRef: GroupUpdateSettingDto,
|
||||
execute: (instance, data) => groupController.updateGSetting(instance, data),
|
||||
});
|
||||
|
||||
res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.put(this.routerPath('toggleEphemeral'), ...guards, async (req, res) => {
|
||||
const response = await this.groupValidate<GroupToggleEphemeralDto>({
|
||||
request: req,
|
||||
schema: toggleEphemeralSchema,
|
||||
ClassRef: GroupToggleEphemeralDto,
|
||||
execute: (instance, data) => groupController.toggleEphemeral(instance, data),
|
||||
});
|
||||
|
||||
res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.delete(this.routerPath('leaveGroup'), ...guards, async (req, res) => {
|
||||
const response = await this.groupValidate<GroupJid>({
|
||||
request: req,
|
||||
schema: {},
|
||||
ClassRef: GroupJid,
|
||||
execute: (instance, data) => groupController.leaveGroup(instance, data),
|
||||
});
|
||||
|
||||
res.status(HttpStatus.OK).json(response);
|
||||
});
|
||||
}
|
||||
|
||||
public readonly router = Router();
|
||||
}
|
37
src/whatsapp/routers/index.router.ts
Normal file
@ -0,0 +1,37 @@
|
||||
import { Router } from 'express';
|
||||
import { Auth, configService } from '../../config/env.config';
|
||||
import { instanceExistsGuard, instanceLoggedGuard } from '../guards/instance.guard';
|
||||
import { authGuard } from '../guards/auth.guard';
|
||||
import { ChatRouter } from './chat.router';
|
||||
import { GroupRouter } from './group.router';
|
||||
import { InstanceRouter } from './instance.router';
|
||||
import { MessageRouter } from './sendMessage.router';
|
||||
import { ViewsRouter } from './view.router';
|
||||
import { WebhookRouter } from './webhook.router';
|
||||
|
||||
enum HttpStatus {
|
||||
OK = 200,
|
||||
CREATED = 201,
|
||||
NOT_FOUND = 404,
|
||||
FORBIDDEN = 403,
|
||||
BAD_REQUEST = 400,
|
||||
UNAUTHORIZED = 401,
|
||||
INTERNAL_SERVER_ERROR = 500,
|
||||
}
|
||||
|
||||
const router = Router();
|
||||
const authType = configService.get<Auth>('AUTHENTICATION').TYPE;
|
||||
const guards = [instanceExistsGuard, instanceLoggedGuard, authGuard[authType]];
|
||||
|
||||
router
|
||||
.use(
|
||||
'/instance',
|
||||
new InstanceRouter(configService, ...guards).router,
|
||||
new ViewsRouter(instanceExistsGuard).router,
|
||||
)
|
||||
.use('/message', new MessageRouter(...guards).router)
|
||||
.use('/chat', new ChatRouter(...guards).router)
|
||||
.use('/group', new GroupRouter(...guards).router)
|
||||
.use('/webhook', new WebhookRouter(...guards).router);
|
||||
|
||||
export { router, HttpStatus };
|
113
src/whatsapp/routers/instance.router.ts
Normal file
@ -0,0 +1,113 @@
|
||||
import { RequestHandler, Router } from 'express';
|
||||
import { instanceNameSchema, oldTokenSchema } from '../../validate/validate.schema';
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
import { instanceController } from '../whatsapp.module';
|
||||
import { RouterBroker } from '../abstract/abstract.router';
|
||||
import { HttpStatus } from './index.router';
|
||||
import { OldToken } from '../services/auth.service';
|
||||
import { Auth, ConfigService, Database } from '../../config/env.config';
|
||||
import { dbserver } from '../../db/db.connect';
|
||||
import { BadRequestException, InternalServerErrorException } from '../../exceptions';
|
||||
|
||||
export class InstanceRouter extends RouterBroker {
|
||||
constructor(readonly configService: ConfigService, ...guards: RequestHandler[]) {
|
||||
super();
|
||||
const auth = configService.get<Auth>('AUTHENTICATION');
|
||||
this.router
|
||||
.post('/create', ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<InstanceDto>({
|
||||
request: req,
|
||||
schema: instanceNameSchema,
|
||||
ClassRef: InstanceDto,
|
||||
execute: (instance) => instanceController.createInstance(instance),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.get(this.routerPath('connect'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<InstanceDto>({
|
||||
request: req,
|
||||
schema: instanceNameSchema,
|
||||
ClassRef: InstanceDto,
|
||||
execute: (instance) => instanceController.connectToWhatsapp(instance),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.get(this.routerPath('connectionState'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<InstanceDto>({
|
||||
request: req,
|
||||
schema: instanceNameSchema,
|
||||
ClassRef: InstanceDto,
|
||||
execute: (instance) => instanceController.connectionState(instance),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.get(this.routerPath('fetchInstances', false), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<InstanceDto>({
|
||||
request: req,
|
||||
schema: null,
|
||||
ClassRef: InstanceDto,
|
||||
execute: (instance) => instanceController.fetchInstances(instance),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.delete(this.routerPath('logout'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<InstanceDto>({
|
||||
request: req,
|
||||
schema: instanceNameSchema,
|
||||
ClassRef: InstanceDto,
|
||||
execute: (instance) => instanceController.logout(instance),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.delete(this.routerPath('delete'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<InstanceDto>({
|
||||
request: req,
|
||||
schema: instanceNameSchema,
|
||||
ClassRef: InstanceDto,
|
||||
execute: (instance) => instanceController.deleteInstance(instance),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
});
|
||||
|
||||
if (auth.TYPE === 'jwt') {
|
||||
this.router.put('/refreshToken', async (req, res) => {
|
||||
const response = await this.dataValidate<OldToken>({
|
||||
request: req,
|
||||
schema: oldTokenSchema,
|
||||
ClassRef: OldToken,
|
||||
execute: (_, data) => instanceController.refreshToken(_, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
});
|
||||
}
|
||||
|
||||
this.router.delete('/deleteDatabase', async (req, res) => {
|
||||
const db = this.configService.get<Database>('DATABASE');
|
||||
if (db.ENABLED) {
|
||||
try {
|
||||
await dbserver.dropDatabase();
|
||||
return res
|
||||
.status(HttpStatus.CREATED)
|
||||
.json({ error: false, message: 'Database deleted' });
|
||||
} catch (error) {
|
||||
return res
|
||||
.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.json({ error: true, message: error.message });
|
||||
}
|
||||
}
|
||||
|
||||
return res
|
||||
.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.json({ error: true, message: 'Database is not enabled' });
|
||||
});
|
||||
}
|
||||
|
||||
public readonly router = Router();
|
||||
}
|
139
src/whatsapp/routers/sendMessage.router.ts
Normal file
@ -0,0 +1,139 @@
|
||||
import { RequestHandler, Router } from 'express';
|
||||
import {
|
||||
audioMessageSchema,
|
||||
buttonMessageSchema,
|
||||
contactMessageSchema,
|
||||
linkPreviewSchema,
|
||||
listMessageSchema,
|
||||
locationMessageSchema,
|
||||
mediaMessageSchema,
|
||||
pollMessageSchema,
|
||||
reactionMessageSchema,
|
||||
textMessageSchema,
|
||||
} from '../../validate/validate.schema';
|
||||
import {
|
||||
SendAudioDto,
|
||||
SendButtonDto,
|
||||
SendContactDto,
|
||||
SendLinkPreviewDto,
|
||||
SendListDto,
|
||||
SendLocationDto,
|
||||
SendMediaDto,
|
||||
SendPollDto,
|
||||
SendReactionDto,
|
||||
SendTextDto,
|
||||
} from '../dto/sendMessage.dto';
|
||||
import { sendMessageController } from '../whatsapp.module';
|
||||
import { RouterBroker } from '../abstract/abstract.router';
|
||||
import { HttpStatus } from './index.router';
|
||||
|
||||
export class MessageRouter extends RouterBroker {
|
||||
constructor(...guards: RequestHandler[]) {
|
||||
super();
|
||||
this.router
|
||||
.post(this.routerPath('sendText'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<SendTextDto>({
|
||||
request: req,
|
||||
schema: textMessageSchema,
|
||||
ClassRef: SendTextDto,
|
||||
execute: (instance, data) => sendMessageController.sendText(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.post(this.routerPath('sendMedia'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<SendMediaDto>({
|
||||
request: req,
|
||||
schema: mediaMessageSchema,
|
||||
ClassRef: SendMediaDto,
|
||||
execute: (instance, data) => sendMessageController.sendMedia(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.post(this.routerPath('sendWhatsAppAudio'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<SendAudioDto>({
|
||||
request: req,
|
||||
schema: audioMessageSchema,
|
||||
ClassRef: SendMediaDto,
|
||||
execute: (instance, data) =>
|
||||
sendMessageController.sendWhatsAppAudio(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.post(this.routerPath('sendButtons'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<SendButtonDto>({
|
||||
request: req,
|
||||
schema: buttonMessageSchema,
|
||||
ClassRef: SendButtonDto,
|
||||
execute: (instance, data) => sendMessageController.sendButtons(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.post(this.routerPath('sendLocation'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<SendLocationDto>({
|
||||
request: req,
|
||||
schema: locationMessageSchema,
|
||||
ClassRef: SendLocationDto,
|
||||
execute: (instance, data) => sendMessageController.sendLocation(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.post(this.routerPath('sendList'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<SendListDto>({
|
||||
request: req,
|
||||
schema: listMessageSchema,
|
||||
ClassRef: SendListDto,
|
||||
execute: (instance, data) => sendMessageController.sendList(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.post(this.routerPath('sendContact'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<SendContactDto>({
|
||||
request: req,
|
||||
schema: contactMessageSchema,
|
||||
ClassRef: SendContactDto,
|
||||
execute: (instance, data) => sendMessageController.sendContact(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.post(this.routerPath('sendReaction'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<SendReactionDto>({
|
||||
request: req,
|
||||
schema: reactionMessageSchema,
|
||||
ClassRef: SendReactionDto,
|
||||
execute: (instance, data) => sendMessageController.sendReaction(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.post(this.routerPath('sendPoll'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<SendPollDto>({
|
||||
request: req,
|
||||
schema: pollMessageSchema,
|
||||
ClassRef: SendPollDto,
|
||||
execute: (instance, data) => sendMessageController.sendPoll(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.post(this.routerPath('sendLinkPreview'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<SendLinkPreviewDto>({
|
||||
request: req,
|
||||
schema: linkPreviewSchema,
|
||||
ClassRef: SendLinkPreviewDto,
|
||||
execute: (instance, data) =>
|
||||
sendMessageController.sendLinkPreview(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
});
|
||||
}
|
||||
|
||||
public readonly router = Router();
|
||||
}
|
15
src/whatsapp/routers/view.router.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { RequestHandler, Router } from 'express';
|
||||
import { RouterBroker } from '../abstract/abstract.router';
|
||||
import { viewsController } from '../whatsapp.module';
|
||||
|
||||
export class ViewsRouter extends RouterBroker {
|
||||
constructor(...guards: RequestHandler[]) {
|
||||
super();
|
||||
|
||||
this.router.get(this.routerPath('qrcode'), ...guards, (req, res) => {
|
||||
return viewsController.qrcode(req, res);
|
||||
});
|
||||
}
|
||||
|
||||
public readonly router = Router();
|
||||
}
|
36
src/whatsapp/routers/webhook.router.ts
Normal file
@ -0,0 +1,36 @@
|
||||
import { RequestHandler, Router } from 'express';
|
||||
import { instanceNameSchema, webhookSchema } from '../../validate/validate.schema';
|
||||
import { RouterBroker } from '../abstract/abstract.router';
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
import { WebhookDto } from '../dto/webhook.dto';
|
||||
import { webhookController } from '../whatsapp.module';
|
||||
import { HttpStatus } from './index.router';
|
||||
|
||||
export class WebhookRouter extends RouterBroker {
|
||||
constructor(...guards: RequestHandler[]) {
|
||||
super();
|
||||
this.router
|
||||
.post(this.routerPath('set'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<WebhookDto>({
|
||||
request: req,
|
||||
schema: webhookSchema,
|
||||
ClassRef: WebhookDto,
|
||||
execute: (instance, data) => webhookController.createWebhook(instance, data),
|
||||
});
|
||||
|
||||
res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.get(this.routerPath('find'), ...guards, async (req, res) => {
|
||||
const response = await this.dataValidate<InstanceDto>({
|
||||
request: req,
|
||||
schema: instanceNameSchema,
|
||||
ClassRef: InstanceDto,
|
||||
execute: (instance) => webhookController.findWebhook(instance),
|
||||
});
|
||||
|
||||
res.status(HttpStatus.OK).json(response);
|
||||
});
|
||||
}
|
||||
|
||||
public readonly router = Router();
|
||||
}
|
136
src/whatsapp/services/auth.service.ts
Normal file
@ -0,0 +1,136 @@
|
||||
import { Auth, ConfigService, Webhook } from '../../config/env.config';
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
import { name as apiName } from '../../../package.json';
|
||||
import { verify, sign } from 'jsonwebtoken';
|
||||
import { Logger } from '../../config/logger.config';
|
||||
import { v4 } from 'uuid';
|
||||
import { isJWT } from 'class-validator';
|
||||
import { BadRequestException } from '../../exceptions';
|
||||
import axios from 'axios';
|
||||
import { WAMonitoringService } from './monitor.service';
|
||||
import { RepositoryBroker } from '../repository/repository.manager';
|
||||
|
||||
export type JwtPayload = {
|
||||
instanceName: string;
|
||||
apiName: string;
|
||||
jwt?: string;
|
||||
apikey?: string;
|
||||
tokenId: string;
|
||||
};
|
||||
|
||||
export class OldToken {
|
||||
oldToken: string;
|
||||
}
|
||||
|
||||
export class AuthService {
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly waMonitor: WAMonitoringService,
|
||||
private readonly repository: RepositoryBroker,
|
||||
) {}
|
||||
|
||||
private readonly logger = new Logger(AuthService.name);
|
||||
|
||||
private async jwt(instance: InstanceDto) {
|
||||
const jwtOpts = this.configService.get<Auth>('AUTHENTICATION').JWT;
|
||||
const token = sign(
|
||||
{
|
||||
instanceName: instance.instanceName,
|
||||
apiName,
|
||||
tokenId: v4(),
|
||||
},
|
||||
jwtOpts.SECRET,
|
||||
{ expiresIn: jwtOpts.EXPIRIN_IN, encoding: 'utf8', subject: 'g-t' },
|
||||
);
|
||||
|
||||
const auth = await this.repository.auth.create({ jwt: token }, instance.instanceName);
|
||||
|
||||
if (auth['error']) {
|
||||
this.logger.error({
|
||||
localError: AuthService.name + '.jwt',
|
||||
error: auth['error'],
|
||||
});
|
||||
throw new BadRequestException('Authentication error', auth['error']?.toString());
|
||||
}
|
||||
|
||||
return { jwt: token };
|
||||
}
|
||||
|
||||
private async apikey(instance: InstanceDto) {
|
||||
const apikey = v4().toUpperCase();
|
||||
|
||||
const auth = await this.repository.auth.create({ apikey }, instance.instanceName);
|
||||
|
||||
if (auth['error']) {
|
||||
this.logger.error({
|
||||
localError: AuthService.name + '.jwt',
|
||||
error: auth['error'],
|
||||
});
|
||||
throw new BadRequestException('Authentication error', auth['error']?.toString());
|
||||
}
|
||||
|
||||
return { apikey };
|
||||
}
|
||||
|
||||
public async generateHash(instance: InstanceDto) {
|
||||
const options = this.configService.get<Auth>('AUTHENTICATION');
|
||||
return (await this[options.TYPE](instance)) as { jwt: string } | { apikey: string };
|
||||
}
|
||||
|
||||
public async refreshToken({ oldToken }: OldToken) {
|
||||
if (!isJWT(oldToken)) {
|
||||
throw new BadRequestException('Invalid "oldToken"');
|
||||
}
|
||||
|
||||
try {
|
||||
const jwtOpts = this.configService.get<Auth>('AUTHENTICATION').JWT;
|
||||
const decode = verify(oldToken, jwtOpts.SECRET, {
|
||||
ignoreExpiration: true,
|
||||
}) as Pick<JwtPayload, 'apiName' | 'instanceName' | 'tokenId'>;
|
||||
|
||||
const tokenStore = await this.repository.auth.find(decode.instanceName);
|
||||
|
||||
const decodeTokenStore = verify(tokenStore.jwt, jwtOpts.SECRET, {
|
||||
ignoreExpiration: true,
|
||||
}) as Pick<JwtPayload, 'apiName' | 'instanceName' | 'tokenId'>;
|
||||
|
||||
if (decode.tokenId !== decodeTokenStore.tokenId) {
|
||||
throw new BadRequestException('Invalid "oldToken"');
|
||||
}
|
||||
|
||||
const token = {
|
||||
jwt: (await this.jwt({ instanceName: decode.instanceName })).jwt,
|
||||
instanceName: decode.instanceName,
|
||||
};
|
||||
|
||||
try {
|
||||
const webhook = await this.repository.webhook.find(decode.instanceName);
|
||||
if (
|
||||
webhook?.enabled &&
|
||||
this.configService.get<Webhook>('WEBHOOK').EVENTS.NEW_JWT_TOKEN
|
||||
) {
|
||||
const httpService = axios.create({ baseURL: webhook.url });
|
||||
await httpService.post(
|
||||
'',
|
||||
{
|
||||
event: 'new.jwt',
|
||||
instance: decode.instanceName,
|
||||
data: token,
|
||||
},
|
||||
{ params: { owner: this.waMonitor.waInstances[decode.instanceName].wuid } },
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
}
|
||||
|
||||
return token;
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
localError: AuthService.name + '.refreshToken',
|
||||
error,
|
||||
});
|
||||
throw new BadRequestException('Invalid "oldToken"');
|
||||
}
|
||||
}
|
||||
}
|
216
src/whatsapp/services/monitor.service.ts
Normal file
@ -0,0 +1,216 @@
|
||||
import { opendirSync, readdirSync, rmSync } from 'fs';
|
||||
import { WAStartupService } from './whatsapp.service';
|
||||
import { INSTANCE_DIR } from '../../config/path.config';
|
||||
import EventEmitter2 from 'eventemitter2';
|
||||
import { join } from 'path';
|
||||
import { Logger } from '../../config/logger.config';
|
||||
import { ConfigService, Database, DelInstance, Redis } from '../../config/env.config';
|
||||
import { RepositoryBroker } from '../repository/repository.manager';
|
||||
import { NotFoundException } from '../../exceptions';
|
||||
import { Db } from 'mongodb';
|
||||
import { RedisCache } from '../../db/redis.client';
|
||||
import { initInstance } from '../whatsapp.module';
|
||||
import { ValidationError } from 'class-validator';
|
||||
|
||||
export class WAMonitoringService {
|
||||
constructor(
|
||||
private readonly eventEmitter: EventEmitter2,
|
||||
private readonly configService: ConfigService,
|
||||
private readonly repository: RepositoryBroker,
|
||||
) {
|
||||
this.removeInstance();
|
||||
this.noConnection();
|
||||
this.delInstanceFiles();
|
||||
|
||||
Object.assign(this.db, configService.get<Database>('DATABASE'));
|
||||
Object.assign(this.redis, configService.get<Redis>('REDIS'));
|
||||
|
||||
this.dbInstance = this.db.ENABLED
|
||||
? this.repository.dbServer?.db(this.db.CONNECTION.DB_PREFIX_NAME + '-instances')
|
||||
: undefined;
|
||||
|
||||
this.redisCache = this.redis.ENABLED ? new RedisCache(this.redis) : undefined;
|
||||
}
|
||||
|
||||
private readonly db: Partial<Database> = {};
|
||||
private readonly redis: Partial<Redis> = {};
|
||||
|
||||
private dbInstance: Db;
|
||||
private redisCache: RedisCache;
|
||||
|
||||
private readonly logger = new Logger(WAMonitoringService.name);
|
||||
public readonly waInstances: Record<string, WAStartupService> = {};
|
||||
|
||||
public delInstanceTime(instance: string) {
|
||||
const time = this.configService.get<DelInstance>('DEL_INSTANCE');
|
||||
if (typeof time === 'number' && time > 0) {
|
||||
setTimeout(() => {
|
||||
if (this.waInstances[instance]?.connectionStatus?.state !== 'open') {
|
||||
delete this.waInstances[instance];
|
||||
}
|
||||
}, 1000 * 60 * time);
|
||||
}
|
||||
}
|
||||
|
||||
public async instanceInfo(instanceName?: string) {
|
||||
if (instanceName && !this.waInstances[instanceName]) {
|
||||
throw new NotFoundException(`Instance "${instanceName}" not found`);
|
||||
}
|
||||
|
||||
const instances: any[] = [];
|
||||
|
||||
for await (const [key, value] of Object.entries(this.waInstances)) {
|
||||
if (value && value.connectionStatus.state === 'open') {
|
||||
instances.push({
|
||||
instance: {
|
||||
instanceName: key,
|
||||
owner: value.wuid,
|
||||
profileName: (await value.getProfileName()) || 'not loaded',
|
||||
profilePictureUrl: value.profilePictureUrl,
|
||||
status: (await value.getProfileStatus()) || '',
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return instances.find((i) => i.instance.instanceName === instanceName) ?? instances;
|
||||
}
|
||||
|
||||
private delInstanceFiles() {
|
||||
setInterval(async () => {
|
||||
if (this.db.ENABLED && this.db.SAVE_DATA.INSTANCE) {
|
||||
const collections = await this.dbInstance.collections();
|
||||
collections.forEach(async (collection) => {
|
||||
const name = collection.namespace.replace(/^[\w-]+./, '');
|
||||
await this.dbInstance.collection(name).deleteMany({
|
||||
$or: [
|
||||
{ _id: { $regex: /^app.state.*/ } },
|
||||
{ _id: { $regex: /^session-.*/ } },
|
||||
],
|
||||
});
|
||||
});
|
||||
} else {
|
||||
const dir = opendirSync(INSTANCE_DIR, { encoding: 'utf-8' });
|
||||
for await (const dirent of dir) {
|
||||
if (dirent.isDirectory()) {
|
||||
const files = readdirSync(join(INSTANCE_DIR, dirent.name), {
|
||||
encoding: 'utf-8',
|
||||
});
|
||||
files.forEach(async (file) => {
|
||||
if (file.match(/^app.state.*/) || file.match(/^session-.*/)) {
|
||||
rmSync(join(INSTANCE_DIR, dirent.name, file), {
|
||||
recursive: true,
|
||||
force: true,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 3600 * 1000 * 2);
|
||||
}
|
||||
|
||||
private async cleaningUp(instanceName: string) {
|
||||
if (this.db.ENABLED && this.db.SAVE_DATA.INSTANCE) {
|
||||
await this.repository.dbServer.connect();
|
||||
const collections: any[] = await this.dbInstance.collections();
|
||||
if (collections.length > 0) {
|
||||
await this.dbInstance.dropCollection(instanceName);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.redis.ENABLED) {
|
||||
this.redisCache.reference = instanceName;
|
||||
await this.redisCache.delAll();
|
||||
return;
|
||||
}
|
||||
rmSync(join(INSTANCE_DIR, instanceName), { recursive: true, force: true });
|
||||
}
|
||||
|
||||
public async loadInstance() {
|
||||
const set = async (name: string) => {
|
||||
const instance = new WAStartupService(
|
||||
this.configService,
|
||||
this.eventEmitter,
|
||||
this.repository,
|
||||
);
|
||||
instance.instanceName = name;
|
||||
await instance.connectToWhatsapp();
|
||||
this.waInstances[name] = instance;
|
||||
};
|
||||
|
||||
try {
|
||||
if (this.redis.ENABLED) {
|
||||
const keys = await this.redisCache.instanceKeys();
|
||||
if (keys?.length > 0) {
|
||||
keys.forEach(async (k) => await set(k.split(':')[1]));
|
||||
} else {
|
||||
initInstance();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.db.ENABLED && this.db.SAVE_DATA.INSTANCE) {
|
||||
await this.repository.dbServer.connect();
|
||||
const collections: any[] = await this.dbInstance.collections();
|
||||
if (collections.length > 0) {
|
||||
collections.forEach(
|
||||
async (coll) => await set(coll.namespace.replace(/^[\w-]+\./, '')),
|
||||
);
|
||||
} else {
|
||||
initInstance();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const dir = opendirSync(INSTANCE_DIR, { encoding: 'utf-8' });
|
||||
for await (const dirent of dir) {
|
||||
if (dirent.isDirectory()) {
|
||||
const files = readdirSync(join(INSTANCE_DIR, dirent.name), {
|
||||
encoding: 'utf-8',
|
||||
});
|
||||
if (files.length === 0) {
|
||||
rmSync(join(INSTANCE_DIR, dirent.name), { recursive: true, force: true });
|
||||
break;
|
||||
}
|
||||
|
||||
await set(dirent.name);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
private removeInstance() {
|
||||
this.eventEmitter.on('remove.instance', async (instanceName: string) => {
|
||||
try {
|
||||
this.waInstances[instanceName] = undefined;
|
||||
} catch {}
|
||||
|
||||
try {
|
||||
this.cleaningUp(instanceName);
|
||||
} finally {
|
||||
this.logger.warn(`Instance "${instanceName}" - REMOVED`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private noConnection() {
|
||||
this.eventEmitter.on('no.connection', async (instanceName) => {
|
||||
try {
|
||||
this.waInstances[instanceName] = undefined;
|
||||
this.cleaningUp(instanceName);
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
localError: 'noConnection',
|
||||
warn: 'Error deleting instance from memory.',
|
||||
error,
|
||||
});
|
||||
} finally {
|
||||
this.logger.warn(`Instance "${instanceName}" - NOT CONNECTION`);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
21
src/whatsapp/services/webhook.service.ts
Normal file
@ -0,0 +1,21 @@
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
import { WebhookDto } from '../dto/webhook.dto';
|
||||
import { WAMonitoringService } from './monitor.service';
|
||||
|
||||
export class WebhookService {
|
||||
constructor(private readonly waMonitor: WAMonitoringService) {}
|
||||
|
||||
public create(instance: InstanceDto, data: WebhookDto) {
|
||||
this.waMonitor.waInstances[instance.instanceName].setWebhook(data);
|
||||
|
||||
return { webhook: { ...instance, webhook: data } };
|
||||
}
|
||||
|
||||
public async find(instance: InstanceDto): Promise<WebhookDto> {
|
||||
try {
|
||||
return await this.waMonitor.waInstances[instance.instanceName].findWebhook();
|
||||
} catch (error) {
|
||||
return { enabled: null, url: '' };
|
||||
}
|
||||
}
|
||||
}
|
1663
src/whatsapp/services/whatsapp.service.ts
Normal file
67
src/whatsapp/types/wa.types.ts
Normal file
@ -0,0 +1,67 @@
|
||||
/* eslint-disable @typescript-eslint/no-namespace */
|
||||
import { AuthenticationState, WAConnectionState } from '@evolution/base';
|
||||
|
||||
export enum Events {
|
||||
APPLICATION_STARTUP = 'application.startup',
|
||||
QRCODE_UPDATED = 'qrcode.updated',
|
||||
CONNECTION_UPDATE = 'connection.update',
|
||||
STATUS_INSTANCE = 'status.instance',
|
||||
MESSAGES_SET = 'messages.set',
|
||||
MESSAGES_UPSERT = 'messages.upsert',
|
||||
MESSAGES_UPDATE = 'messages.update',
|
||||
SEND_MESSAGE = 'send.message',
|
||||
CONTACTS_SET = 'contacts.set',
|
||||
CONTACTS_UPSERT = 'contacts.upsert',
|
||||
CONTACTS_UPDATE = 'contacts.update',
|
||||
PRESENCE_UPDATE = 'presence.update',
|
||||
CHATS_SET = 'chats.set',
|
||||
CHATS_UPDATE = 'chats.update',
|
||||
CHATS_UPSERT = 'chats.upsert',
|
||||
CHATS_DELETE = 'chats.delete',
|
||||
GROUPS_UPSERT = 'groups.upsert',
|
||||
GROUPS_UPDATE = 'groups.update',
|
||||
GROUP_PARTICIPANTS_UPDATE = 'group-participants.update',
|
||||
}
|
||||
|
||||
export declare namespace wa {
|
||||
export type QrCode = { count?: number; base64?: string; code?: string };
|
||||
export type Instance = {
|
||||
qrcode?: QrCode;
|
||||
authState?: { state: AuthenticationState; saveCreds: () => void };
|
||||
name?: string;
|
||||
wuid?: string;
|
||||
profileName?: string;
|
||||
profilePictureUrl?: string;
|
||||
};
|
||||
|
||||
export type LocalWebHook = { enabled?: boolean; url?: string };
|
||||
|
||||
export type StateConnection = {
|
||||
instance?: string;
|
||||
state?: WAConnectionState | 'refused';
|
||||
statusReason?: number;
|
||||
};
|
||||
|
||||
export type StatusMessage =
|
||||
| 'ERROR'
|
||||
| 'PENDING'
|
||||
| 'SERVER_ACK'
|
||||
| 'DELIVERY_ACK'
|
||||
| 'READ'
|
||||
| 'PLAYED';
|
||||
}
|
||||
|
||||
export const TypeMediaMessage = [
|
||||
'imageMessage',
|
||||
'documentMessage',
|
||||
'audioMessage',
|
||||
'videoMessage',
|
||||
'stickerMessage',
|
||||
];
|
||||
|
||||
export const MessageSubtype = [
|
||||
'ephemeralMessage',
|
||||
'documentWithCaptionMessage',
|
||||
'viewOnceMessage',
|
||||
'viewOnceMessageV2',
|
||||
];
|
143
src/whatsapp/whatsapp.module.ts
Normal file
@ -0,0 +1,143 @@
|
||||
import { Auth, configService } from '../config/env.config';
|
||||
import { Logger } from '../config/logger.config';
|
||||
import { eventEmitter } from '../config/event.config';
|
||||
import { MessageRepository } from './repository/message.repository';
|
||||
import { WAMonitoringService } from './services/monitor.service';
|
||||
import { ChatRepository } from './repository/chat.repository';
|
||||
import { ContactRepository } from './repository/contact.repository';
|
||||
import { MessageUpRepository } from './repository/messageUp.repository';
|
||||
import { ChatController } from './controllers/chat.controller';
|
||||
import { InstanceController } from './controllers/instance.controller';
|
||||
import { SendMessageController } from './controllers/sendMessage.controller';
|
||||
import { AuthService } from './services/auth.service';
|
||||
import { GroupController } from './controllers/group.controller';
|
||||
import { ViewsController } from './controllers/views.controller';
|
||||
import { WebhookService } from './services/webhook.service';
|
||||
import { WebhookController } from './controllers/webhook.controller';
|
||||
import { RepositoryBroker } from './repository/repository.manager';
|
||||
import {
|
||||
AuthModel,
|
||||
ChatModel,
|
||||
ContactModel,
|
||||
MessageModel,
|
||||
MessageUpModel,
|
||||
} from './models';
|
||||
import { dbserver } from '../db/db.connect';
|
||||
import { WebhookRepository } from './repository/webhook.repository';
|
||||
import { WebhookModel } from './models/webhook.model';
|
||||
import { AuthRepository } from './repository/auth.repository';
|
||||
import { WAStartupService } from './services/whatsapp.service';
|
||||
import { delay } from '@evolution/base';
|
||||
import { Events } from './types/wa.types';
|
||||
|
||||
const logger = new Logger('WA MODULE');
|
||||
|
||||
const messageRepository = new MessageRepository(MessageModel, configService);
|
||||
const chatRepository = new ChatRepository(ChatModel, configService);
|
||||
const contactRepository = new ContactRepository(ContactModel, configService);
|
||||
const messageUpdateRepository = new MessageUpRepository(MessageUpModel, configService);
|
||||
const webhookRepository = new WebhookRepository(WebhookModel, configService);
|
||||
const authRepository = new AuthRepository(AuthModel, configService);
|
||||
|
||||
export const repository = new RepositoryBroker(
|
||||
messageRepository,
|
||||
chatRepository,
|
||||
contactRepository,
|
||||
messageUpdateRepository,
|
||||
webhookRepository,
|
||||
authRepository,
|
||||
dbserver?.getClient(),
|
||||
);
|
||||
|
||||
export const waMonitor = new WAMonitoringService(eventEmitter, configService, repository);
|
||||
|
||||
const authService = new AuthService(configService, waMonitor, repository);
|
||||
|
||||
const webhookService = new WebhookService(waMonitor);
|
||||
|
||||
export const webhookController = new WebhookController(webhookService);
|
||||
|
||||
export const instanceController = new InstanceController(
|
||||
waMonitor,
|
||||
configService,
|
||||
repository,
|
||||
eventEmitter,
|
||||
authService,
|
||||
webhookService,
|
||||
);
|
||||
export const viewsController = new ViewsController(waMonitor, configService);
|
||||
export const sendMessageController = new SendMessageController(waMonitor);
|
||||
export const chatController = new ChatController(waMonitor);
|
||||
export const groupController = new GroupController(waMonitor);
|
||||
|
||||
export async function initInstance() {
|
||||
const instance = new WAStartupService(configService, eventEmitter, repository);
|
||||
|
||||
const mode = configService.get<Auth>('AUTHENTICATION').INSTANCE.MODE;
|
||||
|
||||
instance.sendDataWebhook(
|
||||
Events.APPLICATION_STARTUP,
|
||||
{
|
||||
message: 'Application startup',
|
||||
mode,
|
||||
},
|
||||
false,
|
||||
);
|
||||
|
||||
if (mode === 'container') {
|
||||
const instanceName = configService.get<Auth>('AUTHENTICATION').INSTANCE.NAME;
|
||||
const instanceWebhook =
|
||||
configService.get<Auth>('AUTHENTICATION').INSTANCE.WEBHOOK_URL;
|
||||
|
||||
instance.instanceName = instanceName;
|
||||
|
||||
waMonitor.waInstances[instance.instanceName] = instance;
|
||||
waMonitor.delInstanceTime(instance.instanceName);
|
||||
|
||||
const hash = await authService.generateHash({
|
||||
instanceName: instance.instanceName,
|
||||
});
|
||||
|
||||
if (instanceWebhook) {
|
||||
try {
|
||||
webhookService.create(instance, { enabled: true, url: instanceWebhook });
|
||||
} catch (error) {
|
||||
this.logger.log(error);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const state = instance.connectionStatus?.state;
|
||||
|
||||
switch (state) {
|
||||
case 'close':
|
||||
await instance.connectToWhatsapp();
|
||||
await delay(2000);
|
||||
return instance.qrCode;
|
||||
case 'connecting':
|
||||
return instance.qrCode;
|
||||
default:
|
||||
return await this.connectionState({ instanceName });
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.log(error);
|
||||
}
|
||||
|
||||
const result = {
|
||||
instance: {
|
||||
instanceName: instance.instanceName,
|
||||
status: 'created',
|
||||
},
|
||||
hash,
|
||||
webhook: instanceWebhook,
|
||||
};
|
||||
|
||||
logger.info(result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
logger.info('Module - ON');
|
0
store/auth/apikey/.gitkeep
Normal file
0
store/auth/jwt/.gitkeep
Normal file
0
store/chats/.gitkeep
Normal file
0
store/contacts/.gitkeep
Normal file
0
store/message-up/.gitkeep
Normal file
0
store/messages/.gitkeep
Normal file
0
store/webhook/.gitkeep
Normal file
22
tsconfig.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"experimentalDecorators": true,
|
||||
"emitDecoratorMetadata": true,
|
||||
"declaration": true,
|
||||
"target": "ES6",
|
||||
"module": "commonjs",
|
||||
"rootDir": "./",
|
||||
"resolveJsonModule": true,
|
||||
"removeComments": true,
|
||||
"outDir": "./dist",
|
||||
"noEmitOnError": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"strict": false,
|
||||
"skipLibCheck": true,
|
||||
"strictNullChecks": false,
|
||||
"incremental": true,
|
||||
"noImplicitAny": false
|
||||
},
|
||||
"exclude": ["node_modules", "./test", "./dist", "./prisma"]
|
||||
}
|
82
views/qrcode.hbs
Normal file
@ -0,0 +1,82 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="pt-br">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
|
||||
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" 'unsafe-inline' crossorigin="anonymous">
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
|
||||
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
|
||||
crossorigin="anonymous"></script>
|
||||
<link rel="shortcut icon" href="/images/atendai-logo.png" type="image/x-icon">
|
||||
<style>
|
||||
code {
|
||||
padding: 10px;
|
||||
background-color: whitesmoke;
|
||||
color: rgb(104, 104, 104);
|
||||
}
|
||||
</style>
|
||||
<title>Generate QRCode</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<div id="root" class="container mt-5 mb-5 w-50">
|
||||
|
||||
<div id="display-qrcode">
|
||||
<h2 class="mb-3 text-secondary">Connect to whatsapp</h2>
|
||||
<div class="input-group mb-3">
|
||||
<input id="input-auth" type="text" class="form-control" aria-describedby="btn-qr-g" value="" placeholder="{{type}}">
|
||||
<input id="input-session" type="text" class="form-control" aria-describedby="btn-qr-g" disabled
|
||||
value="{{instanceName}}">
|
||||
<button id="gen-qrcode" class="btn btn-info text-light" type="submit">Generate qrcode</button>
|
||||
</div>
|
||||
<div id="qrcode-img"></div>
|
||||
</div>
|
||||
|
||||
<hr>
|
||||
|
||||
</div>
|
||||
|
||||
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
|
||||
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
|
||||
<script type="module">
|
||||
|
||||
const log = (...data) => console.log(data);
|
||||
|
||||
$('#gen-qrcode').click(() => {
|
||||
|
||||
const keyAuth = '{{type}}' === 'jwt'? 'authorization': 'apikey';
|
||||
const valueAuth = '{{type}}' === 'jwt'? `Bearer ${$('#input-auth').val()}`: $('#input-auth').val()
|
||||
|
||||
$.ajax({
|
||||
url: `/instance/connect/{{instanceName}}`,
|
||||
headers: { [keyAuth]: valueAuth },
|
||||
type: 'GET',
|
||||
success: (qrcode, status) => {
|
||||
$(`#update-qrcode`).remove();
|
||||
$('#qrcode-img')
|
||||
.append(
|
||||
`<div id="update-qrcode" class="card mb-2">
|
||||
<h5 class="card-title text-center text-secondary mt-3">{{name}}</h5>
|
||||
<div class="card-body container d-flex justify-content-center">
|
||||
<img class="img-thumbnail mt-2 w-50" alt="qrcode.png"
|
||||
src="${qrcode.base64}">
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<code class="text-card d-block">${JSON.stringify({ code: qrcode.code })}</code>
|
||||
</div>
|
||||
</div>`
|
||||
);
|
||||
return;
|
||||
},
|
||||
error: (error) => console.log(error),
|
||||
});
|
||||
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|