mirror of
https://github.com/EvolutionAPI/evolution-api.git
synced 2025-12-19 03:42:23 -06:00
Compare commits
175 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d91876974 | ||
|
|
5043ce8405 | ||
|
|
8e65526ce9 | ||
|
|
cae016f40a | ||
|
|
78150d0fc6 | ||
|
|
f95727edbf | ||
|
|
2d9ca15d74 | ||
|
|
cee6498ea0 | ||
|
|
86c603b3a1 | ||
|
|
960efcecd5 | ||
|
|
b36c37bf33 | ||
|
|
cc6adf0ee2 | ||
|
|
6990a2c9c0 | ||
|
|
b60215100e | ||
|
|
b6506dc661 | ||
|
|
03ee40388c | ||
|
|
6ddad8e85a | ||
|
|
555fa606ea | ||
|
|
ca474236b0 | ||
|
|
ebd70fe454 | ||
|
|
91f009a617 | ||
|
|
293f6a39c5 | ||
|
|
38bf859f43 | ||
|
|
1d81c79fe6 | ||
|
|
c55885b366 | ||
|
|
549ecd8801 | ||
|
|
5c6b70f372 | ||
|
|
418ca971fa | ||
|
|
3d6209618b | ||
|
|
05eb58be0e | ||
|
|
b8fe5603fd | ||
|
|
762453c0e3 | ||
|
|
af1b5caa29 | ||
|
|
50b3379d88 | ||
|
|
c9ac5984ec | ||
|
|
29ba63d621 | ||
|
|
2ce64af502 | ||
|
|
28c517a3d5 | ||
|
|
18ebe27bc3 | ||
|
|
0f7a39a08f | ||
|
|
a8121d7fe6 | ||
|
|
b63b7b0b7b | ||
|
|
14ea5d959f | ||
|
|
86b2999fcf | ||
|
|
f5bd11fc19 | ||
|
|
c060d330de | ||
|
|
1e320f7904 | ||
|
|
975b3ee528 | ||
|
|
5b47bc9ef0 | ||
|
|
053a7981d1 | ||
|
|
5f1f025d65 | ||
|
|
dfb003fd72 | ||
|
|
5239e431c2 | ||
|
|
53cc6132f5 | ||
|
|
0bc1b78db9 | ||
|
|
2a9412c81a | ||
|
|
f707cf4109 | ||
|
|
410cfc8bcb | ||
|
|
f1a3fd872f | ||
|
|
fff0ca5c79 | ||
|
|
bd069200ea | ||
|
|
c898f1e62a | ||
|
|
2002e1c38d | ||
|
|
1f817df5f6 | ||
|
|
8eced6c575 | ||
|
|
afcf6eab71 | ||
|
|
9633412ef6 | ||
|
|
8034e7f587 | ||
|
|
5be01e1c18 | ||
|
|
6371773416 | ||
|
|
52230edc5c | ||
|
|
dd123c6a99 | ||
|
|
5b2a0fdcb1 | ||
|
|
9354af3bc7 | ||
|
|
f48f331d43 | ||
|
|
696261d749 | ||
|
|
0e9d036fe0 | ||
|
|
8e19fe2fb5 | ||
|
|
861b690217 | ||
|
|
f7c9541f5e | ||
|
|
05b5ae8a84 | ||
|
|
2e9c14a0a8 | ||
|
|
3350cec589 | ||
|
|
bd7a42646b | ||
|
|
2ae4ddee18 | ||
|
|
2fb6e2b209 | ||
|
|
91f869b136 | ||
|
|
1284a97625 | ||
|
|
3a5cfbf36f | ||
|
|
47b8ecd43b | ||
|
|
25ce1a4689 | ||
|
|
a5156709ab | ||
|
|
fd2d37d862 | ||
|
|
87bf433e9a | ||
|
|
b5ec79daae | ||
|
|
3b19200997 | ||
|
|
0ab040080c | ||
|
|
5719896d18 | ||
|
|
e9e1cb6ebc | ||
|
|
ceee6a7e74 | ||
|
|
ebfc6d4fa5 | ||
|
|
0d62557a15 | ||
|
|
097c09328f | ||
|
|
732103292b | ||
|
|
3191e9b450 | ||
|
|
bf88fdbb31 | ||
|
|
4c3fb5e762 | ||
|
|
e4b6f4ff0d | ||
|
|
ca0b0d4602 | ||
|
|
d7c3779ff7 | ||
|
|
f0d40eea15 | ||
|
|
68dcc1c86a | ||
|
|
f7dcab3736 | ||
|
|
2fcb476c50 | ||
|
|
44a7cd62c8 | ||
|
|
f7f0f8251b | ||
|
|
395b81a6ac | ||
|
|
da06ed1185 | ||
|
|
67afbd6a77 | ||
|
|
8fce53b4af | ||
|
|
65bba23519 | ||
|
|
283b497788 | ||
|
|
8cc1b8daa8 | ||
|
|
9ccdb45a7a | ||
|
|
f78d360c38 | ||
|
|
6144fbe856 | ||
|
|
8446be7646 | ||
|
|
8875ab1e93 | ||
|
|
7c207a50e1 | ||
|
|
dcc32479ff | ||
|
|
09911c472d | ||
|
|
7a0149ee23 | ||
|
|
3ae8cf32b0 | ||
|
|
11cf947bbb | ||
|
|
60a20f61af | ||
|
|
e65c7b6bcf | ||
|
|
80c892aca3 | ||
|
|
39ee266598 | ||
|
|
aa58d7744e | ||
|
|
ea3b0b3712 | ||
|
|
d9d8707123 | ||
|
|
8e9a1e2ba5 | ||
|
|
e29b4865e8 | ||
|
|
4b60ca175d | ||
|
|
2fbbc7b5a9 | ||
|
|
633dbb82d3 | ||
|
|
95907b3cea | ||
|
|
14c210c771 | ||
|
|
00e7fcc46b | ||
|
|
720efcbcbf | ||
|
|
d95791cc18 | ||
|
|
d45b7af3b6 | ||
|
|
0ad3acaf07 | ||
|
|
e27818ecda | ||
|
|
ff21cf4d4c | ||
|
|
dc19c7fdec | ||
|
|
6c8ffd8ec6 | ||
|
|
96fdb210be | ||
|
|
84ad8e0d6e | ||
|
|
53361682f4 | ||
|
|
0ee243f284 | ||
|
|
26ff0b634f | ||
|
|
f44ab0f678 | ||
|
|
1f128747bb | ||
|
|
3bf975d90f | ||
|
|
92f8951be4 | ||
|
|
e071f56767 | ||
|
|
c85619efcf | ||
|
|
27f9ae1e56 | ||
|
|
7449102d95 | ||
|
|
234a2c71b5 | ||
|
|
4dd5533202 | ||
|
|
a4d1740754 | ||
|
|
1a2ea1c38a | ||
|
|
bb974e10f5 |
38
.github/ISSUE_TEMPLATE/-en--bug-report.md
vendored
38
.github/ISSUE_TEMPLATE/-en--bug-report.md
vendored
@@ -1,38 +0,0 @@
|
||||
---
|
||||
name: "[EN] Bug report"
|
||||
about: Create a report to help us improve
|
||||
title: "[EN][BUG]"
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
### Title: [Brief Description of the Bug]
|
||||
|
||||
#### Description:
|
||||
Describe in detail the problem you encountered. Include any relevant context that may help understand the origin of the bug.
|
||||
|
||||
#### Steps to Reproduce:
|
||||
1. List the steps necessary to reproduce the problem.
|
||||
2. Try to be as specific as possible.
|
||||
3. If the problem occurs in a specific scenario, describe it here.
|
||||
|
||||
#### Expected Behavior:
|
||||
Describe what you expected to happen when following the steps above.
|
||||
|
||||
#### Current Behavior:
|
||||
Explain what actually happens when you follow the steps above.
|
||||
|
||||
#### Screenshots/Videos:
|
||||
If possible, add screenshots or videos illustrating the problem. This can be extremely helpful in understanding the issue.
|
||||
|
||||
#### Environment:
|
||||
- **Server:** [e.g., Ubuntu 18.04]
|
||||
- **API Version:** [e.g., 1.5.4]
|
||||
- **Other Hardware/Software Specifications:** [e.g., CPU, GPU]
|
||||
|
||||
#### Submitting Logs:
|
||||
Please attach logs that may be related to the problem. If the logs contain sensitive information, consider sending them privately to one of the project maintainers.
|
||||
|
||||
#### Additional Notes:
|
||||
Include here any other information that you think might be useful in understanding or resolving the bug.
|
||||
107
.github/ISSUE_TEMPLATE/-en--bug-report.yaml
vendored
Normal file
107
.github/ISSUE_TEMPLATE/-en--bug-report.yaml
vendored
Normal file
@@ -0,0 +1,107 @@
|
||||
name: Bug Report
|
||||
description: Create a report to help us improve.
|
||||
labels:
|
||||
- bug
|
||||
- en
|
||||
# - help wanted
|
||||
# Automatically assign the issue to:
|
||||
# assignees: DavidsonGomes
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: terms
|
||||
attributes:
|
||||
label: Welcome!
|
||||
description: |
|
||||
The issue tracker is only for reporting bugs and feature requests.
|
||||
For user-related support questions, please visit:
|
||||
- [Discord](https://evolution-api.com/discord)
|
||||
- [WhatsApp Group](https://evolution-api.com/whatsapp)
|
||||
<br/>
|
||||
|
||||
**DO NOT OPEN AN ISSUE FOR GENERAL SUPPORT QUESTIONS.**
|
||||
|
||||
options:
|
||||
- label: Yes, I have searched for similar issues on [GitHub](https://github.com/EvolutionAPI/evolution-api/issues) and found none.
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: What did you do?
|
||||
description: |
|
||||
How to write a good bug report?
|
||||
|
||||
- Respect the issue template as much as possible.
|
||||
- The title should be short and descriptive.
|
||||
- Explain the conditions that led you to report this issue: the context.
|
||||
- The context should lead to something, an idea or problem you are facing.
|
||||
- Be clear and concise.
|
||||
- Format your messages to help the reader focus on what matters and understand the structure of your message, use [Markdown syntax](https://help.github.com/articles/github-flavored-markdown)
|
||||
placeholder: Describe the problem you encountered in detail.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: What did you expect?
|
||||
placeholder: Describe what you expected to happen.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: What did you observe instead of what you expected?
|
||||
placeholder: Explain what actually happens when you follow the steps above.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Screenshots/Videos
|
||||
placeholder: |
|
||||
If possible, add screenshots or videos that illustrate the problem. This can be extremely helpful in understanding the issue better.
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Which version of the API are you using?
|
||||
description: |
|
||||
Enter the version number found in the `version` property of the **package.json**.
|
||||
placeholder: Paste the version here.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: select
|
||||
attributes:
|
||||
label: What is your environment?
|
||||
options:
|
||||
- Windows
|
||||
- Linux
|
||||
- Mac
|
||||
- Docker
|
||||
- Other
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Other environment specifications
|
||||
placeholder: 'Hardware/Software: [e.g., CPU, GPU]'
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: If applicable, paste the log output
|
||||
description: |
|
||||
Please attach any logs that might be related to the issue.
|
||||
If the logs contain sensitive information, consider sending them privately to one of the project maintainers.
|
||||
placeholder: Paste the application log here.
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Additional Notes
|
||||
description: Include any other information you think might be useful to understand or resolve the bug.
|
||||
validations:
|
||||
required: false
|
||||
28
.github/ISSUE_TEMPLATE/-en--feature-request.md
vendored
28
.github/ISSUE_TEMPLATE/-en--feature-request.md
vendored
@@ -1,28 +0,0 @@
|
||||
---
|
||||
name: "[EN] Feature request"
|
||||
about: Suggest an idea for the API
|
||||
title: "[EN][FEAT]"
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
### Title: [Brief Description of Feature Request]
|
||||
|
||||
#### Detailed Description:
|
||||
Clearly and in detail, describe the functionality you wish to be implemented. Explain how this fits into the context of the project.
|
||||
|
||||
#### Rationale:
|
||||
Explain why this functionality would be useful for the project. This helps in understanding the importance and priority of the request.
|
||||
|
||||
#### Usage Examples:
|
||||
Provide specific examples of how this feature could be used. This can include scenarios or use cases where the feature would be particularly beneficial.
|
||||
|
||||
#### Possible Implementations:
|
||||
If you have ideas on how this feature might be implemented, please share them here. This is not mandatory but can be helpful for the development team.
|
||||
|
||||
#### Impact on the Project:
|
||||
Discuss how this new feature could impact other parts of the project, if applicable.
|
||||
|
||||
#### Additional Notes:
|
||||
Any other information you believe is relevant to your request.
|
||||
86
.github/ISSUE_TEMPLATE/-en--feature-request.yaml
vendored
Normal file
86
.github/ISSUE_TEMPLATE/-en--feature-request.yaml
vendored
Normal file
@@ -0,0 +1,86 @@
|
||||
name: Feature Request
|
||||
description: Suggest ideas for the project.
|
||||
labels:
|
||||
- enhancement
|
||||
- en
|
||||
# Automatically assign the issue to:
|
||||
# assignees: DavidsonGomes
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: terms
|
||||
attributes:
|
||||
label: Welcome!
|
||||
description: '**DO NOT OPEN FOR GENERAL SUPPORT QUESTIONS.**'
|
||||
|
||||
options:
|
||||
- label: Yes, I have searched for similar requests on [GitHub](https://github.com/code-chat-br/whatsapp-api/issues) and found none.
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: What type of feature?
|
||||
description: |
|
||||
How to write a good feature request?
|
||||
|
||||
- Respect the issue template as much as possible.
|
||||
- The title should be short and descriptive.
|
||||
- Explain the conditions that led you to suggest this feature: the context.
|
||||
- The context should lead to something, an idea or problem you are facing.
|
||||
- Be clear and concise.
|
||||
- Format your messages to help the reader focus on what matters and understand the structure of your message, use [Markdown syntax](https://help.github.com/articles/github-flavored-markdown)
|
||||
options:
|
||||
- Integration
|
||||
- Functionality
|
||||
- Endpoint
|
||||
- Database adjustment
|
||||
- Other
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: What is the motivation for the request?
|
||||
description: |
|
||||
What problem does the feature seek to solve?
|
||||
Clearly and in detail describe the functionality you want to be implemented.
|
||||
Explain how it fits into the context of the project.
|
||||
placeholder: Detailed description
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Usage Examples
|
||||
description: |
|
||||
Provide specific examples of how this functionality could be used.
|
||||
This can include scenarios or use cases where the feature would be particularly beneficial.
|
||||
placeholder: text - image - video - flowcharts
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: How should the feature be developed?
|
||||
description: |
|
||||
Should it be inserted directly into the code?
|
||||
Should it be built as a different application that acts as an extension of the API?
|
||||
For example: a `worker`?
|
||||
|
||||
Discuss how this new functionality could impact other parts of the project, if applicable.
|
||||
|
||||
---
|
||||
|
||||
If you have ideas on how this functionality could be implemented, please share them here.
|
||||
This is not mandatory, but it can be helpful for the development team.
|
||||
|
||||
placeholder: Insert feature ideas here
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Additional Notes
|
||||
description: Any other information you believe is relevant to your request.
|
||||
placeholder: Insert your observations here.
|
||||
validations:
|
||||
required: false
|
||||
38
.github/ISSUE_TEMPLATE/-pt--reportar-bug.md
vendored
38
.github/ISSUE_TEMPLATE/-pt--reportar-bug.md
vendored
@@ -1,38 +0,0 @@
|
||||
---
|
||||
name: "[PT] Reportar bug"
|
||||
about: Reportar um problema
|
||||
title: "[PT][BUG]"
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
### Título: [Breve Descrição do Bug]
|
||||
|
||||
#### Descrição:
|
||||
Descreva detalhadamente o problema que você encontrou. Inclua qualquer contexto relevante que possa ajudar a entender a origem do bug.
|
||||
|
||||
#### Passos para Reproduzir:
|
||||
1. Liste os passos necessários para reproduzir o problema.
|
||||
2. Tente ser o mais específico possível.
|
||||
3. Se o problema ocorrer em um cenário específico, descreva-o aqui.
|
||||
|
||||
#### Comportamento Esperado:
|
||||
Descreva o que você esperava que acontecesse quando seguisse os passos acima.
|
||||
|
||||
#### Comportamento Atual:
|
||||
Explique o que realmente acontece quando você segue os passos acima.
|
||||
|
||||
#### Capturas de Tela/Vídeos:
|
||||
Se possível, adicione capturas de tela ou vídeos que ilustrem o problema. Isso pode ser extremamente útil para entender o problema.
|
||||
|
||||
#### Ambiente:
|
||||
- **Servidor:** [ex: Ubuntu 18.04]
|
||||
- **Versão da API:** [ex: 1.5.4]
|
||||
- **Outras Especificações de Hardware/Software:** [ex: CPU, GPU]
|
||||
|
||||
#### Envio de Logs:
|
||||
Por favor, anexe os logs que possam estar relacionados ao problema. Se os logs contiverem informações sensíveis, considere enviá-los de forma privada para um dos mantenedores do projeto.
|
||||
|
||||
#### Notas Adicionais:
|
||||
Inclua aqui qualquer outra informação que você ache que possa ser útil para entender ou resolver o bug.
|
||||
108
.github/ISSUE_TEMPLATE/-pt--reportar-bug.yaml
vendored
Normal file
108
.github/ISSUE_TEMPLATE/-pt--reportar-bug.yaml
vendored
Normal file
@@ -0,0 +1,108 @@
|
||||
name: Relatório de bug
|
||||
description: Crie um relatório para nos ajudar a melhorar.
|
||||
labels:
|
||||
- bug
|
||||
- pt-br
|
||||
# - help wanted
|
||||
# Atrubuir automaticamente a issue a:
|
||||
# assignees: DavidsonGomes
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: termos
|
||||
attributes:
|
||||
label: Bem-vido!
|
||||
description: |
|
||||
O rastreador de problemas é apenas para relatar bugs e solicitações de recursos.
|
||||
Para perguntas de suporte relacionadas ao usuário final, acesse:
|
||||
- [Discord](https://evolution-api.com/discord)
|
||||
- [Grupo do WhatsApp](https://evolution-api.com/whatsapp)
|
||||
<br/>
|
||||
|
||||
**NÃO ABRA UM PROBLEMA PARA PERGUNTAS GERAIS DE SUPORTE.**
|
||||
|
||||
options:
|
||||
- label: Sim, pesquisei problemas semelhantes no [GitHub](https://github.com/EvolutionAPI/evolution-api/issues) e não encontrei nenhum.
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: O que você fez?
|
||||
description: |
|
||||
Como escrever um bom relatório de bug?
|
||||
|
||||
- Respeite o modelo de problema tanto quanto possível.
|
||||
- O título deve ser curto e descritivo.
|
||||
- Explique as condições que o levaram a reportar este problema: o contexto.
|
||||
- O contexto deve levar a algo, ideia ou problema que você está enfrentando.
|
||||
- Seja claro e conciso.
|
||||
- Formate suas mensagens para ajudar o leitor a se concentrar no que importa e entender a estrutura da sua mensagem, use [sintaxe Markdown](https://help.github.com/articles/github-flavored-markdown)
|
||||
placeholder: Descreva detalhadamente o problema que você encontrou.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: O que você esperava?
|
||||
placeholder: Descreva o que você esperava que acontecesse.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: O que vc observou ao invés do que esperava?
|
||||
placeholder: Explique o que realmente acontece quando você segue os passos acima.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Capturas de Tela/Vídeos
|
||||
placeholder: |
|
||||
Se possível, adicione capturas de tela ou vídeos que ilustrem o problema. Isso pode ser extremamente útil para entender melhor o problema.
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Qual versão da API você está usando?
|
||||
description: |
|
||||
Insira o número da sua versão que está na propriedade `version` do **package.json**.
|
||||
placeholder: Cole aqui a versão.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
id: select
|
||||
attributes:
|
||||
label: Qual é o seu ambiente?
|
||||
options:
|
||||
- Windows
|
||||
- Linux
|
||||
- Mac
|
||||
- Docker
|
||||
- Outro
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Outras expecificações do ambiente
|
||||
placeholder: 'Hardware/Software: [ex: CPU, GPU]'
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Se aplicável, cole a saída do log
|
||||
description: |
|
||||
Por favor, anexe os logs que possam estar relacionados ao problema.
|
||||
Se os logs contiverem informações sensíveis, considere enviá-los de forma privada para um dos mantenedores do projeto.
|
||||
placeholder: Cole aqui o log da aplicação
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Notas Adicionais
|
||||
description: Inclua aqui qualquer outra informação que você ache que possa ser útil para entender ou resolver o bug.
|
||||
validations:
|
||||
required: false
|
||||
|
||||
28
.github/ISSUE_TEMPLATE/-pt--solicitar-recurso.md
vendored
28
.github/ISSUE_TEMPLATE/-pt--solicitar-recurso.md
vendored
@@ -1,28 +0,0 @@
|
||||
---
|
||||
name: "[PT] Solicitar recurso"
|
||||
about: Sugira novos recursos para a API
|
||||
title: "[PT][FEAT]"
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
### Título: [Breve Descrição da Solicitação de Recurso]
|
||||
|
||||
#### Descrição Detalhada:
|
||||
Descreva claramente e em detalhes a funcionalidade que você deseja que seja implementada. Explique como isso se encaixa no contexto do projeto.
|
||||
|
||||
#### Racional:
|
||||
Explique por que essa funcionalidade seria útil para o projeto. Isso ajuda a entender a importância e a prioridade da solicitação.
|
||||
|
||||
#### Exemplos de Uso:
|
||||
Forneça exemplos específicos de como essa funcionalidade poderia ser utilizada. Isso pode incluir cenários ou casos de uso onde a funcionalidade seria particularmente benéfica.
|
||||
|
||||
#### Possíveis Implementações:
|
||||
Se você tem ideias sobre como essa funcionalidade pode ser implementada, por favor, compartilhe-as aqui. Isso não é obrigatório, mas pode ser útil para a equipe de desenvolvimento.
|
||||
|
||||
#### Impacto no Projeto:
|
||||
Discuta como essa nova funcionalidade poderia impactar outras partes do projeto, se aplicável.
|
||||
|
||||
#### Notas Adicionais:
|
||||
Qualquer outra informação que você acredita ser relevante para a sua solicitação.
|
||||
86
.github/ISSUE_TEMPLATE/-pt--solicitar-recurso.yaml
vendored
Normal file
86
.github/ISSUE_TEMPLATE/-pt--solicitar-recurso.yaml
vendored
Normal file
@@ -0,0 +1,86 @@
|
||||
name: Solicitação de recursos
|
||||
description: Sugira ideias para o projeto.
|
||||
labels:
|
||||
- enhancement
|
||||
- pt-br
|
||||
# Automatically assign the issue to:
|
||||
# assignees: DavidsonGomes
|
||||
body:
|
||||
- type: checkboxes
|
||||
id: termos
|
||||
attributes:
|
||||
label: Bem-vindo!
|
||||
description: '**NÃO ABRA PARA PERGUNTAS GERAIS DE SUPORTE.**'
|
||||
|
||||
options:
|
||||
- label: Sim, pesquisei solicitações semelhantes no [GitHub](https://github.com/code-chat-br/whatsapp-api/issues) e não encontrei nenhum.
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: Qual tipo de recurso?
|
||||
description: |
|
||||
Como escrever uma boa solicitação de bug?
|
||||
|
||||
- Respeite o modelo de problema tanto quanto possível.
|
||||
- O título deve ser curto e descritivo.
|
||||
- Explique as condições que o levaram a reportar este problema: o contexto.
|
||||
- O contexto deve levar a algo, ideia ou problema que você está enfrentando.
|
||||
- Seja claro e conciso.
|
||||
- Formate suas mensagens para ajudar o leitor a se concentrar no que importa e entender a estrutura da sua mensagem, use [sintaxe Markdown](https://help.github.com/articles/github-flavored-markdown)
|
||||
options:
|
||||
- Integração
|
||||
- Funcionalidade
|
||||
- Endpoint
|
||||
- Ajuste de banco de dados
|
||||
- Outro
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Qual a motivação para a solicitação?
|
||||
description: |
|
||||
Qual problema o recurso busca resolver?
|
||||
Descreva claramente e em detalhes a funcionalidade que você deseja que seja implementada.
|
||||
Explique como isso se encaixa no contexto do projeto.
|
||||
placeholder: Descrição detalhada
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Exemplos de Uso
|
||||
description: |
|
||||
Forneça exemplos específicos de como essa funcionalidade poderia ser utilizada.
|
||||
Isso pode incluir cenários ou casos de uso onde a funcionalidade seria particularmente benéfica.
|
||||
placeholder: texto - imagem - video - fluxogramas
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Como o recurso deve ser desenvolvido?
|
||||
description: |
|
||||
Deve ser inserido diretamente no código?
|
||||
Deve ser construído uma aplicação diferente que atuará como uma extenção da api?
|
||||
Por exemplo: um `worker`?
|
||||
|
||||
Discuta como essa nova funcionalidade poderia impactar outras partes do projeto, se aplicável.
|
||||
|
||||
---
|
||||
|
||||
Se você tem ideias sobre como essa funcionalidade pode ser implementada, por favor, compartilhe-as aqui.
|
||||
Isso não é obrigatório, mas pode ser útil para a equipe de desenvolvimento.
|
||||
|
||||
placeholder: Insira ideias para o recurso
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Notas Adicionais
|
||||
description: Qualquer outra informação que você acredita ser relevante para a sua solicitação.
|
||||
placeholder: Insira aqui as sua observções.
|
||||
validations:
|
||||
required: false
|
||||
70
.github/workflows/publish_docker_image.yml
vendored
70
.github/workflows/publish_docker_image.yml
vendored
@@ -2,63 +2,47 @@ name: Build Docker image
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
tags:
|
||||
- "*.*.*"
|
||||
|
||||
jobs:
|
||||
build-amd:
|
||||
build_deploy:
|
||||
name: Build and Deploy
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Check out the repo
|
||||
uses: actions/checkout@v3
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Extract existing image metadata
|
||||
id: image-meta
|
||||
uses: docker/metadata-action@v4
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: atendai/evolution-api
|
||||
tags: type=semver,pattern=v{{version}}
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v2
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Build and push AMD image
|
||||
uses: docker/build-push-action@v4
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
labels: ${{ steps.image-meta.outputs.labels }}
|
||||
platforms: linux/amd64
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
build-arm:
|
||||
runs-on: buildjet-4vcpu-ubuntu-2204-arm
|
||||
steps:
|
||||
- name: Check out the repo
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Extract existing image metadata
|
||||
id: image-meta
|
||||
uses: docker/metadata-action@v4
|
||||
with:
|
||||
images: atendai/evolution-api
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Build and push ARM image
|
||||
uses: docker/build-push-action@v4
|
||||
with:
|
||||
context: .
|
||||
labels: ${{ steps.image-meta.outputs.labels }}
|
||||
platforms: linux/arm64
|
||||
push: true
|
||||
- name: Image digest
|
||||
run: echo ${{ steps.docker_build.outputs.digest }}
|
||||
48
.github/workflows/publish_docker_image_homolog.yml
vendored
Normal file
48
.github/workflows/publish_docker_image_homolog.yml
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
name: Build Docker image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- develop
|
||||
|
||||
jobs:
|
||||
build_deploy:
|
||||
name: Build and Deploy
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: atendai/evolution-api
|
||||
tags: homolog
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
- name: Image digest
|
||||
run: echo ${{ steps.docker_build.outputs.digest }}
|
||||
48
.github/workflows/publish_docker_image_latest.yml
vendored
Normal file
48
.github/workflows/publish_docker_image_latest.yml
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
name: Build Docker image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build_deploy:
|
||||
name: Build and Deploy
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: atendai/evolution-api
|
||||
tags: latest
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
- name: Image digest
|
||||
run: echo ${{ steps.docker_build.outputs.digest }}
|
||||
48
.github/workflows/publish_docker_image_v2.yml
vendored
Normal file
48
.github/workflows/publish_docker_image_v2.yml
vendored
Normal file
@@ -0,0 +1,48 @@
|
||||
name: Build Docker image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- v2.0.0
|
||||
|
||||
jobs:
|
||||
build_deploy:
|
||||
name: Build and Deploy
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: atendai/evolution-api
|
||||
tags: v2.0.0-alpha
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
- name: Image digest
|
||||
run: echo ${{ steps.docker_build.outputs.digest }}
|
||||
97
CHANGELOG.md
97
CHANGELOG.md
@@ -1,6 +1,103 @@
|
||||
# 1.8.7
|
||||
|
||||
### Features
|
||||
|
||||
* Wavoip integration
|
||||
|
||||
# 1.8.6
|
||||
|
||||
### Features
|
||||
|
||||
* Adds method to fetch contacts with last message
|
||||
|
||||
### Fixed
|
||||
|
||||
* Retry and Reconnect system in rabbitmq integration
|
||||
|
||||
### Feature
|
||||
|
||||
* RabbitMQ optimization with parameterized settings via environment variables (MESSAGE_TTL, MAX_LENGTH and MAX_LENGTH_BYTES)
|
||||
* Non-persistent messages to reduce disk usage
|
||||
* Automatic cleanup of expired messages in queues
|
||||
|
||||
# 1.8.5 (2025-02-03 12:32)
|
||||
|
||||
### Fixed
|
||||
|
||||
* Update Baileys Version
|
||||
|
||||
# 1.8.4 (2025-01-31 10:00)
|
||||
|
||||
### Features
|
||||
|
||||
* Added prefix key to queue name in RabbitMQ
|
||||
|
||||
# 1.8.3 (2024-11-29 10:00)
|
||||
|
||||
### Fixed
|
||||
|
||||
* Fixed issue sending group messages when ignore groups enabled
|
||||
* Fixed groups_ignore in /instance/create and maintaining compatibility
|
||||
|
||||
# 1.8.2 (2024-07-03 13:50)
|
||||
|
||||
### Fixed
|
||||
|
||||
* Corretion in globall rabbitmq queue name
|
||||
* Improvement in the use of mongodb database for credentials
|
||||
* Fixed base64 in webhook for documentWithCaption
|
||||
* Fixed Generate pairing code
|
||||
|
||||
# 1.8.1 (2024-06-08 21:32)
|
||||
|
||||
### Feature
|
||||
|
||||
* New method of saving sessions to a file using worker, made in partnership with [codechat](https://github.com/code-chat-br/whatsapp-api)
|
||||
|
||||
### Fixed
|
||||
|
||||
* Correction of variables breaking lines in typebot
|
||||
|
||||
# 1.8.0 (2024-05-27 16:10)
|
||||
|
||||
### Feature
|
||||
|
||||
* Now in the manager, when logging in with the client's apikey, the listing only shows the instance corresponding to the provided apikey (only with MongoDB)
|
||||
* New global mode for rabbitmq events
|
||||
* Build in docker for linux/amd64, linux/arm64 platforms
|
||||
|
||||
### Fixed
|
||||
|
||||
* Correction in message formatting when generated by AI as markdown in typebot
|
||||
* Security fix in fetch instance with client key when not connected to mongodb
|
||||
|
||||
# 1.7.5 (2024-05-21 08:50)
|
||||
|
||||
### Fixed
|
||||
|
||||
* Add merge_brazil_contacts function to solve nine digit in brazilian numbers
|
||||
* Optimize ChatwootService method for updating contact
|
||||
* Fix swagger auth
|
||||
* Update aws sdk v3
|
||||
* Fix getOpenConversationByContact and init queries error
|
||||
* Method to mark chat as unread
|
||||
* Added environment variable to manually select the WhatsApp web version for the baileys lib (optional)
|
||||
|
||||
# 1.7.4 (2024-04-28 09:46)
|
||||
|
||||
### Fixed
|
||||
|
||||
* Adjusts in proxy on fetchAgent
|
||||
* Recovering messages lost with redis cache
|
||||
* Log when init redis cache service
|
||||
* Recovering messages lost with redis cache
|
||||
* Chatwoot inbox name
|
||||
* Update Baileys version
|
||||
|
||||
# 1.7.3 (2024-04-18 12:07)
|
||||
|
||||
### Fixed
|
||||
|
||||
* Revert fix audio encoding
|
||||
* Recovering messages lost with redis cache
|
||||
* Adjusts in redis for save instances
|
||||
|
||||
@@ -33,10 +33,7 @@ CLEAN_STORE_CHATS=true
|
||||
|
||||
# Permanent data storage
|
||||
DATABASE_ENABLED=false
|
||||
DATABASE_CONNECTION_URI=mongodb://root:root@mongodb:27017/?authSource=admin &
|
||||
readPreference=primary &
|
||||
ssl=false &
|
||||
directConnection=true
|
||||
DATABASE_CONNECTION_URI=mongodb://root:root@mongodb:27017/?authSource=admin&readPreference=primary&ssl=false&directConnection=true
|
||||
DATABASE_CONNECTION_DB_PREFIX_NAME=evdocker
|
||||
|
||||
# Choose the data you want to save in the application's database or store
|
||||
@@ -47,9 +44,33 @@ DATABASE_SAVE_DATA_CONTACTS=false
|
||||
DATABASE_SAVE_DATA_CHATS=false
|
||||
|
||||
RABBITMQ_ENABLED=false
|
||||
RABBITMQ_RABBITMQ_MODE=global
|
||||
RABBITMQ_EXCHANGE_NAME=evolution_exchange
|
||||
RABBITMQ_URI=amqp://guest:guest@rabbitmq:5672
|
||||
RABBITMQ_EXCHANGE_NAME=evolution_exchange
|
||||
RABBITMQ_GLOBAL_ENABLED=false
|
||||
RABBITMQ_EVENTS_APPLICATION_STARTUP=false
|
||||
RABBITMQ_EVENTS_QRCODE_UPDATED=true
|
||||
RABBITMQ_EVENTS_MESSAGES_SET=true
|
||||
RABBITMQ_EVENTS_MESSAGES_UPSERT=true
|
||||
RABBITMQ_EVENTS_MESSAGES_UPDATE=true
|
||||
RABBITMQ_EVENTS_MESSAGES_DELETE=true
|
||||
RABBITMQ_EVENTS_SEND_MESSAGE=true
|
||||
RABBITMQ_EVENTS_CONTACTS_SET=true
|
||||
RABBITMQ_EVENTS_CONTACTS_UPSERT=true
|
||||
RABBITMQ_EVENTS_CONTACTS_UPDATE=true
|
||||
RABBITMQ_EVENTS_PRESENCE_UPDATE=true
|
||||
RABBITMQ_EVENTS_CHATS_SET=true
|
||||
RABBITMQ_EVENTS_CHATS_UPSERT=true
|
||||
RABBITMQ_EVENTS_CHATS_UPDATE=true
|
||||
RABBITMQ_EVENTS_CHATS_DELETE=true
|
||||
RABBITMQ_EVENTS_GROUPS_UPSERT=true
|
||||
RABBITMQ_EVENTS_GROUPS_UPDATE=true
|
||||
RABBITMQ_EVENTS_GROUP_PARTICIPANTS_UPDATE=true
|
||||
RABBITMQ_EVENTS_CONNECTION_UPDATE=true
|
||||
RABBITMQ_EVENTS_LABELS_EDIT=true
|
||||
RABBITMQ_EVENTS_LABELS_ASSOCIATION=true
|
||||
RABBITMQ_EVENTS_CALL=true
|
||||
RABBITMQ_EVENTS_TYPEBOT_START=false
|
||||
RABBITMQ_EVENTS_TYPEBOT_CHANGE_STATUS=false
|
||||
|
||||
WEBSOCKET_ENABLED=false
|
||||
WEBSOCKET_GLOBAL_EVENTS=false
|
||||
@@ -113,7 +134,7 @@ CONFIG_SESSION_PHONE_NAME=Chrome
|
||||
|
||||
# Set qrcode display limit
|
||||
QRCODE_LIMIT=30
|
||||
QRCODE_COLOR=#198754
|
||||
QRCODE_COLOR='#198754'
|
||||
|
||||
# old | latest
|
||||
TYPEBOT_API_VERSION=latest
|
||||
@@ -125,7 +146,7 @@ CHATWOOT_MESSAGE_DELETE=false # false | true
|
||||
# If you leave this option as true, when sending a message in Chatwoot, the client's last message will be marked as read on WhatsApp.
|
||||
CHATWOOT_MESSAGE_READ=false # false | true
|
||||
# This db connection is used to import messages from whatsapp to chatwoot database
|
||||
CHATWOOT_IMPORT_DATABASE_CONNECTION_URI=postgres://user:password@hostname:port/dbname
|
||||
CHATWOOT_IMPORT_DATABASE_CONNECTION_URI=postgres://user:password@hostname:port/dbname?sslmode=disable
|
||||
CHATWOOT_IMPORT_DATABASE_PLACEHOLDER_MEDIA_MESSAGE=true
|
||||
|
||||
CACHE_REDIS_ENABLED=false
|
||||
|
||||
32
Dockerfile
32
Dockerfile
@@ -1,6 +1,6 @@
|
||||
FROM node:20.7.0-alpine AS builder
|
||||
|
||||
LABEL version="1.7.3" description="Api to control whatsapp features through http requests."
|
||||
LABEL version="1.8.0" description="Api to control whatsapp features through http requests."
|
||||
LABEL maintainer="Davidson Gomes" git="https://github.com/DavidsonGomes"
|
||||
LABEL contact="contato@agenciadgcode.com"
|
||||
|
||||
@@ -59,9 +59,35 @@ ENV DATABASE_SAVE_DATA_CONTACTS=false
|
||||
ENV DATABASE_SAVE_DATA_CHATS=false
|
||||
|
||||
ENV RABBITMQ_ENABLED=false
|
||||
ENV RABBITMQ_MODE=global
|
||||
ENV RABBITMQ_EXCHANGE_NAME=evolution_exchange
|
||||
ENV RABBITMQ_URI=amqp://guest:guest@rabbitmq:5672
|
||||
ENV RABBITMQ_EXCHANGE_NAME=evolution_exchange
|
||||
ENV RABBITMQ_GLOBAL_ENABLED=false
|
||||
ENV RABBITMQ_EVENTS_APPLICATION_STARTUP=false
|
||||
ENV RABBITMQ_EVENTS_INSTANCE_CREATE=false
|
||||
ENV RABBITMQ_EVENTS_INSTANCE_DELETE=false
|
||||
ENV RABBITMQ_EVENTS_QRCODE_UPDATED=true
|
||||
ENV RABBITMQ_EVENTS_MESSAGES_SET=true
|
||||
ENV RABBITMQ_EVENTS_MESSAGES_UPSERT=true
|
||||
ENV RABBITMQ_EVENTS_MESSAGES_UPDATE=true
|
||||
ENV RABBITMQ_EVENTS_MESSAGES_DELETE=true
|
||||
ENV RABBITMQ_EVENTS_SEND_MESSAGE=true
|
||||
ENV RABBITMQ_EVENTS_CONTACTS_SET=true
|
||||
ENV RABBITMQ_EVENTS_CONTACTS_UPSERT=true
|
||||
ENV RABBITMQ_EVENTS_CONTACTS_UPDATE=true
|
||||
ENV RABBITMQ_EVENTS_PRESENCE_UPDATE=true
|
||||
ENV RABBITMQ_EVENTS_CHATS_SET=true
|
||||
ENV RABBITMQ_EVENTS_CHATS_UPSERT=true
|
||||
ENV RABBITMQ_EVENTS_CHATS_UPDATE=true
|
||||
ENV RABBITMQ_EVENTS_CHATS_DELETE=true
|
||||
ENV RABBITMQ_EVENTS_GROUPS_UPSERT=true
|
||||
ENV RABBITMQ_EVENTS_GROUPS_UPDATE=true
|
||||
ENV RABBITMQ_EVENTS_GROUP_PARTICIPANTS_UPDATE=true
|
||||
ENV RABBITMQ_EVENTS_CONNECTION_UPDATE=true
|
||||
ENV RABBITMQ_EVENTS_LABELS_EDIT=true
|
||||
ENV RABBITMQ_EVENTS_LABELS_ASSOCIATION=true
|
||||
ENV RABBITMQ_EVENTS_CALL=true
|
||||
ENV RABBITMQ_EVENTS_TYPEBOT_START=false
|
||||
ENV RABBITMQ_EVENTS_TYPEBOT_CHANGE_STATUS=false
|
||||
|
||||
ENV WEBSOCKET_ENABLED=false
|
||||
ENV WEBSOCKET_GLOBAL_EVENTS=false
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "evolution-api",
|
||||
"version": "1.7.3",
|
||||
"version": "1.8.6",
|
||||
"description": "Rest api for communication with WhatsApp",
|
||||
"main": "./dist/src/main.js",
|
||||
"scripts": {
|
||||
@@ -42,14 +42,14 @@
|
||||
"homepage": "https://github.com/EvolutionAPI/evolution-api#readme",
|
||||
"dependencies": {
|
||||
"@adiwajshing/keyed-db": "^0.2.4",
|
||||
"@aws-sdk/client-sqs": "^3.569.0",
|
||||
"@ffmpeg-installer/ffmpeg": "^1.1.0",
|
||||
"@figuro/chatwoot-sdk": "^1.1.16",
|
||||
"@hapi/boom": "^10.0.1",
|
||||
"@sentry/node": "^7.59.2",
|
||||
"@whiskeysockets/baileys": "github:AtendAI/Baileys",
|
||||
"amqplib": "^0.10.3",
|
||||
"aws-sdk": "^2.1499.0",
|
||||
"axios": "^1.6.5",
|
||||
"baileys": "github:EvolutionAPI/Baileys",
|
||||
"class-validator": "^0.14.1",
|
||||
"compression": "^1.7.4",
|
||||
"cors": "^2.8.5",
|
||||
@@ -84,6 +84,7 @@
|
||||
"redis": "^4.6.5",
|
||||
"sharp": "^0.32.2",
|
||||
"socket.io": "^4.7.1",
|
||||
"socket.io-client": "^4.8.1",
|
||||
"socks-proxy-agent": "^8.0.1",
|
||||
"swagger-ui-express": "^5.0.0",
|
||||
"uuid": "^9.0.0",
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
BlockUserDto,
|
||||
DeleteMessage,
|
||||
getBase64FromMediaMessageDto,
|
||||
MarkChatUnreadDto,
|
||||
NumberDto,
|
||||
PrivacySettingDto,
|
||||
ProfileNameDto,
|
||||
@@ -40,6 +41,11 @@ export class ChatController {
|
||||
return await this.waMonitor.waInstances[instanceName].archiveChat(data);
|
||||
}
|
||||
|
||||
public async markChatUnread({ instanceName }: InstanceDto, data: MarkChatUnreadDto) {
|
||||
logger.verbose('requested markChatUnread from ' + instanceName + ' instance');
|
||||
return await this.waMonitor.waInstances[instanceName].markChatUnread(data);
|
||||
}
|
||||
|
||||
public async deleteMessage({ instanceName }: InstanceDto, data: DeleteMessage) {
|
||||
logger.verbose('requested deleteMessage from ' + instanceName + ' instance');
|
||||
return await this.waMonitor.waInstances[instanceName].deleteMessage(data);
|
||||
@@ -80,6 +86,11 @@ export class ChatController {
|
||||
return await this.waMonitor.waInstances[instanceName].fetchChats();
|
||||
}
|
||||
|
||||
public async fetchContactsWithLastMessage({ instanceName }: InstanceDto) {
|
||||
logger.verbose('requested fetchContactsWithLastMessage from ' + instanceName + ' instance');
|
||||
return await this.waMonitor.waInstances[instanceName].fetchContactsWithLastMessage();
|
||||
}
|
||||
|
||||
public async sendPresence({ instanceName }: InstanceDto, data: SendPresenceDto) {
|
||||
logger.verbose('requested sendPresence from ' + instanceName + ' instance');
|
||||
return await this.waMonitor.waInstances[instanceName].sendPresence(data);
|
||||
|
||||
@@ -1,26 +1,27 @@
|
||||
import { delay } from '@whiskeysockets/baileys';
|
||||
import { delay } from 'baileys';
|
||||
import { isURL } from 'class-validator';
|
||||
import EventEmitter2 from 'eventemitter2';
|
||||
import { v4 } from 'uuid';
|
||||
|
||||
import { ConfigService, HttpServer, WaBusiness } from '../../config/env.config';
|
||||
import { Auth, ConfigService, HttpServer, WaBusiness } from '../../config/env.config';
|
||||
import { Logger } from '../../config/logger.config';
|
||||
import { BadRequestException, InternalServerErrorException } from '../../exceptions';
|
||||
import { BadRequestException, InternalServerErrorException, UnauthorizedException } from '../../exceptions';
|
||||
import { InstanceDto, SetPresenceDto } from '../dto/instance.dto';
|
||||
import { ChatwootService } from '../integrations/chatwoot/services/chatwoot.service';
|
||||
import { RabbitmqService } from '../integrations/rabbitmq/services/rabbitmq.service';
|
||||
import { SqsService } from '../integrations/sqs/services/sqs.service';
|
||||
import { TypebotService } from '../integrations/typebot/services/typebot.service';
|
||||
import { WebsocketService } from '../integrations/websocket/services/websocket.service';
|
||||
import { ProviderFiles } from '../provider/sessions';
|
||||
import { RepositoryBroker } from '../repository/repository.manager';
|
||||
import { AuthService, OldToken } from '../services/auth.service';
|
||||
import { CacheService } from '../services/cache.service';
|
||||
import { BaileysStartupService } from '../services/channels/whatsapp.baileys.service';
|
||||
import { BusinessStartupService } from '../services/channels/whatsapp.business.service';
|
||||
import { IntegrationService } from '../services/integration.service';
|
||||
import { WAMonitoringService } from '../services/monitor.service';
|
||||
import { SettingsService } from '../services/settings.service';
|
||||
import { WebhookService } from '../services/webhook.service';
|
||||
import { BaileysStartupService } from '../services/whatsapp/whatsapp.baileys.service';
|
||||
import { BusinessStartupService } from '../services/whatsapp/whatsapp.business.service';
|
||||
import { Events, Integration, wa } from '../types/wa.types';
|
||||
import { ProxyController } from './proxy.controller';
|
||||
|
||||
@@ -42,7 +43,8 @@ export class InstanceController {
|
||||
private readonly proxyService: ProxyController,
|
||||
private readonly cache: CacheService,
|
||||
private readonly chatwootCache: CacheService,
|
||||
private readonly messagesLostCache: CacheService,
|
||||
private readonly baileysCache: CacheService,
|
||||
private readonly providerFiles: ProviderFiles,
|
||||
) {}
|
||||
|
||||
private readonly logger = new Logger(InstanceController.name);
|
||||
@@ -65,6 +67,8 @@ export class InstanceController {
|
||||
chatwoot_reopen_conversation,
|
||||
chatwoot_conversation_pending,
|
||||
chatwoot_import_contacts,
|
||||
chatwoot_name_inbox,
|
||||
chatwoot_merge_brazil_contacts,
|
||||
chatwoot_import_messages,
|
||||
chatwoot_days_limit_import_messages,
|
||||
reject_call,
|
||||
@@ -74,6 +78,7 @@ export class InstanceController {
|
||||
read_messages,
|
||||
read_status,
|
||||
sync_full_history,
|
||||
wavoipToken,
|
||||
websocket_enabled,
|
||||
websocket_events,
|
||||
rabbitmq_enabled,
|
||||
@@ -108,7 +113,8 @@ export class InstanceController {
|
||||
this.repository,
|
||||
this.cache,
|
||||
this.chatwootCache,
|
||||
this.messagesLostCache,
|
||||
this.baileysCache,
|
||||
this.providerFiles,
|
||||
);
|
||||
} else {
|
||||
instance = new BaileysStartupService(
|
||||
@@ -117,7 +123,8 @@ export class InstanceController {
|
||||
this.repository,
|
||||
this.cache,
|
||||
this.chatwootCache,
|
||||
this.messagesLostCache,
|
||||
this.baileysCache,
|
||||
this.providerFiles,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -390,11 +397,12 @@ export class InstanceController {
|
||||
const settings: wa.LocalSettings = {
|
||||
reject_call: reject_call || false,
|
||||
msg_call: msg_call || '',
|
||||
groups_ignore: groups_ignore || true,
|
||||
groups_ignore: groups_ignore === undefined ? true : groups_ignore || false,
|
||||
always_online: always_online || false,
|
||||
read_messages: read_messages || false,
|
||||
read_status: read_status || false,
|
||||
sync_full_history: sync_full_history ?? false,
|
||||
wavoipToken: wavoipToken ?? '',
|
||||
};
|
||||
|
||||
this.logger.verbose('settings: ' + JSON.stringify(settings));
|
||||
@@ -513,11 +521,12 @@ export class InstanceController {
|
||||
token: chatwoot_token,
|
||||
url: chatwoot_url,
|
||||
sign_msg: chatwoot_sign_msg || false,
|
||||
name_inbox: instance.instanceName.split('-cwId-')[0],
|
||||
name_inbox: chatwoot_name_inbox ?? instance.instanceName.split('-cwId-')[0],
|
||||
number,
|
||||
reopen_conversation: chatwoot_reopen_conversation || false,
|
||||
conversation_pending: chatwoot_conversation_pending || false,
|
||||
import_contacts: chatwoot_import_contacts ?? true,
|
||||
merge_brazil_contacts: chatwoot_merge_brazil_contacts ?? false,
|
||||
import_messages: chatwoot_import_messages ?? true,
|
||||
days_limit_import_messages: chatwoot_days_limit_import_messages ?? 60,
|
||||
auto_create: true,
|
||||
@@ -573,11 +582,12 @@ export class InstanceController {
|
||||
sign_msg: chatwoot_sign_msg || false,
|
||||
reopen_conversation: chatwoot_reopen_conversation || false,
|
||||
conversation_pending: chatwoot_conversation_pending || false,
|
||||
merge_brazil_contacts: chatwoot_merge_brazil_contacts ?? false,
|
||||
import_contacts: chatwoot_import_contacts ?? true,
|
||||
import_messages: chatwoot_import_messages ?? true,
|
||||
days_limit_import_messages: chatwoot_days_limit_import_messages || 60,
|
||||
number,
|
||||
name_inbox: instance.instanceName,
|
||||
name_inbox: chatwoot_name_inbox ?? instance.instanceName,
|
||||
webhook_url: `${urlServer}/chatwoot/webhook/${encodeURIComponent(instance.instanceName)}`,
|
||||
},
|
||||
};
|
||||
@@ -675,11 +685,26 @@ export class InstanceController {
|
||||
};
|
||||
}
|
||||
|
||||
public async fetchInstances({ instanceName, instanceId, number }: InstanceDto) {
|
||||
if (instanceName) {
|
||||
this.logger.verbose('requested fetchInstances from ' + instanceName + ' instance');
|
||||
this.logger.verbose('instanceName: ' + instanceName);
|
||||
return this.waMonitor.instanceInfo(instanceName);
|
||||
public async fetchInstances({ instanceName, instanceId, number }: InstanceDto, key: string) {
|
||||
const env = this.configService.get<Auth>('AUTHENTICATION').API_KEY;
|
||||
|
||||
let name = instanceName;
|
||||
let arrayReturn = false;
|
||||
|
||||
if (env.KEY !== key) {
|
||||
const instanceByKey = await this.repository.auth.findByKey(key);
|
||||
if (instanceByKey) {
|
||||
name = instanceByKey._id;
|
||||
arrayReturn = true;
|
||||
} else {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
}
|
||||
|
||||
if (name) {
|
||||
this.logger.verbose('requested fetchInstances from ' + name + ' instance');
|
||||
this.logger.verbose('instanceName: ' + name);
|
||||
return this.waMonitor.instanceInfo(name, arrayReturn);
|
||||
} else if (instanceId || number) {
|
||||
return this.waMonitor.instanceInfoById(instanceId, number);
|
||||
}
|
||||
@@ -714,23 +739,18 @@ export class InstanceController {
|
||||
this.logger.verbose('requested deleteInstance from ' + instanceName + ' instance');
|
||||
const { instance } = await this.connectionState({ instanceName });
|
||||
|
||||
if (instance.state === 'open') {
|
||||
throw new BadRequestException('The "' + instanceName + '" instance needs to be disconnected');
|
||||
}
|
||||
try {
|
||||
this.waMonitor.waInstances[instanceName]?.removeRabbitmqQueues();
|
||||
this.waMonitor.waInstances[instanceName]?.clearCacheChatwoot();
|
||||
|
||||
if (instance.state === 'connecting') {
|
||||
this.logger.verbose('logging out instance: ' + instanceName);
|
||||
|
||||
if (instance.state === 'connecting' || instance.state === 'open') {
|
||||
await this.logout({ instanceName });
|
||||
}
|
||||
|
||||
this.logger.verbose('deleting instance: ' + instanceName);
|
||||
|
||||
try {
|
||||
this.waMonitor.waInstances[instanceName].sendDataWebhook(Events.INSTANCE_DELETE, {
|
||||
this.waMonitor.waInstances[instanceName]?.sendDataWebhook(Events.INSTANCE_DELETE, {
|
||||
instanceName,
|
||||
instanceId: (await this.repository.auth.find(instanceName))?.instanceId,
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { proto, WAPresence, WAPrivacyOnlineValue, WAPrivacyValue, WAReadReceiptsValue } from '@whiskeysockets/baileys';
|
||||
import { proto, WAPresence, WAPrivacyOnlineValue, WAPrivacyValue, WAReadReceiptsValue } from 'baileys';
|
||||
|
||||
export class OnWhatsAppDto {
|
||||
constructor(
|
||||
@@ -73,13 +73,18 @@ export class ArchiveChatDto {
|
||||
archive: boolean;
|
||||
}
|
||||
|
||||
export class MarkChatUnreadDto {
|
||||
lastMessage?: LastMessage;
|
||||
chat?: string;
|
||||
}
|
||||
|
||||
class PrivacySetting {
|
||||
readreceipts: WAReadReceiptsValue;
|
||||
profile: WAPrivacyValue;
|
||||
status: WAPrivacyValue;
|
||||
online: WAPrivacyOnlineValue;
|
||||
last: WAPrivacyValue;
|
||||
groupadd: WAPrivacyValue;
|
||||
groupadd: any;
|
||||
}
|
||||
|
||||
export class PrivacySettingDto {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { WAPresence } from '@whiskeysockets/baileys';
|
||||
import { WAPresence } from 'baileys';
|
||||
|
||||
import { ProxyDto } from './proxy.dto';
|
||||
|
||||
@@ -21,15 +21,18 @@ export class InstanceDto {
|
||||
read_messages?: boolean;
|
||||
read_status?: boolean;
|
||||
sync_full_history?: boolean;
|
||||
wavoipToken?: string;
|
||||
chatwoot_account_id?: string;
|
||||
chatwoot_token?: string;
|
||||
chatwoot_url?: string;
|
||||
chatwoot_sign_msg?: boolean;
|
||||
chatwoot_reopen_conversation?: boolean;
|
||||
chatwoot_conversation_pending?: boolean;
|
||||
chatwoot_merge_brazil_contacts?: boolean;
|
||||
chatwoot_import_contacts?: boolean;
|
||||
chatwoot_import_messages?: boolean;
|
||||
chatwoot_days_limit_import_messages?: number;
|
||||
chatwoot_name_inbox?: string;
|
||||
websocket_enabled?: boolean;
|
||||
websocket_events?: string[];
|
||||
rabbitmq_enabled?: boolean;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { proto, WAPresence } from '@whiskeysockets/baileys';
|
||||
import { proto, WAPresence } from 'baileys';
|
||||
|
||||
export class Quoted {
|
||||
key: proto.IMessageKey;
|
||||
|
||||
@@ -6,4 +6,5 @@ export class SettingsDto {
|
||||
read_messages?: boolean;
|
||||
read_status?: boolean;
|
||||
sync_full_history?: boolean;
|
||||
wavoipToken?: string;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { NextFunction, Request, Response } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
import { name } from '../../../package.json';
|
||||
import { Auth, configService } from '../../config/env.config';
|
||||
import { Auth, configService, Database } from '../../config/env.config';
|
||||
import { Logger } from '../../config/logger.config';
|
||||
import { ForbiddenException, UnauthorizedException } from '../../exceptions';
|
||||
import { InstanceDto } from '../dto/instance.dto';
|
||||
@@ -58,6 +58,11 @@ async function jwtGuard(req: Request, res: Response, next: NextFunction) {
|
||||
async function apikey(req: Request, _: Response, next: NextFunction) {
|
||||
const env = configService.get<Auth>('AUTHENTICATION').API_KEY;
|
||||
const key = req.get('apikey');
|
||||
const db = configService.get<Database>('DATABASE');
|
||||
|
||||
if (!key) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
|
||||
if (env.KEY === key) {
|
||||
return next();
|
||||
@@ -66,12 +71,21 @@ async function apikey(req: Request, _: Response, next: NextFunction) {
|
||||
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 param = req.params as unknown as InstanceDto;
|
||||
|
||||
try {
|
||||
const param = req.params as unknown as InstanceDto;
|
||||
const instanceKey = await repository.auth.find(param.instanceName);
|
||||
if (instanceKey.apikey === key) {
|
||||
return next();
|
||||
if (param?.instanceName) {
|
||||
const instanceKey = await repository.auth.find(param.instanceName);
|
||||
if (instanceKey?.apikey === key) {
|
||||
return next();
|
||||
}
|
||||
} else {
|
||||
if (req.originalUrl.includes('/instance/fetchInstances') && db.ENABLED) {
|
||||
const instanceByKey = await repository.auth.findByKey(key);
|
||||
if (instanceByKey) {
|
||||
return next();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
|
||||
@@ -53,11 +53,15 @@ export class ChatwootController {
|
||||
data.conversation_pending = false;
|
||||
data.import_contacts = false;
|
||||
data.import_messages = false;
|
||||
data.merge_brazil_contacts = false;
|
||||
data.days_limit_import_messages = 0;
|
||||
data.auto_create = false;
|
||||
data.name_inbox = '';
|
||||
}
|
||||
|
||||
data.name_inbox = instance.instanceName;
|
||||
if (!data.name_inbox || data.name_inbox === '') {
|
||||
data.name_inbox = instance.instanceName;
|
||||
}
|
||||
|
||||
const result = await this.chatwootService.create(instance, data);
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ export class ChatwootDto {
|
||||
number?: string;
|
||||
reopen_conversation?: boolean;
|
||||
conversation_pending?: boolean;
|
||||
merge_brazil_contacts?: boolean;
|
||||
import_contacts?: boolean;
|
||||
import_messages?: boolean;
|
||||
days_limit_import_messages?: number;
|
||||
|
||||
@@ -14,6 +14,7 @@ export class ChatwootRaw {
|
||||
number?: string;
|
||||
reopen_conversation?: boolean;
|
||||
conversation_pending?: boolean;
|
||||
merge_brazil_contacts?: boolean;
|
||||
import_contacts?: boolean;
|
||||
import_messages?: boolean;
|
||||
days_limit_import_messages?: number;
|
||||
@@ -31,6 +32,7 @@ const chatwootSchema = new Schema<ChatwootRaw>({
|
||||
number: { type: String, required: true },
|
||||
reopen_conversation: { type: Boolean, required: true },
|
||||
conversation_pending: { type: Boolean, required: true },
|
||||
merge_brazil_contacts: { type: Boolean, required: true },
|
||||
import_contacts: { type: Boolean, required: true },
|
||||
import_messages: { type: Boolean, required: true },
|
||||
days_limit_import_messages: { type: Number, required: true },
|
||||
|
||||
@@ -9,6 +9,7 @@ import ChatwootClient, {
|
||||
} from '@figuro/chatwoot-sdk';
|
||||
import { request as chatwootRequest } from '@figuro/chatwoot-sdk/dist/core/request';
|
||||
import axios from 'axios';
|
||||
import { proto } from 'baileys';
|
||||
import FormData from 'form-data';
|
||||
import { createReadStream, unlinkSync, writeFileSync } from 'fs';
|
||||
import Jimp from 'jimp';
|
||||
@@ -85,12 +86,14 @@ export class ChatwootService {
|
||||
return client;
|
||||
}
|
||||
|
||||
public getClientCwConfig(): ChatwootAPIConfig {
|
||||
public getClientCwConfig(): ChatwootAPIConfig & { name_inbox: string; merge_brazil_contacts: boolean } {
|
||||
return {
|
||||
basePath: this.provider.url,
|
||||
with_credentials: true,
|
||||
credentials: 'include',
|
||||
token: this.provider.token,
|
||||
name_inbox: this.provider.name_inbox,
|
||||
merge_brazil_contacts: this.provider.merge_brazil_contacts,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -110,7 +113,7 @@ export class ChatwootService {
|
||||
|
||||
await this.initInstanceChatwoot(
|
||||
instance,
|
||||
instance.instanceName.split('-cwId-')[0],
|
||||
data.name_inbox ?? instance.instanceName.split('-cwId-')[0],
|
||||
`${urlServer}/chatwoot/webhook/${encodeURIComponent(instance.instanceName)}`,
|
||||
true,
|
||||
data.number,
|
||||
@@ -416,10 +419,48 @@ export class ChatwootService {
|
||||
}
|
||||
}
|
||||
|
||||
private async mergeBrazilianContacts(contacts: any[]) {
|
||||
try {
|
||||
//sdk chatwoot não tem função merge
|
||||
this.logger.verbose('merging contacts');
|
||||
const contact = await chatwootRequest(this.getClientCwConfig(), {
|
||||
method: 'POST',
|
||||
url: `/api/v1/accounts/${this.provider.account_id}/actions/contact_merge`,
|
||||
body: {
|
||||
base_contact_id: contacts.find((contact) => contact.phone_number.length === 14)?.id,
|
||||
mergee_contact_id: contacts.find((contact) => contact.phone_number.length === 13)?.id,
|
||||
},
|
||||
});
|
||||
|
||||
return contact;
|
||||
} catch {
|
||||
this.logger.error('Error merging contacts');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private findContactInContactList(contacts: any[], query: string) {
|
||||
const phoneNumbers = this.getNumbers(query);
|
||||
const searchableFields = this.getSearchableFields();
|
||||
|
||||
// eslint-disable-next-line prettier/prettier
|
||||
if (contacts.length === 2 && this.getClientCwConfig().merge_brazil_contacts && query.startsWith('+55')) {
|
||||
const contact = this.mergeBrazilianContacts(contacts);
|
||||
if (contact) {
|
||||
return contact;
|
||||
}
|
||||
}
|
||||
|
||||
const phone = phoneNumbers.reduce(
|
||||
(savedNumber, number) => (number.length > savedNumber.length ? number : savedNumber),
|
||||
'',
|
||||
);
|
||||
|
||||
const contact_with9 = contacts.find((contact) => contact.phone_number === phone);
|
||||
if (contact_with9) {
|
||||
return contact_with9;
|
||||
}
|
||||
|
||||
for (const contact of contacts) {
|
||||
for (const field of searchableFields) {
|
||||
if (contact[field] && phoneNumbers.includes(contact[field])) {
|
||||
@@ -447,7 +488,7 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
private getSearchableFields() {
|
||||
return ['phone_number', 'identifier'];
|
||||
return ['phone_number'];
|
||||
}
|
||||
|
||||
private getFilterPayload(query: string) {
|
||||
@@ -461,7 +502,7 @@ export class ChatwootService {
|
||||
const queryOperator = fieldsToSearch.length - 1 === index1 && numbers.length - 1 === index2 ? null : 'OR';
|
||||
filterPayload.push({
|
||||
attribute_key: field,
|
||||
filter_operator: ['phone_number', 'identifier'].includes(field) ? 'equal_to' : 'contains',
|
||||
filter_operator: 'equal_to',
|
||||
values: [number.replace('+', '')],
|
||||
query_operator: queryOperator,
|
||||
});
|
||||
@@ -559,53 +600,44 @@ export class ChatwootService {
|
||||
|
||||
const picture_url = await this.waMonitor.waInstances[instance.instanceName].profilePicture(chatId);
|
||||
|
||||
const findContact = await this.findContact(instance, chatId);
|
||||
let contact = await this.findContact(instance, chatId);
|
||||
|
||||
let contact: any;
|
||||
if (body.key.fromMe) {
|
||||
if (findContact) {
|
||||
contact = await this.updateContact(instance, findContact.id, {
|
||||
avatar_url: picture_url.profilePictureUrl || null,
|
||||
});
|
||||
} else {
|
||||
const jid = isGroup ? null : body.key.remoteJid;
|
||||
contact = await this.createContact(
|
||||
instance,
|
||||
chatId,
|
||||
filterInbox.id,
|
||||
isGroup,
|
||||
nameContact,
|
||||
picture_url.profilePictureUrl || null,
|
||||
jid,
|
||||
);
|
||||
if (contact) {
|
||||
if (!body.key.fromMe) {
|
||||
const waProfilePictureFile =
|
||||
picture_url?.profilePictureUrl?.split('#')[0].split('?')[0].split('/').pop() || '';
|
||||
const chatwootProfilePictureFile = contact?.thumbnail?.split('#')[0].split('?')[0].split('/').pop() || '';
|
||||
const pictureNeedsUpdate = waProfilePictureFile !== chatwootProfilePictureFile;
|
||||
const nameNeedsUpdate =
|
||||
!contact.name ||
|
||||
contact.name === chatId ||
|
||||
(`+${chatId}`.startsWith('+55')
|
||||
? this.getNumbers(`+${chatId}`).some(
|
||||
(v) => contact.name === v || contact.name === v.substring(3) || contact.name === v.substring(1),
|
||||
)
|
||||
: false);
|
||||
|
||||
const contactNeedsUpdate = pictureNeedsUpdate || nameNeedsUpdate;
|
||||
if (contactNeedsUpdate) {
|
||||
this.logger.verbose('update contact in chatwoot');
|
||||
contact = await this.updateContact(instance, contact.id, {
|
||||
...(nameNeedsUpdate && { name: nameContact }),
|
||||
...(waProfilePictureFile === '' && { avatar: null }),
|
||||
...(pictureNeedsUpdate && { avatar_url: picture_url?.profilePictureUrl }),
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (findContact) {
|
||||
if (!findContact.name || findContact.name === chatId) {
|
||||
contact = await this.updateContact(instance, findContact.id, {
|
||||
name: nameContact,
|
||||
avatar_url: picture_url.profilePictureUrl || null,
|
||||
});
|
||||
} else {
|
||||
contact = await this.updateContact(instance, findContact.id, {
|
||||
avatar_url: picture_url.profilePictureUrl || null,
|
||||
});
|
||||
}
|
||||
if (!contact) {
|
||||
contact = await this.findContact(instance, chatId);
|
||||
}
|
||||
} else {
|
||||
const jid = isGroup ? null : body.key.remoteJid;
|
||||
contact = await this.createContact(
|
||||
instance,
|
||||
chatId,
|
||||
filterInbox.id,
|
||||
isGroup,
|
||||
nameContact,
|
||||
picture_url.profilePictureUrl || null,
|
||||
jid,
|
||||
);
|
||||
}
|
||||
const jid = isGroup ? null : body.key.remoteJid;
|
||||
contact = await this.createContact(
|
||||
instance,
|
||||
chatId,
|
||||
filterInbox.id,
|
||||
isGroup,
|
||||
nameContact,
|
||||
picture_url.profilePictureUrl || null,
|
||||
jid,
|
||||
);
|
||||
}
|
||||
|
||||
if (!contact) {
|
||||
@@ -615,20 +647,13 @@ export class ChatwootService {
|
||||
|
||||
const contactId = contact?.payload?.id || contact?.payload?.contact?.id || contact?.id;
|
||||
|
||||
if (!body.key.fromMe && contact.name === chatId && nameContact !== chatId) {
|
||||
this.logger.verbose('update contact name in chatwoot');
|
||||
await this.updateContact(instance, contactId, {
|
||||
name: nameContact,
|
||||
});
|
||||
}
|
||||
|
||||
this.logger.verbose('get contact conversations in chatwoot');
|
||||
const contactConversations = (await client.contacts.listConversations({
|
||||
accountId: this.provider.account_id,
|
||||
id: contactId,
|
||||
})) as any;
|
||||
|
||||
if (contactConversations) {
|
||||
if (contactConversations?.payload?.length) {
|
||||
let conversation: any;
|
||||
if (this.provider.reopen_conversation) {
|
||||
conversation = contactConversations.payload.find((conversation) => conversation.inbox_id == filterInbox.id);
|
||||
@@ -710,7 +735,11 @@ export class ChatwootService {
|
||||
}
|
||||
|
||||
this.logger.verbose('find inbox by name');
|
||||
const findByName = inbox.payload.find((inbox) => inbox.name === instance.instanceName.split('-cwId-')[0]);
|
||||
let findByName = inbox.payload.find((inbox) => inbox.name === this.getClientCwConfig().name_inbox);
|
||||
|
||||
if (!findByName) {
|
||||
findByName = inbox.payload.find((inbox) => inbox.name === this.getClientCwConfig().name_inbox.split('-cwId-')[0]);
|
||||
}
|
||||
|
||||
if (!findByName) {
|
||||
this.logger.warn('inbox not found');
|
||||
@@ -787,26 +816,15 @@ export class ChatwootService {
|
||||
return null;
|
||||
}
|
||||
|
||||
const payload = [
|
||||
['inbox_id', inbox.id.toString()],
|
||||
['contact_id', contact.id.toString()],
|
||||
['status', 'open'],
|
||||
];
|
||||
const conversations = (await client.contacts.listConversations({
|
||||
accountId: this.provider.account_id,
|
||||
id: contact.id,
|
||||
})) as any;
|
||||
|
||||
return (
|
||||
(
|
||||
(await client.conversations.filter({
|
||||
accountId: this.provider.account_id,
|
||||
payload: payload.map((item, i, payload) => {
|
||||
return {
|
||||
attribute_key: item[0],
|
||||
filter_operator: 'equal_to',
|
||||
values: [item[1]],
|
||||
query_operator: i < payload.length - 1 ? 'AND' : null,
|
||||
};
|
||||
}),
|
||||
})) as { payload: conversation[] }
|
||||
).payload[0] || undefined
|
||||
conversations.payload.find(
|
||||
(conversation) => conversation.inbox_id === inbox.id && conversation.status === 'open',
|
||||
) || undefined
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1077,6 +1095,10 @@ export class ChatwootService {
|
||||
return messageSent;
|
||||
}
|
||||
|
||||
if (type === 'image' && parsedMedia && parsedMedia?.ext === '.gif') {
|
||||
type = 'document';
|
||||
}
|
||||
|
||||
this.logger.verbose('send media to instance: ' + waInstance.instanceName);
|
||||
const data: SendMediaDto = {
|
||||
number: number,
|
||||
@@ -1106,6 +1128,26 @@ export class ChatwootService {
|
||||
}
|
||||
}
|
||||
|
||||
public async onSendMessageError(instance: InstanceDto, conversation: number, error?: string) {
|
||||
const client = await this.clientCw(instance);
|
||||
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
|
||||
client.messages.create({
|
||||
accountId: this.provider.account_id,
|
||||
conversationId: conversation,
|
||||
data: {
|
||||
content: i18next.t('cw.message.notsent', {
|
||||
error: error?.length > 0 ? `_${error}_` : '',
|
||||
}),
|
||||
message_type: 'outgoing',
|
||||
private: true,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
public async receiveWebhook(instance: InstanceDto, body: any) {
|
||||
try {
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
@@ -1274,6 +1316,11 @@ export class ChatwootService {
|
||||
return { message: 'bot' };
|
||||
}
|
||||
|
||||
if (!waInstance && body.conversation?.id) {
|
||||
this.onSendMessageError(instance, body.conversation?.id, 'Instance not found');
|
||||
return { message: 'bot' };
|
||||
}
|
||||
|
||||
this.logger.verbose('Format message to send');
|
||||
let formatText: string;
|
||||
if (senderName === null || senderName === undefined) {
|
||||
@@ -1310,6 +1357,9 @@ export class ChatwootService {
|
||||
formatText,
|
||||
options,
|
||||
);
|
||||
if (!messageSent && body.conversation?.id) {
|
||||
this.onSendMessageError(instance, body.conversation?.id);
|
||||
}
|
||||
|
||||
this.updateChatwootMessageId(
|
||||
{
|
||||
@@ -1343,23 +1393,34 @@ export class ChatwootService {
|
||||
},
|
||||
};
|
||||
|
||||
const messageSent = await waInstance?.textMessage(data, true);
|
||||
let messageSent: MessageRaw | proto.WebMessageInfo;
|
||||
try {
|
||||
messageSent = await waInstance?.textMessage(data, true);
|
||||
if (!messageSent) {
|
||||
throw new Error('Message not sent');
|
||||
}
|
||||
|
||||
this.updateChatwootMessageId(
|
||||
{
|
||||
...messageSent,
|
||||
owner: instance.instanceName,
|
||||
},
|
||||
{
|
||||
messageId: body.id,
|
||||
inboxId: body.inbox?.id,
|
||||
conversationId: body.conversation?.id,
|
||||
contactInbox: {
|
||||
sourceId: body.conversation?.contact_inbox?.source_id,
|
||||
this.updateChatwootMessageId(
|
||||
{
|
||||
...messageSent,
|
||||
owner: instance.instanceName,
|
||||
},
|
||||
},
|
||||
instance,
|
||||
);
|
||||
{
|
||||
messageId: body.id,
|
||||
inboxId: body.inbox?.id,
|
||||
conversationId: body.conversation?.id,
|
||||
contactInbox: {
|
||||
sourceId: body.conversation?.contact_inbox?.source_id,
|
||||
},
|
||||
},
|
||||
instance,
|
||||
);
|
||||
} catch (error) {
|
||||
if (!messageSent && body.conversation?.id) {
|
||||
this.onSendMessageError(instance, body.conversation?.id, error.toString());
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1845,7 +1906,8 @@ export class ChatwootService {
|
||||
|
||||
let nameFile: string;
|
||||
const messageBody = body?.message[body?.messageType];
|
||||
const originalFilename = messageBody?.fileName || messageBody?.message?.documentMessage?.fileName;
|
||||
const originalFilename =
|
||||
messageBody?.fileName || messageBody?.filename || messageBody?.message?.documentMessage?.fileName;
|
||||
if (originalFilename) {
|
||||
const parsedFile = path.parse(originalFilename);
|
||||
if (parsedFile.name && parsedFile.ext) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { inbox } from '@figuro/chatwoot-sdk';
|
||||
import { proto } from '@whiskeysockets/baileys';
|
||||
import { proto } from 'baileys';
|
||||
|
||||
import { InstanceDto } from '../../../../api/dto/instance.dto';
|
||||
import { ChatwootRaw, ContactRaw, MessageRaw } from '../../../../api/models';
|
||||
|
||||
@@ -30,10 +30,12 @@ export const chatwootSchema: JSONSchema7 = {
|
||||
url: { type: 'string' },
|
||||
sign_msg: { type: 'boolean', enum: [true, false] },
|
||||
sign_delimiter: { type: ['string', 'null'] },
|
||||
name_inbox: { type: ['string', 'null'] },
|
||||
reopen_conversation: { type: 'boolean', enum: [true, false] },
|
||||
conversation_pending: { type: 'boolean', enum: [true, false] },
|
||||
auto_create: { type: 'boolean', enum: [true, false] },
|
||||
import_contacts: { type: 'boolean', enum: [true, false] },
|
||||
merge_brazil_contacts: { type: 'boolean', enum: [true, false] },
|
||||
import_messages: { type: 'boolean', enum: [true, false] },
|
||||
days_limit_import_messages: { type: 'number' },
|
||||
},
|
||||
|
||||
@@ -6,44 +6,184 @@ import { Logger } from '../../../../config/logger.config';
|
||||
const logger = new Logger('AMQP');
|
||||
|
||||
let amqpChannel: amqp.Channel | null = null;
|
||||
let amqpConnection: amqp.Connection | null = null;
|
||||
let reconnectAttempts = 0;
|
||||
const maxReconnectAttempts = 10;
|
||||
const reconnectInterval = 5000; // 5 segundos
|
||||
|
||||
type ResolveCallback = () => void;
|
||||
type RejectCallback = (error: Error) => void;
|
||||
|
||||
export const initAMQP = () => {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const uri = configService.get<Rabbitmq>('RABBITMQ').URI;
|
||||
amqp.connect(uri, (error, connection) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
|
||||
connection.createChannel((channelError, channel) => {
|
||||
if (channelError) {
|
||||
reject(channelError);
|
||||
return;
|
||||
}
|
||||
|
||||
const exchangeName = 'evolution_exchange';
|
||||
|
||||
channel.assertExchange(exchangeName, 'topic', {
|
||||
durable: true,
|
||||
autoDelete: false,
|
||||
});
|
||||
|
||||
amqpChannel = channel;
|
||||
|
||||
logger.info('AMQP initialized');
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
connectToRabbitMQ(resolve, reject);
|
||||
});
|
||||
};
|
||||
|
||||
const connectToRabbitMQ = (resolve?: ResolveCallback, reject?: RejectCallback) => {
|
||||
const uri = configService.get<Rabbitmq>('RABBITMQ').URI;
|
||||
amqp.connect(uri, (error, connection) => {
|
||||
if (error) {
|
||||
logger.error(`Failed to connect to RabbitMQ: ${error.message}`);
|
||||
handleConnectionError(error, resolve, reject);
|
||||
return;
|
||||
}
|
||||
|
||||
reconnectAttempts = 0;
|
||||
amqpConnection = connection;
|
||||
|
||||
connection.on('error', (err) => {
|
||||
logger.error(`RabbitMQ connection error: ${err.message}`);
|
||||
scheduleReconnect();
|
||||
});
|
||||
|
||||
connection.on('close', () => {
|
||||
logger.warn('RabbitMQ connection closed unexpectedly');
|
||||
scheduleReconnect();
|
||||
});
|
||||
|
||||
createChannel(connection, resolve, reject);
|
||||
});
|
||||
};
|
||||
|
||||
const createChannel = (connection: amqp.Connection, resolve?: ResolveCallback, reject?: RejectCallback) => {
|
||||
connection.createChannel((channelError, channel) => {
|
||||
if (channelError) {
|
||||
logger.error(`Failed to create channel: ${channelError.message}`);
|
||||
if (reject) {
|
||||
reject(channelError);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const exchangeName = 'evolution_exchange';
|
||||
|
||||
channel.assertExchange(exchangeName, 'topic', {
|
||||
durable: true,
|
||||
autoDelete: false,
|
||||
});
|
||||
|
||||
channel.on('error', (err) => {
|
||||
logger.error(`RabbitMQ channel error: ${err.message}`);
|
||||
amqpChannel = null;
|
||||
createChannel(connection);
|
||||
});
|
||||
|
||||
channel.on('close', () => {
|
||||
logger.warn('RabbitMQ channel closed');
|
||||
amqpChannel = null;
|
||||
createChannel(connection);
|
||||
});
|
||||
|
||||
amqpChannel = channel;
|
||||
|
||||
logger.info('AMQP initialized');
|
||||
if (resolve) {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const scheduleReconnect = () => {
|
||||
if (reconnectAttempts >= maxReconnectAttempts) {
|
||||
logger.error(`Exceeded maximum ${maxReconnectAttempts} reconnection attempts to RabbitMQ`);
|
||||
return;
|
||||
}
|
||||
|
||||
amqpChannel = null;
|
||||
|
||||
if (amqpConnection) {
|
||||
try {
|
||||
amqpConnection.close();
|
||||
} catch (err) {
|
||||
// Ignora erro ao fechar conexão que já pode estar fechada
|
||||
}
|
||||
amqpConnection = null;
|
||||
}
|
||||
|
||||
reconnectAttempts++;
|
||||
const delay = reconnectInterval * Math.pow(1.5, reconnectAttempts - 1); // Backoff exponencial
|
||||
|
||||
logger.info(`Reconnection attempt ${reconnectAttempts} to RabbitMQ in ${delay}ms`);
|
||||
|
||||
setTimeout(() => {
|
||||
connectToRabbitMQ();
|
||||
}, delay);
|
||||
};
|
||||
|
||||
const handleConnectionError = (error: Error, resolve?: ResolveCallback, reject?: RejectCallback) => {
|
||||
if (reject && reconnectAttempts === 0) {
|
||||
// Na inicialização, rejeitar a Promise se for a primeira tentativa
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
|
||||
scheduleReconnect();
|
||||
};
|
||||
|
||||
export const getAMQP = (): amqp.Channel | null => {
|
||||
return amqpChannel;
|
||||
};
|
||||
|
||||
export const initGlobalQueues = () => {
|
||||
logger.info('Initializing global queues');
|
||||
const rabbitmqConfig = configService.get<Rabbitmq>('RABBITMQ');
|
||||
const events = rabbitmqConfig.EVENTS;
|
||||
const prefixKey = rabbitmqConfig.PREFIX_KEY;
|
||||
const messageTtl = rabbitmqConfig.MESSAGE_TTL;
|
||||
const maxLength = rabbitmqConfig.MAX_LENGTH;
|
||||
const maxLengthBytes = rabbitmqConfig.MAX_LENGTH_BYTES;
|
||||
|
||||
if (!events) {
|
||||
logger.warn('No events to initialize on AMQP');
|
||||
return;
|
||||
}
|
||||
|
||||
const eventKeys = Object.keys(events);
|
||||
|
||||
eventKeys.forEach((event) => {
|
||||
if (events[event] === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
const queueName =
|
||||
prefixKey !== ''
|
||||
? `${prefixKey}.${event.replace(/_/g, '.').toLowerCase()}`
|
||||
: `${event.replace(/_/g, '.').toLowerCase()}`;
|
||||
|
||||
const amqp = getAMQP();
|
||||
const exchangeName = 'evolution_exchange';
|
||||
|
||||
amqp.assertExchange(exchangeName, 'topic', {
|
||||
durable: true,
|
||||
autoDelete: false,
|
||||
});
|
||||
|
||||
amqp.assertQueue(queueName, {
|
||||
durable: true,
|
||||
autoDelete: false,
|
||||
arguments: {
|
||||
'x-queue-type': 'quorum',
|
||||
'x-message-ttl': messageTtl,
|
||||
'x-max-length': maxLength,
|
||||
'x-max-length-bytes': maxLengthBytes,
|
||||
'x-overflow': 'reject-publish',
|
||||
},
|
||||
});
|
||||
|
||||
amqp.bindQueue(queueName, exchangeName, event);
|
||||
});
|
||||
};
|
||||
|
||||
export const initQueues = (instanceName: string, events: string[]) => {
|
||||
if (!events || !events.length) return;
|
||||
if (!events || !events.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const rabbitmqConfig = configService.get<Rabbitmq>('RABBITMQ');
|
||||
const messageTtl = rabbitmqConfig.MESSAGE_TTL;
|
||||
const maxLength = rabbitmqConfig.MAX_LENGTH;
|
||||
const maxLengthBytes = rabbitmqConfig.MAX_LENGTH_BYTES;
|
||||
|
||||
const queues = events.map((event) => {
|
||||
return `${event.replace(/_/g, '.').toLowerCase()}`;
|
||||
@@ -65,6 +205,10 @@ export const initQueues = (instanceName: string, events: string[]) => {
|
||||
autoDelete: false,
|
||||
arguments: {
|
||||
'x-queue-type': 'quorum',
|
||||
'x-message-ttl': messageTtl,
|
||||
'x-max-length': maxLength,
|
||||
'x-max-length-bytes': maxLengthBytes,
|
||||
'x-overflow': 'reject-publish',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -73,7 +217,9 @@ export const initQueues = (instanceName: string, events: string[]) => {
|
||||
};
|
||||
|
||||
export const removeQueues = (instanceName: string, events: string[]) => {
|
||||
if (!events || !events.length) return;
|
||||
if (!events || !events.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
const channel = getAMQP();
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { SQS } from 'aws-sdk';
|
||||
import { SQS } from '@aws-sdk/client-sqs';
|
||||
|
||||
import { configService, Sqs } from '../../../../config/env.config';
|
||||
import { Logger } from '../../../../config/logger.config';
|
||||
@@ -12,8 +12,11 @@ export const initSQS = () => {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const awsConfig = configService.get<Sqs>('SQS');
|
||||
sqs = new SQS({
|
||||
accessKeyId: awsConfig.ACCESS_KEY_ID,
|
||||
secretAccessKey: awsConfig.SECRET_ACCESS_KEY,
|
||||
credentials: {
|
||||
accessKeyId: awsConfig.ACCESS_KEY_ID,
|
||||
secretAccessKey: awsConfig.SECRET_ACCESS_KEY,
|
||||
},
|
||||
|
||||
region: awsConfig.REGION,
|
||||
});
|
||||
|
||||
|
||||
@@ -519,18 +519,36 @@ export class TypebotService {
|
||||
text += element.text;
|
||||
}
|
||||
|
||||
if (
|
||||
element.children &&
|
||||
(element.type === 'p' ||
|
||||
element.type === 'a' ||
|
||||
element.type === 'inline-variable' ||
|
||||
element.type === 'variable')
|
||||
) {
|
||||
if (element.children && element.type !== 'a') {
|
||||
for (const child of element.children) {
|
||||
text += applyFormatting(child);
|
||||
}
|
||||
}
|
||||
|
||||
if (element.type === 'p' && element.type !== 'inline-variable') {
|
||||
text = text.trim() + '\n';
|
||||
}
|
||||
|
||||
if (element.type === 'inline-variable') {
|
||||
text = text.trim();
|
||||
}
|
||||
|
||||
if (element.type === 'ol') {
|
||||
text =
|
||||
'\n' +
|
||||
text
|
||||
.split('\n')
|
||||
.map((line, index) => (line ? `${index + 1}. ${line}` : ''))
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
if (element.type === 'li') {
|
||||
text = text
|
||||
.split('\n')
|
||||
.map((line) => (line ? ` ${line}` : ''))
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
let formats = '';
|
||||
|
||||
if (element.bold) {
|
||||
@@ -568,6 +586,8 @@ export class TypebotService {
|
||||
|
||||
formattedText = formattedText.replace(/\*\*/g, '').replace(/__/, '').replace(/~~/, '').replace(/\n$/, '');
|
||||
|
||||
formattedText = formattedText.replace(/\n$/, '');
|
||||
|
||||
await instance.textMessage({
|
||||
number: remoteJid.split('@')[0],
|
||||
options: {
|
||||
|
||||
@@ -8,13 +8,17 @@ const logger = new Logger('Socket');
|
||||
|
||||
let io: SocketIO;
|
||||
|
||||
const cors = configService.get<Cors>('CORS').ORIGIN;
|
||||
const origin = configService.get<Cors>('CORS').ORIGIN;
|
||||
const methods = configService.get<Cors>('CORS').METHODS;
|
||||
const credentials = configService.get<Cors>('CORS').CREDENTIALS;
|
||||
|
||||
export const initIO = (httpServer: Server) => {
|
||||
if (configService.get<Websocket>('WEBSOCKET')?.ENABLED) {
|
||||
io = new SocketIO(httpServer, {
|
||||
cors: {
|
||||
origin: cors,
|
||||
origin,
|
||||
methods,
|
||||
credentials,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -9,12 +9,12 @@ export class IntegrationRaw {
|
||||
token?: string;
|
||||
}
|
||||
|
||||
const sqsSchema = new Schema<IntegrationRaw>({
|
||||
const integrationSchema = new Schema<IntegrationRaw>({
|
||||
_id: { type: String, _id: true },
|
||||
integration: { type: String, required: true },
|
||||
number: { type: String, required: true },
|
||||
token: { type: String, required: true },
|
||||
});
|
||||
|
||||
export const IntegrationModel = dbserver?.model(IntegrationRaw.name, sqsSchema, 'integration');
|
||||
export const IntegrationModel = dbserver?.model(IntegrationRaw.name, integrationSchema, 'integration');
|
||||
export type IntegrationModel = typeof IntegrationModel;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import Long from 'long';
|
||||
import { Schema } from 'mongoose';
|
||||
|
||||
import { dbserver } from '../../libs/db.connect';
|
||||
@@ -23,15 +24,16 @@ export class MessageRaw {
|
||||
key?: Key;
|
||||
pushName?: string;
|
||||
participant?: string;
|
||||
message?: object;
|
||||
message?: any;
|
||||
messageType?: string;
|
||||
messageTimestamp?: number | Long.Long;
|
||||
messageTimestamp?: number | Long;
|
||||
owner: string;
|
||||
source?: 'android' | 'web' | 'ios' | 'unknown' | 'desktop';
|
||||
source_id?: string;
|
||||
source_reply_id?: string;
|
||||
chatwoot?: ChatwootMessage;
|
||||
contextInfo?: any;
|
||||
status?: wa.StatusMessage | any;
|
||||
}
|
||||
|
||||
type MessageRawBoolean<T> = {
|
||||
|
||||
@@ -11,6 +11,7 @@ export class SettingsRaw {
|
||||
read_messages?: boolean;
|
||||
read_status?: boolean;
|
||||
sync_full_history?: boolean;
|
||||
wavoipToken?: string;
|
||||
}
|
||||
|
||||
const settingsSchema = new Schema<SettingsRaw>({
|
||||
@@ -22,6 +23,7 @@ const settingsSchema = new Schema<SettingsRaw>({
|
||||
read_messages: { type: Boolean, required: true },
|
||||
read_status: { type: Boolean, required: true },
|
||||
sync_full_history: { type: Boolean, required: true },
|
||||
wavoipToken: { type: String, required: true },
|
||||
});
|
||||
|
||||
export const SettingsModel = dbserver?.model(SettingsRaw.name, settingsSchema, 'settings');
|
||||
|
||||
150
src/api/provider/sessions.ts
Normal file
150
src/api/provider/sessions.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
import axios from 'axios';
|
||||
import { execSync } from 'child_process';
|
||||
|
||||
import { Auth, ConfigService, ProviderSession } from '../../config/env.config';
|
||||
import { Logger } from '../../config/logger.config';
|
||||
|
||||
type ResponseSuccess = { status: number; data?: any };
|
||||
type ResponseProvider = Promise<[ResponseSuccess?, Error?]>;
|
||||
|
||||
export class ProviderFiles {
|
||||
constructor(private readonly configService: ConfigService) {
|
||||
this.baseUrl = `http://${this.config.HOST}:${this.config.PORT}/session/${this.config.PREFIX}`;
|
||||
this.globalApiToken = this.configService.get<Auth>('AUTHENTICATION').API_KEY.KEY;
|
||||
}
|
||||
|
||||
private readonly logger = new Logger(ProviderFiles.name);
|
||||
|
||||
private baseUrl: string;
|
||||
private globalApiToken: string;
|
||||
|
||||
private readonly config = Object.freeze(this.configService.get<ProviderSession>('PROVIDER'));
|
||||
|
||||
get isEnabled() {
|
||||
return !!this.config?.ENABLED;
|
||||
}
|
||||
|
||||
public async onModuleInit() {
|
||||
if (this.config.ENABLED) {
|
||||
const url = `http://${this.config.HOST}:${this.config.PORT}`;
|
||||
try {
|
||||
const response = await axios.options(url + '/ping');
|
||||
if (response?.data != 'pong') {
|
||||
throw new Error('Offline file provider.');
|
||||
}
|
||||
|
||||
await axios.post(`${url}/session`, { group: this.config.PREFIX }, { headers: { apikey: this.globalApiToken } });
|
||||
} catch (error) {
|
||||
this.logger.error(['Failed to connect to the file server', error?.message, error?.stack]);
|
||||
const pid = process.pid;
|
||||
execSync(`kill -9 ${pid}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async onModuleDestroy() {
|
||||
//
|
||||
}
|
||||
|
||||
public async create(instance: string): ResponseProvider {
|
||||
try {
|
||||
const response = await axios.post(
|
||||
`${this.baseUrl}`,
|
||||
{
|
||||
instance,
|
||||
},
|
||||
{ headers: { apikey: this.globalApiToken } },
|
||||
);
|
||||
return [{ status: response.status, data: response?.data }];
|
||||
} catch (error) {
|
||||
return [
|
||||
{
|
||||
status: error?.response?.status,
|
||||
data: error?.response?.data,
|
||||
},
|
||||
error,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public async write(instance: string, key: string, data: any): ResponseProvider {
|
||||
try {
|
||||
const response = await axios.post(`${this.baseUrl}/${instance}/${key}`, data, {
|
||||
headers: { apikey: this.globalApiToken },
|
||||
});
|
||||
return [{ status: response.status, data: response?.data }];
|
||||
} catch (error) {
|
||||
return [
|
||||
{
|
||||
status: error?.response?.status,
|
||||
data: error?.response?.data,
|
||||
},
|
||||
error,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public async read(instance: string, key: string): ResponseProvider {
|
||||
try {
|
||||
const response = await axios.get(`${this.baseUrl}/${instance}/${key}`, {
|
||||
headers: { apikey: this.globalApiToken },
|
||||
});
|
||||
return [{ status: response.status, data: response?.data }];
|
||||
} catch (error) {
|
||||
return [
|
||||
{
|
||||
status: error?.response?.status,
|
||||
data: error?.response?.data,
|
||||
},
|
||||
error,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public async delete(instance: string, key: string): ResponseProvider {
|
||||
try {
|
||||
const response = await axios.delete(`${this.baseUrl}/${instance}/${key}`, {
|
||||
headers: { apikey: this.globalApiToken },
|
||||
});
|
||||
return [{ status: response.status, data: response?.data }];
|
||||
} catch (error) {
|
||||
return [
|
||||
{
|
||||
status: error?.response?.status,
|
||||
data: error?.response?.data,
|
||||
},
|
||||
error,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public async allInstances(): ResponseProvider {
|
||||
try {
|
||||
const response = await axios.get(`${this.baseUrl}/list-instances`, { headers: { apikey: this.globalApiToken } });
|
||||
return [{ status: response.status, data: response?.data as string[] }];
|
||||
} catch (error) {
|
||||
return [
|
||||
{
|
||||
status: error?.response?.status,
|
||||
data: error?.response?.data,
|
||||
},
|
||||
error,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
public async removeSession(instance: string): ResponseProvider {
|
||||
try {
|
||||
const response = await axios.delete(`${this.baseUrl}/${instance}`, { headers: { apikey: this.globalApiToken } });
|
||||
return [{ status: response.status, data: response?.data }];
|
||||
} catch (error) {
|
||||
return [
|
||||
{
|
||||
status: error?.response?.status,
|
||||
data: error?.response?.data,
|
||||
},
|
||||
error,
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,20 @@ export class AuthRepository extends Repository {
|
||||
}
|
||||
}
|
||||
|
||||
public async findByKey(key: string): Promise<AuthRaw> {
|
||||
try {
|
||||
this.logger.verbose('finding auth');
|
||||
if (this.dbSettings.ENABLED) {
|
||||
this.logger.verbose('finding auth in db');
|
||||
return await this.authModel.findOne({ apikey: key });
|
||||
}
|
||||
|
||||
return {};
|
||||
} catch (error) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
public async list(): Promise<AuthRaw[]> {
|
||||
try {
|
||||
if (this.dbSettings.ENABLED) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
blockUserSchema,
|
||||
contactValidateSchema,
|
||||
deleteMessageSchema,
|
||||
markChatUnreadSchema,
|
||||
messageUpSchema,
|
||||
messageValidateSchema,
|
||||
presenceSchema,
|
||||
@@ -24,6 +25,7 @@ import {
|
||||
BlockUserDto,
|
||||
DeleteMessage,
|
||||
getBase64FromMediaMessageDto,
|
||||
MarkChatUnreadDto,
|
||||
NumberDto,
|
||||
PrivacySettingDto,
|
||||
ProfileNameDto,
|
||||
@@ -98,6 +100,23 @@ export class ChatRouter extends RouterBroker {
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.put(this.routerPath('markChatUnread'), ...guards, async (req, res) => {
|
||||
logger.verbose('request received in markChatUnread');
|
||||
logger.verbose('request body: ');
|
||||
logger.verbose(req.body);
|
||||
|
||||
logger.verbose('request query: ');
|
||||
logger.verbose(req.query);
|
||||
|
||||
const response = await this.dataValidate<MarkChatUnreadDto>({
|
||||
request: req,
|
||||
schema: markChatUnreadSchema,
|
||||
ClassRef: MarkChatUnreadDto,
|
||||
execute: (instance, data) => chatController.markChatUnread(instance, data),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.CREATED).json(response);
|
||||
})
|
||||
.delete(this.routerPath('deleteMessageForEveryone'), ...guards, async (req, res) => {
|
||||
logger.verbose('request received in deleteMessageForEveryone');
|
||||
logger.verbose('request body: ');
|
||||
@@ -234,6 +253,23 @@ export class ChatRouter extends RouterBroker {
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.get(this.routerPath('fetchContactsWithLastMessage'), ...guards, async (req, res) => {
|
||||
logger.verbose('request received in fetchContactsWithLastMessage');
|
||||
logger.verbose('request body: ');
|
||||
logger.verbose(req.body);
|
||||
|
||||
logger.verbose('request query: ');
|
||||
logger.verbose(req.query);
|
||||
|
||||
const response = await this.dataValidate<InstanceDto>({
|
||||
request: req,
|
||||
schema: null,
|
||||
ClassRef: InstanceDto,
|
||||
execute: (instance) => chatController.fetchContactsWithLastMessage(instance),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.post(this.routerPath('sendPresence'), ...guards, async (req, res) => {
|
||||
logger.verbose('request received in sendPresence');
|
||||
logger.verbose('request body: ');
|
||||
|
||||
@@ -99,20 +99,28 @@ export class InstanceRouter extends RouterBroker {
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
})
|
||||
.get(this.routerPath('fetchInstances', false), ...guards, async (req, res) => {
|
||||
logger.verbose('request received in fetchInstances');
|
||||
logger.verbose('request body: ');
|
||||
logger.verbose(req.body);
|
||||
try {
|
||||
logger.verbose('request received in fetchInstances');
|
||||
logger.verbose('request body: ');
|
||||
logger.verbose(req.body);
|
||||
|
||||
logger.verbose('request query: ');
|
||||
logger.verbose(req.query);
|
||||
const response = await this.dataValidate<InstanceDto>({
|
||||
request: req,
|
||||
schema: null,
|
||||
ClassRef: InstanceDto,
|
||||
execute: (instance) => instanceController.fetchInstances(instance),
|
||||
});
|
||||
const key = req.get('apikey');
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
logger.verbose('request query: ');
|
||||
logger.verbose(req.query);
|
||||
const response = await this.dataValidate<InstanceDto>({
|
||||
request: req,
|
||||
schema: null,
|
||||
ClassRef: InstanceDto,
|
||||
execute: (instance) => instanceController.fetchInstances(instance, key),
|
||||
});
|
||||
|
||||
return res.status(HttpStatus.OK).json(response);
|
||||
} catch (error) {
|
||||
logger.error('fetchInstances');
|
||||
logger.error(error);
|
||||
return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ error: true, message: error.message });
|
||||
}
|
||||
})
|
||||
.post(this.routerPath('setPresence'), ...guards, async (req, res) => {
|
||||
logger.verbose('request received in setPresence');
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { CacheEngine } from '../cache/cacheengine';
|
||||
import { configService } from '../config/env.config';
|
||||
import { configService, ProviderSession } from '../config/env.config';
|
||||
import { eventEmitter } from '../config/event.config';
|
||||
import { Logger } from '../config/logger.config';
|
||||
import { dbserver } from '../libs/db.connect';
|
||||
@@ -47,6 +47,7 @@ import {
|
||||
WebsocketModel,
|
||||
} from './models';
|
||||
import { LabelModel } from './models/label.model';
|
||||
import { ProviderFiles } from './provider/sessions';
|
||||
import { AuthRepository } from './repository/auth.repository';
|
||||
import { ChatRepository } from './repository/chat.repository';
|
||||
import { ContactRepository } from './repository/contact.repository';
|
||||
@@ -108,7 +109,13 @@ export const repository = new RepositoryBroker(
|
||||
|
||||
export const cache = new CacheService(new CacheEngine(configService, 'instance').getEngine());
|
||||
const chatwootCache = new CacheService(new CacheEngine(configService, ChatwootService.name).getEngine());
|
||||
const messagesLostCache = new CacheService(new CacheEngine(configService, 'baileys').getEngine());
|
||||
const baileysCache = new CacheService(new CacheEngine(configService, 'baileys').getEngine());
|
||||
|
||||
let providerFiles: ProviderFiles = null;
|
||||
|
||||
if (configService.get<ProviderSession>('PROVIDER')?.ENABLED) {
|
||||
providerFiles = new ProviderFiles(configService);
|
||||
}
|
||||
|
||||
export const waMonitor = new WAMonitoringService(
|
||||
eventEmitter,
|
||||
@@ -116,7 +123,8 @@ export const waMonitor = new WAMonitoringService(
|
||||
repository,
|
||||
cache,
|
||||
chatwootCache,
|
||||
messagesLostCache,
|
||||
baileysCache,
|
||||
providerFiles,
|
||||
);
|
||||
|
||||
const authService = new AuthService(configService, waMonitor, repository);
|
||||
@@ -167,7 +175,8 @@ export const instanceController = new InstanceController(
|
||||
proxyController,
|
||||
cache,
|
||||
chatwootCache,
|
||||
messagesLostCache,
|
||||
baileysCache,
|
||||
providerFiles,
|
||||
);
|
||||
export const sendMessageController = new SendMessageController(waMonitor);
|
||||
export const chatController = new ChatController(waMonitor);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { BufferJSON } from '@whiskeysockets/baileys';
|
||||
import { BufferJSON } from 'baileys';
|
||||
|
||||
import { Logger } from '../../config/logger.config';
|
||||
import { ICache } from '../abstract/abstract.cache';
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { WASocket } from '@whiskeysockets/baileys';
|
||||
import axios from 'axios';
|
||||
import { WASocket } from 'baileys';
|
||||
import { execSync } from 'child_process';
|
||||
import { isURL } from 'class-validator';
|
||||
import EventEmitter2 from 'eventemitter2';
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
Database,
|
||||
HttpServer,
|
||||
Log,
|
||||
Rabbitmq,
|
||||
Sqs,
|
||||
Webhook,
|
||||
Websocket,
|
||||
@@ -38,17 +39,17 @@ import { waMonitor } from '../server.module';
|
||||
import { Events, wa } from '../types/wa.types';
|
||||
import { CacheService } from './cache.service';
|
||||
|
||||
export class WAStartupService {
|
||||
export class ChannelStartupService {
|
||||
constructor(
|
||||
public readonly configService: ConfigService,
|
||||
public readonly eventEmitter: EventEmitter2,
|
||||
public readonly repository: RepositoryBroker,
|
||||
public readonly chatwootCache: CacheService,
|
||||
) {
|
||||
this.logger.verbose('WAStartupService initialized');
|
||||
this.logger.verbose('ChannelStartupService initialized');
|
||||
}
|
||||
|
||||
public readonly logger = new Logger(WAStartupService.name);
|
||||
public readonly logger = new Logger(ChannelStartupService.name);
|
||||
|
||||
public client: WASocket;
|
||||
public readonly instance: wa.Instance = {};
|
||||
@@ -136,11 +137,13 @@ export class WAStartupService {
|
||||
|
||||
public async findIntegration() {
|
||||
this.logger.verbose('Finding integration');
|
||||
const data = await this.repository.integration.find(this.instanceName);
|
||||
let data: any;
|
||||
|
||||
data = await this.repository.integration.find(this.instanceName);
|
||||
|
||||
if (!data) {
|
||||
this.logger.verbose('Integration not found');
|
||||
throw new NotFoundException('Integration not found');
|
||||
this.repository.integration.create({ integration: 'WHATSAPP-BAILEYS', number: '', token: '' }, this.instanceName);
|
||||
data = { integration: 'WHATSAPP-BAILEYS', number: '', token: '' };
|
||||
}
|
||||
|
||||
this.logger.verbose(`Integration: ${data.integration}`);
|
||||
@@ -178,6 +181,9 @@ export class WAStartupService {
|
||||
this.localSettings.sync_full_history = data?.sync_full_history;
|
||||
this.logger.verbose(`Settings sync_full_history: ${this.localSettings.sync_full_history}`);
|
||||
|
||||
this.localSettings.wavoipToken = data?.wavoipToken;
|
||||
this.logger.verbose(`Settings wavoipToken: ${this.localSettings.wavoipToken}`);
|
||||
|
||||
this.logger.verbose('Settings loaded');
|
||||
}
|
||||
|
||||
@@ -191,8 +197,15 @@ export class WAStartupService {
|
||||
this.logger.verbose(`Settings read_messages: ${data.read_messages}`);
|
||||
this.logger.verbose(`Settings read_status: ${data.read_status}`);
|
||||
this.logger.verbose(`Settings sync_full_history: ${data.sync_full_history}`);
|
||||
this.logger.verbose(`Settings wavoipToken: ${data.wavoipToken}`);
|
||||
Object.assign(this.localSettings, data);
|
||||
this.logger.verbose('Settings set');
|
||||
|
||||
// restart instance
|
||||
if (this.localSettings.wavoipToken && this.localSettings.wavoipToken.length > 0) {
|
||||
this.client.ws.close();
|
||||
this.client.ws.connect();
|
||||
}
|
||||
}
|
||||
|
||||
public async findSettings() {
|
||||
@@ -211,6 +224,7 @@ export class WAStartupService {
|
||||
this.logger.verbose(`Settings read_messages: ${data.read_messages}`);
|
||||
this.logger.verbose(`Settings read_status: ${data.read_status}`);
|
||||
this.logger.verbose(`Settings sync_full_history: ${data.sync_full_history}`);
|
||||
this.logger.verbose(`Settings wavoipToken: ${data.wavoipToken}`);
|
||||
return {
|
||||
reject_call: data.reject_call,
|
||||
msg_call: data.msg_call,
|
||||
@@ -219,6 +233,7 @@ export class WAStartupService {
|
||||
read_messages: data.read_messages,
|
||||
read_status: data.read_status,
|
||||
sync_full_history: data.sync_full_history,
|
||||
wavoipToken: data.wavoipToken,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -303,6 +318,9 @@ export class WAStartupService {
|
||||
this.localChatwoot.conversation_pending = data?.conversation_pending;
|
||||
this.logger.verbose(`Chatwoot conversation pending: ${this.localChatwoot.conversation_pending}`);
|
||||
|
||||
this.localChatwoot.merge_brazil_contacts = data?.merge_brazil_contacts;
|
||||
this.logger.verbose(`Chatwoot merge brazil contacts: ${this.localChatwoot.merge_brazil_contacts}`);
|
||||
|
||||
this.localChatwoot.import_contacts = data?.import_contacts;
|
||||
this.logger.verbose(`Chatwoot import contacts: ${this.localChatwoot.import_contacts}`);
|
||||
|
||||
@@ -326,6 +344,7 @@ export class WAStartupService {
|
||||
this.logger.verbose(`Chatwoot sign delimiter: ${data.sign_delimiter}`);
|
||||
this.logger.verbose(`Chatwoot reopen conversation: ${data.reopen_conversation}`);
|
||||
this.logger.verbose(`Chatwoot conversation pending: ${data.conversation_pending}`);
|
||||
this.logger.verbose(`Chatwoot merge brazil contacts: ${data.merge_brazil_contacts}`);
|
||||
this.logger.verbose(`Chatwoot import contacts: ${data.import_contacts}`);
|
||||
this.logger.verbose(`Chatwoot import messages: ${data.import_messages}`);
|
||||
this.logger.verbose(`Chatwoot days limit import messages: ${data.days_limit_import_messages}`);
|
||||
@@ -354,6 +373,7 @@ export class WAStartupService {
|
||||
this.logger.verbose(`Chatwoot sign delimiter: ${data.sign_delimiter}`);
|
||||
this.logger.verbose(`Chatwoot reopen conversation: ${data.reopen_conversation}`);
|
||||
this.logger.verbose(`Chatwoot conversation pending: ${data.conversation_pending}`);
|
||||
this.logger.verbose(`Chatwoot merge brazilian contacts: ${data.merge_brazil_contacts}`);
|
||||
this.logger.verbose(`Chatwoot import contacts: ${data.import_contacts}`);
|
||||
this.logger.verbose(`Chatwoot import messages: ${data.import_messages}`);
|
||||
this.logger.verbose(`Chatwoot days limit import messages: ${data.days_limit_import_messages}`);
|
||||
@@ -368,6 +388,7 @@ export class WAStartupService {
|
||||
sign_delimiter: data.sign_delimiter || null,
|
||||
reopen_conversation: data.reopen_conversation,
|
||||
conversation_pending: data.conversation_pending,
|
||||
merge_brazil_contacts: data.merge_brazil_contacts,
|
||||
import_contacts: data.import_contacts,
|
||||
import_messages: data.import_messages,
|
||||
days_limit_import_messages: data.days_limit_import_messages,
|
||||
@@ -677,13 +698,54 @@ export class WAStartupService {
|
||||
});
|
||||
};
|
||||
|
||||
public async sendDataWebhook<T = any>(event: Events, data: T, local = true) {
|
||||
private async retryWebhookRequest(
|
||||
httpService: any,
|
||||
postData: any,
|
||||
baseURL: string,
|
||||
isGlobal = false,
|
||||
maxRetries = 10,
|
||||
delaySeconds = 30,
|
||||
) {
|
||||
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
await httpService.post('', postData);
|
||||
if (attempt > 1) {
|
||||
this.logger.verbose(`Webhook ${isGlobal ? 'global' : 'local'} enviado com sucesso na tentativa ${attempt}`);
|
||||
}
|
||||
return;
|
||||
} catch (error) {
|
||||
if (attempt === maxRetries) {
|
||||
throw error; // Propaga o erro após todas as tentativas
|
||||
}
|
||||
|
||||
this.logger.warn({
|
||||
local: `${ChannelStartupService.name}.retryWebhookRequest-${isGlobal ? 'global' : 'local'}`,
|
||||
message: `Tentativa ${attempt}/${maxRetries} falhou. Próxima tentativa em ${delaySeconds} segundos`,
|
||||
error: error?.message,
|
||||
url: baseURL,
|
||||
});
|
||||
|
||||
// Aguarda o delay antes da próxima tentativa
|
||||
await new Promise((resolve) => setTimeout(resolve, delaySeconds * 1000));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async sendDataWebhook<T = any>(
|
||||
event: Events,
|
||||
data: T,
|
||||
local = true,
|
||||
integration = ['websocket', 'rabbitmq', 'sqs', 'webhook'],
|
||||
) {
|
||||
const webhookGlobal = this.configService.get<Webhook>('WEBHOOK');
|
||||
const webhookLocal = this.localWebhook.events;
|
||||
const websocketLocal = this.localWebsocket.events;
|
||||
const rabbitmqLocal = this.localRabbitmq.events;
|
||||
const sqsLocal = this.localSqs.events;
|
||||
const serverUrl = this.configService.get<HttpServer>('SERVER').URL;
|
||||
const rabbitmqEnabled = this.configService.get<Rabbitmq>('RABBITMQ').ENABLED;
|
||||
const rabbitmqGlobal = this.configService.get<Rabbitmq>('RABBITMQ').GLOBAL_ENABLED;
|
||||
const rabbitmqEvents = this.configService.get<Rabbitmq>('RABBITMQ').EVENTS;
|
||||
const we = event.replace(/[.-]/gm, '_').toUpperCase();
|
||||
const transformedWe = we.replace(/_/gm, '-').toLowerCase();
|
||||
const tzoffset = new Date().getTimezoneOffset() * 60000; //offset in milliseconds
|
||||
@@ -694,73 +756,152 @@ export class WAStartupService {
|
||||
const tokenStore = await this.repository.auth.find(this.instanceName);
|
||||
const instanceApikey = tokenStore?.apikey || 'Apikey not found';
|
||||
|
||||
if (this.localRabbitmq.enabled) {
|
||||
if (rabbitmqEnabled && integration.includes('rabbitmq')) {
|
||||
const amqp = getAMQP();
|
||||
|
||||
if (amqp) {
|
||||
if (this.localRabbitmq.enabled && amqp) {
|
||||
if (Array.isArray(rabbitmqLocal) && rabbitmqLocal.includes(we)) {
|
||||
const exchangeName = this.instanceName ?? 'evolution_exchange';
|
||||
|
||||
// await amqp.assertExchange(exchangeName, 'topic', {
|
||||
// durable: true,
|
||||
// autoDelete: false,
|
||||
// });
|
||||
let retry = 0;
|
||||
|
||||
await this.assertExchangeAsync(amqp, exchangeName, 'topic', {
|
||||
durable: true,
|
||||
autoDelete: false,
|
||||
});
|
||||
while (retry < 3) {
|
||||
try {
|
||||
await amqp.assertExchange(exchangeName, 'topic', {
|
||||
durable: true,
|
||||
autoDelete: false,
|
||||
});
|
||||
|
||||
const queueName = `${this.instanceName}.${event}`;
|
||||
const eventName = event.replace(/_/g, '.').toLowerCase();
|
||||
|
||||
await amqp.assertQueue(queueName, {
|
||||
durable: true,
|
||||
autoDelete: false,
|
||||
arguments: {
|
||||
'x-queue-type': 'quorum',
|
||||
},
|
||||
});
|
||||
const queueName = `${this.instanceName}.${eventName}`;
|
||||
|
||||
await amqp.bindQueue(queueName, exchangeName, event);
|
||||
await amqp.assertQueue(queueName, {
|
||||
durable: true,
|
||||
autoDelete: false,
|
||||
arguments: {
|
||||
'x-queue-type': 'quorum',
|
||||
},
|
||||
});
|
||||
|
||||
const message = {
|
||||
event,
|
||||
instance: this.instance.name,
|
||||
data,
|
||||
server_url: serverUrl,
|
||||
date_time: now,
|
||||
sender: this.wuid,
|
||||
};
|
||||
await amqp.bindQueue(queueName, exchangeName, eventName);
|
||||
|
||||
if (expose && instanceApikey) {
|
||||
message['apikey'] = instanceApikey;
|
||||
const message = {
|
||||
event,
|
||||
instance: this.instance.name,
|
||||
data,
|
||||
server_url: serverUrl,
|
||||
date_time: now,
|
||||
sender: this.wuid,
|
||||
};
|
||||
|
||||
if (expose && instanceApikey) {
|
||||
message['apikey'] = instanceApikey;
|
||||
}
|
||||
|
||||
await amqp.publish(exchangeName, event, Buffer.from(JSON.stringify(message)), {
|
||||
persistent: false,
|
||||
expiration: this.configService.get<Rabbitmq>('RABBITMQ').MESSAGE_TTL.toString(),
|
||||
});
|
||||
|
||||
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
|
||||
const logData = {
|
||||
local: ChannelStartupService.name + '.sendData-RabbitMQ',
|
||||
event,
|
||||
instance: this.instance.name,
|
||||
data,
|
||||
server_url: serverUrl,
|
||||
apikey: (expose && instanceApikey) || null,
|
||||
date_time: now,
|
||||
sender: this.wuid,
|
||||
};
|
||||
|
||||
if (expose && instanceApikey) {
|
||||
logData['apikey'] = instanceApikey;
|
||||
}
|
||||
|
||||
this.logger.log(logData);
|
||||
}
|
||||
break;
|
||||
} catch (error) {
|
||||
retry++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await amqp.publish(exchangeName, event, Buffer.from(JSON.stringify(message)));
|
||||
if (rabbitmqGlobal && rabbitmqEvents[we] && amqp) {
|
||||
const exchangeName = 'evolution_exchange';
|
||||
const prefixKey = this.configService.get<Rabbitmq>('RABBITMQ').PREFIX_KEY;
|
||||
|
||||
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
|
||||
const logData = {
|
||||
local: WAStartupService.name + '.sendData-RabbitMQ',
|
||||
let retry = 0;
|
||||
|
||||
while (retry < 3) {
|
||||
try {
|
||||
await amqp.assertExchange(exchangeName, 'topic', {
|
||||
durable: true,
|
||||
autoDelete: false,
|
||||
});
|
||||
|
||||
const queueName = prefixKey
|
||||
? `${prefixKey}.${event.replace(/_/g, '.').toLowerCase()}`
|
||||
: event.replace(/_/g, '.').toLowerCase();
|
||||
|
||||
await amqp.assertQueue(queueName, {
|
||||
durable: true,
|
||||
autoDelete: false,
|
||||
arguments: {
|
||||
'x-queue-type': 'quorum',
|
||||
},
|
||||
});
|
||||
|
||||
await amqp.bindQueue(queueName, exchangeName, queueName);
|
||||
|
||||
const message = {
|
||||
event,
|
||||
instance: this.instance.name,
|
||||
data,
|
||||
server_url: serverUrl,
|
||||
apikey: (expose && instanceApikey) || null,
|
||||
date_time: now,
|
||||
sender: this.wuid,
|
||||
};
|
||||
|
||||
if (expose && instanceApikey) {
|
||||
logData['apikey'] = instanceApikey;
|
||||
message['apikey'] = instanceApikey;
|
||||
}
|
||||
|
||||
this.logger.log(logData);
|
||||
await amqp.publish(exchangeName, queueName, Buffer.from(JSON.stringify(message)), {
|
||||
persistent: false,
|
||||
expiration: this.configService.get<Rabbitmq>('RABBITMQ').MESSAGE_TTL.toString(),
|
||||
});
|
||||
|
||||
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
|
||||
const logData = {
|
||||
local: ChannelStartupService.name + '.sendData-RabbitMQ-Global',
|
||||
event,
|
||||
instance: this.instance.name,
|
||||
data,
|
||||
server_url: serverUrl,
|
||||
apikey: (expose && instanceApikey) || null,
|
||||
date_time: now,
|
||||
sender: this.wuid,
|
||||
};
|
||||
|
||||
if (expose && instanceApikey) {
|
||||
logData['apikey'] = instanceApikey;
|
||||
}
|
||||
|
||||
this.logger.log(logData);
|
||||
}
|
||||
|
||||
break;
|
||||
} catch (error) {
|
||||
retry++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.localSqs.enabled) {
|
||||
if (this.localSqs.enabled && integration.includes('sqs')) {
|
||||
const sqs = getSQS();
|
||||
|
||||
if (sqs) {
|
||||
@@ -796,7 +937,7 @@ export class WAStartupService {
|
||||
sqs.sendMessage(params, (err, data) => {
|
||||
if (err) {
|
||||
this.logger.error({
|
||||
local: WAStartupService.name + '.sendData-SQS',
|
||||
local: ChannelStartupService.name + '.sendData-SQS',
|
||||
message: err?.message,
|
||||
hostName: err?.hostname,
|
||||
code: err?.code,
|
||||
@@ -808,7 +949,7 @@ export class WAStartupService {
|
||||
} else {
|
||||
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
|
||||
const logData = {
|
||||
local: WAStartupService.name + '.sendData-SQS',
|
||||
local: ChannelStartupService.name + '.sendData-SQS',
|
||||
event,
|
||||
instance: this.instance.name,
|
||||
data,
|
||||
@@ -830,7 +971,7 @@ export class WAStartupService {
|
||||
}
|
||||
}
|
||||
|
||||
if (this.configService.get<Websocket>('WEBSOCKET')?.ENABLED) {
|
||||
if (this.configService.get<Websocket>('WEBSOCKET')?.ENABLED && integration.includes('websocket')) {
|
||||
this.logger.verbose('Sending data to websocket on channel: ' + this.instance.name);
|
||||
const io = getIO();
|
||||
|
||||
@@ -852,7 +993,7 @@ export class WAStartupService {
|
||||
|
||||
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
|
||||
const logData = {
|
||||
local: WAStartupService.name + '.sendData-WebsocketGlobal',
|
||||
local: ChannelStartupService.name + '.sendData-WebsocketGlobal',
|
||||
event,
|
||||
instance: this.instance.name,
|
||||
data,
|
||||
@@ -882,7 +1023,7 @@ export class WAStartupService {
|
||||
|
||||
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
|
||||
const logData = {
|
||||
local: WAStartupService.name + '.sendData-Websocket',
|
||||
local: ChannelStartupService.name + '.sendData-Websocket',
|
||||
event,
|
||||
instance: this.instance.name,
|
||||
data,
|
||||
@@ -904,7 +1045,7 @@ export class WAStartupService {
|
||||
const globalApiKey = this.configService.get<Auth>('AUTHENTICATION').API_KEY.KEY;
|
||||
|
||||
if (local) {
|
||||
if (Array.isArray(webhookLocal) && webhookLocal.includes(we)) {
|
||||
if (Array.isArray(webhookLocal) && webhookLocal.includes(we) && integration.includes('webhook')) {
|
||||
this.logger.verbose('Sending data to webhook local');
|
||||
let baseURL: string;
|
||||
|
||||
@@ -916,7 +1057,7 @@ export class WAStartupService {
|
||||
|
||||
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
|
||||
const logData = {
|
||||
local: WAStartupService.name + '.sendDataWebhook-local',
|
||||
local: ChannelStartupService.name + '.sendDataWebhook-local',
|
||||
url: baseURL,
|
||||
event,
|
||||
instance: this.instance.name,
|
||||
@@ -952,12 +1093,13 @@ export class WAStartupService {
|
||||
postData['apikey'] = instanceApikey;
|
||||
}
|
||||
|
||||
await httpService.post('', postData);
|
||||
await this.retryWebhookRequest(httpService, postData, baseURL);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
local: WAStartupService.name + '.sendDataWebhook-local',
|
||||
message: error?.message,
|
||||
local: ChannelStartupService.name + '.sendDataWebhook-local',
|
||||
message: 'Todas as tentativas de envio do webhook local falharam',
|
||||
lastError: error?.message,
|
||||
hostName: error?.hostname,
|
||||
syscall: error?.syscall,
|
||||
code: error?.code,
|
||||
@@ -971,7 +1113,7 @@ export class WAStartupService {
|
||||
}
|
||||
}
|
||||
|
||||
if (webhookGlobal.GLOBAL?.ENABLED) {
|
||||
if (webhookGlobal.GLOBAL?.ENABLED && integration.includes('webhook')) {
|
||||
if (webhookGlobal.EVENTS[we]) {
|
||||
this.logger.verbose('Sending data to webhook global');
|
||||
const globalWebhook = this.configService.get<Webhook>('WEBHOOK').GLOBAL;
|
||||
@@ -988,7 +1130,7 @@ export class WAStartupService {
|
||||
|
||||
if (this.configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
|
||||
const logData = {
|
||||
local: WAStartupService.name + '.sendDataWebhook-global',
|
||||
local: ChannelStartupService.name + '.sendDataWebhook-global',
|
||||
url: globalURL,
|
||||
event,
|
||||
instance: this.instance.name,
|
||||
@@ -1023,12 +1165,13 @@ export class WAStartupService {
|
||||
postData['apikey'] = globalApiKey;
|
||||
}
|
||||
|
||||
await httpService.post('', postData);
|
||||
await this.retryWebhookRequest(httpService, postData, globalURL, true);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
local: WAStartupService.name + '.sendDataWebhook-global',
|
||||
message: error?.message,
|
||||
local: ChannelStartupService.name + '.sendDataWebhook-global',
|
||||
message: 'Todas as tentativas de envio do webhook global falharam',
|
||||
lastError: error?.message,
|
||||
hostName: error?.hostname,
|
||||
syscall: error?.syscall,
|
||||
code: error?.code,
|
||||
@@ -1202,4 +1345,36 @@ export class WAStartupService {
|
||||
this.logger.verbose('Fetching chats');
|
||||
return await this.repository.chat.find({ where: { owner: this.instance.name } });
|
||||
}
|
||||
|
||||
public async fetchContactsWithLastMessage() {
|
||||
this.logger.verbose('Searching for contacts with last message');
|
||||
const contacts = await this.repository.contact.find({ where: { owner: this.instance.name } });
|
||||
const result = [];
|
||||
const seenIds = new Set();
|
||||
|
||||
for (const contact of contacts) {
|
||||
if (seenIds.has(contact.id)) {
|
||||
continue;
|
||||
}
|
||||
seenIds.add(contact.id);
|
||||
|
||||
const messages = await this.repository.message.find({
|
||||
where: {
|
||||
owner: this.instance.name,
|
||||
key: { remoteJid: contact.id },
|
||||
},
|
||||
limit: 1,
|
||||
});
|
||||
if (messages && messages.length > 0) {
|
||||
result.push({
|
||||
id: contact.id,
|
||||
pushName: contact?.pushName ?? null,
|
||||
profilePictureUrl: contact?.profilePictureUrl ?? null,
|
||||
owner: contact.owner,
|
||||
lastMessage: messages[0],
|
||||
});
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
78
src/api/services/channels/voiceCalls/transport.type.ts
Normal file
78
src/api/services/channels/voiceCalls/transport.type.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import { BinaryNode, Contact, JidWithDevice, proto, WAConnectionState } from 'baileys';
|
||||
|
||||
export interface ServerToClientEvents {
|
||||
withAck: (d: string, callback: (e: number) => void) => void;
|
||||
onWhatsApp: onWhatsAppType;
|
||||
profilePictureUrl: ProfilePictureUrlType;
|
||||
assertSessions: AssertSessionsType;
|
||||
createParticipantNodes: CreateParticipantNodesType;
|
||||
getUSyncDevices: GetUSyncDevicesType;
|
||||
generateMessageTag: GenerateMessageTagType;
|
||||
sendNode: SendNodeType;
|
||||
'signalRepository:decryptMessage': SignalRepositoryDecryptMessageType;
|
||||
}
|
||||
|
||||
export interface ClientToServerEvents {
|
||||
init: (
|
||||
me: Contact | undefined,
|
||||
account: proto.IADVSignedDeviceIdentity | undefined,
|
||||
status: WAConnectionState,
|
||||
) => void;
|
||||
'CB:call': (packet: any) => void;
|
||||
'CB:ack,class:call': (packet: any) => void;
|
||||
'connection.update:status': (
|
||||
me: Contact | undefined,
|
||||
account: proto.IADVSignedDeviceIdentity | undefined,
|
||||
status: WAConnectionState,
|
||||
) => void;
|
||||
'connection.update:qr': (qr: string) => void;
|
||||
}
|
||||
|
||||
export type onWhatsAppType = (jid: string, callback: onWhatsAppCallback) => void;
|
||||
export type onWhatsAppCallback = (
|
||||
response: {
|
||||
exists: boolean;
|
||||
jid: string;
|
||||
}[],
|
||||
) => void;
|
||||
|
||||
export type ProfilePictureUrlType = (
|
||||
jid: string,
|
||||
type: 'image' | 'preview',
|
||||
timeoutMs: number | undefined,
|
||||
callback: ProfilePictureUrlCallback,
|
||||
) => void;
|
||||
export type ProfilePictureUrlCallback = (response: string | undefined) => void;
|
||||
|
||||
export type AssertSessionsType = (jids: string[], force: boolean, callback: AssertSessionsCallback) => void;
|
||||
export type AssertSessionsCallback = (response: boolean) => void;
|
||||
|
||||
export type CreateParticipantNodesType = (
|
||||
jids: string[],
|
||||
message: any,
|
||||
extraAttrs: any,
|
||||
callback: CreateParticipantNodesCallback,
|
||||
) => void;
|
||||
export type CreateParticipantNodesCallback = (nodes: any, shouldIncludeDeviceIdentity: boolean) => void;
|
||||
|
||||
export type GetUSyncDevicesType = (
|
||||
jids: string[],
|
||||
useCache: boolean,
|
||||
ignoreZeroDevices: boolean,
|
||||
callback: GetUSyncDevicesTypeCallback,
|
||||
) => void;
|
||||
export type GetUSyncDevicesTypeCallback = (jids: JidWithDevice[]) => void;
|
||||
|
||||
export type GenerateMessageTagType = (callback: GenerateMessageTagTypeCallback) => void;
|
||||
export type GenerateMessageTagTypeCallback = (response: string) => void;
|
||||
|
||||
export type SendNodeType = (stanza: BinaryNode, callback: SendNodeTypeCallback) => void;
|
||||
export type SendNodeTypeCallback = (response: boolean) => void;
|
||||
|
||||
export type SignalRepositoryDecryptMessageType = (
|
||||
jid: string,
|
||||
type: 'pkmsg' | 'msg',
|
||||
ciphertext: Buffer,
|
||||
callback: SignalRepositoryDecryptMessageCallback,
|
||||
) => void;
|
||||
export type SignalRepositoryDecryptMessageCallback = (response: any) => void;
|
||||
181
src/api/services/channels/voiceCalls/useVoiceCallsBaileys.ts
Normal file
181
src/api/services/channels/voiceCalls/useVoiceCallsBaileys.ts
Normal file
@@ -0,0 +1,181 @@
|
||||
import { ConnectionState, WAConnectionState, WASocket } from 'baileys';
|
||||
import { io, Socket } from 'socket.io-client';
|
||||
|
||||
import { ClientToServerEvents, ServerToClientEvents } from './transport.type';
|
||||
|
||||
let baileys_connection_state: WAConnectionState = 'close';
|
||||
|
||||
export const useVoiceCallsBaileys = async (
|
||||
wavoip_token: string,
|
||||
baileys_sock: WASocket,
|
||||
status?: WAConnectionState,
|
||||
logger?: boolean,
|
||||
) => {
|
||||
baileys_connection_state = status ?? 'close';
|
||||
|
||||
const socket: Socket<ServerToClientEvents, ClientToServerEvents> = io('https://devices.wavoip.com/baileys', {
|
||||
transports: ['websocket'],
|
||||
path: `/${wavoip_token}/websocket`,
|
||||
});
|
||||
|
||||
socket.on('connect', () => {
|
||||
if (logger) console.log('[*] - Wavoip connected', socket.id);
|
||||
|
||||
socket.emit(
|
||||
'init',
|
||||
baileys_sock.authState.creds.me,
|
||||
baileys_sock.authState.creds.account,
|
||||
baileys_connection_state,
|
||||
);
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
if (logger) console.log('[*] - Wavoip disconnect');
|
||||
});
|
||||
|
||||
socket.on('connect_error', (error) => {
|
||||
if (socket.active) {
|
||||
if (logger)
|
||||
console.log(
|
||||
'[*] - Wavoip connection error temporary failure, the socket will automatically try to reconnect',
|
||||
error,
|
||||
);
|
||||
} else {
|
||||
if (logger) console.log('[*] - Wavoip connection error', error.message);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('onWhatsApp', async (jid, callback) => {
|
||||
try {
|
||||
const response: any = await baileys_sock.onWhatsApp(jid);
|
||||
|
||||
callback(response);
|
||||
|
||||
if (logger) console.log('[*] Success on call onWhatsApp function', response, jid);
|
||||
} catch (error) {
|
||||
if (logger) console.error('[*] Error on call onWhatsApp function', error);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('profilePictureUrl', async (jid, type, timeoutMs, callback) => {
|
||||
try {
|
||||
const response = await baileys_sock.profilePictureUrl(jid, type, timeoutMs);
|
||||
|
||||
callback(response);
|
||||
|
||||
if (logger) console.log('[*] Success on call profilePictureUrl function', response);
|
||||
} catch (error) {
|
||||
if (logger) console.error('[*] Error on call profilePictureUrl function', error);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('assertSessions', async (jids, force, callback) => {
|
||||
try {
|
||||
const response = await baileys_sock.assertSessions(jids, force);
|
||||
|
||||
callback(response);
|
||||
|
||||
if (logger) console.log('[*] Success on call assertSessions function', response);
|
||||
} catch (error) {
|
||||
if (logger) console.error('[*] Error on call assertSessions function', error);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('createParticipantNodes', async (jids, message, extraAttrs, callback) => {
|
||||
try {
|
||||
const response = await baileys_sock.createParticipantNodes(jids, message, extraAttrs);
|
||||
|
||||
callback(response, true);
|
||||
|
||||
if (logger) console.log('[*] Success on call createParticipantNodes function', response);
|
||||
} catch (error) {
|
||||
if (logger) console.error('[*] Error on call createParticipantNodes function', error);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('getUSyncDevices', async (jids, useCache, ignoreZeroDevices, callback) => {
|
||||
try {
|
||||
const response = await baileys_sock.getUSyncDevices(jids, useCache, ignoreZeroDevices);
|
||||
|
||||
callback(response);
|
||||
|
||||
if (logger) console.log('[*] Success on call getUSyncDevices function', response);
|
||||
} catch (error) {
|
||||
if (logger) console.error('[*] Error on call getUSyncDevices function', error);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('generateMessageTag', async (callback) => {
|
||||
try {
|
||||
const response = await baileys_sock.generateMessageTag();
|
||||
|
||||
callback(response);
|
||||
|
||||
if (logger) console.log('[*] Success on call generateMessageTag function', response);
|
||||
} catch (error) {
|
||||
if (logger) console.error('[*] Error on call generateMessageTag function', error);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('sendNode', async (stanza, callback) => {
|
||||
try {
|
||||
console.log('sendNode', JSON.stringify(stanza));
|
||||
const response = await baileys_sock.sendNode(stanza);
|
||||
|
||||
callback(true);
|
||||
|
||||
if (logger) console.log('[*] Success on call sendNode function', response);
|
||||
} catch (error) {
|
||||
if (logger) console.error('[*] Error on call sendNode function', error);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('signalRepository:decryptMessage', async (jid, type, ciphertext, callback) => {
|
||||
try {
|
||||
const response = await baileys_sock.signalRepository.decryptMessage({
|
||||
jid: jid,
|
||||
type: type,
|
||||
ciphertext: ciphertext,
|
||||
});
|
||||
|
||||
callback(response);
|
||||
|
||||
if (logger) console.log('[*] Success on call signalRepository:decryptMessage function', response);
|
||||
} catch (error) {
|
||||
if (logger) console.error('[*] Error on call signalRepository:decryptMessage function', error);
|
||||
}
|
||||
});
|
||||
|
||||
// we only use this connection data to inform the webphone that the device is connected and creeds account to generate e2e whatsapp key for make call packets
|
||||
baileys_sock.ev.on('connection.update', (update: Partial<ConnectionState>) => {
|
||||
const { connection } = update;
|
||||
|
||||
if (connection) {
|
||||
baileys_connection_state = connection;
|
||||
socket
|
||||
.timeout(1000)
|
||||
.emit(
|
||||
'connection.update:status',
|
||||
baileys_sock.authState.creds.me,
|
||||
baileys_sock.authState.creds.account,
|
||||
connection,
|
||||
);
|
||||
}
|
||||
|
||||
if (update.qr) {
|
||||
socket.timeout(1000).emit('connection.update:qr', update.qr);
|
||||
}
|
||||
});
|
||||
|
||||
baileys_sock.ws.on('CB:call', (packet) => {
|
||||
if (logger) console.log('[*] Signling received');
|
||||
socket.volatile.timeout(1000).emit('CB:call', packet);
|
||||
});
|
||||
|
||||
baileys_sock.ws.on('CB:ack,class:call', (packet) => {
|
||||
if (logger) console.log('[*] Signling ack received');
|
||||
socket.volatile.timeout(1000).emit('CB:ack,class:call', packet);
|
||||
});
|
||||
|
||||
return socket;
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
@@ -23,19 +23,21 @@ import {
|
||||
SendTextDto,
|
||||
} from '../../dto/sendMessage.dto';
|
||||
import { ContactRaw, MessageRaw, MessageUpdateRaw, SettingsRaw } from '../../models';
|
||||
import { ProviderFiles } from '../../provider/sessions';
|
||||
import { RepositoryBroker } from '../../repository/repository.manager';
|
||||
import { Events, wa } from '../../types/wa.types';
|
||||
import { CacheService } from './../cache.service';
|
||||
import { WAStartupService } from './../whatsapp.service';
|
||||
import { ChannelStartupService } from './../channel.service';
|
||||
|
||||
export class BusinessStartupService extends WAStartupService {
|
||||
export class BusinessStartupService extends ChannelStartupService {
|
||||
constructor(
|
||||
public readonly configService: ConfigService,
|
||||
public readonly eventEmitter: EventEmitter2,
|
||||
public readonly repository: RepositoryBroker,
|
||||
public readonly cache: CacheService,
|
||||
public readonly chatwootCache: CacheService,
|
||||
public readonly messagesLostCache: CacheService,
|
||||
public readonly baileysCache: CacheService,
|
||||
private readonly providerFiles: ProviderFiles,
|
||||
) {
|
||||
super(configService, eventEmitter, repository, chatwootCache);
|
||||
this.logger.verbose('BusinessStartupService initialized');
|
||||
@@ -741,6 +743,7 @@ export class BusinessStartupService extends WAStartupService {
|
||||
[message['type']]: message['id'],
|
||||
preview_url: linkPreview,
|
||||
caption: message['caption'],
|
||||
filename: message['fileName'],
|
||||
},
|
||||
};
|
||||
quoted ? (content.context = { message_id: quoted.id }) : content;
|
||||
@@ -1210,7 +1213,7 @@ export class BusinessStartupService extends WAStartupService {
|
||||
try {
|
||||
const msg = data.message;
|
||||
this.logger.verbose('Getting base64 from media message');
|
||||
const messageType = msg.messageType + 'Message';
|
||||
const messageType = msg.messageType.includes('Message') ? msg.messageType : msg.messageType + 'Message';
|
||||
const mediaMessage = msg.message[messageType];
|
||||
|
||||
this.logger.verbose('Media message downloaded');
|
||||
@@ -1258,6 +1261,9 @@ export class BusinessStartupService extends WAStartupService {
|
||||
public async archiveChat() {
|
||||
throw new BadRequestException('Method not available on WhatsApp Business API');
|
||||
}
|
||||
public async markChatUnread() {
|
||||
throw new BadRequestException('Method not available on WhatsApp Business API');
|
||||
}
|
||||
public async fetchProfile() {
|
||||
throw new BadRequestException('Method not available on WhatsApp Business API');
|
||||
}
|
||||
@@ -22,7 +22,8 @@ export class IntegrationService {
|
||||
const result = await this.waMonitor.waInstances[instance.instanceName].findIntegration();
|
||||
|
||||
if (Object.keys(result).length === 0) {
|
||||
throw new Error('Integration not found');
|
||||
this.create(instance, { integration: 'WHATSAPP-BAILEYS', number: '', token: '' });
|
||||
return { integration: 'WHATSAPP-BAILEYS', number: '', token: '' };
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
@@ -5,7 +5,15 @@ import { Db } from 'mongodb';
|
||||
import { Collection } from 'mongoose';
|
||||
import { join } from 'path';
|
||||
|
||||
import { Auth, CacheConf, ConfigService, Database, DelInstance, HttpServer } from '../../config/env.config';
|
||||
import {
|
||||
Auth,
|
||||
CacheConf,
|
||||
ConfigService,
|
||||
Database,
|
||||
DelInstance,
|
||||
HttpServer,
|
||||
ProviderSession,
|
||||
} from '../../config/env.config';
|
||||
import { Logger } from '../../config/logger.config';
|
||||
import { INSTANCE_DIR, STORE_DIR } from '../../config/path.config';
|
||||
import { NotFoundException } from '../../exceptions';
|
||||
@@ -22,11 +30,12 @@ import {
|
||||
WebhookModel,
|
||||
WebsocketModel,
|
||||
} from '../models';
|
||||
import { ProviderFiles } from '../provider/sessions';
|
||||
import { RepositoryBroker } from '../repository/repository.manager';
|
||||
import { Integration } from '../types/wa.types';
|
||||
import { CacheService } from './cache.service';
|
||||
import { BaileysStartupService } from './whatsapp/whatsapp.baileys.service';
|
||||
import { BusinessStartupService } from './whatsapp/whatsapp.business.service';
|
||||
import { BaileysStartupService } from './channels/whatsapp.baileys.service';
|
||||
import { BusinessStartupService } from './channels/whatsapp.business.service';
|
||||
|
||||
export class WAMonitoringService {
|
||||
constructor(
|
||||
@@ -35,7 +44,8 @@ export class WAMonitoringService {
|
||||
private readonly repository: RepositoryBroker,
|
||||
private readonly cache: CacheService,
|
||||
private readonly chatwootCache: CacheService,
|
||||
private readonly messagesLostCache: CacheService,
|
||||
private readonly baileysCache: CacheService,
|
||||
private readonly providerFiles: ProviderFiles,
|
||||
) {
|
||||
this.logger.verbose('instance created');
|
||||
|
||||
@@ -58,6 +68,8 @@ export class WAMonitoringService {
|
||||
private readonly logger = new Logger(WAMonitoringService.name);
|
||||
public readonly waInstances: Record<string, BaileysStartupService | BusinessStartupService> = {};
|
||||
|
||||
private readonly providerSession = Object.freeze(this.configService.get<ProviderSession>('PROVIDER'));
|
||||
|
||||
public delInstanceTime(instance: string) {
|
||||
const time = this.configService.get<DelInstance>('DEL_INSTANCE');
|
||||
if (typeof time === 'number' && time > 0) {
|
||||
@@ -83,7 +95,7 @@ export class WAMonitoringService {
|
||||
}
|
||||
}
|
||||
|
||||
public async instanceInfo(instanceName?: string) {
|
||||
public async instanceInfo(instanceName?: string, arrayReturn = false) {
|
||||
this.logger.verbose('get instance info');
|
||||
if (instanceName && !this.waInstances[instanceName]) {
|
||||
throw new NotFoundException(`Instance "${instanceName}" not found`);
|
||||
@@ -171,6 +183,9 @@ export class WAMonitoringService {
|
||||
|
||||
this.logger.verbose('return instance info: ' + instances.length);
|
||||
|
||||
if (arrayReturn) {
|
||||
return [instances.find((i) => i.instance.instanceName === instanceName) ?? instances];
|
||||
}
|
||||
return instances.find((i) => i.instance.instanceName === instanceName) ?? instances;
|
||||
}
|
||||
|
||||
@@ -254,12 +269,18 @@ export class WAMonitoringService {
|
||||
}
|
||||
|
||||
this.logger.verbose('cleaning up instance in files: ' + instanceName);
|
||||
if (this.providerSession?.ENABLED) {
|
||||
await this.providerFiles.removeSession(instanceName);
|
||||
}
|
||||
rmSync(join(INSTANCE_DIR, instanceName), { recursive: true, force: true });
|
||||
}
|
||||
|
||||
public async cleaningStoreFiles(instanceName: string) {
|
||||
if (!this.db.ENABLED) {
|
||||
this.logger.verbose('cleaning store files instance: ' + instanceName);
|
||||
if (this.providerSession?.ENABLED) {
|
||||
await this.providerFiles.removeSession(instanceName);
|
||||
}
|
||||
rmSync(join(INSTANCE_DIR, instanceName), { recursive: true, force: true });
|
||||
|
||||
execSync(`rm -rf ${join(STORE_DIR, 'chats', instanceName)}`);
|
||||
@@ -302,7 +323,9 @@ export class WAMonitoringService {
|
||||
this.logger.verbose('Loading instances');
|
||||
|
||||
try {
|
||||
if (this.redis.REDIS.ENABLED && this.redis.REDIS.SAVE_INSTANCES) {
|
||||
if (this.providerSession?.ENABLED) {
|
||||
await this.loadInstancesFromProvider();
|
||||
} else if (this.redis.REDIS.ENABLED && this.redis.REDIS.SAVE_INSTANCES) {
|
||||
await this.loadInstancesFromRedis();
|
||||
} else if (this.db.ENABLED && this.db.SAVE_DATA.INSTANCE) {
|
||||
await this.loadInstancesFromDatabase();
|
||||
@@ -345,7 +368,8 @@ export class WAMonitoringService {
|
||||
this.repository,
|
||||
this.cache,
|
||||
this.chatwootCache,
|
||||
this.messagesLostCache,
|
||||
this.baileysCache,
|
||||
this.providerFiles,
|
||||
);
|
||||
|
||||
instance.instanceName = name;
|
||||
@@ -356,7 +380,8 @@ export class WAMonitoringService {
|
||||
this.repository,
|
||||
this.cache,
|
||||
this.chatwootCache,
|
||||
this.messagesLostCache,
|
||||
this.baileysCache,
|
||||
this.providerFiles,
|
||||
);
|
||||
|
||||
instance.instanceName = name;
|
||||
@@ -398,6 +423,18 @@ export class WAMonitoringService {
|
||||
}
|
||||
}
|
||||
|
||||
private async loadInstancesFromProvider() {
|
||||
this.logger.verbose('Provider in files enabled');
|
||||
const [instances] = await this.providerFiles.allInstances();
|
||||
|
||||
if (!instances?.data) {
|
||||
this.logger.verbose('No instances found');
|
||||
return;
|
||||
}
|
||||
|
||||
await Promise.all(instances?.data?.map(async (instanceName: string) => this.setInstance(instanceName)));
|
||||
}
|
||||
|
||||
private async loadInstancesFromFiles() {
|
||||
this.logger.verbose('Store in files enabled');
|
||||
const dir = opendirSync(INSTANCE_DIR, { encoding: 'utf-8' });
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/* eslint-disable @typescript-eslint/no-namespace */
|
||||
import { AuthenticationState, WAConnectionState } from '@whiskeysockets/baileys';
|
||||
import { AuthenticationState, WAConnectionState } from 'baileys';
|
||||
|
||||
export enum Events {
|
||||
APPLICATION_STARTUP = 'application.startup',
|
||||
@@ -69,6 +69,7 @@ export declare namespace wa {
|
||||
number?: string;
|
||||
reopen_conversation?: boolean;
|
||||
conversation_pending?: boolean;
|
||||
merge_brazil_contacts?: boolean;
|
||||
import_contacts?: boolean;
|
||||
import_messages?: boolean;
|
||||
days_limit_import_messages?: number;
|
||||
@@ -82,6 +83,7 @@ export declare namespace wa {
|
||||
read_messages?: boolean;
|
||||
read_status?: boolean;
|
||||
sync_full_history?: boolean;
|
||||
wavoipToken?: string;
|
||||
};
|
||||
|
||||
export type LocalWebsocket = {
|
||||
|
||||
5
src/cache/cacheengine.ts
vendored
5
src/cache/cacheengine.ts
vendored
@@ -1,8 +1,11 @@
|
||||
import { ICache } from '../api/abstract/abstract.cache';
|
||||
import { CacheConf, ConfigService } from '../config/env.config';
|
||||
import { Logger } from '../config/logger.config';
|
||||
import { LocalCache } from './localcache';
|
||||
import { RedisCache } from './rediscache';
|
||||
|
||||
const logger = new Logger('Redis');
|
||||
|
||||
export class CacheEngine {
|
||||
private engine: ICache;
|
||||
|
||||
@@ -14,6 +17,8 @@ export class CacheEngine {
|
||||
} else if (cacheConf?.LOCAL?.ENABLED) {
|
||||
this.engine = new LocalCache(configService, module);
|
||||
}
|
||||
|
||||
logger.info(`RedisCache initialized for ${module}`);
|
||||
}
|
||||
|
||||
public getEngine() {
|
||||
|
||||
2
src/cache/rediscache.ts
vendored
2
src/cache/rediscache.ts
vendored
@@ -1,4 +1,4 @@
|
||||
import { BufferJSON } from '@whiskeysockets/baileys';
|
||||
import { BufferJSON } from 'baileys';
|
||||
import { RedisClientType } from 'redis';
|
||||
|
||||
import { ICache } from '../api/abstract/abstract.cache';
|
||||
|
||||
@@ -28,6 +28,13 @@ export type Log = {
|
||||
BAILEYS: LogBaileys;
|
||||
};
|
||||
|
||||
export type ProviderSession = {
|
||||
ENABLED: boolean;
|
||||
HOST: string;
|
||||
PORT: string;
|
||||
PREFIX: string;
|
||||
};
|
||||
|
||||
export type SaveData = {
|
||||
INSTANCE: boolean;
|
||||
NEW_MESSAGE: boolean;
|
||||
@@ -63,11 +70,46 @@ export type Database = {
|
||||
SAVE_DATA: SaveData;
|
||||
};
|
||||
|
||||
export type EventsRabbitmq = {
|
||||
APPLICATION_STARTUP: boolean;
|
||||
INSTANCE_CREATE: boolean;
|
||||
INSTANCE_DELETE: boolean;
|
||||
QRCODE_UPDATED: boolean;
|
||||
MESSAGES_SET: boolean;
|
||||
MESSAGES_UPSERT: boolean;
|
||||
MESSAGES_UPDATE: boolean;
|
||||
MESSAGES_DELETE: 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;
|
||||
LABELS_EDIT: boolean;
|
||||
LABELS_ASSOCIATION: boolean;
|
||||
GROUPS_UPSERT: boolean;
|
||||
GROUP_UPDATE: boolean;
|
||||
GROUP_PARTICIPANTS_UPDATE: boolean;
|
||||
CALL: boolean;
|
||||
NEW_JWT_TOKEN: boolean;
|
||||
TYPEBOT_START: boolean;
|
||||
TYPEBOT_CHANGE_STATUS: boolean;
|
||||
};
|
||||
|
||||
export type Rabbitmq = {
|
||||
ENABLED: boolean;
|
||||
MODE: string; // global, single, isolated
|
||||
EXCHANGE_NAME: string; // available for global and single, isolated mode will use instance name as exchange
|
||||
URI: string;
|
||||
EXCHANGE_NAME: string;
|
||||
PREFIX_KEY?: string;
|
||||
GLOBAL_ENABLED: boolean;
|
||||
MESSAGE_TTL: number;
|
||||
MAX_LENGTH: number;
|
||||
MAX_LENGTH_BYTES: number;
|
||||
EVENTS: EventsRabbitmq;
|
||||
};
|
||||
|
||||
export type Sqs = {
|
||||
@@ -155,7 +197,7 @@ export type CacheConfLocal = {
|
||||
};
|
||||
export type SslConf = { PRIVKEY: string; FULLCHAIN: string };
|
||||
export type Webhook = { GLOBAL?: GlobalWebhook; EVENTS: EventsWebhook };
|
||||
export type ConfigSessionPhone = { CLIENT: string; NAME: string };
|
||||
export type ConfigSessionPhone = { CLIENT: string; NAME: string; VERSION: string };
|
||||
export type QrCode = { LIMIT: number; COLOR: string };
|
||||
export type Typebot = { API_VERSION: string; KEEP_OPEN: boolean };
|
||||
export type Chatwoot = {
|
||||
@@ -178,6 +220,7 @@ export interface Env {
|
||||
SERVER: HttpServer;
|
||||
CORS: Cors;
|
||||
SSL_CONF: SslConf;
|
||||
PROVIDER: ProviderSession;
|
||||
STORE: StoreConf;
|
||||
CLEAN_STORE: CleanStoreConf;
|
||||
DATABASE: Database;
|
||||
@@ -243,6 +286,12 @@ export class ConfigService {
|
||||
PRIVKEY: process.env?.SSL_CONF_PRIVKEY || '',
|
||||
FULLCHAIN: process.env?.SSL_CONF_FULLCHAIN || '',
|
||||
},
|
||||
PROVIDER: {
|
||||
ENABLED: process.env?.PROVIDER_ENABLED === 'true',
|
||||
HOST: process.env.PROVIDER_HOST,
|
||||
PORT: process.env?.PROVIDER_PORT || '5656',
|
||||
PREFIX: process.env?.PROVIDER_PREFIX || 'evolution',
|
||||
},
|
||||
STORE: {
|
||||
MESSAGES: process.env?.STORE_MESSAGES === 'true',
|
||||
MESSAGE_UP: process.env?.STORE_MESSAGE_UP === 'true',
|
||||
@@ -251,8 +300,8 @@ export class ConfigService {
|
||||
LABELS: process.env?.STORE_LABELS === 'true',
|
||||
},
|
||||
CLEAN_STORE: {
|
||||
CLEANING_INTERVAL: Number.isInteger(process.env?.CLEAN_STORE_CLEANING_TERMINAL)
|
||||
? Number.parseInt(process.env.CLEAN_STORE_CLEANING_TERMINAL)
|
||||
CLEANING_INTERVAL: Number.isInteger(process.env?.CLEAN_STORE_CLEANING_INTERVAL)
|
||||
? Number.parseInt(process.env.CLEAN_STORE_CLEANING_INTERVAL)
|
||||
: 7200,
|
||||
MESSAGES: process.env?.CLEAN_STORE_MESSAGES === 'true',
|
||||
MESSAGE_UP: process.env?.CLEAN_STORE_MESSAGE_UP === 'true',
|
||||
@@ -276,9 +325,42 @@ export class ConfigService {
|
||||
},
|
||||
RABBITMQ: {
|
||||
ENABLED: process.env?.RABBITMQ_ENABLED === 'true',
|
||||
MODE: process.env?.RABBITMQ_MODE || 'isolated',
|
||||
GLOBAL_ENABLED: process.env?.RABBITMQ_GLOBAL_ENABLED === 'true',
|
||||
EXCHANGE_NAME: process.env?.RABBITMQ_EXCHANGE_NAME || 'evolution_exchange',
|
||||
PREFIX_KEY: process.env?.RABBITMQ_PREFIX_KEY || '',
|
||||
URI: process.env.RABBITMQ_URI || '',
|
||||
MESSAGE_TTL: Number.parseInt(process.env?.RABBITMQ_MESSAGE_TTL) || 604800,
|
||||
MAX_LENGTH: Number.parseInt(process.env?.RABBITMQ_MAX_LENGTH) || 10000,
|
||||
MAX_LENGTH_BYTES: Number.parseInt(process.env?.RABBITMQ_MAX_LENGTH_BYTES) || 8192,
|
||||
EVENTS: {
|
||||
APPLICATION_STARTUP: process.env?.RABBITMQ_EVENTS_APPLICATION_STARTUP === 'true',
|
||||
INSTANCE_CREATE: process.env?.RABBITMQ_EVENTS_INSTANCE_CREATE === 'true',
|
||||
INSTANCE_DELETE: process.env?.RABBITMQ_EVENTS_INSTANCE_DELETE === 'true',
|
||||
QRCODE_UPDATED: process.env?.RABBITMQ_EVENTS_QRCODE_UPDATED === 'true',
|
||||
MESSAGES_SET: process.env?.RABBITMQ_EVENTS_MESSAGES_SET === 'true',
|
||||
MESSAGES_UPSERT: process.env?.RABBITMQ_EVENTS_MESSAGES_UPSERT === 'true',
|
||||
MESSAGES_UPDATE: process.env?.RABBITMQ_EVENTS_MESSAGES_UPDATE === 'true',
|
||||
MESSAGES_DELETE: process.env?.RABBITMQ_EVENTS_MESSAGES_DELETE === 'true',
|
||||
SEND_MESSAGE: process.env?.RABBITMQ_EVENTS_SEND_MESSAGE === 'true',
|
||||
CONTACTS_SET: process.env?.RABBITMQ_EVENTS_CONTACTS_SET === 'true',
|
||||
CONTACTS_UPDATE: process.env?.RABBITMQ_EVENTS_CONTACTS_UPDATE === 'true',
|
||||
CONTACTS_UPSERT: process.env?.RABBITMQ_EVENTS_CONTACTS_UPSERT === 'true',
|
||||
PRESENCE_UPDATE: process.env?.RABBITMQ_EVENTS_PRESENCE_UPDATE === 'true',
|
||||
CHATS_SET: process.env?.RABBITMQ_EVENTS_CHATS_SET === 'true',
|
||||
CHATS_UPDATE: process.env?.RABBITMQ_EVENTS_CHATS_UPDATE === 'true',
|
||||
CHATS_UPSERT: process.env?.RABBITMQ_EVENTS_CHATS_UPSERT === 'true',
|
||||
CHATS_DELETE: process.env?.RABBITMQ_EVENTS_CHATS_DELETE === 'true',
|
||||
CONNECTION_UPDATE: process.env?.RABBITMQ_EVENTS_CONNECTION_UPDATE === 'true',
|
||||
LABELS_EDIT: process.env?.RABBITMQ_EVENTS_LABELS_EDIT === 'true',
|
||||
LABELS_ASSOCIATION: process.env?.RABBITMQ_EVENTS_LABELS_ASSOCIATION === 'true',
|
||||
GROUPS_UPSERT: process.env?.RABBITMQ_EVENTS_GROUPS_UPSERT === 'true',
|
||||
GROUP_UPDATE: process.env?.RABBITMQ_EVENTS_GROUPS_UPDATE === 'true',
|
||||
GROUP_PARTICIPANTS_UPDATE: process.env?.RABBITMQ_EVENTS_GROUP_PARTICIPANTS_UPDATE === 'true',
|
||||
CALL: process.env?.RABBITMQ_EVENTS_CALL === 'true',
|
||||
NEW_JWT_TOKEN: process.env?.RABBITMQ_EVENTS_NEW_JWT_TOKEN === 'true',
|
||||
TYPEBOT_START: process.env?.RABBITMQ_EVENTS_TYPEBOT_START === 'true',
|
||||
TYPEBOT_CHANGE_STATUS: process.env?.RABBITMQ_EVENTS_TYPEBOT_CHANGE_STATUS === 'true',
|
||||
},
|
||||
},
|
||||
SQS: {
|
||||
ENABLED: process.env?.SQS_ENABLED === 'true',
|
||||
@@ -292,9 +374,9 @@ export class ConfigService {
|
||||
GLOBAL_EVENTS: process.env?.WEBSOCKET_GLOBAL_EVENTS === 'true',
|
||||
},
|
||||
WA_BUSINESS: {
|
||||
TOKEN_WEBHOOK: process.env.WA_BUSINESS_TOKEN_WEBHOOK || '',
|
||||
URL: process.env.WA_BUSINESS_URL || '',
|
||||
VERSION: process.env.WA_BUSINESS_VERSION || '',
|
||||
TOKEN_WEBHOOK: process.env.WA_BUSINESS_TOKEN_WEBHOOK || 'evolution',
|
||||
URL: process.env.WA_BUSINESS_URL || 'https://graph.facebook.com',
|
||||
VERSION: process.env.WA_BUSINESS_VERSION || 'v19.0',
|
||||
LANGUAGE: process.env.WA_BUSINESS_LANGUAGE || 'en',
|
||||
},
|
||||
LOG: {
|
||||
@@ -360,6 +442,7 @@ export class ConfigService {
|
||||
CONFIG_SESSION_PHONE: {
|
||||
CLIENT: process.env?.CONFIG_SESSION_PHONE_CLIENT || 'Evolution API',
|
||||
NAME: process.env?.CONFIG_SESSION_PHONE_NAME || 'Chrome',
|
||||
VERSION: process.env?.CONFIG_SESSION_PHONE_VERSION || null,
|
||||
},
|
||||
QRCODE: {
|
||||
LIMIT: Number.parseInt(process.env.QRCODE_LIMIT) || 30,
|
||||
|
||||
@@ -49,6 +49,14 @@ LOG:
|
||||
DEL_INSTANCE: false # or false
|
||||
DEL_TEMP_INSTANCES: true # Delete instances with status closed on start
|
||||
|
||||
# Seesion Files Providers
|
||||
# Provider responsible for managing credentials files and WhatsApp sessions.
|
||||
PROVIDER:
|
||||
ENABLED: true
|
||||
HOST: 127.0.0.1
|
||||
PORT: 5656
|
||||
PREFIX: evolution
|
||||
|
||||
# Temporary data storage
|
||||
STORE:
|
||||
MESSAGES: true
|
||||
@@ -79,9 +87,42 @@ DATABASE:
|
||||
|
||||
RABBITMQ:
|
||||
ENABLED: false
|
||||
MODE: "global"
|
||||
EXCHANGE_NAME: "evolution_exchange"
|
||||
URI: "amqp://guest:guest@localhost:5672"
|
||||
EXCHANGE_NAME: evolution_exchange
|
||||
PREFIX_KEY: evolution
|
||||
GLOBAL_ENABLED: true
|
||||
# Tempo de vida das mensagens: 1 hora em milissegundos (3600000 = 60 * 60 * 1000)
|
||||
MESSAGE_TTL: 3600000
|
||||
# Limite máximo de mensagens por fila (quando atingido, novas mensagens são rejeitadas)
|
||||
MAX_LENGTH: 1000
|
||||
# Tamanho máximo em bytes permitido para filas: 10MB (10485760 = 10 * 1024 * 1024)
|
||||
MAX_LENGTH_BYTES: 10485760
|
||||
EVENTS:
|
||||
APPLICATION_STARTUP: false
|
||||
INSTANCE_CREATE: false
|
||||
INSTANCE_DELETE: false
|
||||
QRCODE_UPDATED: false
|
||||
MESSAGES_SET: false
|
||||
MESSAGES_UPSERT: true
|
||||
MESSAGES_UPDATE: true
|
||||
MESSAGES_DELETE: false
|
||||
SEND_MESSAGE: false
|
||||
CONTACTS_SET: false
|
||||
CONTACTS_UPSERT: false
|
||||
CONTACTS_UPDATE: false
|
||||
PRESENCE_UPDATE: false
|
||||
CHATS_SET: false
|
||||
CHATS_UPSERT: false
|
||||
CHATS_UPDATE: false
|
||||
CHATS_DELETE: false
|
||||
GROUPS_UPSERT: true
|
||||
GROUP_UPDATE: true
|
||||
GROUP_PARTICIPANTS_UPDATE: true
|
||||
CONNECTION_UPDATE: true
|
||||
CALL: false
|
||||
# This events is used with Typebot
|
||||
TYPEBOT_START: false
|
||||
TYPEBOT_CHANGE_STATUS: false
|
||||
|
||||
SQS:
|
||||
ENABLED: true
|
||||
@@ -168,7 +209,7 @@ CHATWOOT:
|
||||
# This db connection is used to import messages from whatsapp to chatwoot database
|
||||
DATABASE:
|
||||
CONNECTION:
|
||||
URI: "postgres://user:password@hostname:port/dbname"
|
||||
URI: "postgres://user:password@hostname:port/dbname?sslmode=disable"
|
||||
PLACEHOLDER_MEDIA_MESSAGE: true
|
||||
|
||||
# Cache to optimize application performance
|
||||
|
||||
@@ -25,7 +25,7 @@ info:
|
||||
</font>
|
||||
|
||||
[](https://god.gw.postman.com/run-collection/26869335-5546d063-156b-4529-915f-909dd628c090?action=collection%2Ffork&source=rip_markdown&collection-url=entityId%3D26869335-5546d063-156b-4529-915f-909dd628c090%26entityType%3Dcollection%26workspaceId%3D339a4ee7-378b-45c9-b5b8-fd2c0a9c2442)
|
||||
version: 1.7.3
|
||||
version: 1.8.2
|
||||
contact:
|
||||
name: DavidsonGomes
|
||||
email: contato@agenciadgcode.com
|
||||
@@ -194,6 +194,8 @@ paths:
|
||||
type: string
|
||||
description: Check the connection state of your instance.
|
||||
example: "evolution"
|
||||
security:
|
||||
- apikeyAuth: []
|
||||
responses:
|
||||
"200":
|
||||
description: Successful response
|
||||
@@ -2242,6 +2244,9 @@ paths:
|
||||
conversation_pending:
|
||||
type: boolean
|
||||
description: "Indicates whether to mark conversations as pending."
|
||||
merge_brazil_contacts:
|
||||
type: boolean
|
||||
description: "Indicates whether to merge Brazil numbers in case of numbers with and without ninth digit."
|
||||
import_contacts:
|
||||
type: boolean
|
||||
description: "Indicates whether to import contacts from phone to Chatwoot when connecting."
|
||||
|
||||
21
src/main.ts
21
src/main.ts
@@ -6,12 +6,13 @@ import cors from 'cors';
|
||||
import express, { json, NextFunction, Request, Response, urlencoded } from 'express';
|
||||
import { join } from 'path';
|
||||
|
||||
import { initAMQP } from './api/integrations/rabbitmq/libs/amqp.server';
|
||||
import { initAMQP, initGlobalQueues } from './api/integrations/rabbitmq/libs/amqp.server';
|
||||
import { initSQS } from './api/integrations/sqs/libs/sqs.server';
|
||||
import { initIO } from './api/integrations/websocket/libs/socket.server';
|
||||
import { ProviderFiles } from './api/provider/sessions';
|
||||
import { HttpStatus, router } from './api/routes/index.router';
|
||||
import { waMonitor } from './api/server.module';
|
||||
import { Auth, configService, Cors, HttpServer, Rabbitmq, Sqs, Webhook } from './config/env.config';
|
||||
import { Auth, configService, Cors, HttpServer, ProviderSession, Rabbitmq, Sqs, Webhook } from './config/env.config';
|
||||
import { onUnexpectedError } from './config/error.config';
|
||||
import { Logger } from './config/logger.config';
|
||||
import { ROOT_DIR } from './config/path.config';
|
||||
@@ -22,10 +23,18 @@ function initWA() {
|
||||
waMonitor.loadInstance();
|
||||
}
|
||||
|
||||
function bootstrap() {
|
||||
async function bootstrap() {
|
||||
const logger = new Logger('SERVER');
|
||||
const app = express();
|
||||
|
||||
let providerFiles: ProviderFiles = null;
|
||||
|
||||
if (configService.get<ProviderSession>('PROVIDER')?.ENABLED) {
|
||||
providerFiles = new ProviderFiles(configService);
|
||||
await providerFiles.onModuleInit();
|
||||
logger.info('Provider:Files - ON');
|
||||
}
|
||||
|
||||
app.use(
|
||||
cors({
|
||||
origin(requestOrigin, callback) {
|
||||
@@ -128,7 +137,11 @@ function bootstrap() {
|
||||
|
||||
initIO(server);
|
||||
|
||||
if (configService.get<Rabbitmq>('RABBITMQ')?.ENABLED) initAMQP();
|
||||
if (configService.get<Rabbitmq>('RABBITMQ')?.ENABLED) {
|
||||
initAMQP().then(() => {
|
||||
if (configService.get<Rabbitmq>('RABBITMQ')?.GLOBAL_ENABLED) initGlobalQueues();
|
||||
});
|
||||
}
|
||||
|
||||
if (configService.get<Sqs>('SQS')?.ENABLED) initSQS();
|
||||
|
||||
|
||||
@@ -22,5 +22,6 @@
|
||||
"cw.contactMessage.contact": "Contact",
|
||||
"cw.contactMessage.name": "Name",
|
||||
"cw.contactMessage.number": "Number",
|
||||
"cw.message.notsent": "🚨 The message could not be sent. Please check your connection. {{error}}",
|
||||
"cw.message.edited": "Edited Message"
|
||||
}
|
||||
@@ -22,5 +22,6 @@
|
||||
"cw.contactMessage.contact": "Contacto",
|
||||
"cw.contactMessage.name": "Nombre",
|
||||
"cw.contactMessage.number": "Numero",
|
||||
"cw.message.notsent": "🚨 El mensaje no se pudo enviar. Comprueba tu conexión. {{error}}",
|
||||
"cw.message.edited": "Mensaje editado"
|
||||
}
|
||||
@@ -22,5 +22,6 @@
|
||||
"cw.contactMessage.contact": "Contato",
|
||||
"cw.contactMessage.name": "Nome",
|
||||
"cw.contactMessage.number": "Número",
|
||||
"cw.message.notsent": "🚨 Não foi possível enviar a mensagem. Verifique sua conexão. {{error}}",
|
||||
"cw.message.edited": "Mensagem editada"
|
||||
}
|
||||
@@ -1,29 +1,55 @@
|
||||
import {
|
||||
AuthenticationCreds,
|
||||
AuthenticationState,
|
||||
BufferJSON,
|
||||
initAuthCreds,
|
||||
proto,
|
||||
SignalDataTypeMap,
|
||||
} from '@whiskeysockets/baileys';
|
||||
import { AuthenticationState, BufferJSON, initAuthCreds, WAProto as proto } from 'baileys';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
|
||||
import { configService, Database } from '../config/env.config';
|
||||
import { Logger } from '../config/logger.config';
|
||||
import { INSTANCE_DIR } from '../config/path.config';
|
||||
import { dbserver } from '../libs/db.connect';
|
||||
|
||||
const fixFileName = (file) => {
|
||||
if (!file) {
|
||||
return undefined;
|
||||
}
|
||||
const replacedSlash = file.replace(/\//g, '__');
|
||||
const replacedColon = replacedSlash.replace(/:/g, '-');
|
||||
return replacedColon;
|
||||
};
|
||||
|
||||
async function fileExists(file) {
|
||||
try {
|
||||
const stat = await fs.stat(file);
|
||||
if (stat.isFile()) return true;
|
||||
} catch (error) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export async function useMultiFileAuthStateDb(
|
||||
coll: string,
|
||||
): Promise<{ state: AuthenticationState; saveCreds: () => Promise<void> }> {
|
||||
const logger = new Logger(useMultiFileAuthStateDb.name);
|
||||
|
||||
const client = dbserver.getClient();
|
||||
|
||||
const logger = new Logger(useMultiFileAuthStateDb.name);
|
||||
|
||||
const collection = client
|
||||
.db(configService.get<Database>('DATABASE').CONNECTION.DB_PREFIX_NAME + '-instances')
|
||||
.collection(coll);
|
||||
|
||||
const writeData = async (data: any, key: string): Promise<any> => {
|
||||
const sessionId = coll;
|
||||
|
||||
const localFolder = path.join(INSTANCE_DIR, sessionId);
|
||||
const localFile = (key: string) => path.join(localFolder, fixFileName(key) + '.json');
|
||||
await fs.mkdir(localFolder, { recursive: true });
|
||||
|
||||
async function writeData(data: any, key: string): Promise<any> {
|
||||
try {
|
||||
const dataString = JSON.stringify(data, BufferJSON.replacer);
|
||||
|
||||
if (key != 'creds') {
|
||||
await fs.writeFile(localFile(key), dataString);
|
||||
return;
|
||||
}
|
||||
await client.connect();
|
||||
let msgParsed = JSON.parse(JSON.stringify(data, BufferJSON.replacer));
|
||||
if (Array.isArray(msgParsed)) {
|
||||
@@ -37,42 +63,59 @@ export async function useMultiFileAuthStateDb(
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const readData = async (key: string): Promise<any> => {
|
||||
async function readData(key: string): Promise<any> {
|
||||
try {
|
||||
await client.connect();
|
||||
let data = (await collection.findOne({ _id: key })) as any;
|
||||
if (data?.content_array) {
|
||||
data = data.content_array;
|
||||
if (key != 'creds') {
|
||||
if (!(await fileExists(localFile(key)))) return null;
|
||||
const rawData = await fs.readFile(localFile(key), { encoding: 'utf-8' });
|
||||
|
||||
const parsedData = JSON.parse(rawData, BufferJSON.reviver);
|
||||
return parsedData;
|
||||
} else {
|
||||
await client.connect();
|
||||
let data = (await collection.findOne({ _id: key })) as any;
|
||||
if (data?.content_array) {
|
||||
data = data.content_array;
|
||||
}
|
||||
const creds = JSON.stringify(data);
|
||||
return JSON.parse(creds, BufferJSON.reviver);
|
||||
}
|
||||
const creds = JSON.stringify(data);
|
||||
return JSON.parse(creds, BufferJSON.reviver);
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const removeData = async (key: string) => {
|
||||
async function removeData(key: string): Promise<any> {
|
||||
try {
|
||||
await client.connect();
|
||||
return await collection.deleteOne({ _id: key });
|
||||
if (key != 'creds') {
|
||||
await fs.unlink(localFile(key));
|
||||
} else {
|
||||
await client.connect();
|
||||
return await collection.deleteOne({ _id: key });
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds();
|
||||
let creds = await readData('creds');
|
||||
if (!creds) {
|
||||
creds = initAuthCreds();
|
||||
await writeData(creds, 'creds');
|
||||
}
|
||||
|
||||
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] } = {};
|
||||
get: async (type, ids) => {
|
||||
const data = {};
|
||||
await Promise.all(
|
||||
ids.map(async (id) => {
|
||||
let value = await readData(`${type}-${id}`);
|
||||
@@ -83,25 +126,24 @@ export async function useMultiFileAuthStateDb(
|
||||
data[id] = value;
|
||||
}),
|
||||
);
|
||||
|
||||
return data;
|
||||
},
|
||||
set: async (data: any) => {
|
||||
const tasks: Promise<void>[] = [];
|
||||
set: async (data) => {
|
||||
const tasks = [];
|
||||
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 await writeData(creds, 'creds');
|
||||
saveCreds: () => {
|
||||
return writeData(creds, 'creds');
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
132
src/utils/use-multi-file-auth-state-provider-files.ts
Normal file
132
src/utils/use-multi-file-auth-state-provider-files.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* ┌──────────────────────────────────────────────────────────────────────────────┐
|
||||
* │ @author jrCleber │
|
||||
* │ @filename use-multi-file-auth-state-provider-files.ts │
|
||||
* │ Developed by: Cleber Wilson │
|
||||
* │ Creation date: May 31, 2024 │
|
||||
* │ Contact: contato@codechat.dev │
|
||||
* ├──────────────────────────────────────────────────────────────────────────────┤
|
||||
* │ @copyright © Cleber Wilson 2023. All rights reserved. │
|
||||
* │ Licensed under the Apache License, Version 2.0 │
|
||||
* │ │
|
||||
* │ @license "https://github.com/code-chat-br/whatsapp-api/blob/main/LICENSE" │
|
||||
* │ │
|
||||
* │ You may not use this file except in compliance with the License. │
|
||||
* │ You may obtain a copy of the License at │
|
||||
* │ │
|
||||
* │ http://www.apache.org/licenses/LICENSE-2.0 │
|
||||
* │ │
|
||||
* │ Unless required by applicable law or agreed to in writing, software │
|
||||
* │ distributed under the License is distributed on an "AS IS" BASIS, │
|
||||
* │ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. │
|
||||
* │ │
|
||||
* │ See the License for the specific language governing permissions and │
|
||||
* │ limitations under the License. │
|
||||
* │ │
|
||||
* │ @type {AuthState} │
|
||||
* │ @function useMultiFileAuthStateRedisDb │
|
||||
* │ @returns {Promise<AuthState>} │
|
||||
* ├──────────────────────────────────────────────────────────────────────────────┤
|
||||
* │ @important │
|
||||
* │ For any future changes to the code in this file, it is recommended to │
|
||||
* │ contain, together with the modification, the information of the developer │
|
||||
* │ who changed it and the date of modification. │
|
||||
* └──────────────────────────────────────────────────────────────────────────────┘
|
||||
*/
|
||||
|
||||
import { AuthenticationCreds, AuthenticationState, BufferJSON, initAuthCreds, proto, SignalDataTypeMap } from 'baileys';
|
||||
import { isNotEmpty } from 'class-validator';
|
||||
|
||||
import { ProviderFiles } from '../api/provider/sessions';
|
||||
import { Logger } from '../config/logger.config';
|
||||
|
||||
export type AuthState = { state: AuthenticationState; saveCreds: () => Promise<void> };
|
||||
|
||||
export class AuthStateProvider {
|
||||
constructor(private readonly providerFiles: ProviderFiles) {}
|
||||
|
||||
private readonly logger = new Logger(AuthStateProvider.name);
|
||||
|
||||
public async authStateProvider(instance: string): Promise<AuthState> {
|
||||
const [, error] = await this.providerFiles.create(instance);
|
||||
if (error) {
|
||||
this.logger.error(['Failed to create folder on file server', error?.message, error?.stack]);
|
||||
return;
|
||||
}
|
||||
|
||||
const writeData = async (data: any, key: string): Promise<any> => {
|
||||
const json = JSON.stringify(data, BufferJSON.replacer);
|
||||
const [response, error] = await this.providerFiles.write(instance, key, {
|
||||
data: json,
|
||||
});
|
||||
if (error) {
|
||||
// this.logger.error(['writeData', error?.message, error?.stack]);
|
||||
return;
|
||||
}
|
||||
return response;
|
||||
};
|
||||
|
||||
const readData = async (key: string): Promise<any> => {
|
||||
const [response, error] = await this.providerFiles.read(instance, key);
|
||||
if (error) {
|
||||
// this.logger.error(['readData', error?.message, error?.stack]);
|
||||
return;
|
||||
}
|
||||
if (isNotEmpty(response?.data)) {
|
||||
return JSON.parse(JSON.stringify(response.data), BufferJSON.reviver);
|
||||
}
|
||||
};
|
||||
|
||||
const removeData = async (key: string) => {
|
||||
const [response, error] = await this.providerFiles.delete(instance, key);
|
||||
if (error) {
|
||||
// this.logger.error(['removeData', error?.message, error?.stack]);
|
||||
return;
|
||||
}
|
||||
|
||||
return response;
|
||||
};
|
||||
|
||||
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');
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,4 @@
|
||||
import {
|
||||
AuthenticationCreds,
|
||||
AuthenticationState,
|
||||
initAuthCreds,
|
||||
proto,
|
||||
SignalDataTypeMap,
|
||||
} from '@whiskeysockets/baileys';
|
||||
import { AuthenticationCreds, AuthenticationState, initAuthCreds, proto, SignalDataTypeMap } from 'baileys';
|
||||
|
||||
import { CacheService } from '../api/services/cache.service';
|
||||
import { Logger } from '../config/logger.config';
|
||||
|
||||
@@ -597,6 +597,33 @@ export const archiveChatSchema: JSONSchema7 = {
|
||||
required: ['archive'],
|
||||
};
|
||||
|
||||
export const markChatUnreadSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
properties: {
|
||||
chat: { type: 'string' },
|
||||
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'),
|
||||
},
|
||||
},
|
||||
required: ['lastMessage'],
|
||||
};
|
||||
|
||||
export const deleteMessageSchema: JSONSchema7 = {
|
||||
$id: v4(),
|
||||
type: 'object',
|
||||
@@ -975,9 +1002,26 @@ export const settingsSchema: JSONSchema7 = {
|
||||
read_messages: { type: 'boolean', enum: [true, false] },
|
||||
read_status: { type: 'boolean', enum: [true, false] },
|
||||
sync_full_history: { type: 'boolean', enum: [true, false] },
|
||||
wavoipToken: { type: 'string' },
|
||||
},
|
||||
required: ['reject_call', 'groups_ignore', 'always_online', 'read_messages', 'read_status', 'sync_full_history'],
|
||||
...isNotEmpty('reject_call', 'groups_ignore', 'always_online', 'read_messages', 'read_status', 'sync_full_history'),
|
||||
required: [
|
||||
'reject_call',
|
||||
'groups_ignore',
|
||||
'always_online',
|
||||
'read_messages',
|
||||
'read_status',
|
||||
'sync_full_history',
|
||||
'wavoipToken',
|
||||
],
|
||||
...isNotEmpty(
|
||||
'reject_call',
|
||||
'groups_ignore',
|
||||
'always_online',
|
||||
'read_messages',
|
||||
'read_status',
|
||||
'sync_full_history',
|
||||
'wavoipToken',
|
||||
),
|
||||
};
|
||||
|
||||
export const websocketSchema: JSONSchema7 = {
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
<!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 rel="shortcut icon" href="https://evolution-api.com/files/evolution-api-favicon.png" type="image/x-icon">
|
||||
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css"
|
||||
integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
|
||||
<title>Instance Manager</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<div class="container mt-4">
|
||||
<!-- Botão para abrir o modal de adicionar nova instância -->
|
||||
<button class="btn btn-primary mb-3" data-toggle="modal" data-target="#actionModal" data-action="add">Nova
|
||||
Instância</button>
|
||||
|
||||
<!-- Tabela de instâncias -->
|
||||
<table class="table table-bordered">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Nome da Instância</th>
|
||||
<th>Status</th>
|
||||
<th>API Key</th>
|
||||
<th>Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<!-- Iterando sobre as instâncias e preenchendo a tabela -->
|
||||
{{#each instances}}
|
||||
<tr>
|
||||
<td>{{this.instance.instanceName}}</td>
|
||||
<td>{{this.instance.status}}</td>
|
||||
<td>{{this.instance.apikey}}</td>
|
||||
<td>
|
||||
<!-- Dropdown de ações para cada instância -->
|
||||
<div class="dropdown">
|
||||
<button class="btn btn-secondary dropdown-toggle" type="button" id="actionDropdown"
|
||||
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
|
||||
Ações
|
||||
</button>
|
||||
<div class="dropdown-menu" aria-labelledby="actionDropdown">
|
||||
<a class="dropdown-item" href="#" data-toggle="modal" data-target="#actionModal"
|
||||
data-action="connect">Connect</a>
|
||||
<a class="dropdown-item" href="#" data-toggle="modal" data-target="#actionModal"
|
||||
data-action="restart">Restart</a>
|
||||
<!-- Adicione mais itens de ação aqui -->
|
||||
<!-- ... -->
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{{/each}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- Modal de ações -->
|
||||
<div class="modal fade" id="actionModal" tabindex="-1" role="dialog" aria-labelledby="actionModalLabel"
|
||||
aria-hidden="true">
|
||||
<div class="modal-dialog" role="document">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="actionModalLabel">Ação</h5>
|
||||
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>
|
||||
<button type="button" class="btn btn-primary">Salvar</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"
|
||||
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
|
||||
crossorigin="anonymous"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"
|
||||
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
|
||||
crossorigin="anonymous"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.min.js"
|
||||
integrity="sha384-+sLIOodYLS7CIrQpBjl+C7nPvqq+FbNUBDunl/OZv93DB7Ln/533i8e/mZXLi/P+"
|
||||
crossorigin="anonymous"></script>
|
||||
|
||||
<script>
|
||||
$(document).ready(function(){
|
||||
$('#actionModal').on('show.bs.modal', function(event) {
|
||||
var button = $(event.relatedTarget);
|
||||
var action = button.data('action');
|
||||
|
||||
console.log(action);
|
||||
|
||||
if (action === 'connect') {
|
||||
|
||||
} else if (action === 'restart') {
|
||||
|
||||
}
|
||||
});
|
||||
})
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
Reference in New Issue
Block a user