Compare commits

...

279 Commits
1.1.5 ... 1.4.7

Author SHA1 Message Date
Davidson Gomes
d344e513c4 Merge branch 'release/1.4.7' 2023-07-27 08:52:52 -03:00
Davidson Gomes
9af7f67930 version: 1.4.7 2023-07-27 08:52:45 -03:00
Davidson Gomes
f95d938fb6 fix: Adjusts in return errors 2023-07-27 08:51:58 -03:00
Davidson Gomes
f74a7e87bd version: 1.4.7 2023-07-27 08:48:03 -03:00
Davidson Gomes
d3fce5fc89 fix: Fixed problem of getting message when deleting message in chatwoot 2023-07-27 08:45:02 -03:00
Davidson Gomes
14f3f3d2ac fix: fixed error return bug 2023-07-27 08:36:37 -03:00
Davidson Gomes
127d5b97c4 fix: fixed error return bug 2023-07-27 08:36:18 -03:00
Davidson Gomes
7ef1c097e8 text: Fix problem No Session 2023-07-26 21:45:49 -03:00
Davidson Gomes
80e3116cd8 text: Fix problem No Session 2023-07-26 21:45:23 -03:00
Davidson Gomes
46bac55bb3 Merge tag '1.4.6' into develop
* Fixed bug of creating new inbox by chatwoot
* When conversation reopens is pending when conversation pending is true
* Added docker-compose file with dockerhub image
2023-07-26 18:42:10 -03:00
Davidson Gomes
2cadafd5c1 Merge branch 'release/1.4.6' 2023-07-26 18:41:39 -03:00
Davidson Gomes
bb27dca21c Merge pull request #36 from moskoweb/groupJid-query-or-body
Correção Validação de Grupo por Query e Body
2023-07-26 18:41:06 -03:00
Davidson Gomes
86fc9fbffa Merge branch 'develop' into groupJid-query-or-body 2023-07-26 18:40:54 -03:00
Alan Mosko
9bdbfc6f4f wip 2023-07-26 18:28:18 -03:00
Davidson Gomes
28a7d9c62b fix: Adjusts in instance name 2023-07-26 18:02:45 -03:00
Davidson Gomes
2ca344b17c Merge tag '1.4.6' into develop
* Fixed bug of creating new inbox by chatwoot
* When conversation reopens is pending when conversation pending is true
* Added docker-compose file with dockerhub image
2023-07-26 17:54:42 -03:00
Davidson Gomes
1bf2278f31 version: 1.4.6 2023-07-26 17:54:29 -03:00
Davidson Gomes
6188ab0d30 Merge branch 'main' of github.com:EvolutionAPI/evolution-api 2023-07-26 17:47:53 -03:00
Davidson Gomes
f016b53013 Merge tag '1.4.6' into develop
* Fixed bug of creating new inbox by chatwoot
* When conversation reopens is pending when conversation pending is true
* Added docker-compose file with dockerhub image
2023-07-26 17:47:01 -03:00
Davidson Gomes
127cd3e843 Merge branch 'release/1.4.6' 2023-07-26 17:46:52 -03:00
Davidson Gomes
457dbe5831 version: 1.4.6 2023-07-26 17:46:45 -03:00
Davidson Gomes
8d73fb1161 Merge pull request #35 from EvolutionAPI/revert-34-groupJid-query-or-body
Revert "GroupJid por Query ou por Body"
2023-07-26 17:45:41 -03:00
Davidson Gomes
af5746bb39 Revert "GroupJid por Query ou por Body" 2023-07-26 17:45:28 -03:00
Davidson Gomes
3f27d018c7 Merge pull request #34 from moskoweb/groupJid-query-or-body
fix: GroupJid por Query ou por Body
2023-07-26 17:45:16 -03:00
Davidson Gomes
68402393b5 Merge branch 'main' into groupJid-query-or-body 2023-07-26 17:43:28 -03:00
Davidson Gomes
2ad33857f4 Merge tag '1.4.6' into develop
* Fixed bug of creating new inbox by chatwoot
* When conversation reopens is pending when conversation pending is true
* Added docker-compose file with dockerhub image
2023-07-26 17:41:18 -03:00
Davidson Gomes
d3c7677dc7 Merge branch 'release/1.4.6' 2023-07-26 17:41:10 -03:00
Davidson Gomes
73e92f9ef5 version: 1.4.6 2023-07-26 17:41:06 -03:00
Davidson Gomes
fcc8748daf Merge branch 'release/1.4.6' 2023-07-26 17:40:07 -03:00
Davidson Gomes
312ee249b6 version: 1.4.6 2023-07-26 17:39:59 -03:00
Davidson Gomes
e4548f6961 fix: Added docker-compose file with dockerhub image 2023-07-26 17:39:32 -03:00
Davidson Gomes
1b93aac8c5 fix: When conversation reopens is pending when conversation pending is true 2023-07-26 17:33:31 -03:00
Alan Mosko
e7ed666037 Update abstract.router.ts 2023-07-26 17:27:25 -03:00
Davidson Gomes
85ca0683ed fix: fixed bug of creating new inbox by chatwoot 2023-07-26 17:15:09 -03:00
Davidson Gomes
78689a23e5 Code Formatter
fix: Code Formatter
2023-07-26 12:44:01 -03:00
Davidson Gomes
ba63a55883 Merge branch 'develop' into formatter 2023-07-26 12:43:37 -03:00
Alan Mosko
dc3d59bae1 wip 2023-07-26 11:12:00 -03:00
Alan Mosko
0a851b935e Update .gitignore 2023-07-26 11:10:23 -03:00
Alan Mosko
ddc75d710f wip 2023-07-26 11:08:14 -03:00
Alan Mosko
5482601b41 Squashed commit of the following:
commit fb6e58b3c4
Merge: 1d3d557 67e9845
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Wed Jul 26 09:39:37 2023 -0300

    Merge branch 'release/1.4.5'

commit 67e98456bb
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Wed Jul 26 09:39:27 2023 -0300

    fix: Fix mids going duplicated in chatwoot

commit 3e47420534
Merge: 3f41974 1d3d557
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Wed Jul 26 09:38:44 2023 -0300

    Merge tag '1.4.5' into develop

    * Fixed problems in localization template in chatwoot
    * Fix mids going duplicated in chatwoot

commit 1d3d557c43
Merge: 6b926dc 3f41974
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Wed Jul 26 09:38:36 2023 -0300

    Merge branch 'release/1.4.5'

commit 3f41974a75
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Wed Jul 26 09:38:22 2023 -0300

    fix: Fix mids going duplicated in chatwoot

commit 3e3c7397a5
Merge: de0c9a1 dcb5170
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Wed Jul 26 09:36:10 2023 -0300

    Merge branch 'develop' of github.com:EvolutionAPI/evolution-api into develop

commit dcb51702e7
Merge: 4769d75 dd0c1e2
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Wed Jul 26 09:36:01 2023 -0300

    Merge pull request #30 from codephix/patch-1

    Update whatsapp.service.ts

commit de0c9a1eff
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Wed Jul 26 09:34:10 2023 -0300

    fix: fixed problems in localization template

commit dd0c1e20a7
Author: CodePhix <contato@codephix.com>
Date:   Tue Jul 25 19:59:42 2023 -0300

    Update whatsapp.service.ts

commit 4769d75dc3
Merge: ecae077 6b926dc
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 16:20:04 2023 -0300

    Merge tag '1.4.4' into develop

    * Fixed chatwoot line wrap issue
    * Solved receive location in chatwoot
    * When requesting the pairing code, it also brings the qr code
    * Option reopen_conversation in chatwoot endpoint
    * Option conversation_pending in chatwoot endpoint

commit 6b926dc697
Merge: 2b6dbfd ecae077
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 16:19:54 2023 -0300

    Merge branch 'release/1.4.4'

commit ecae077c6d
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 16:16:49 2023 -0300

    fix: Option conversation_pending in chatwoot endpoint

commit 78ab1bed35
Merge: 6bb1abd 2b6dbfd
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 15:31:16 2023 -0300

    Merge tag '1.4.4' into develop

    * Fixed chatwoot line wrap issue
    * Solved receive location in chatwoot
    * When requesting the pairing code, it also brings the qr code
    * Option reopen_conversation in chatwoot endpoint
    * Option conversation_pending in chatwoot endpoint

commit 2b6dbfde6b
Merge: 82b1567 6bb1abd
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 15:31:06 2023 -0300

    Merge branch 'release/1.4.4'

commit 6bb1abd7f0
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 15:29:42 2023 -0300

    fix: Option conversation_pending in chatwoot endpoint

commit aef92240cc
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 15:20:21 2023 -0300

    fix: Option conversation_pending in chatwoot endpoint

commit f0d8c2d095
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 13:19:15 2023 -0300

    fix: Solved receive location in chatwoot

commit 14529f2c35
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 12:47:35 2023 -0300

    fix: When requesting the pairing code, it also brings the qr code

commit 89f40d54d9
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 12:41:54 2023 -0300

    fix: Solved receive location in chatwoot

commit 4c006970a2
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 11:52:26 2023 -0300

    fix: Fixed chatwoot line wrap issue

commit de676041df
Merge: 1cd7291 82b1567
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 10:51:53 2023 -0300

    Merge tag '1.4.3' into develop

    * Adjusts in settings with options always_online, read_messages and read_status
    * Fixed send webhook for event CALL
    * Create instance with settings

commit 82b1567ae5
Merge: f95f312 1cd7291
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 10:51:42 2023 -0300

    Merge branch 'release/1.4.3'

commit 1cd7291068
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 10:51:28 2023 -0300

    version: 1.4.3

commit fdee1df5b3
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 10:42:45 2023 -0300

    fix: Create instance with settings

commit c314d00ccd
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 10:42:34 2023 -0300

    fix: Create instance with settings

commit 62e2a8a6e3
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 10:23:18 2023 -0300

    fix: Fixed send webhook for event CALL

commit a12231a0aa
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Tue Jul 25 09:57:28 2023 -0300

    fix: Adjusts in settings with options always_online, read_messages and read_status

commit 183efd427a
Merge: 4d9ca4b f95f312
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Mon Jul 24 20:52:58 2023 -0300

    Merge tag '1.4.2' into develop

    * Fixed validation is set settings
    * Adjusts in group validations
    * Ajusts in sticker message to chatwoot

commit f95f3126c3
Merge: cc91f2e 4d9ca4b
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Mon Jul 24 20:52:46 2023 -0300

    Merge branch 'release/1.4.2'

commit 4d9ca4b451
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Mon Jul 24 20:52:34 2023 -0300

    version: 1.4.2

commit c76334a68a
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Mon Jul 24 20:32:29 2023 -0300

    fix: Ajusts in sticker message to chatwoot

commit f475391ba6
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Mon Jul 24 20:32:15 2023 -0300

    fix: Ajusts in sticker message to chatwoot

commit b77f22790b
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Mon Jul 24 20:13:18 2023 -0300

    fix: Fixed validation is set settings

commit 757a578c6e
Merge: c582476 f8e1892
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Mon Jul 24 20:12:51 2023 -0300

    Merge branch 'develop' of github.com:EvolutionAPI/evolution-api into develop

commit c5824767c8
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Mon Jul 24 20:11:49 2023 -0300

    fix: Fixed validation is set settings

commit 84f3f07279
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Mon Jul 24 20:11:15 2023 -0300

    fix: Fixed validation is set settings

commit f8e1892eee
Merge: 036a8ed 58ed6f3
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Mon Jul 24 20:08:24 2023 -0300

    fix: group validation

    Group validation

commit 036a8edca0
Merge: 3d8e6f4 ef4be6a
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Mon Jul 24 20:07:05 2023 -0300

    fix: Promote All Participants in Create Group

    Promote All Participants in Create Group

commit 58ed6f395f
Author: Alan Mosko <moskoweb@gmail.com>
Date:   Mon Jul 24 19:59:09 2023 -0300

    Validação de Grupo

commit ef4be6a612
Author: Alan Mosko <moskoweb@gmail.com>
Date:   Mon Jul 24 19:53:03 2023 -0300

    Start

commit 3d8e6f4394
Merge: 8b6e577 0cc1f18
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Mon Jul 24 19:08:39 2023 -0300

    fix: Fixed mentions

    Fixed mentions

commit 0cc1f18a7e
Author: Alan Mosko <moskoweb@gmail.com>
Date:   Mon Jul 24 19:05:32 2023 -0300

    [BUG] Correção de mencionar

    Caso seja enviado everyOne como false sem passar nada no mentioned

commit 8b6e577b8f
Merge: f9abd90 cc91f2e
Author: Davidson Gomes <davidsongviolao@gmail.com>
Date:   Mon Jul 24 18:28:57 2023 -0300

    Merge tag '1.4.1' into develop

    * Fixed reconnect with pairing code or qrcode
    * Fixed problem in createJid
2023-07-26 10:59:15 -03:00
Alan Mosko
249aecbc0d wip 2023-07-26 10:58:13 -03:00
Alan Mosko
03f3020e9f wip 2023-07-26 10:30:56 -03:00
Alan Mosko
e151eb85f0 wip 2023-07-26 10:30:26 -03:00
Davidson Gomes
348586553e Merge tag '1.4.5' into develop
* Fixed problems in localization template in chatwoot
* Fix mids going duplicated in chatwoot
2023-07-26 09:39:45 -03:00
Davidson Gomes
fb6e58b3c4 Merge branch 'release/1.4.5' 2023-07-26 09:39:37 -03:00
Davidson Gomes
67e98456bb fix: Fix mids going duplicated in chatwoot 2023-07-26 09:39:27 -03:00
Davidson Gomes
3e47420534 Merge tag '1.4.5' into develop
* Fixed problems in localization template in chatwoot
* Fix mids going duplicated in chatwoot
2023-07-26 09:38:44 -03:00
Davidson Gomes
1d3d557c43 Merge branch 'release/1.4.5' 2023-07-26 09:38:36 -03:00
Davidson Gomes
3f41974a75 fix: Fix mids going duplicated in chatwoot 2023-07-26 09:38:22 -03:00
Davidson Gomes
3e3c7397a5 Merge branch 'develop' of github.com:EvolutionAPI/evolution-api into develop 2023-07-26 09:36:10 -03:00
Davidson Gomes
dcb51702e7 Merge pull request #30 from codephix/patch-1
Update whatsapp.service.ts
2023-07-26 09:36:01 -03:00
Davidson Gomes
de0c9a1eff fix: fixed problems in localization template 2023-07-26 09:34:10 -03:00
CodePhix
dd0c1e20a7 Update whatsapp.service.ts 2023-07-25 19:59:42 -03:00
Davidson Gomes
4769d75dc3 Merge tag '1.4.4' into develop
* Fixed chatwoot line wrap issue
* Solved receive location in chatwoot
* When requesting the pairing code, it also brings the qr code
* Option reopen_conversation in chatwoot endpoint
* Option conversation_pending in chatwoot endpoint
2023-07-25 16:20:04 -03:00
Davidson Gomes
6b926dc697 Merge branch 'release/1.4.4' 2023-07-25 16:19:54 -03:00
Davidson Gomes
ecae077c6d fix: Option conversation_pending in chatwoot endpoint 2023-07-25 16:16:49 -03:00
Davidson Gomes
78ab1bed35 Merge tag '1.4.4' into develop
* Fixed chatwoot line wrap issue
* Solved receive location in chatwoot
* When requesting the pairing code, it also brings the qr code
* Option reopen_conversation in chatwoot endpoint
* Option conversation_pending in chatwoot endpoint
2023-07-25 15:31:16 -03:00
Davidson Gomes
2b6dbfde6b Merge branch 'release/1.4.4' 2023-07-25 15:31:06 -03:00
Davidson Gomes
6bb1abd7f0 fix: Option conversation_pending in chatwoot endpoint 2023-07-25 15:29:42 -03:00
Davidson Gomes
aef92240cc fix: Option conversation_pending in chatwoot endpoint 2023-07-25 15:20:21 -03:00
Davidson Gomes
f0d8c2d095 fix: Solved receive location in chatwoot 2023-07-25 13:19:15 -03:00
Davidson Gomes
14529f2c35 fix: When requesting the pairing code, it also brings the qr code 2023-07-25 12:47:35 -03:00
Davidson Gomes
89f40d54d9 fix: Solved receive location in chatwoot 2023-07-25 12:41:54 -03:00
Davidson Gomes
4c006970a2 fix: Fixed chatwoot line wrap issue 2023-07-25 11:52:26 -03:00
Davidson Gomes
de676041df Merge tag '1.4.3' into develop
* Adjusts in settings with options always_online, read_messages and read_status
* Fixed send webhook for event CALL
* Create instance with settings
2023-07-25 10:51:53 -03:00
Davidson Gomes
82b1567ae5 Merge branch 'release/1.4.3' 2023-07-25 10:51:42 -03:00
Davidson Gomes
1cd7291068 version: 1.4.3 2023-07-25 10:51:28 -03:00
Davidson Gomes
fdee1df5b3 fix: Create instance with settings 2023-07-25 10:42:45 -03:00
Davidson Gomes
c314d00ccd fix: Create instance with settings 2023-07-25 10:42:34 -03:00
Davidson Gomes
62e2a8a6e3 fix: Fixed send webhook for event CALL 2023-07-25 10:23:18 -03:00
Davidson Gomes
a12231a0aa fix: Adjusts in settings with options always_online, read_messages and read_status 2023-07-25 09:57:28 -03:00
Davidson Gomes
183efd427a Merge tag '1.4.2' into develop
* Fixed validation is set settings
* Adjusts in group validations
* Ajusts in sticker message to chatwoot
2023-07-24 20:52:58 -03:00
Davidson Gomes
f95f3126c3 Merge branch 'release/1.4.2' 2023-07-24 20:52:46 -03:00
Davidson Gomes
4d9ca4b451 version: 1.4.2 2023-07-24 20:52:34 -03:00
Davidson Gomes
c76334a68a fix: Ajusts in sticker message to chatwoot 2023-07-24 20:32:29 -03:00
Davidson Gomes
f475391ba6 fix: Ajusts in sticker message to chatwoot 2023-07-24 20:32:15 -03:00
Davidson Gomes
b77f22790b fix: Fixed validation is set settings 2023-07-24 20:13:18 -03:00
Davidson Gomes
757a578c6e Merge branch 'develop' of github.com:EvolutionAPI/evolution-api into develop 2023-07-24 20:12:51 -03:00
Davidson Gomes
c5824767c8 fix: Fixed validation is set settings 2023-07-24 20:11:49 -03:00
Davidson Gomes
84f3f07279 fix: Fixed validation is set settings 2023-07-24 20:11:15 -03:00
Davidson Gomes
f8e1892eee fix: group validation
Group validation
2023-07-24 20:08:24 -03:00
Davidson Gomes
036a8edca0 fix: Promote All Participants in Create Group
Promote All Participants in Create Group
2023-07-24 20:07:05 -03:00
Alan Mosko
58ed6f395f Validação de Grupo 2023-07-24 19:59:09 -03:00
Alan Mosko
ef4be6a612 Start 2023-07-24 19:53:03 -03:00
Davidson Gomes
3d8e6f4394 fix: Fixed mentions
Fixed mentions
2023-07-24 19:08:39 -03:00
Alan Mosko
0cc1f18a7e [BUG] Correção de mencionar
Caso seja enviado everyOne como false sem passar nada no mentioned
2023-07-24 19:05:32 -03:00
Davidson Gomes
8b6e577b8f Merge tag '1.4.1' into develop
* Fixed reconnect with pairing code or qrcode
* Fixed problem in createJid
2023-07-24 18:28:57 -03:00
Davidson Gomes
cc91f2e5db Merge branch 'release/1.4.1' 2023-07-24 18:28:45 -03:00
Davidson Gomes
8d1f2313ac version: 1.4.1 2023-07-24 18:28:39 -03:00
Davidson Gomes
f9abd90cc9 fix: connection state 2023-07-24 18:28:01 -03:00
Davidson Gomes
f7293255cf fix: Fixed reconnect with pairing code or qrcode 2023-07-24 18:21:11 -03:00
Davidson Gomes
7d6a130cf9 Merge tag '1.4.0' into develop
* Added connection functionality via pairing code
* Added fetch profile endpoint in chat controller
* Created settings controller
* Added reject call and send text message when receiving a call
* Added setting to ignore group messages
* Added connection with pairing code in chatwoot with command /init:{NUMBER}
* Added encoding option in endpoint sendWhatsAppAudio

* Added link preview option in send text message
* Fixed problem with fileSha256 appearing when sending a sticker in chatwoot
* Fixed issue where it was not possible to open a conversation when sent at first by me on my cell phone in chatwoot
* Now it only updates the contact name if it is the same as the phone number in chatwoot
* Now accepts all chatwoot inbox templates
* Command to create new instances set to /new_instance:{NAME}:{NUMBER}
* Fix in chatwoot set, sign msg can now be disabled

- Chatwoot: v2.18.0 - v3.0.0 (Beta)
2023-07-24 17:05:43 -03:00
Davidson Gomes
be7bb2e39f Merge branch 'release/1.4.0' 2023-07-24 17:05:33 -03:00
Davidson Gomes
1c30728880 version: 1.4.0 2023-07-24 17:05:18 -03:00
Davidson Gomes
8d91e7cb1d feat: Added encoding option in endpoint sendWhatsAppAudio 2023-07-24 16:21:29 -03:00
Davidson Gomes
68d980795a fix: fix in chatwoot set, sign msg can now be disabled 2023-07-24 15:13:46 -03:00
Davidson Gomes
45c11a5a8e fix: fix in chatwoot set, sign msg can now be disabled 2023-07-24 15:12:13 -03:00
Davidson Gomes
4d00351db7 fix: command to create new instances set to /new_instance:<NAME>:<NUMBER> 2023-07-24 15:05:26 -03:00
Davidson Gomes
fff420b652 fix: command to create new instances set to /new_instance:<NAME>:<NUMBER> 2023-07-24 15:05:03 -03:00
Davidson Gomes
7103a95305 feat: Added connection with pairing code in chatwoot 2023-07-24 13:43:18 -03:00
Davidson Gomes
bcada5d553 fix: Now accepts all chatwoot inbox templates 2023-07-24 13:03:40 -03:00
Davidson Gomes
c9b24ff612 fix: adjusts for chatwoot v3 2023-07-24 12:55:27 -03:00
Davidson Gomes
854c7ed04d fix: Improvement for Validation of Numbers and Groups 2023-07-24 12:02:38 -03:00
Davidson Gomes
c0054959cd fix: Improvement for Validation of Numbers and Groups
Improvement for Validation of Numbers and Groups
2023-07-24 12:00:33 -03:00
Davidson Gomes
1aa837d220 fix: Adjusts in chatwoot integration 2023-07-24 11:58:52 -03:00
Alan Mosko
95df402c4c wip 2023-07-24 11:57:15 -03:00
Davidson Gomes
2f3d6f7e63 fix: Fixed problem with fileSha256 appearing when sending a sticker in chatwoot 2023-07-24 11:48:10 -03:00
Alan Mosko
ffe1523170 Update whatsapp.service.ts 2023-07-24 11:42:06 -03:00
Davidson Gomes
a73d5f4b4d Merge branch 'develop' of github.com:EvolutionAPI/evolution-api into develop 2023-07-24 11:18:12 -03:00
Davidson Gomes
f35b62ed12 fix: Adjusts in createJid 2023-07-24 11:18:08 -03:00
Davidson Gomes
20abdd2908 fix: Adjusts in createJid to sendContact
Adjusts in createJid to sendContact
2023-07-24 11:17:35 -03:00
Alan Mosko
28c2c7285c Gerar Wuid no SendContact 2023-07-24 11:15:58 -03:00
Davidson Gomes
3ca8ab12a4 fix: Adjusts in createJid
Adjusts in createJid
2023-07-24 11:13:30 -03:00
Alan Mosko
fd82aa143c wip 2023-07-24 11:10:32 -03:00
Davidson Gomes
1fcbd4f9fd feat: Added reject call and send text message when receiving a call and Added setting to ignore group messages 2023-07-24 10:18:16 -03:00
Davidson Gomes
73d9cd62a5 feat: Created settings Controller 2023-07-24 09:42:29 -03:00
Davidson Gomes
be699d24a1 feat: Added fetch profile endpoint in chat controller and link preview option in send text message 2023-07-23 22:26:38 -03:00
Davidson Gomes
798eb90bed feat: Added fetch profile endpoint in chat controller and link preview option in send text message 2023-07-23 22:24:21 -03:00
Davidson Gomes
c252f5f8d9 Merge pull request #20 from EvolutionAPI/revert-18-fetch-profile
Revert "Adição de FetchProfile"
2023-07-23 22:05:38 -03:00
Davidson Gomes
76d77ad76f Revert "Adição de FetchProfile" 2023-07-23 22:05:21 -03:00
Davidson Gomes
69f5cdd61a feat: added fetchProfile endpoint in chat controller
Added fetchProfile endpoint in chat controller
2023-07-23 21:30:11 -03:00
Davidson Gomes
9f52f20660 feat: Add LinkPreview Option
Add LinkPreview Option
2023-07-23 21:25:20 -03:00
Alan Mosko
90048afa9d Add LinkPreview Option 2023-07-23 11:24:16 -03:00
Alan Mosko
1ec3ed32ee Melhorias 2023-07-23 10:18:00 -03:00
Davidson Gomes
16ed5821e2 Added connection functionality via pairing code 2023-07-21 20:58:37 -03:00
Davidson Gomes
b681e33944 Added connection functionality via pairing code 2023-07-21 20:38:10 -03:00
Davidson Gomes
8f4d44a212 Added connection functionality via pairing code 2023-07-21 20:37:58 -03:00
Davidson Gomes
93a5d07f9a Merge tag '1.3.2' into develop
* Fix in update settings that needed to restart after updated
* Correction in the use of the api with mongodb
* Adjustments to search endpoint for contacts, chats, messages and Status messages
* Now when deleting the instance, the data referring to it in mongodb is also deleted
* It is now validated if the instance name contains uppercase and special characters
* For compatibility reasons, container mode has been removed
* Added docker-compose files example
2023-07-21 17:20:19 -03:00
Davidson Gomes
40c230c7db Merge branch 'release/1.3.2' 2023-07-21 17:20:08 -03:00
Davidson Gomes
d0fa3b92f8 version: 1.3.2 2023-07-21 17:19:59 -03:00
Davidson Gomes
2a7727cf5f Merge tag '1.3.2' into develop
* Fix in update settings that needed to restart after updated
* Correction in the use of the api with mongodb
* Adjustments to search endpoint for contacts, chats, messages and Status messages
* Now when deleting the instance, the data referring to it in mongodb is also deleted
* It is now validated if the instance name contains uppercase and special characters
* For compatibility reasons, container mode has been removed
* Added docker-compose files example
2023-07-21 17:18:50 -03:00
Davidson Gomes
98722e7acf Merge branch 'release/1.3.2' 2023-07-21 17:18:40 -03:00
Davidson Gomes
683fe4c3db fix: added docker-compose files example 2023-07-21 16:00:58 -03:00
Alan Mosko
e851696430 Adição de Profile Route 2023-07-21 15:32:28 -03:00
Davidson Gomes
b2ccf965bb fix: added docker-compose files example 2023-07-21 15:14:46 -03:00
Davidson Gomes
f847f38812 fix: added docker-compose files example 2023-07-21 15:13:49 -03:00
Davidson Gomes
19039aa281 fix: For compatibility reasons, container mode has been removed 2023-07-21 13:12:55 -03:00
Davidson Gomes
091b920a22 fix: It is now validated if the instance name contains uppercase and special characters 2023-07-21 12:40:58 -03:00
Davidson Gomes
d7f264c1c2 fix: It is now validated if the instance name contains uppercase and special characters 2023-07-21 12:26:43 -03:00
Davidson Gomes
897f8164b9 fix: Now when deleting the instance, the data referring to it in mongodb is also deleted 2023-07-21 12:13:03 -03:00
Davidson Gomes
796287a776 fix: Adjustments to search endpoint for contacts, chats, messages and Status messages 2023-07-21 11:38:36 -03:00
Davidson Gomes
763e30bd1d fix: fix in update settings that needed to restart after updated 2023-07-21 09:34:39 -03:00
Davidson Gomes
5121374d60 Merge tag '1.3.1' into develop
version: 1.3.1
2023-07-21 08:26:24 -03:00
Davidson Gomes
3e3a175bdc Merge branch 'release/1.3.1' 2023-07-21 08:26:15 -03:00
Davidson Gomes
4a1aa9130b version: 1.3.1 2023-07-21 08:26:05 -03:00
Davidson Gomes
5a3f5f60b6 test: container mode with chatwoot 2023-07-20 10:08:57 -03:00
Davidson Gomes
8c1600be55 Merge tag '1.3.1' into develop
* Adjust in create store files
2023-07-20 07:49:54 -03:00
Davidson Gomes
7d3ae2347b Merge branch 'release/1.3.1' 2023-07-20 07:49:43 -03:00
Davidson Gomes
27add47db4 fix: Adjust in create store files 2023-07-20 07:49:32 -03:00
Davidson Gomes
836bcab036 Merge branch 'develop' of github.com:EvolutionAPI/evolution-api into develop 2023-07-20 07:15:36 -03:00
Davidson Gomes
2d20a07dfb fix: Adjust in create store files 2023-07-20 07:14:07 -03:00
Davidson Gomes
24c5c70466 fix: remove comments in .env to docker
fix: remove comments in .env to docker
2023-07-19 12:32:47 -03:00
Davidson Gomes
22ead22499 Merge branch 'develop' into patch-1 2023-07-19 12:32:06 -03:00
Davidson Gomes
65e1620b43 Merge tag '1.3.0' into develop
* Added messages.delete event
* Added restart instance endpoint
* Created automation for creating instances in the chatwoot bot with the command '#inbox_whatsapp:<INSTANCE_NAME>'
* Change Baileys version to: 6.4.0
* Send contact in chatwoot
* Send contact array in chatwoot
* Added apiKey in webhook and serverUrl in fetchInstance if EXPOSE_IN_FETCH_INSTANCES: true
* Translation set to default (english) in chatwoot

* Fixed error to send message in large groups
* Docker files adjusted
* Fixed in the postman collection the webhookByEvent parameter by webhook_by_events
* Added validations in create instance
* Removed link preview endpoint, now it's done automatically from sending conventional text
* Added group membership validation before sending message to groups
* Adjusts in docker files
* Adjusts in returns in endpoints chatwoot and webhook
* Fixed ghost mentions in send text message
* Fixed bug that saved contacts from groups came without number in chatwoot
* Fixed problem to receive csat in chatwoot
* Fixed require fileName for document only in base64 for send media message
* Bug fix when sending mobile message change contact name to number in chatwoot
* Bug fix when connecting whatsapp does not send confirmation message
* Fixed quoted message with id or message directly
* Adjust in validation for mexican and argentine numbers
* Adjust in create store files

- Chatwoot: v2.18.0
2023-07-19 11:33:42 -03:00
Davidson Gomes
acac09375e Merge branch 'release/1.3.0' 2023-07-19 11:33:32 -03:00
Davidson Gomes
83cf859da3 version: 1.3.0 2023-07-19 11:33:23 -03:00
Alan Mosko
956c391f13 Remoção de Comentários dos Valores
Ao subir um container de testes, verifiquei que os comentários subiram como valores dos campos, o que invalidou algumas conigurações.
2023-07-19 10:15:05 -03:00
Davidson Gomes
7767a2607e test: chatwoot 2023-07-19 08:18:07 -03:00
Davidson Gomes
429d1ac183 fix: Adjust in create store files 2023-07-19 08:14:11 -03:00
Davidson Gomes
f42928f88f fix: Adjust in create store files 2023-07-19 08:13:59 -03:00
Davidson Gomes
2d816ab92d Merge pull request #5 from w3nder/develop
fix: create store folder
2023-07-19 08:11:16 -03:00
Davidson Gomes
aa75380662 fix: Adjust in validation for mexican and argentine numbers 2023-07-19 08:02:24 -03:00
Davidson Gomes
3cf0ced62e test: status/stories 2023-07-18 20:23:18 -03:00
Davidson Gomes
41fa700fb3 feat: translation set to default (english) in chatwoot 2023-07-18 16:01:05 -03:00
Davidson Gomes
a4ef9fb9b7 feat: translation set to default (english) in chatwoot 2023-07-18 15:55:24 -03:00
Davidson Gomes
1db23b5277 fix: Adjusts to receive contact with no whatsapp 2023-07-18 15:53:53 -03:00
Davidson Gomes
584f0cbac0 fix: Adjusts to receive contact with more numbers 2023-07-18 15:13:41 -03:00
Davidson Gomes
dc432a19a3 fix: Adjusts to receive contact with more numbers 2023-07-18 14:57:18 -03:00
Davidson Gomes
6727b1cfca fix: Adjusts to receive contact with more numbers 2023-07-18 14:49:38 -03:00
Davidson Gomes
8c7b0698f3 feat: Added apiKey in webhook and serverUrl in fetchInstance if EXPOSE_IN_FETCH_INSTANCES: true 2023-07-18 14:30:40 -03:00
Davidson Gomes
69e1622e82 feat: Send contact array in chatwoot 2023-07-18 13:17:03 -03:00
w3nder
af7a5d3248 Merge branch 'develop' of github.com:EvolutionAPI/evolution-api into develop 2023-07-18 13:08:59 -03:00
w3nder
7b1a4554ad fix: create folder store 2023-07-18 13:08:53 -03:00
Davidson Gomes
b3e213c133 fix: Added replace special caracters and espaces in instanceName 2023-07-18 12:58:53 -03:00
Davidson Gomes
a9fafec79d fix: Bug fix when connecting whatsapp does not send confirmation message 2023-07-18 12:50:18 -03:00
Davidson Gomes
7cacf7bbaf fix: Bug fix when connecting whatsapp does not send confirmation message 2023-07-18 12:47:03 -03:00
Davidson Gomes
44bf39f7b7 feat: Send contact in chatwoot 2023-07-18 12:36:26 -03:00
Davidson Gomes
0db8f7295b feat: Send contact in chatwoot 2023-07-18 12:33:55 -03:00
Davidson Gomes
c1226062b1 test: contacts update 2023-07-18 11:25:34 -03:00
Davidson Gomes
819ed168da fix: Fixed require fileName for document only in base64 for send media message 2023-07-18 11:23:40 -03:00
Davidson Gomes
19940953e2 fix: Fixed require fileName for document only in base64 for send media message 2023-07-18 11:21:55 -03:00
Davidson Gomes
f4af3eaf5d fix: adjusts in docker files 2023-07-18 11:00:40 -03:00
Davidson Gomes
718563fe6a fix: adjusts in docker files 2023-07-18 10:58:53 -03:00
Davidson Gomes
7e996ad6fa fix: change Baileys version, fixed problem to receive csat in chatwoot 2023-07-18 10:56:26 -03:00
Davidson Gomes
0b07fb6a49 fix: fixed bug that saved contacts from groups came without number in chatwoot 2023-07-17 15:40:46 -03:00
Davidson Gomes
0cb87e6ed9 feat: Created automation for creating instances in the chatwoot bot with the command #inbox_whatsapp:<INSTANCE_NAME> 2023-07-17 15:37:49 -03:00
Davidson Gomes
71a3e75ae2 fix: Fixed ghost mentions in send text message 2023-07-17 14:57:52 -03:00
Davidson Gomes
a2448ea4c1 fix: adjusts in returns in endpoints chatwoot and webhook 2023-07-17 11:33:18 -03:00
Davidson Gomes
8a14141021 fix: adjusts in returns in endpoints chatwoot and webhook 2023-07-17 11:33:08 -03:00
Davidson Gomes
69353892d9 feat: Added restart instance endpoint 2023-07-16 21:55:12 -03:00
Davidson Gomes
7a2fcc3469 fix: adjusts in dockerfile 2023-07-16 19:21:17 -03:00
Davidson Gomes
dfa6dd5011 fix: adjusts in dockerfile 2023-07-16 19:15:39 -03:00
Davidson Gomes
654400c0cf fix: adjusts in dockerfile 2023-07-16 19:14:00 -03:00
Davidson Gomes
3c15fc1b0d fix: adjusts in dockerfile 2023-07-16 19:05:17 -03:00
Davidson Gomes
4b32485e3c fix: adjusts in dockerfile 2023-07-16 18:52:21 -03:00
Davidson Gomes
b90736ed25 fix: adjusts in dockerfile 2023-07-16 18:51:03 -03:00
Davidson Gomes
f28d5c7781 fix: adjusts in dockerfile 2023-07-16 18:44:10 -03:00
Davidson Gomes
0654627478 fix: adjusts in dockerfile 2023-07-16 18:35:48 -03:00
Davidson Gomes
2e91a2ecdb fix: adjusts in env files 2023-07-16 18:26:53 -03:00
Davidson Gomes
66a8ceb27a feat: added messages.delete event 2023-07-16 18:16:51 -03:00
Davidson Gomes
e6b0addb6c feat: added messages.delete event 2023-07-16 18:16:05 -03:00
Davidson Gomes
c00f132145 fix: Added group membership validation before sending message to groups 2023-07-16 18:01:43 -03:00
Davidson Gomes
b9eb8d45b2 fix: removed link preview endpoint, now it's done automatically from sending conventional text 2023-07-16 17:57:37 -03:00
Davidson Gomes
ec7ad70458 fix: Now it's getting the API URL directly in the request, no longer need the variable in the env file 2023-07-16 17:38:01 -03:00
Davidson Gomes
64e19699fb fix: Docker files adjusted 2023-07-16 15:05:02 -03:00
Davidson Gomes
6d3e1b0cbe fix: Fixed error to send message in large groups 2023-07-16 15:01:38 -03:00
Davidson Gomes
d3a53e1d3c Merge tag '1.2.2' into develop
* Tweak in route "/" with version info
* Adjusts chatwoot version

- Chatwoot: v2.18.0
2023-07-15 09:37:39 -03:00
Davidson Gomes
23bbb3ee32 Merge branch 'release/1.2.2' 2023-07-15 09:37:25 -03:00
Davidson Gomes
56bfcd52b7 fix: Adjusts chatwoot version 2023-07-15 09:37:17 -03:00
Davidson Gomes
1c19b6de1e fix: Adjusts chatwoot version 2023-07-15 09:37:03 -03:00
Davidson Gomes
85bed0bdf1 Merge tag '1.2.1-3' into develop
* Adjusts in docker files
* Save picture url groups in chatwoot
2023-07-14 19:05:19 -03:00
Davidson Gomes
0102796769 Merge branch 'release/1.2.1-3' 2023-07-14 19:04:43 -03:00
Davidson Gomes
50b2a72f1b fix: change Baileys fork 2023-07-14 19:04:34 -03:00
Davidson Gomes
04cc239756 Merge tag '1.2.1-2' into develop
v
2023-07-14 19:04:00 -03:00
Davidson Gomes
0c20da2481 Merge branch 'release/1.2.1-2' 2023-07-14 19:03:51 -03:00
Davidson Gomes
72d2a563f3 fix: change Baileys fork 2023-07-14 19:03:41 -03:00
Davidson Gomes
6f3f8c944d Merge tag '1.2.1-1' into develop
* Adjusts in docker files
* Save picture url groups in chatwoot
2023-07-14 18:38:18 -03:00
Davidson Gomes
ed60fd2e82 Merge branch 'release/1.2.1-1' 2023-07-14 18:38:07 -03:00
Davidson Gomes
636fef4693 fix: change Baileys fork 2023-07-14 18:36:44 -03:00
Davidson Gomes
77775e2f85 Merge branch 'release/1.2.1' 2023-07-14 18:04:32 -03:00
Davidson Gomes
b260959a6e fix: Save picture url groups in chatwoot 2023-07-14 18:04:20 -03:00
Davidson Gomes
2a04f7b378 feat: Save picture url groups in chatwoot 2023-07-14 17:54:48 -03:00
Davidson Gomes
d4766f9c81 feat: Save picture url groups in chatwoot 2023-07-14 17:22:30 -03:00
Davidson Gomes
7f4c9b5b11 feat: Save picture url groups in chatwoot 2023-07-14 17:04:39 -03:00
Davidson Gomes
70f7c8ce89 feat: Save picture url groups in chatwoot 2023-07-14 17:04:15 -03:00
Davidson Gomes
f33a6aba39 fix: Adjusts in docker files 2023-07-14 15:29:04 -03:00
Davidson Gomes
236d717f10 Merge branch 'helioelias-feature/mongo-express-rebrow' into develop 2023-07-14 15:27:49 -03:00
Davidson Gomes
0fc160f57c fix: Adjusts in docker files 2023-07-14 15:27:33 -03:00
Helio Elias
666023d89a docker-compose full services 2023-07-14 18:04:36 +00:00
Helio Elias
8c4f2991c7 Change network in docker-compose(api, mongo and redis), add mongo-express and rebrow, tools for maintenance and visualize data 2023-07-14 17:59:29 +00:00
Helio Elias
4453dff36d Change network in docker-compose(api, mongo and redis), add mongo-express and rebrow, tools for maintenance and visualize data 2023-07-14 17:35:42 +00:00
Davidson Gomes
90b043561f Merge tag '1.2.0-1' into develop
v
2023-07-14 14:18:01 -03:00
Davidson Gomes
43a8b34673 Merge branch 'release/1.2.0-1' 2023-07-14 14:17:57 -03:00
Davidson Gomes
6005d33c94 feat: Added verbose logs and format chatwoot service 2023-07-14 14:17:48 -03:00
Davidson Gomes
cffb4736ce Merge tag '1.2.0' into develop
* Native integration with chatwoot
* Added returning or non-returning participants option in fetchAllGroups
* Added group integration to chatwoot
* Added automation on create instance to chatwoot
* Added verbose logs and format chatwoot service

* Adjusts in docker-compose files
* Adjusts in number validation for AR and MX numbers
* Adjusts in env files, removed save old_messages
* Fix when sending a message to a group I don't belong returns a bad request
* Fits the format on return from the fetchAllGroups endpoint
* Adjust in send document with caption from chatwoot
* Fixed message with undefind in chatwoot
* Changed message in path /
* Test duplicate message media in groups chatwoot
* Optimize send message from group with mentions
* Fixed name of the profile status in fetchInstances
* Fixed error 500 when logout in instance with status = close
2023-07-14 13:17:44 -03:00
Davidson Gomes
be54331d05 Merge branch 'release/1.2.0' 2023-07-14 13:17:18 -03:00
Davidson Gomes
e19b8255d3 feat: Added verbose logs and format chatwoot service 2023-07-14 13:16:54 -03:00
Davidson Gomes
d680900f07 feat: Added verbose logs and format chatwoot service 2023-07-14 11:56:42 -03:00
Davidson Gomes
78bd4fd7de fix: Fixed error 500 when logout in instance with status = close 2023-07-14 09:43:04 -03:00
Davidson Gomes
01d4a95d2d fix: Fixed error 500 when logout in instance with status = close 2023-07-14 09:42:56 -03:00
Davidson Gomes
bb4490307d fix: Fixed name of the profile status in fetchInstances 2023-07-14 08:42:26 -03:00
Davidson Gomes
be492a3e3f fix: optimize send message from group with mentions 2023-07-14 08:31:43 -03:00
Davidson Gomes
a7b05f1e85 fix: optimize send message from group with mentions 2023-07-14 06:40:33 -03:00
Davidson Gomes
1c5ae4eb4d fix: optimize send message from group with mentions 2023-07-13 20:12:29 -03:00
Davidson Gomes
16d03d20ac fix: optimize send message from group with mentions 2023-07-13 20:05:38 -03:00
Davidson Gomes
8f062fab7d fix: optimize send message from group with mentions 2023-07-13 20:05:26 -03:00
Davidson Gomes
2565b934a5 fix: test duplicate message media in groups chatwoot 2023-07-13 19:55:23 -03:00
Davidson Gomes
7e88a9084d fix: test duplicate message media in groups chatwoot 2023-07-13 19:23:59 -03:00
Davidson Gomes
ef03292e35 fix: fixed message with undefind in chatwoot 2023-07-13 17:31:32 -03:00
Davidson Gomes
d309ede623 fix: fixed message with undefind in chatwoot 2023-07-13 17:31:15 -03:00
Davidson Gomes
834a80c35a feat: automation chatwoot 2023-07-13 16:34:16 -03:00
Davidson Gomes
99b0288d1b feat: automation chatwoot 2023-07-13 16:26:01 -03:00
Davidson Gomes
926f58f336 feat: automation chatwoot 2023-07-13 16:19:31 -03:00
Davidson Gomes
b7bfe99520 feat: automation chatwoot 2023-07-13 15:53:40 -03:00
Davidson Gomes
fa60b68425 feat: automation chatwoot 2023-07-13 15:45:14 -03:00
Davidson Gomes
8622e1e4ff feat: automation chatwoot 2023-07-13 15:39:40 -03:00
Davidson Gomes
3e13ae9740 feat: added group integration to chatwoot 2023-07-13 12:41:29 -03:00
Davidson Gomes
e5cd577fbf feat: added group integration to chatwoot 2023-07-13 12:32:24 -03:00
Davidson Gomes
86985231ff feat: added group integration to chatwoot 2023-07-13 12:32:10 -03:00
Davidson Gomes
e64926a429 fix: Adjust in send document with caption from chatwoot 2023-07-13 11:35:42 -03:00
Davidson Gomes
6232190cfe fix: Adjust in send document with caption from chatwoot 2023-07-13 11:35:30 -03:00
Davidson Gomes
eb83d89307 feat: Show webhook_url for chatwoot 2023-07-13 11:19:48 -03:00
Davidson Gomes
b4a9941452 feat: Native integration with chatwoot 2023-07-13 08:29:08 -03:00
Davidson Gomes
be782ba512 feat: Added returning or non-returning participants option in fetchAllGroups 2023-07-13 07:19:32 -03:00
Davidson Gomes
db54f247a2 feat: chatwoot integration completed 2023-07-13 00:34:34 -03:00
Davidson Gomes
0fc3b47c88 feat: chatwoot integration completed 2023-07-13 00:27:18 -03:00
Davidson Gomes
3eda2a1f2a feat: chatwoot integration completed 2023-07-12 21:01:06 -03:00
Davidson Gomes
c45b2adad6 Merge branch 'feature/connect-chatwoot' into develop 2023-07-12 20:58:38 -03:00
Davidson Gomes
702dbebfbe feat: chatwoot integration completed 2023-07-12 20:58:18 -03:00
Davidson Gomes
052303cc93 feat: chatwoot integration completed 2023-07-12 20:28:51 -03:00
Davidson Gomes
69380146e4 fix: Adjusts in env files, removed save old_messages 2023-07-12 16:39:02 -03:00
Davidson Gomes
514fb56209 feat: chatwoot service and webhook endpoint 2023-07-12 16:37:21 -03:00
Davidson Gomes
57b61070d9 feat: Save chatwoot creds 2023-07-12 15:41:07 -03:00
Davidson Gomes
86ce00365a fix: Adjusts in env files, removed save old_messages 2023-07-12 14:39:43 -03:00
Davidson Gomes
a8bd32bef3 fix: Adjusts in env files, removed save old_messages 2023-07-12 14:31:05 -03:00
Davidson Gomes
ae8801dd8a fix: Adjusts in env files, removed save old_messages 2023-07-12 14:10:24 -03:00
Davidson Gomes
0a4e52e663 fix: Adjusts in env files, removed save old_messages 2023-07-12 11:52:00 -03:00
Davidson Gomes
95045db74e fix: Adjusts in number validation for AR and MX numbers 2023-07-12 11:15:45 -03:00
Davidson Gomes
19e7c0be0b Merge tag '1.1.5' into develop
v
2023-07-12 07:21:04 -03:00
76 changed files with 4328 additions and 1629 deletions

BIN
.DS_Store vendored

Binary file not shown.

View File

@@ -3,10 +3,14 @@ module.exports = {
parserOptions: { parserOptions: {
sourceType: 'CommonJS', sourceType: 'CommonJS',
}, },
plugins: ['@typescript-eslint/eslint-plugin'], plugins: [
'@typescript-eslint',
'simple-import-sort',
'import'
],
extends: [ extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended', 'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
'plugin:prettier/recommended' 'plugin:prettier/recommended'
], ],
globals: { globals: {
@@ -26,7 +30,11 @@ module.exports = {
'@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-empty-function': 'off', '@typescript-eslint/no-empty-function': 'off',
'@typescript-eslint/no-non-null-assertion': 'off', '@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-unused-vars': 'off', '@typescript-eslint/no-unused-vars': 'error',
'import/first': 'error',
'import/no-duplicates': 'error',
'simple-import-sort/imports': 'error',
'simple-import-sort/exports': 'error',
'@typescript-eslint/ban-types': [ '@typescript-eslint/ban-types': [
'error', 'error',
{ {

8
.gitignore vendored
View File

@@ -16,16 +16,19 @@ lerna-debug.log*
/docker-compose-data /docker-compose-data
/docker-data /docker-data
docker-compose.yaml
# Package # Package
/yarn.lock /yarn.lock
/package-lock.json /package-lock.json
# IDE - VSCode # IDEs
.vscode/* .vscode/*
!.vscode/settings.json !.vscode/settings.json
!.vscode/tasks.json !.vscode/tasks.json
!.vscode/launch.json !.vscode/launch.json
!.vscode/extensions.json !.vscode/extensions.json
.nova/*
# Prisma # Prisma
/prisma/migrations /prisma/migrations
@@ -38,3 +41,6 @@ lerna-debug.log*
/store /store
/temp/* /temp/*
.DS_Store
*.DS_Store

View File

@@ -2,8 +2,11 @@ module.exports = {
semi: true, semi: true,
trailingComma: 'all', trailingComma: 'all',
singleQuote: true, singleQuote: true,
printWidth: 90, printWidth: 120,
arrowParens: 'always',
tabWidth: 2, tabWidth: 2,
bracketSameLine: true, useTabs: false,
bracketSpacing: true bracketSameLine: false,
bracketSpacing: true,
parser: 'typescript'
} }

View File

@@ -1,3 +1,191 @@
# 1.4.7 (2023-07-27 08:47)
### Fixed
* Fixed error return bug
* Fixed problem of getting message when deleting message in chatwoot
* Change in error return pattern
# 1.4.6 (2023-07-26 17:54)
### Fixed
* Fixed bug of creating new inbox by chatwoot
* When conversation reopens is pending when conversation pending is true
* Added docker-compose file with dockerhub image
# 1.4.5 (2023-07-26 09:32)
### Fixed
* Fixed problems in localization template in chatwoot
* Fix mids going duplicated in chatwoot
# 1.4.4 (2023-07-25 15:24)
### Fixed
* Fixed chatwoot line wrap issue
* Solved receive location in chatwoot
* When requesting the pairing code, it also brings the qr code
* Option reopen_conversation in chatwoot endpoint
* Option conversation_pending in chatwoot endpoint
# 1.4.3 (2023-07-25 10:51)
### Fixed
* Adjusts in settings with options always_online, read_messages and read_status
* Fixed send webhook for event CALL
* Create instance with settings
# 1.4.2 (2023-07-24 20:52)
### Fixed
* Fixed validation is set settings
* Adjusts in group validations
* Ajusts in sticker message to chatwoot
# 1.4.1 (2023-07-24 18:28)
### Fixed
* Fixed reconnect with pairing code or qrcode
* Fixed problem in createJid
# 1.4.0 (2023-07-24 17:03)
### Features
* Added connection functionality via pairing code
* Added fetch profile endpoint in chat controller
* Created settings controller
* Added reject call and send text message when receiving a call
* Added setting to ignore group messages
* Added connection with pairing code in chatwoot with command /init:{NUMBER}
* Added encoding option in endpoint sendWhatsAppAudio
### Fixed
* Added link preview option in send text message
* Fixed problem with fileSha256 appearing when sending a sticker in chatwoot
* Fixed issue where it was not possible to open a conversation when sent at first by me on my cell phone in chatwoot
* Now it only updates the contact name if it is the same as the phone number in chatwoot
* Now accepts all chatwoot inbox templates
* Command to create new instances set to /new_instance:{NAME}:{NUMBER}
* Fix in chatwoot set, sign msg can now be disabled
### Integrations
- Chatwoot: v2.18.0 - v3.0.0 (Beta)
# 1.3.2 (2023-07-21 17:19)
### Fixed
* Fix in update settings that needed to restart after updated
* Correction in the use of the api with mongodb
* Adjustments to search endpoint for contacts, chats, messages and Status messages
* Now when deleting the instance, the data referring to it in mongodb is also deleted
* It is now validated if the instance name contains uppercase and special characters
* For compatibility reasons, container mode has been removed
* Added docker-compose files example
### Integrations
- Chatwoot: v2.18.0
# 1.3.1 (2023-07-20 07:48)
### Fixed
* Adjust in create store files
### Integrations
- Chatwoot: v2.18.0
# 1.3.0 (2023-07-19 11:33)
### Features
* Added messages.delete event
* Added restart instance endpoint
* Created automation for creating instances in the chatwoot bot with the command '#inbox_whatsapp:{INSTANCE_NAME}
* Change Baileys version to: 6.4.0
* Send contact in chatwoot
* Send contact array in chatwoot
* Added apiKey in webhook and serverUrl in fetchInstance if EXPOSE_IN_FETCH_INSTANCES: true
* Translation set to default (english) in chatwoot
### Fixed
* Fixed error to send message in large groups
* Docker files adjusted
* Fixed in the postman collection the webhookByEvent parameter by webhook_by_events
* Added validations in create instance
* Removed link preview endpoint, now it's done automatically from sending conventional text
* Added group membership validation before sending message to groups
* Adjusts in docker files
* Adjusts in returns in endpoints chatwoot and webhook
* Fixed ghost mentions in send text message
* Fixed bug that saved contacts from groups came without number in chatwoot
* Fixed problem to receive csat in chatwoot
* Fixed require fileName for document only in base64 for send media message
* Bug fix when sending mobile message change contact name to number in chatwoot
* Bug fix when connecting whatsapp does not send confirmation message
* Fixed quoted message with id or message directly
* Adjust in validation for mexican and argentine numbers
* Adjust in create store files
### Integrations
- Chatwoot: v2.18.0
# 1.2.2 (2023-07-15 09:36)
### Fixed
* Tweak in route "/" with version info
* Adjusts chatwoot version
### Integrations
- Chatwoot: v2.18.0
# 1.2.1 (2023-07-14 19:04)
### Fixed
* Adjusts in docker files
* Save picture url groups in chatwoot
# 1.2.0 (2023-07-14 15:28)
### Features
* Native integration with chatwoot
* Added returning or non-returning participants option in fetchAllGroups
* Added group integration to chatwoot
* Added automation on create instance to chatwoot
* Added verbose logs and format chatwoot service
### Fixed
* Adjusts in docker-compose files
* Adjusts in number validation for AR and MX numbers
* Adjusts in env files, removed save old_messages
* Fix when sending a message to a group I don't belong returns a bad request
* Fits the format on return from the fetchAllGroups endpoint
* Adjust in send document with caption from chatwoot
* Fixed message with undefind in chatwoot
* Changed message in path /
* Test duplicate message media in groups chatwoot
* Optimize send message from group with mentions
* Fixed name of the profile status in fetchInstances
* Fixed error 500 when logout in instance with status = close
# 1.1.5 (2023-07-12 07:17) # 1.1.5 (2023-07-12 07:17)
### Fixed ### Fixed

View File

@@ -1,11 +1,16 @@
CORS_ORIGIN='*' # Or separate by commas - ex.: 'yourdomain1.com, yourdomain2.com' # Server URL - Set your application url
CORS_METHODS='POST,GET,PUT,DELETE' SERVER_URL=http://localhost:8080
# Cors - * for all or set separate by commas - ex.: 'yourdomain1.com, yourdomain2.com'
CORS_ORIGIN=*
CORS_METHODS=POST,GET,PUT,DELETE
CORS_CREDENTIALS=true CORS_CREDENTIALS=true
# Determine the logs to be displayed # Determine the logs to be displayed
LOG_LEVEL='ERROR,WARN,DEBUG,INFO,LOG,VERBOSE,DARK,WEBHOOKS' LOG_LEVEL=ERROR,WARN,DEBUG,INFO,LOG,VERBOSE,DARK,WEBHOOKS
LOG_COLOR=true LOG_COLOR=true
LOG_BAILEYS=error # "fatal" | "error" | "warn" | "info" | "debug" | "trace" # Log Baileys - "fatal" | "error" | "warn" | "info" | "debug" | "trace"
LOG_BAILEYS=error
# Determine how long the instance should be deleted from memory in case of no connection. # Determine how long the instance should be deleted from memory in case of no connection.
# Default time: 5 minutes # Default time: 5 minutes
@@ -18,32 +23,33 @@ STORE_MESSAGE_UP=true
STORE_CONTACTS=true STORE_CONTACTS=true
STORE_CHATS=true STORE_CHATS=true
CLEAN_STORE_CLEANING_INTERVAL=7200 # seconds === 2h # Set Store Interval in Seconds (7200 = 2h)
CLEAN_STORE_CLEANING_INTERVAL=7200
CLEAN_STORE_MESSAGES=true CLEAN_STORE_MESSAGES=true
CLEAN_STORE_MESSAGE_UP=true CLEAN_STORE_MESSAGE_UP=true
CLEAN_STORE_CONTACTS=true CLEAN_STORE_CONTACTS=true
CLEAN_STORE_CHATS=true CLEAN_STORE_CHATS=true
# Permanent data storage # Permanent data storage
DATABASE_ENABLED=false DATABASE_ENABLED=true
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=evolution DATABASE_CONNECTION_DB_PREFIX_NAME=evdocker
# Choose the data you want to save in the application's database or store # Choose the data you want to save in the application's database or store
DATABASE_SAVE_DATA_INSTANCE=false DATABASE_SAVE_DATA_INSTANCE=false
DATABASE_SAVE_DATA_OLD_MESSAGE=false
DATABASE_SAVE_DATA_NEW_MESSAGE=false DATABASE_SAVE_DATA_NEW_MESSAGE=false
DATABASE_SAVE_MESSAGE_UPDATE=false DATABASE_SAVE_MESSAGE_UPDATE=false
DATABASE_SAVE_DATA_CONTACTS=false DATABASE_SAVE_DATA_CONTACTS=false
DATABASE_SAVE_DATA_CHATS=false DATABASE_SAVE_DATA_CHATS=false
REDIS_ENABLED=false REDIS_ENABLED=true
REDIS_URI=redis://redis:6379 REDIS_URI=redis://redis:6379
REDIS_PREFIX_KEY=evolution REDIS_PREFIX_KEY=evdocker
# Webhook Settings # Global Webhook Settings
# Each instance's Webhook URL and events will be requested at the time it is created
## Define a global webhook that will listen for enabled events from all instances ## Define a global webhook that will listen for enabled events from all instances
WEBHOOK_GLOBAL_URL='<url>' WEBHOOK_GLOBAL_URL=''
WEBHOOK_GLOBAL_ENABLED=false WEBHOOK_GLOBAL_ENABLED=false
# With this option activated, you work with a url per webhook event, respecting the global url and the name of each event # With this option activated, you work with a url per webhook event, respecting the global url and the name of each event
WEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS=false WEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS=false
@@ -53,6 +59,8 @@ WEBHOOK_EVENTS_QRCODE_UPDATED=true
WEBHOOK_EVENTS_MESSAGES_SET=true WEBHOOK_EVENTS_MESSAGES_SET=true
WEBHOOK_EVENTS_MESSAGES_UPSERT=true WEBHOOK_EVENTS_MESSAGES_UPSERT=true
WEBHOOK_EVENTS_MESSAGES_UPDATE=true WEBHOOK_EVENTS_MESSAGES_UPDATE=true
WEBHOOK_EVENTS_MESSAGES_DELETE=true
WEBHOOK_EVENTS_SEND_MESSAGE=true
WEBHOOK_EVENTS_CONTACTS_SET=true WEBHOOK_EVENTS_CONTACTS_SET=true
WEBHOOK_EVENTS_CONTACTS_UPSERT=true WEBHOOK_EVENTS_CONTACTS_UPSERT=true
WEBHOOK_EVENTS_CONTACTS_UPDATE=true WEBHOOK_EVENTS_CONTACTS_UPDATE=true
@@ -65,28 +73,28 @@ WEBHOOK_EVENTS_GROUPS_UPSERT=true
WEBHOOK_EVENTS_GROUPS_UPDATE=true WEBHOOK_EVENTS_GROUPS_UPDATE=true
WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE=true WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE=true
WEBHOOK_EVENTS_CONNECTION_UPDATE=true WEBHOOK_EVENTS_CONNECTION_UPDATE=true
WEBHOOK_EVENTS_CALL=true
# This event fires every time a new token is requested via the refresh route # This event fires every time a new token is requested via the refresh route
WEBHOOK_EVENTS_NEW_JWT_TOKEN=false WEBHOOK_EVENTS_NEW_JWT_TOKEN=false
# Name that will be displayed on smartphone connection # Name that will be displayed on smartphone connection
CONFIG_SESSION_PHONE_CLIENT='Evolution API' CONFIG_SESSION_PHONE_CLIENT=EvolutionAPI
CONFIG_SESSION_PHONE_NAME=chrome # chrome | firefox | edge | opera | safari # Browser Name = chrome | firefox | edge | opera | safari
CONFIG_SESSION_PHONE_NAME=chrome
# Set qrcode display limit # Set qrcode display limit
QRCODE_LIMIT=30 QRCODE_LIMIT=30
# Defines an authentication type for the api # Defines an authentication type for the api
AUTHENTICATION_TYPE='apikey' # jwt or 'apikey' # We recommend using the apikey because it will allow you to use a custom token,
# if you use jwt, a random token will be generated and may be expired and you will have to generate a new token
# jwt or 'apikey'
AUTHENTICATION_TYPE=apikey
## Define a global apikey to access all instances. ## Define a global apikey to access all instances.
### OBS: This key must be inserted in the request header to create an instance. ### OBS: This key must be inserted in the request header to create an instance.
AUTHENTICATION_API_KEY='B6D711FCDE4D4FD5936544120E713976' AUTHENTICATION_API_KEY=B6D711FCDE4D4FD5936544120E713976
AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES=true AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES=true
## Set the secret key to encrypt and decrypt your token and its expiration time ## Set the secret key to encrypt and decrypt your token and its expiration time
AUTHENTICATION_JWT_EXPIRIN_IN=0 # seconds - 3600s ===1h | zero (0) - never expires # seconds - 3600s ===1h | zero (0) - never expires
AUTHENTICATION_JWT_SECRET='L0YWtjb2w554WFqPG' AUTHENTICATION_JWT_EXPIRIN_IN=0
# Set the instance name and webhook url to create an instance in init the application AUTHENTICATION_JWT_SECRET='L=0YWt]b2w[WF>#>:&E`'
# With this option activated, you work with a url per webhook event, respecting the local url and the name of each event
AUTHENTICATION_INSTANCE_MODE=server # container or server
# if you are using container mode, set the container name and the webhook url to default instance
AUTHENTICATION_INSTANCE_NAME=evolution
AUTHENTICATION_INSTANCE_WEBHOOK_URL='<url>'

View File

@@ -1,27 +1,41 @@
version: '3.3' version: '3.3'
networks:
evolution-net:
driver: bridge
services: services:
mongodb: mongodb:
container_name: mongodb container_name: mongodb
image: mongo image: mongo
restart: always restart: always
volumes:
- evolution_mongodb_data:/data/db
- evolution_mongodb_configdb:/data/configdb
ports: ports:
- 27017:27017 - 27017:27017
environment: environment:
MONGO_INITDB_ROOT_USERNAME: root - MONGO_INITDB_ROOT_USERNAME=root
MONGO_INITDB_ROOT_PASSWORD: root - MONGO_INITDB_ROOT_PASSWORD=root
networks: - PUID=1000
- evolution-net - PGID=1000
volumes:
- evolution_mongodb_data:/data/db
- evolution_mongodb_configdb:/data/configdb
expose: expose:
- 27017 - 27017
mongo-express:
image: mongo-express
environment:
ME_CONFIG_BASICAUTH_USERNAME: root
ME_CONFIG_BASICAUTH_PASSWORD: root
ME_CONFIG_MONGODB_SERVER: mongodb
ME_CONFIG_MONGODB_ADMINUSERNAME: root
ME_CONFIG_MONGODB_ADMINPASSWORD: root
ports:
- 8081:8081
links:
- mongodb
volumes: volumes:
evolution_mongodb_data: evolution_mongodb_data:
evolution_mongodb_configdb: evolution_mongodb_configdb:
networks:
evolution-net:
external: true

View File

@@ -1,17 +1,21 @@
version: '3.3' version: '3.3'
networks:
evolution-net:
driver: bridge
services: services:
redis: redis:
image: redis:latest image: redis:latest
container_name: redis container_name: redis
command: >
redis-server
--port 6379
--appendonly yes
volumes:
- evolution_redis:/data
ports: ports:
- 6379:6379 - 6379:6379
networks:
- evolution-net
volumes: volumes:
evolution_redis: evolution_redis:
networks:
evolution-net:
external: true

View File

@@ -13,82 +13,91 @@ COPY ./package.json .
ENV DOCKER_ENV=true ENV DOCKER_ENV=true
ENV SERVER_TYPE="http" ENV SERVER_URL=http://localhost:8080
ENV SERVER_PORT=8080
ENV CORS_ORIGIN="*" ENV CORS_ORIGIN=*
ENV CORS_METHODS="POST,GET,PUT,DELETE" ENV CORS_METHODS=POST,GET,PUT,DELETE
ENV CORS_CREDENTIALS=true ENV CORS_CREDENTIALS=true
ENV LOG_LEVEL=$LOG_LEVEL ENV LOG_LEVEL=ERROR,WARN,DEBUG,INFO,LOG,VERBOSE,DARK,WEBHOOKS
ENV LOG_COLOR=$LOG_COLOR ENV LOG_COLOR=true
ENV LOG_BAILEYS=error
ENV DEL_INSTANCE=$DEL_INSTANCE ENV DEL_INSTANCE=false
ENV STORE_MESSAGES=$STORE_MESSAGE ENV STORE_MESSAGES=true
ENV STORE_MESSAGE_UP=$STORE_MESSAGE_UP ENV STORE_MESSAGE_UP=true
ENV STORE_CONTACTS=$STORE_CONTACTS ENV STORE_CONTACTS=true
ENV STORE_CHATS=$STORE_CHATS ENV STORE_CHATS=true
ENV CLEAN_STORE_CLEANING_INTERVAL=$CLEAN_STORE_CLEANING_INTERVAL ENV CLEAN_STORE_CLEANING_INTERVAL=7200
ENV CLEAN_STORE_MESSAGES=$CLEAN_STORE_MESSAGE ENV CLEAN_STORE_MESSAGES=true
ENV CLEAN_STORE_MESSAGE_UP=$CLEAN_STORE_MESSAGE_UP ENV CLEAN_STORE_MESSAGE_UP=true
ENV CLEAN_STORE_CONTACTS=$CLEAN_STORE_CONTACTS ENV CLEAN_STORE_CONTACTS=true
ENV CLEAN_STORE_CHATS=$CLEAN_STORE_CHATS ENV CLEAN_STORE_CHATS=true
ENV DATABASE_ENABLED=$DATABASE_ENABLED ENV DATABASE_ENABLED=false
ENV DATABASE_CONNECTION_URI=$DATABASE_CONNECTION_URI ENV DATABASE_CONNECTION_URI=mongodb://root:root@mongodb:27017/?authSource=admin&readPreference=primary&ssl=false&directConnection=true
ENV DATABASE_CONNECTION_DB_PREFIX_NAME=$DATABASE_CONNECTION_DB_PREFIX_NAME ENV DATABASE_CONNECTION_DB_PREFIX_NAME=evolution
ENV DATABASE_SAVE_DATA_INSTANCE=$DATABASE_SAVE_DATA_INSTANCE
ENV DATABASE_SAVE_DATA_OLD_MESSAGE=$DATABASE_SAVE_DATA_OLD_MESSAGE
ENV DATABASE_SAVE_DATA_NEW_MESSAGE=$DATABASE_SAVE_DATA_NEW_MESSAGE
ENV DATABASE_SAVE_MESSAGE_UPDATE=$DATABASE_SAVE_MESSAGE_UPDATE
ENV DATABASE_SAVE_DATA_CONTACTS=$DATABASE_SAVE_DATA_CONTACTS
ENV DATABASE_SAVE_DATA_CHATS=$DATABASE_SAVE_DATA_CHATS
ENV REDIS_ENABLED=$REDIS_ENABLED ENV DATABASE_SAVE_DATA_INSTANCE=false
ENV REDIS_URI=$REDIS_URI ENV DATABASE_SAVE_DATA_NEW_MESSAGE=false
ENV REDIS_PREFIX_KEY=$REDIS_PREFIX_KEY ENV DATABASE_SAVE_MESSAGE_UPDATE=false
ENV DATABASE_SAVE_DATA_CONTACTS=false
ENV DATABASE_SAVE_DATA_CHATS=false
ENV WEBHOOK_GLOBAL_URL=$WEBHOOK_GLOBAL_URL ENV REDIS_ENABLED=false
ENV WEBHOOK_GLOBAL_ENABLED=$WEBHOOK_GLOBAL_ENABLED ENV REDIS_URI=redis://redis:6379
ENV WEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS=$WEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS ENV REDIS_PREFIX_KEY=evolution
ENV WEBHOOK_EVENTS_APPLICATION_STARTUP=$WEBHOOK_EVENTS_APPLICATION_STARTUP ENV WEBHOOK_GLOBAL_URL=<url>
ENV WEBHOOK_EVENTS_QRCODE_UPDATED=$WEBHOOK_EVENTS_QRCODE_UPDATED ENV WEBHOOK_GLOBAL_ENABLED=false
ENV WEBHOOK_EVENTS_MESSAGES_SET=$WEBHOOK_EVENTS_MESSAGES_SET
ENV WEBHOOK_EVENTS_MESSAGES_UPDATE=$WEBHOOK_EVENTS_MESSAGES_UPDATE
ENV WEBHOOK_EVENTS_MESSAGES_UPSERT=$WEBHOOK_EVENTS_MESSAGES_UPSERT
ENV WEBHOOK_EVENTS_CONTACTS_SET=$WEBHOOK_EVENTS_CONTACTS_SET
ENV WEBHOOK_EVENTS_CONTACTS_UPSERT=$WEBHOOK_EVENTS_CONTACTS_UPSERT
ENV WEBHOOK_EVENTS_CONTACTS_UPDATE=$WEBHOOK_EVENTS_CONTACTS_UPDATE
ENV WEBHOOK_EVENTS_PRESENCE_UPDATE=$WEBHOOK_EVENTS_PRESENCE_UPDATE
ENV WEBHOOK_EVENTS_CHATS_SET=$WEBHOOK_EVENTS_CHATS_SET
ENV WEBHOOK_EVENTS_CHATS_UPSERT=$WEBHOOK_EVENTS_CHATS_UPSERT
ENV WEBHOOK_EVENTS_CHATS_UPDATE=$WEBHOOK_EVENTS_CHATS_UPDATE
ENV WEBHOOK_EVENTS_CONNECTION_UPDATE=$WEBHOOK_EVENTS_CONNECTION_UPDATE
ENV WEBHOOK_EVENTS_GROUPS_UPSERT=$WEBHOOK_EVENTS_GROUPS_UPSERT
ENV WEBHOOK_EVENTS_GROUPS_UPDATE=$WEBHOOK_EVENTS_GROUPS_UPDATE
ENV WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE=$WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE
ENV WEBHOOK_EVENTS_NEW_JWT_TOKEN=$WEBHOOK_EVENTS_NEW_JWT_TOKEN ENV WEBHOOK_GLOBAL_WEBHOOK_BY_EVENTS=false
ENV CONFIG_SESSION_PHONE_CLIENT=$CONFIG_SESSION_PHONE_CLIENT ENV WEBHOOK_EVENTS_APPLICATION_STARTUP=false
ENV CONFIG_SESSION_PHONE_NAME=$CONFIG_SESSION_PHONE_NAME ENV WEBHOOK_EVENTS_QRCODE_UPDATED=true
ENV WEBHOOK_EVENTS_MESSAGES_SET=true
ENV WEBHOOK_EVENTS_MESSAGES_UPSERT=true
ENV WEBHOOK_EVENTS_MESSAGES_UPDATE=true
ENV WEBHOOK_EVENTS_MESSAGES_DELETE=true
ENV WEBHOOK_EVENTS_SEND_MESSAGE=true
ENV WEBHOOK_EVENTS_CONTACTS_SET=true
ENV WEBHOOK_EVENTS_CONTACTS_UPSERT=true
ENV WEBHOOK_EVENTS_CONTACTS_UPDATE=true
ENV WEBHOOK_EVENTS_PRESENCE_UPDATE=true
ENV WEBHOOK_EVENTS_CHATS_SET=true
ENV WEBHOOK_EVENTS_CHATS_UPSERT=true
ENV WEBHOOK_EVENTS_CHATS_UPDATE=true
ENV WEBHOOK_EVENTS_CHATS_DELETE=true
ENV WEBHOOK_EVENTS_GROUPS_UPSERT=true
ENV WEBHOOK_EVENTS_GROUPS_UPDATE=true
ENV WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE=true
ENV WEBHOOK_EVENTS_CONNECTION_UPDATE=true
ENV WEBHOOK_EVENTS_CALL=true
ENV QRCODE_LIMIT=$QRCODE_LIMIT ENV WEBHOOK_EVENTS_NEW_JWT_TOKEN=false
ENV AUTHENTICATION_TYPE=$AUTHENTICATION_TYPE ENV CONFIG_SESSION_PHONE_CLIENT=EvolutionAPI
ENV CONFIG_SESSION_PHONE_NAME=chrome
ENV AUTHENTICATION_API_KEY=$AUTHENTICATION_API_KEY ENV QRCODE_LIMIT=30
ENV AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES=$AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES
ENV AUTHENTICATION_JWT_EXPIRIN_IN=$AUTHENTICATION_JWT_EXPIRIN_IN ENV AUTHENTICATION_TYPE=apikey
ENV AUTHENTICATION_JWT_SECRET="L=0YWt]b2w[WF>#>:&E`"
ENV AUTHENTICATION_INSTANCE_NAME=$AUTHENTICATION_INSTANCE_NAME ENV AUTHENTICATION_API_KEY=B6D711FCDE4D4FD5936544120E713976
ENV AUTHENTICATION_INSTANCE_WEBHOOK_URL=$AUTHENTICATION_INSTANCE_WEBHOOK_URL ENV AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES=true
ENV AUTHENTICATION_INSTANCE_MODE=$AUTHENTICATION_INSTANCE_MODE
ENV AUTHENTICATION_JWT_EXPIRIN_IN=0
ENV AUTHENTICATION_JWT_SECRET='L=0YWt]b2w[WF>#>:&E`'
ENV AUTHENTICATION_INSTANCE_MODE=server
ENV AUTHENTICATION_INSTANCE_NAME=evolution
ENV AUTHENTICATION_INSTANCE_WEBHOOK_URL=<url>
ENV AUTHENTICATION_INSTANCE_CHATWOOT_ACCOUNT_ID=1
ENV AUTHENTICATION_INSTANCE_CHATWOOT_TOKEN=123456
ENV AUTHENTICATION_INSTANCE_CHATWOOT_URL=<url>
RUN npm install RUN npm install

View File

@@ -1,9 +1,5 @@
version: '3.3' version: '3.3'
networks:
evolution-net:
driver: bridge
services: services:
api: api:
container_name: evolution_api container_name: evolution_api
@@ -14,14 +10,19 @@ services:
volumes: volumes:
- evolution_instances:/evolution/instances - evolution_instances:/evolution/instances
- evolution_store:/evolution/store - evolution_store:/evolution/store
networks:
- evolution-net
env_file: env_file:
- ./Docker/.env - ./Docker/.env
command: ['node', './dist/src/main.js'] command: ['node', './dist/src/main.js']
networks:
- evolution-net
expose: expose:
- 8080 - 8080
volumes: volumes:
evolution_instances: evolution_instances:
evolution_store: evolution_store:
networks:
evolution-net:
external: true

View File

@@ -0,0 +1,79 @@
version: '3.3'
services:
api:
container_name: evolution_api
image: evolution/api:local
restart: always
ports:
- 8080:8080
volumes:
- evolution_instances:/evolution/instances
- evolution_store:/evolution/store
networks:
- evolution-net
env_file:
- ./Docker/.env
command: ['node', './dist/src/main.js']
expose:
- 8080
mongodb:
container_name: mongodb
image: mongo
restart: always
ports:
- 27017:27017
environment:
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=root
- PUID=1000
- PGID=1000
volumes:
- evolution_mongodb_data:/data/db
- evolution_mongodb_configdb:/data/configdb
networks:
- evolution-net
expose:
- 27017
mongo-express:
image: mongo-express
networks:
- evolution-net
environment:
ME_CONFIG_BASICAUTH_USERNAME: root
ME_CONFIG_BASICAUTH_PASSWORD: root
ME_CONFIG_MONGODB_SERVER: mongodb
ME_CONFIG_MONGODB_ADMINUSERNAME: root
ME_CONFIG_MONGODB_ADMINPASSWORD: root
ports:
- 8081:8081
links:
- mongodb
redis:
image: redis:latest
container_name: redis
command: >
redis-server
--port 6379
--appendonly yes
volumes:
- evolution_redis:/data
networks:
- evolution-net
ports:
- 6379:6379
volumes:
evolution_instances:
evolution_store:
evolution_mongodb_data:
evolution_mongodb_configdb:
evolution_redis:
networks:
evolution-net:
external: true

View File

@@ -0,0 +1,28 @@
version: '3.3'
services:
api:
container_name: evolution_api
image: davidsongomes/evolution-api:latest
restart: always
ports:
- 8080:8080
volumes:
- evolution_instances:/evolution/instances
- evolution_store:/evolution/store
networks:
- evolution-net
env_file:
- ./Docker/.env
command: ['node', './dist/src/main.js']
expose:
- 8080
volumes:
evolution_instances:
evolution_store:
networks:
evolution-net:
external: true

View File

@@ -1,6 +1,6 @@
{ {
"name": "evolution-api", "name": "evolution-api",
"version": "1.1.4", "version": "1.4.7",
"description": "Rest api for communication with WhatsApp", "description": "Rest api for communication with WhatsApp",
"main": "./dist/src/main.js", "main": "./dist/src/main.js",
"scripts": { "scripts": {
@@ -8,7 +8,8 @@
"start": "ts-node --files --transpile-only ./src/main.ts", "start": "ts-node --files --transpile-only ./src/main.ts",
"start:prod": "bash start.sh", "start:prod": "bash start.sh",
"dev:server": "clear && tsnd --files --transpile-only --respawn --ignore-watch node_modules ./src/main.ts", "dev:server": "clear && tsnd --files --transpile-only --respawn --ignore-watch node_modules ./src/main.ts",
"test": "clear && tsnd --files --transpile-only --respawn --ignore-watch node_modules ./test/all.test.ts" "test": "clear && tsnd --files --transpile-only --respawn --ignore-watch node_modules ./test/all.test.ts",
"lint": "eslint --fix --ext .ts src"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@@ -42,7 +43,9 @@
"dependencies": { "dependencies": {
"@adiwajshing/keyed-db": "^0.2.4", "@adiwajshing/keyed-db": "^0.2.4",
"@ffmpeg-installer/ffmpeg": "^1.1.0", "@ffmpeg-installer/ffmpeg": "^1.1.0",
"@figuro/chatwoot-sdk": "^1.1.14",
"@hapi/boom": "^10.0.1", "@hapi/boom": "^10.0.1",
"@sentry/node": "^7.59.2",
"@whiskeysockets/baileys": "github:EvolutionAPI/Baileys", "@whiskeysockets/baileys": "github:EvolutionAPI/Baileys",
"axios": "^1.3.5", "axios": "^1.3.5",
"class-validator": "^0.13.2", "class-validator": "^0.13.2",
@@ -78,16 +81,19 @@
"@types/express": "^4.17.17", "@types/express": "^4.17.17",
"@types/js-yaml": "^4.0.5", "@types/js-yaml": "^4.0.5",
"@types/jsonwebtoken": "^8.5.9", "@types/jsonwebtoken": "^8.5.9",
"@types/mime-types": "^2.1.1",
"@types/node": "^18.15.11", "@types/node": "^18.15.11",
"@types/qrcode": "^1.5.0", "@types/qrcode": "^1.5.0",
"@types/qrcode-terminal": "^0.12.0", "@types/qrcode-terminal": "^0.12.0",
"@types/uuid": "^8.3.4", "@types/uuid": "^8.3.4",
"@typescript-eslint/eslint-plugin": "^5.57.1", "@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.57.1", "@typescript-eslint/parser": "^5.62.0",
"eslint": "^8.38.0", "eslint": "^8.45.0",
"eslint-config-prettier": "^8.8.0", "eslint-config-prettier": "^8.8.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-prettier": "^4.2.1", "eslint-plugin-prettier": "^4.2.1",
"prettier": "^2.8.7", "eslint-plugin-simple-import-sort": "^10.0.0",
"prettier": "^2.8.8",
"ts-node-dev": "^2.0.0", "ts-node-dev": "^2.0.0",
"typescript": "^4.9.5" "typescript": "^4.9.5"
} }

View File

@@ -1,10 +1,9 @@
import { isBooleanString } from 'class-validator';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { load } from 'js-yaml'; import { load } from 'js-yaml';
import { join } from 'path'; import { join } from 'path';
import { SRC_DIR } from './path.config';
import { isBooleanString } from 'class-validator';
export type HttpServer = { TYPE: 'http' | 'https'; PORT: number }; export type HttpServer = { TYPE: 'http' | 'https'; PORT: number; URL: string };
export type HttpMethods = 'POST' | 'GET' | 'PUT' | 'DELETE'; export type HttpMethods = 'POST' | 'GET' | 'PUT' | 'DELETE';
export type Cors = { export type Cors = {
@@ -15,15 +14,7 @@ export type Cors = {
export type LogBaileys = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace'; export type LogBaileys = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';
export type LogLevel = export type LogLevel = 'ERROR' | 'WARN' | 'DEBUG' | 'INFO' | 'LOG' | 'VERBOSE' | 'DARK' | 'WEBHOOKS';
| 'ERROR'
| 'WARN'
| 'DEBUG'
| 'INFO'
| 'LOG'
| 'VERBOSE'
| 'DARK'
| 'WEBHOOKS';
export type Log = { export type Log = {
LEVEL: LogLevel[]; LEVEL: LogLevel[];
@@ -33,7 +24,6 @@ export type Log = {
export type SaveData = { export type SaveData = {
INSTANCE: boolean; INSTANCE: boolean;
OLD_MESSAGE: boolean;
NEW_MESSAGE: boolean; NEW_MESSAGE: boolean;
MESSAGE_UPDATE: boolean; MESSAGE_UPDATE: boolean;
CONTACTS: boolean; CONTACTS: boolean;
@@ -77,6 +67,8 @@ export type EventsWebhook = {
MESSAGES_SET: boolean; MESSAGES_SET: boolean;
MESSAGES_UPSERT: boolean; MESSAGES_UPSERT: boolean;
MESSAGES_UPDATE: boolean; MESSAGES_UPDATE: boolean;
MESSAGES_DELETE: boolean;
SEND_MESSAGE: boolean;
CONTACTS_SET: boolean; CONTACTS_SET: boolean;
CONTACTS_UPDATE: boolean; CONTACTS_UPDATE: boolean;
CONTACTS_UPSERT: boolean; CONTACTS_UPSERT: boolean;
@@ -89,22 +81,18 @@ export type EventsWebhook = {
GROUPS_UPSERT: boolean; GROUPS_UPSERT: boolean;
GROUP_UPDATE: boolean; GROUP_UPDATE: boolean;
GROUP_PARTICIPANTS_UPDATE: boolean; GROUP_PARTICIPANTS_UPDATE: boolean;
CALL: boolean;
NEW_JWT_TOKEN: boolean; NEW_JWT_TOKEN: boolean;
}; };
export type ApiKey = { KEY: string }; export type ApiKey = { KEY: string };
export type Jwt = { EXPIRIN_IN: number; SECRET: string }; export type Jwt = { EXPIRIN_IN: number; SECRET: string };
export type Instance = {
NAME: string;
WEBHOOK_URL: string;
MODE: string;
};
export type Auth = { export type Auth = {
API_KEY: ApiKey; API_KEY: ApiKey;
EXPOSE_IN_FETCH_INSTANCES: boolean; EXPOSE_IN_FETCH_INSTANCES: boolean;
JWT: Jwt; JWT: Jwt;
TYPE: 'jwt' | 'apikey'; TYPE: 'jwt' | 'apikey';
INSTANCE: Instance;
}; };
export type DelInstance = number | boolean; export type DelInstance = number | boolean;
@@ -160,9 +148,7 @@ export class ConfigService {
} }
private envYaml(): Env { private envYaml(): Env {
return load( return load(readFileSync(join(process.cwd(), 'src', 'env.yml'), { encoding: 'utf-8' })) as Env;
readFileSync(join(process.cwd(), 'src', 'env.yml'), { encoding: 'utf-8' }),
) as Env;
} }
private envProcess(): Env { private envProcess(): Env {
@@ -170,6 +156,7 @@ export class ConfigService {
SERVER: { SERVER: {
TYPE: process.env.SERVER_TYPE as 'http' | 'https', TYPE: process.env.SERVER_TYPE as 'http' | 'https',
PORT: Number.parseInt(process.env.SERVER_PORT), PORT: Number.parseInt(process.env.SERVER_PORT),
URL: process.env.SERVER_URL,
}, },
CORS: { CORS: {
ORIGIN: process.env.CORS_ORIGIN.split(','), ORIGIN: process.env.CORS_ORIGIN.split(','),
@@ -189,7 +176,7 @@ export class ConfigService {
CLEAN_STORE: { CLEAN_STORE: {
CLEANING_INTERVAL: Number.isInteger(process.env?.CLEAN_STORE_CLEANING_TERMINAL) CLEANING_INTERVAL: Number.isInteger(process.env?.CLEAN_STORE_CLEANING_TERMINAL)
? Number.parseInt(process.env.CLEAN_STORE_CLEANING_TERMINAL) ? Number.parseInt(process.env.CLEAN_STORE_CLEANING_TERMINAL)
: undefined, : 7200,
MESSAGES: process.env?.CLEAN_STORE_MESSAGES === 'true', MESSAGES: process.env?.CLEAN_STORE_MESSAGES === 'true',
MESSAGE_UP: process.env?.CLEAN_STORE_MESSAGE_UP === 'true', MESSAGE_UP: process.env?.CLEAN_STORE_MESSAGE_UP === 'true',
CONTACTS: process.env?.CLEAN_STORE_CONTACTS === 'true', CONTACTS: process.env?.CLEAN_STORE_CONTACTS === 'true',
@@ -203,7 +190,6 @@ export class ConfigService {
ENABLED: process.env?.DATABASE_ENABLED === 'true', ENABLED: process.env?.DATABASE_ENABLED === 'true',
SAVE_DATA: { SAVE_DATA: {
INSTANCE: process.env?.DATABASE_SAVE_DATA_INSTANCE === 'true', INSTANCE: process.env?.DATABASE_SAVE_DATA_INSTANCE === 'true',
OLD_MESSAGE: process.env?.DATABASE_SAVE_DATA_OLD_MESSAGE === 'true',
NEW_MESSAGE: process.env?.DATABASE_SAVE_DATA_NEW_MESSAGE === 'true', NEW_MESSAGE: process.env?.DATABASE_SAVE_DATA_NEW_MESSAGE === 'true',
MESSAGE_UPDATE: process.env?.DATABASE_SAVE_MESSAGE_UPDATE === 'true', MESSAGE_UPDATE: process.env?.DATABASE_SAVE_MESSAGE_UPDATE === 'true',
CONTACTS: process.env?.DATABASE_SAVE_DATA_CONTACTS === 'true', CONTACTS: process.env?.DATABASE_SAVE_DATA_CONTACTS === 'true',
@@ -222,7 +208,7 @@ export class ConfigService {
}, },
DEL_INSTANCE: isBooleanString(process.env?.DEL_INSTANCE) DEL_INSTANCE: isBooleanString(process.env?.DEL_INSTANCE)
? process.env.DEL_INSTANCE === 'true' ? process.env.DEL_INSTANCE === 'true'
: Number.parseInt(process.env.DEL_INSTANCE), : Number.parseInt(process.env.DEL_INSTANCE) || false,
WEBHOOK: { WEBHOOK: {
GLOBAL: { GLOBAL: {
URL: process.env?.WEBHOOK_GLOBAL_URL, URL: process.env?.WEBHOOK_GLOBAL_URL,
@@ -235,6 +221,8 @@ export class ConfigService {
MESSAGES_SET: process.env?.WEBHOOK_EVENTS_MESSAGES_SET === 'true', MESSAGES_SET: process.env?.WEBHOOK_EVENTS_MESSAGES_SET === 'true',
MESSAGES_UPSERT: process.env?.WEBHOOK_EVENTS_MESSAGES_UPSERT === 'true', MESSAGES_UPSERT: process.env?.WEBHOOK_EVENTS_MESSAGES_UPSERT === 'true',
MESSAGES_UPDATE: process.env?.WEBHOOK_EVENTS_MESSAGES_UPDATE === 'true', MESSAGES_UPDATE: process.env?.WEBHOOK_EVENTS_MESSAGES_UPDATE === 'true',
MESSAGES_DELETE: process.env?.WEBHOOK_EVENTS_MESSAGES_DELETE === 'true',
SEND_MESSAGE: process.env?.WEBHOOK_EVENTS_SEND_MESSAGE === 'true',
CONTACTS_SET: process.env?.WEBHOOK_EVENTS_CONTACTS_SET === 'true', CONTACTS_SET: process.env?.WEBHOOK_EVENTS_CONTACTS_SET === 'true',
CONTACTS_UPDATE: process.env?.WEBHOOK_EVENTS_CONTACTS_UPDATE === 'true', CONTACTS_UPDATE: process.env?.WEBHOOK_EVENTS_CONTACTS_UPDATE === 'true',
CONTACTS_UPSERT: process.env?.WEBHOOK_EVENTS_CONTACTS_UPSERT === 'true', CONTACTS_UPSERT: process.env?.WEBHOOK_EVENTS_CONTACTS_UPSERT === 'true',
@@ -246,36 +234,30 @@ export class ConfigService {
CONNECTION_UPDATE: process.env?.WEBHOOK_EVENTS_CONNECTION_UPDATE === 'true', CONNECTION_UPDATE: process.env?.WEBHOOK_EVENTS_CONNECTION_UPDATE === 'true',
GROUPS_UPSERT: process.env?.WEBHOOK_EVENTS_GROUPS_UPSERT === 'true', GROUPS_UPSERT: process.env?.WEBHOOK_EVENTS_GROUPS_UPSERT === 'true',
GROUP_UPDATE: process.env?.WEBHOOK_EVENTS_GROUPS_UPDATE === 'true', GROUP_UPDATE: process.env?.WEBHOOK_EVENTS_GROUPS_UPDATE === 'true',
GROUP_PARTICIPANTS_UPDATE: GROUP_PARTICIPANTS_UPDATE: process.env?.WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE === 'true',
process.env?.WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE === 'true', CALL: process.env?.WEBHOOK_EVENTS_CALL === 'true',
NEW_JWT_TOKEN: process.env?.WEBHOOK_EVENTS_NEW_JWT_TOKEN === 'true', NEW_JWT_TOKEN: process.env?.WEBHOOK_EVENTS_NEW_JWT_TOKEN === 'true',
}, },
}, },
CONFIG_SESSION_PHONE: { CONFIG_SESSION_PHONE: {
CLIENT: process.env?.CONFIG_SESSION_PHONE_CLIENT, CLIENT: process.env?.CONFIG_SESSION_PHONE_CLIENT || 'Evolution API',
NAME: process.env?.CONFIG_SESSION_PHONE_NAME, NAME: process.env?.CONFIG_SESSION_PHONE_NAME || 'chrome',
}, },
QRCODE: { QRCODE: {
LIMIT: Number.parseInt(process.env.QRCODE_LIMIT), LIMIT: Number.parseInt(process.env.QRCODE_LIMIT) || 30,
}, },
AUTHENTICATION: { AUTHENTICATION: {
TYPE: process.env.AUTHENTICATION_TYPE as 'jwt', TYPE: process.env.AUTHENTICATION_TYPE as 'jwt',
API_KEY: { API_KEY: {
KEY: process.env.AUTHENTICATION_API_KEY, KEY: process.env.AUTHENTICATION_API_KEY,
}, },
EXPOSE_IN_FETCH_INSTANCES: EXPOSE_IN_FETCH_INSTANCES: process.env?.AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES === 'true',
process.env?.AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES === 'true',
JWT: { JWT: {
EXPIRIN_IN: Number.isInteger(process.env?.AUTHENTICATION_JWT_EXPIRIN_IN) EXPIRIN_IN: Number.isInteger(process.env?.AUTHENTICATION_JWT_EXPIRIN_IN)
? Number.parseInt(process.env.AUTHENTICATION_JWT_EXPIRIN_IN) ? Number.parseInt(process.env.AUTHENTICATION_JWT_EXPIRIN_IN)
: 3600, : 3600,
SECRET: process.env.AUTHENTICATION_JWT_SECRET, SECRET: process.env.AUTHENTICATION_JWT_SECRET,
}, },
INSTANCE: {
NAME: process.env.AUTHENTICATION_INSTANCE_NAME,
WEBHOOK_URL: process.env.AUTHENTICATION_INSTANCE_WEBHOOK_URL,
MODE: process.env.AUTHENTICATION_INSTANCE_MODE,
},
}, },
}; };
} }

View File

@@ -1,6 +1,7 @@
import { configService, Log } from './env.config';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import { configService, Log } from './env.config';
const formatDateLog = (timestamp: number) => const formatDateLog = (timestamp: number) =>
dayjs(timestamp) dayjs(timestamp)
.toDate() .toDate()

View File

@@ -1,4 +1,5 @@
import mongoose from 'mongoose'; import mongoose from 'mongoose';
import { configService, Database } from '../config/env.config'; import { configService, Database } from '../config/env.config';
import { Logger } from '../config/logger.config'; import { Logger } from '../config/logger.config';

View File

@@ -1,7 +1,8 @@
import { createClient, RedisClientType } from '@redis/client'; import { createClient, RedisClientType } from '@redis/client';
import { Logger } from '../config/logger.config';
import { BufferJSON } from '@whiskeysockets/baileys'; import { BufferJSON } from '@whiskeysockets/baileys';
import { Redis } from '../config/env.config'; import { Redis } from '../config/env.config';
import { Logger } from '../config/logger.config';
export class RedisCache { export class RedisCache {
constructor() { constructor() {
@@ -59,11 +60,7 @@ export class RedisCache {
this.logger.verbose('writeData: ' + field); this.logger.verbose('writeData: ' + field);
const json = JSON.stringify(data, BufferJSON.replacer); const json = JSON.stringify(data, BufferJSON.replacer);
return await this.client.hSet( return await this.client.hSet(this.redisEnv.PREFIX_KEY + ':' + this.instanceName, field, json);
this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
field,
json,
);
} catch (error) { } catch (error) {
this.logger.error(error); this.logger.error(error);
} }
@@ -72,10 +69,7 @@ export class RedisCache {
public async readData(field: string) { public async readData(field: string) {
try { try {
this.logger.verbose('readData: ' + field); this.logger.verbose('readData: ' + field);
const data = await this.client.hGet( const data = await this.client.hGet(this.redisEnv.PREFIX_KEY + ':' + this.instanceName, field);
this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
field,
);
if (data) { if (data) {
this.logger.verbose('readData: ' + field + ' success'); this.logger.verbose('readData: ' + field + ' success');
@@ -92,10 +86,7 @@ export class RedisCache {
public async removeData(field: string) { public async removeData(field: string) {
try { try {
this.logger.verbose('removeData: ' + field); this.logger.verbose('removeData: ' + field);
return await this.client.hDel( return await this.client.hDel(this.redisEnv.PREFIX_KEY + ':' + this.instanceName, field);
this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
field,
);
} catch (error) { } catch (error) {
this.logger.error(error); this.logger.error(error);
} }
@@ -104,9 +95,7 @@ export class RedisCache {
public async delAll(hash?: string) { public async delAll(hash?: string) {
try { try {
this.logger.verbose('instance delAll: ' + hash); this.logger.verbose('instance delAll: ' + hash);
const result = await this.client.del( const result = await this.client.del(hash || this.redisEnv.PREFIX_KEY + ':' + this.instanceName);
hash || this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
);
return result; return result;
} catch (error) { } catch (error) {

View File

@@ -8,10 +8,11 @@
SERVER: SERVER:
TYPE: http # https TYPE: http # https
PORT: 8080 # 443 PORT: 8080 # 443
URL: localhost
CORS: CORS:
ORIGIN: ORIGIN:
- '*' - "*"
# - yourdomain.com # - yourdomain.com
METHODS: METHODS:
- POST - POST
@@ -38,7 +39,7 @@ LOG:
- DARK - DARK
- WEBHOOKS - WEBHOOKS
COLOR: true COLOR: true
BAILEYS: error # "fatal" | "error" | "warn" | "info" | "debug" | "trace" BAILEYS: error # fatal | error | warn | info | debug | trace
# Determine how long the instance should be deleted from memory in case of no connection. # Determine how long the instance should be deleted from memory in case of no connection.
# Default time: 5 minutes # Default time: 5 minutes
@@ -63,12 +64,11 @@ CLEAN_STORE:
DATABASE: DATABASE:
ENABLED: false ENABLED: false
CONNECTION: CONNECTION:
URI: 'mongodb://root:root@localhost:27017/?authSource=admin&readPreference=primary&ssl=false&directConnection=true' URI: "mongodb://root:root@localhost:27017/?authSource=admin&readPreference=primary&ssl=false&directConnection=true"
DB_PREFIX_NAME: evolution DB_PREFIX_NAME: evolution
# Choose the data you want to save in the application's database or store # Choose the data you want to save in the application's database or store
SAVE_DATA: SAVE_DATA:
INSTANCE: false INSTANCE: false
OLD_MESSAGE: false
NEW_MESSAGE: false NEW_MESSAGE: false
MESSAGE_UPDATE: false MESSAGE_UPDATE: false
CONTACTS: false CONTACTS: false
@@ -76,10 +76,11 @@ DATABASE:
REDIS: REDIS:
ENABLED: false ENABLED: false
URI: 'redis://localhost:6379' URI: "redis://localhost:6379"
PREFIX_KEY: 'evolution' PREFIX_KEY: "evolution"
# Webhook Settings # Global Webhook Settings
# Each instance's Webhook URL and events will be requested at the time it is created
WEBHOOK: WEBHOOK:
# Define a global webhook that will listen for enabled events from all instances # Define a global webhook that will listen for enabled events from all instances
GLOBAL: GLOBAL:
@@ -88,13 +89,15 @@ WEBHOOK:
# With this option activated, you work with a url per webhook event, respecting the global url and the name of each event # With this option activated, you work with a url per webhook event, respecting the global url and the name of each event
WEBHOOK_BY_EVENTS: false WEBHOOK_BY_EVENTS: false
# Automatically maps webhook paths # Automatically maps webhook paths
# Set the events you want to hear # Set the events you want to hear
EVENTS: EVENTS:
APPLICATION_STARTUP: false APPLICATION_STARTUP: false
QRCODE_UPDATED: true QRCODE_UPDATED: true
MESSAGES_SET: true MESSAGES_SET: true
MESSAGES_UPSERT: true MESSAGES_UPSERT: true
MESSAGES_UPDATE: true MESSAGES_UPDATE: true
MESSAGES_DELETE: true
SEND_MESSAGE: true
CONTACTS_SET: true CONTACTS_SET: true
CONTACTS_UPSERT: true CONTACTS_UPSERT: true
CONTACTS_UPDATE: true CONTACTS_UPDATE: true
@@ -107,12 +110,13 @@ WEBHOOK:
GROUP_UPDATE: true GROUP_UPDATE: true
GROUP_PARTICIPANTS_UPDATE: true GROUP_PARTICIPANTS_UPDATE: true
CONNECTION_UPDATE: true CONNECTION_UPDATE: true
CALL: true
# This event fires every time a new token is requested via the refresh route # This event fires every time a new token is requested via the refresh route
NEW_JWT_TOKEN: false NEW_JWT_TOKEN: false
CONFIG_SESSION_PHONE: CONFIG_SESSION_PHONE:
# Name that will be displayed on smartphone connection # Name that will be displayed on smartphone connection
CLIENT: 'Evolution API' CLIENT: "Evolution API"
NAME: chrome # chrome | firefox | edge | opera | safari NAME: chrome # chrome | firefox | edge | opera | safari
# Set qrcode display limit # Set qrcode display limit
@@ -120,6 +124,8 @@ QRCODE:
LIMIT: 30 LIMIT: 30
# Defines an authentication type for the api # Defines an authentication type for the api
# We recommend using the apikey because it will allow you to use a custom token,
# if you use jwt, a random token will be generated and may be expired and you will have to generate a new token
AUTHENTICATION: AUTHENTICATION:
TYPE: apikey # jwt or apikey TYPE: apikey # jwt or apikey
# Define a global apikey to access all instances # Define a global apikey to access all instances
@@ -131,11 +137,4 @@ AUTHENTICATION:
# Set the secret key to encrypt and decrypt your token and its expiration time. # Set the secret key to encrypt and decrypt your token and its expiration time.
JWT: JWT:
EXPIRIN_IN: 0 # seconds - 3600s === 1h | zero (0) - never expires EXPIRIN_IN: 0 # seconds - 3600s === 1h | zero (0) - never expires
SECRET: L=0YWt]b2w[WF>#>:&E` SECRET: L=0YWt]b2w[WF>#>:&E`
# Set the instance name and webhook url to create an instance in init the application
INSTANCE:
# With this option activated, you work with a url per webhook event, respecting the local url and the name of each event
MODE: server # container or server
# if you are using container mode, set the container name and the webhook url to default instance
NAME: evolution
WEBHOOK_URL: <url>

View File

@@ -1,79 +1,90 @@
import 'express-async-errors';
import compression from 'compression'; import compression from 'compression';
import { configService, Cors, HttpServer } from './config/env.config';
import cors from 'cors'; import cors from 'cors';
import express, { json, NextFunction, Request, Response, urlencoded } from 'express'; import express, { json, NextFunction, Request, Response, urlencoded } from 'express';
import { join } from 'path'; import { join } from 'path';
import { configService, Cors, HttpServer } from './config/env.config';
import { onUnexpectedError } from './config/error.config'; import { onUnexpectedError } from './config/error.config';
import { Logger } from './config/logger.config'; import { Logger } from './config/logger.config';
import { ROOT_DIR } from './config/path.config'; import { ROOT_DIR } from './config/path.config';
import { waMonitor } from './whatsapp/whatsapp.module';
import { HttpStatus, router } from './whatsapp/routers/index.router';
import 'express-async-errors';
import { ServerUP } from './utils/server-up'; import { ServerUP } from './utils/server-up';
import { HttpStatus, router } from './whatsapp/routers/index.router';
import { waMonitor } from './whatsapp/whatsapp.module';
function initWA() { function initWA() {
waMonitor.loadInstance(); waMonitor.loadInstance();
} }
function bootstrap() { function bootstrap() {
const logger = new Logger('SERVER'); const logger = new Logger('SERVER');
const app = express(); const app = express();
app.use( app.use(
cors({ cors({
origin(requestOrigin, callback) { origin(requestOrigin, callback) {
const { ORIGIN } = configService.get<Cors>('CORS'); const { ORIGIN } = configService.get<Cors>('CORS');
!requestOrigin ? (requestOrigin = '*') : undefined; !requestOrigin ? (requestOrigin = '*') : undefined;
if (ORIGIN.indexOf(requestOrigin) !== -1) { if (ORIGIN.indexOf(requestOrigin) !== -1) {
return callback(null, true); return callback(null, true);
} }
return callback(new Error('Not allowed by CORS')); return callback(new Error('Not allowed by CORS'));
}, },
methods: [...configService.get<Cors>('CORS').METHODS], methods: [...configService.get<Cors>('CORS').METHODS],
credentials: configService.get<Cors>('CORS').CREDENTIALS, credentials: configService.get<Cors>('CORS').CREDENTIALS,
}), }),
urlencoded({ extended: true, limit: '136mb' }), urlencoded({ extended: true, limit: '136mb' }),
json({ limit: '136mb' }), json({ limit: '136mb' }),
compression(), compression(),
); );
app.set('view engine', 'hbs'); app.set('view engine', 'hbs');
app.set('views', join(ROOT_DIR, 'views')); app.set('views', join(ROOT_DIR, 'views'));
app.use(express.static(join(ROOT_DIR, 'public'))); app.use(express.static(join(ROOT_DIR, 'public')));
app.use('/', router); app.use('/', router);
app.use( app.use(
(err: Error, req: Request, res: Response, next: NextFunction) => { (err: Error, req: Request, res: Response, next: NextFunction) => {
if (err) { if (err) {
return res.status(err['status'] || 500).json(err); return res.status(err['status'] || 500).json({
} status: 'ERROR',
}, error: err['error'] || 'Internal Server Error',
(req: Request, res: Response, next: NextFunction) => { response: {
const { method, url } = req; message: err['message'] || 'Internal Server Error',
},
}
);
}
res.status(HttpStatus.NOT_FOUND).json({ next();
status: HttpStatus.NOT_FOUND, },
message: `Cannot ${method.toUpperCase()} ${url}`, (req: Request, res: Response, next: NextFunction) => {
error: 'Not Found', const { method, url } = req;
});
next(); res.status(HttpStatus.NOT_FOUND).json({
}, status: HttpStatus.NOT_FOUND,
); error: 'Not Found',
response: {
message: `Cannot ${method.toUpperCase()} ${url}`,
},
});
const httpServer = configService.get<HttpServer>('SERVER'); next();
},
);
ServerUP.app = app; const httpServer = configService.get<HttpServer>('SERVER');
const server = ServerUP[httpServer.TYPE];
server.listen(httpServer.PORT, () => ServerUP.app = app;
logger.log(httpServer.TYPE.toUpperCase() + ' - ON: ' + httpServer.PORT), const server = ServerUP[httpServer.TYPE];
);
initWA(); server.listen(httpServer.PORT, () => logger.log(httpServer.TYPE.toUpperCase() + ' - ON: ' + httpServer.PORT));
onUnexpectedError(); initWA();
onUnexpectedError();
} }
bootstrap(); bootstrap();

View File

@@ -1,8 +1,9 @@
import { Express } from 'express'; import { Express } from 'express';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { configService, SslConf } from '../config/env.config';
import * as https from 'https';
import * as http from 'http'; import * as http from 'http';
import * as https from 'https';
import { configService, SslConf } from '../config/env.config';
export class ServerUP { export class ServerUP {
static #app: Express; static #app: Express;

View File

@@ -6,6 +6,7 @@ import {
proto, proto,
SignalDataTypeMap, SignalDataTypeMap,
} from '@whiskeysockets/baileys'; } from '@whiskeysockets/baileys';
import { configService, Database } from '../config/env.config'; import { configService, Database } from '../config/env.config';
import { Logger } from '../config/logger.config'; import { Logger } from '../config/logger.config';
import { dbserver } from '../db/db.connect'; import { dbserver } from '../db/db.connect';
@@ -24,12 +25,12 @@ export async function useMultiFileAuthStateDb(
const writeData = async (data: any, key: string): Promise<any> => { const writeData = async (data: any, key: string): Promise<any> => {
try { try {
await client.connect(); await client.connect();
return await collection.replaceOne( return await collection.replaceOne({ _id: key }, JSON.parse(JSON.stringify(data, BufferJSON.replacer)), {
{ _id: key }, upsert: true,
JSON.parse(JSON.stringify(data, BufferJSON.replacer)), });
{ upsert: true }, } catch (error) {
); logger.error(error);
} catch {} }
}; };
const readData = async (key: string): Promise<any> => { const readData = async (key: string): Promise<any> => {
@@ -38,14 +39,18 @@ export async function useMultiFileAuthStateDb(
const data = await collection.findOne({ _id: key }); const data = await collection.findOne({ _id: key });
const creds = JSON.stringify(data); const creds = JSON.stringify(data);
return JSON.parse(creds, BufferJSON.reviver); return JSON.parse(creds, BufferJSON.reviver);
} catch {} } catch (error) {
logger.error(error);
}
}; };
const removeData = async (key: string) => { const removeData = async (key: string) => {
try { try {
await client.connect(); await client.connect();
return await collection.deleteOne({ _id: key }); return await collection.deleteOne({ _id: key });
} catch {} } catch (error) {
logger.error(error);
}
}; };
const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds(); const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds();

View File

@@ -5,9 +5,9 @@ import {
proto, proto,
SignalDataTypeMap, SignalDataTypeMap,
} from '@whiskeysockets/baileys'; } from '@whiskeysockets/baileys';
import { RedisCache } from '../db/redis.client';
import { Logger } from '../config/logger.config'; import { Logger } from '../config/logger.config';
import { Redis } from '../config/env.config'; import { RedisCache } from '../db/redis.client';
export async function useMultiFileAuthStateRedisDb(cache: RedisCache): Promise<{ export async function useMultiFileAuthStateRedisDb(cache: RedisCache): Promise<{
state: AuthenticationState; state: AuthenticationState;

View File

@@ -39,6 +39,8 @@ export const instanceNameSchema: JSONSchema7 = {
'MESSAGES_SET', 'MESSAGES_SET',
'MESSAGES_UPSERT', 'MESSAGES_UPSERT',
'MESSAGES_UPDATE', 'MESSAGES_UPDATE',
'MESSAGES_DELETE',
'SEND_MESSAGE',
'CONTACTS_SET', 'CONTACTS_SET',
'CONTACTS_UPSERT', 'CONTACTS_UPSERT',
'CONTACTS_UPDATE', 'CONTACTS_UPDATE',
@@ -51,11 +53,13 @@ export const instanceNameSchema: JSONSchema7 = {
'GROUP_UPDATE', 'GROUP_UPDATE',
'GROUP_PARTICIPANTS_UPDATE', 'GROUP_PARTICIPANTS_UPDATE',
'CONNECTION_UPDATE', 'CONNECTION_UPDATE',
'CALL',
'NEW_JWT_TOKEN', 'NEW_JWT_TOKEN',
], ],
}, },
}, },
qrcode: { type: 'boolean', enum: [true, false] }, qrcode: { type: 'boolean', enum: [true, false] },
number: { type: 'string', pattern: '^\\d+[\\.@\\w-]+' },
token: { type: 'string' }, token: { type: 'string' },
}, },
...isNotEmpty('instanceName'), ...isNotEmpty('instanceName'),
@@ -80,8 +84,8 @@ const quotedOptionsSchema: JSONSchema7 = {
remoteJid: { type: 'string' }, remoteJid: { type: 'string' },
fromMe: { type: 'boolean', enum: [true, false] }, fromMe: { type: 'boolean', enum: [true, false] },
}, },
required: ['id', 'remoteJid', 'fromMe'], required: ['id'],
...isNotEmpty('id', 'remoteJid'), ...isNotEmpty('id'),
}, },
message: { type: 'object' }, message: { type: 'object' },
}, },
@@ -121,7 +125,6 @@ const optionsSchema: JSONSchema7 = {
const numberDefinition: JSONSchema7Definition = { const numberDefinition: JSONSchema7Definition = {
type: 'string', type: 'string',
pattern: '^\\d+[\\.@\\w-]+',
description: 'Invalid format', description: 'Invalid format',
}; };
@@ -143,24 +146,6 @@ export const textMessageSchema: JSONSchema7 = {
required: ['textMessage', 'number'], required: ['textMessage', 'number'],
}; };
export const linkPreviewSchema: JSONSchema7 = {
$id: v4(),
type: 'object',
properties: {
number: { ...numberDefinition },
options: { ...optionsSchema },
linkPreview: {
type: 'object',
properties: {
text: { type: 'string' },
},
required: ['text'],
...isNotEmpty('text'),
},
},
required: ['linkPreview', 'number'],
};
export const pollMessageSchema: JSONSchema7 = { export const pollMessageSchema: JSONSchema7 = {
$id: v4(), $id: v4(),
type: 'object', type: 'object',
@@ -414,7 +399,7 @@ export const contactMessageSchema: JSONSchema7 = {
email: { type: 'string' }, email: { type: 'string' },
url: { type: 'string' }, url: { type: 'string' },
}, },
required: ['fullName', 'wuid', 'phoneNumber'], required: ['fullName', 'phoneNumber'],
...isNotEmpty('fullName'), ...isNotEmpty('fullName'),
}, },
minItems: 1, minItems: 1,
@@ -461,7 +446,6 @@ export const whatsappNumberSchema: JSONSchema7 = {
uniqueItems: true, uniqueItems: true,
items: { items: {
type: 'string', type: 'string',
pattern: '^\\d+',
description: '"numbers" must be an array of numeric strings', description: '"numbers" must be an array of numeric strings',
}, },
}, },
@@ -472,7 +456,7 @@ export const readMessageSchema: JSONSchema7 = {
$id: v4(), $id: v4(),
type: 'object', type: 'object',
properties: { properties: {
readMessages: { read_messages: {
type: 'array', type: 'array',
minItems: 1, minItems: 1,
uniqueItems: true, uniqueItems: true,
@@ -487,7 +471,7 @@ export const readMessageSchema: JSONSchema7 = {
}, },
}, },
}, },
required: ['readMessages'], required: ['read_messages'],
}; };
export const privacySettingsSchema: JSONSchema7 = { export const privacySettingsSchema: JSONSchema7 = {
@@ -603,6 +587,17 @@ export const profilePictureSchema: JSONSchema7 = {
}, },
}; };
export const profileSchema: JSONSchema7 = {
type: 'object',
properties: {
wuid: { type: 'string' },
name: { type: 'string' },
picture: { type: 'string' },
status: { type: 'string' },
isBusiness: { type: 'boolean' },
},
};
export const messageValidateSchema: JSONSchema7 = { export const messageValidateSchema: JSONSchema7 = {
$id: v4(), $id: v4(),
type: 'object', type: 'object',
@@ -673,6 +668,7 @@ export const createGroupSchema: JSONSchema7 = {
subject: { type: 'string' }, subject: { type: 'string' },
description: { type: 'string' }, description: { type: 'string' },
profilePicture: { type: 'string' }, profilePicture: { type: 'string' },
promoteParticipants: { type: 'boolean', enum: [true, false] },
participants: { participants: {
type: 'array', type: 'array',
minItems: 1, minItems: 1,
@@ -699,6 +695,16 @@ export const groupJidSchema: JSONSchema7 = {
...isNotEmpty('groupJid'), ...isNotEmpty('groupJid'),
}; };
export const getParticipantsSchema: JSONSchema7 = {
$id: v4(),
type: 'object',
properties: {
getParticipants: { type: 'string', enum: ['true', 'false'] },
},
required: ['getParticipants'],
...isNotEmpty('getParticipants'),
};
export const groupSendInviteSchema: JSONSchema7 = { export const groupSendInviteSchema: JSONSchema7 = {
$id: v4(), $id: v4(),
type: 'object', type: 'object',
@@ -835,6 +841,8 @@ export const webhookSchema: JSONSchema7 = {
'MESSAGES_SET', 'MESSAGES_SET',
'MESSAGES_UPSERT', 'MESSAGES_UPSERT',
'MESSAGES_UPDATE', 'MESSAGES_UPDATE',
'MESSAGES_DELETE',
'SEND_MESSAGE',
'CONTACTS_SET', 'CONTACTS_SET',
'CONTACTS_UPSERT', 'CONTACTS_UPSERT',
'CONTACTS_UPDATE', 'CONTACTS_UPDATE',
@@ -847,6 +855,7 @@ export const webhookSchema: JSONSchema7 = {
'GROUP_UPDATE', 'GROUP_UPDATE',
'GROUP_PARTICIPANTS_UPDATE', 'GROUP_PARTICIPANTS_UPDATE',
'CONNECTION_UPDATE', 'CONNECTION_UPDATE',
'CALL',
'NEW_JWT_TOKEN', 'NEW_JWT_TOKEN',
], ],
}, },
@@ -855,3 +864,34 @@ export const webhookSchema: JSONSchema7 = {
required: ['url', 'enabled'], required: ['url', 'enabled'],
...isNotEmpty('url'), ...isNotEmpty('url'),
}; };
export const chatwootSchema: JSONSchema7 = {
$id: v4(),
type: 'object',
properties: {
enabled: { type: 'boolean', enum: [true, false] },
account_id: { type: 'string' },
token: { type: 'string' },
url: { type: 'string' },
sign_msg: { type: 'boolean', enum: [true, false] },
reopen_conversation: { type: 'boolean', enum: [true, false] },
conversation_pending: { type: 'boolean', enum: [true, false] },
},
required: ['enabled', 'account_id', 'token', 'url', 'sign_msg', 'reopen_conversation', 'conversation_pending'],
...isNotEmpty('account_id', 'token', 'url', 'sign_msg', 'reopen_conversation', 'conversation_pending'),
};
export const settingsSchema: JSONSchema7 = {
$id: v4(),
type: 'object',
properties: {
reject_call: { type: 'boolean', enum: [true, false] },
msg_call: { type: 'string' },
groups_ignore: { type: 'boolean', enum: [true, false] },
always_online: { type: 'boolean', enum: [true, false] },
read_messages: { type: 'boolean', enum: [true, false] },
read_status: { type: 'boolean', enum: [true, false] },
},
required: ['reject_call', 'groups_ignore', 'always_online', 'read_messages', 'read_status'],
...isNotEmpty('reject_call', 'groups_ignore', 'always_online', 'read_messages', 'read_status'),
};

View File

@@ -1,5 +1,6 @@
import { existsSync, mkdirSync, writeFileSync } from 'fs'; import { existsSync, mkdirSync, writeFileSync } from 'fs';
import { join } from 'path'; import { join } from 'path';
import { ConfigService, Database } from '../../config/env.config'; import { ConfigService, Database } from '../../config/env.config';
import { ROOT_DIR } from '../../config/path.config'; import { ROOT_DIR } from '../../config/path.config';
@@ -34,11 +35,9 @@ export abstract class Repository implements IRepository {
mkdirSync(create.path, { recursive: true }); mkdirSync(create.path, { recursive: true });
} }
try { try {
writeFileSync( writeFileSync(join(create.path, create.fileName + '.json'), JSON.stringify({ ...create.data }), {
join(create.path, create.fileName + '.json'), encoding: 'utf-8',
JSON.stringify({ ...create.data }), });
{ encoding: 'utf-8' },
);
return { message: 'create - success' }; return { message: 'create - success' };
} finally { } finally {
@@ -46,19 +45,23 @@ export abstract class Repository implements IRepository {
} }
}; };
public insert(data: any, instanceName: string, saveDb = false): Promise<IInsert> { // eslint-disable-next-line
public insert(data: any, instanceName: string, saveDb = false): Promise<IInsert> {
throw new Error('Method not implemented.'); throw new Error('Method not implemented.');
} }
public update(data: any, instanceName: string, saveDb = false): Promise<IInsert> { // eslint-disable-next-line
public update(data: any, instanceName: string, saveDb = false): Promise<IInsert> {
throw new Error('Method not implemented.'); throw new Error('Method not implemented.');
} }
public find(query: any): Promise<any> { // eslint-disable-next-line
public find(query: any): Promise<any> {
throw new Error('Method not implemented.'); throw new Error('Method not implemented.');
} }
delete(query: any, force?: boolean): Promise<any> { // eslint-disable-next-line
delete(query: any, force?: boolean): Promise<any> {
throw new Error('Method not implemented.'); throw new Error('Method not implemented.');
} }
} }

View File

@@ -1,11 +1,13 @@
import { InstanceDto } from '../dto/instance.dto';
import { JSONSchema7 } from 'json-schema';
import { Request } from 'express';
import { validate } from 'jsonschema';
import { BadRequestException } from '../../exceptions';
import 'express-async-errors'; import 'express-async-errors';
import { Request } from 'express';
import { JSONSchema7 } from 'json-schema';
import { validate } from 'jsonschema';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { GroupInvite, GroupJid } from '../dto/group.dto'; import { BadRequestException } from '../../exceptions';
import { GetParticipant, GroupInvite } from '../dto/group.dto';
import { InstanceDto } from '../dto/instance.dto';
type DataValidate<T> = { type DataValidate<T> = {
request: Request; request: Request;
@@ -99,21 +101,29 @@ export abstract class RouterBroker {
public async groupValidate<T>(args: DataValidate<T>) { public async groupValidate<T>(args: DataValidate<T>) {
const { request, ClassRef, schema, execute } = args; const { request, ClassRef, schema, execute } = args;
const groupJid = request.query as unknown as GroupJid;
if (!groupJid?.groupJid) {
throw new BadRequestException(
'The group id needs to be informed in the query',
'ex: "groupJid=120362@g.us"',
);
}
const instance = request.params as unknown as InstanceDto; const instance = request.params as unknown as InstanceDto;
const body = request.body; const body = request.body;
let groupJid = body?.groupJid;
if (!groupJid) {
if (request.query?.groupJid) {
groupJid = request.query.groupJid;
} else {
throw new BadRequestException('The group id needs to be informed in the query', 'ex: "groupJid=120362@g.us"');
}
}
if (!groupJid.endsWith('@g.us')) {
groupJid = groupJid + '@g.us';
}
Object.assign(body, {
groupJid: groupJid,
});
const ref = new ClassRef(); const ref = new ClassRef();
Object.assign(body, groupJid);
Object.assign(ref, body); Object.assign(ref, body);
const v = validate(ref, schema); const v = validate(ref, schema);
@@ -160,7 +170,44 @@ export abstract class RouterBroker {
const v = validate(ref, schema); const v = validate(ref, schema);
console.log(v, '@checkei aqui'); if (!v.valid) {
const message: any[] = v.errors.map(({ property, stack, schema }) => {
let message: string;
if (schema['description']) {
message = schema['description'];
} else {
message = stack.replace('instance.', '');
}
return {
property: property.replace('instance.', ''),
message,
};
});
logger.error([...message]);
throw new BadRequestException(...message);
}
return await execute(instance, ref);
}
public async getParticipantsValidate<T>(args: DataValidate<T>) {
const { request, ClassRef, schema, execute } = args;
const getParticipants = request.query as unknown as GetParticipant;
if (!getParticipants?.getParticipants) {
throw new BadRequestException('The getParticipants needs to be informed in the query');
}
const instance = request.params as unknown as InstanceDto;
const body = request.body;
const ref = new ClassRef();
Object.assign(body, getParticipants);
Object.assign(ref, body);
const v = validate(ref, schema);
if (!v.valid) { if (!v.valid) {
const message: any[] = v.errors.map(({ property, stack, schema }) => { const message: any[] = v.errors.map(({ property, stack, schema }) => {

View File

@@ -1,7 +1,8 @@
import { proto } from '@whiskeysockets/baileys'; import { Logger } from '../../config/logger.config';
import { import {
ArchiveChatDto, ArchiveChatDto,
DeleteMessage, DeleteMessage,
getBase64FromMediaMessageDto,
NumberDto, NumberDto,
PrivacySettingDto, PrivacySettingDto,
ProfileNameDto, ProfileNameDto,
@@ -9,14 +10,12 @@ import {
ProfileStatusDto, ProfileStatusDto,
ReadMessageDto, ReadMessageDto,
WhatsAppNumberDto, WhatsAppNumberDto,
getBase64FromMediaMessageDto,
} from '../dto/chat.dto'; } from '../dto/chat.dto';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { ContactQuery } from '../repository/contact.repository'; import { ContactQuery } from '../repository/contact.repository';
import { MessageQuery } from '../repository/message.repository'; import { MessageQuery } from '../repository/message.repository';
import { MessageUpQuery } from '../repository/messageUp.repository'; import { MessageUpQuery } from '../repository/messageUp.repository';
import { WAMonitoringService } from '../services/monitor.service'; import { WAMonitoringService } from '../services/monitor.service';
import { Logger } from '../../config/logger.config';
const logger = new Logger('ChatController'); const logger = new Logger('ChatController');
@@ -48,18 +47,18 @@ export class ChatController {
return await this.waMonitor.waInstances[instanceName].profilePicture(data.number); return await this.waMonitor.waInstances[instanceName].profilePicture(data.number);
} }
public async fetchProfile({ instanceName }: InstanceDto, data: NumberDto) {
logger.verbose('requested fetchProfile from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].fetchProfile(instanceName, data.number);
}
public async fetchContacts({ instanceName }: InstanceDto, query: ContactQuery) { public async fetchContacts({ instanceName }: InstanceDto, query: ContactQuery) {
logger.verbose('requested fetchContacts from ' + instanceName + ' instance'); logger.verbose('requested fetchContacts from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].fetchContacts(query); return await this.waMonitor.waInstances[instanceName].fetchContacts(query);
} }
public async getBase64FromMediaMessage( public async getBase64FromMediaMessage({ instanceName }: InstanceDto, data: getBase64FromMediaMessageDto) {
{ instanceName }: InstanceDto, logger.verbose('requested getBase64FromMediaMessage from ' + instanceName + ' instance');
data: getBase64FromMediaMessageDto,
) {
logger.verbose(
'requested getBase64FromMediaMessage from ' + instanceName + ' instance',
);
return await this.waMonitor.waInstances[instanceName].getBase64FromMediaMessage(data); return await this.waMonitor.waInstances[instanceName].getBase64FromMediaMessage(data);
} }
@@ -83,22 +82,14 @@ export class ChatController {
return await this.waMonitor.waInstances[instanceName].fetchPrivacySettings(); return await this.waMonitor.waInstances[instanceName].fetchPrivacySettings();
} }
public async updatePrivacySettings( public async updatePrivacySettings({ instanceName }: InstanceDto, data: PrivacySettingDto) {
{ instanceName }: InstanceDto,
data: PrivacySettingDto,
) {
logger.verbose('requested updatePrivacySettings from ' + instanceName + ' instance'); logger.verbose('requested updatePrivacySettings from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].updatePrivacySettings(data); return await this.waMonitor.waInstances[instanceName].updatePrivacySettings(data);
} }
public async fetchBusinessProfile( public async fetchBusinessProfile({ instanceName }: InstanceDto, data: ProfilePictureDto) {
{ instanceName }: InstanceDto,
data: ProfilePictureDto,
) {
logger.verbose('requested fetchBusinessProfile from ' + instanceName + ' instance'); logger.verbose('requested fetchBusinessProfile from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].fetchBusinessProfile( return await this.waMonitor.waInstances[instanceName].fetchBusinessProfile(data.number);
data.number,
);
} }
public async updateProfileName({ instanceName }: InstanceDto, data: ProfileNameDto) { public async updateProfileName({ instanceName }: InstanceDto, data: ProfileNameDto) {
@@ -106,30 +97,17 @@ export class ChatController {
return await this.waMonitor.waInstances[instanceName].updateProfileName(data.name); return await this.waMonitor.waInstances[instanceName].updateProfileName(data.name);
} }
public async updateProfileStatus( public async updateProfileStatus({ instanceName }: InstanceDto, data: ProfileStatusDto) {
{ instanceName }: InstanceDto,
data: ProfileStatusDto,
) {
logger.verbose('requested updateProfileStatus from ' + instanceName + ' instance'); logger.verbose('requested updateProfileStatus from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].updateProfileStatus( return await this.waMonitor.waInstances[instanceName].updateProfileStatus(data.status);
data.status,
);
} }
public async updateProfilePicture( public async updateProfilePicture({ instanceName }: InstanceDto, data: ProfilePictureDto) {
{ instanceName }: InstanceDto,
data: ProfilePictureDto,
) {
logger.verbose('requested updateProfilePicture from ' + instanceName + ' instance'); logger.verbose('requested updateProfilePicture from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].updateProfilePicture( return await this.waMonitor.waInstances[instanceName].updateProfilePicture(data.picture);
data.picture,
);
} }
public async removeProfilePicture( public async removeProfilePicture({ instanceName }: InstanceDto) {
{ instanceName }: InstanceDto,
data: ProfilePictureDto,
) {
logger.verbose('requested removeProfilePicture from ' + instanceName + ' instance'); logger.verbose('requested removeProfilePicture from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].removeProfilePicture(); return await this.waMonitor.waInstances[instanceName].removeProfilePicture();
} }

View File

@@ -0,0 +1,99 @@
import { isURL } from 'class-validator';
import { ConfigService, HttpServer } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { BadRequestException } from '../../exceptions';
import { ChatwootDto } from '../dto/chatwoot.dto';
import { InstanceDto } from '../dto/instance.dto';
import { ChatwootService } from '../services/chatwoot.service';
import { waMonitor } from '../whatsapp.module';
const logger = new Logger('ChatwootController');
export class ChatwootController {
constructor(private readonly chatwootService: ChatwootService, private readonly configService: ConfigService) {}
public async createChatwoot(instance: InstanceDto, data: ChatwootDto) {
logger.verbose('requested createChatwoot from ' + instance.instanceName + ' instance');
if (data.enabled) {
if (!isURL(data.url, { require_tld: false })) {
throw new BadRequestException('url is not valid');
}
if (!data.account_id) {
throw new BadRequestException('account_id is required');
}
if (!data.token) {
throw new BadRequestException('token is required');
}
if (data.sign_msg !== true && data.sign_msg !== false) {
throw new BadRequestException('sign_msg is required');
}
}
if (!data.enabled) {
logger.verbose('chatwoot disabled');
data.account_id = '';
data.token = '';
data.url = '';
data.sign_msg = false;
data.reopen_conversation = false;
data.conversation_pending = false;
}
data.name_inbox = instance.instanceName;
const result = this.chatwootService.create(instance, data);
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
const response = {
...result,
webhook_url: `${urlServer}/chatwoot/webhook/${instance.instanceName}`,
};
return response;
}
public async findChatwoot(instance: InstanceDto) {
logger.verbose('requested findChatwoot from ' + instance.instanceName + ' instance');
const result = await this.chatwootService.find(instance);
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
if (Object.keys(result).length === 0) {
return {
enabled: false,
url: '',
account_id: '',
token: '',
sign_msg: false,
name_inbox: '',
webhook_url: '',
};
}
const response = {
...result,
webhook_url: `${urlServer}/chatwoot/webhook/${instance.instanceName}`,
};
return response;
}
public async receiveWebhook(instance: InstanceDto, data: any) {
logger.verbose('requested receiveWebhook from ' + instance.instanceName + ' instance');
const chatwootService = new ChatwootService(waMonitor, this.configService);
return chatwootService.receiveWebhook(instance, data);
}
public async newInstance(data: any) {
const chatwootService = new ChatwootService(waMonitor, this.configService);
return chatwootService.newInstance(data);
}
}

View File

@@ -1,5 +1,7 @@
import { Logger } from '../../config/logger.config';
import { import {
CreateGroupDto, CreateGroupDto,
GetParticipant,
GroupDescriptionDto, GroupDescriptionDto,
GroupInvite, GroupInvite,
GroupJid, GroupJid,
@@ -12,7 +14,6 @@ import {
} from '../dto/group.dto'; } from '../dto/group.dto';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { WAMonitoringService } from '../services/monitor.service'; import { WAMonitoringService } from '../services/monitor.service';
import { Logger } from '../../config/logger.config';
const logger = new Logger('ChatController'); const logger = new Logger('ChatController');
@@ -25,33 +26,18 @@ export class GroupController {
} }
public async updateGroupPicture(instance: InstanceDto, update: GroupPictureDto) { public async updateGroupPicture(instance: InstanceDto, update: GroupPictureDto) {
logger.verbose( logger.verbose('requested updateGroupPicture from ' + instance.instanceName + ' instance');
'requested updateGroupPicture from ' + instance.instanceName + ' instance', return await this.waMonitor.waInstances[instance.instanceName].updateGroupPicture(update);
);
return await this.waMonitor.waInstances[instance.instanceName].updateGroupPicture(
update,
);
} }
public async updateGroupSubject(instance: InstanceDto, update: GroupSubjectDto) { public async updateGroupSubject(instance: InstanceDto, update: GroupSubjectDto) {
logger.verbose( logger.verbose('requested updateGroupSubject from ' + instance.instanceName + ' instance');
'requested updateGroupSubject from ' + instance.instanceName + ' instance', return await this.waMonitor.waInstances[instance.instanceName].updateGroupSubject(update);
);
return await this.waMonitor.waInstances[instance.instanceName].updateGroupSubject(
update,
);
} }
public async updateGroupDescription( public async updateGroupDescription(instance: InstanceDto, update: GroupDescriptionDto) {
instance: InstanceDto, logger.verbose('requested updateGroupDescription from ' + instance.instanceName + ' instance');
update: GroupDescriptionDto, return await this.waMonitor.waInstances[instance.instanceName].updateGroupDescription(update);
) {
logger.verbose(
'requested updateGroupDescription from ' + instance.instanceName + ' instance',
);
return await this.waMonitor.waInstances[instance.instanceName].updateGroupDescription(
update,
);
} }
public async findGroupInfo(instance: InstanceDto, groupJid: GroupJid) { public async findGroupInfo(instance: InstanceDto, groupJid: GroupJid) {
@@ -59,11 +45,9 @@ export class GroupController {
return await this.waMonitor.waInstances[instance.instanceName].findGroup(groupJid); return await this.waMonitor.waInstances[instance.instanceName].findGroup(groupJid);
} }
public async fetchAllGroups(instance: InstanceDto) { public async fetchAllGroups(instance: InstanceDto, getPaticipants: GetParticipant) {
logger.verbose( logger.verbose('requested fetchAllGroups from ' + instance.instanceName + ' instance');
'requested fetchAllGroups from ' + instance.instanceName + ' instance', return await this.waMonitor.waInstances[instance.instanceName].fetchAllGroups(getPaticipants);
);
return await this.waMonitor.waInstances[instance.instanceName].fetchAllGroups();
} }
public async inviteCode(instance: InstanceDto, groupJid: GroupJid) { public async inviteCode(instance: InstanceDto, groupJid: GroupJid) {
@@ -82,49 +66,28 @@ export class GroupController {
} }
public async revokeInviteCode(instance: InstanceDto, groupJid: GroupJid) { public async revokeInviteCode(instance: InstanceDto, groupJid: GroupJid) {
logger.verbose( logger.verbose('requested revokeInviteCode from ' + instance.instanceName + ' instance');
'requested revokeInviteCode from ' + instance.instanceName + ' instance', return await this.waMonitor.waInstances[instance.instanceName].revokeInviteCode(groupJid);
);
return await this.waMonitor.waInstances[instance.instanceName].revokeInviteCode(
groupJid,
);
} }
public async findParticipants(instance: InstanceDto, groupJid: GroupJid) { public async findParticipants(instance: InstanceDto, groupJid: GroupJid) {
logger.verbose( logger.verbose('requested findParticipants from ' + instance.instanceName + ' instance');
'requested findParticipants from ' + instance.instanceName + ' instance', return await this.waMonitor.waInstances[instance.instanceName].findParticipants(groupJid);
);
return await this.waMonitor.waInstances[instance.instanceName].findParticipants(
groupJid,
);
} }
public async updateGParticipate( public async updateGParticipate(instance: InstanceDto, update: GroupUpdateParticipantDto) {
instance: InstanceDto, logger.verbose('requested updateGParticipate from ' + instance.instanceName + ' instance');
update: GroupUpdateParticipantDto, return await this.waMonitor.waInstances[instance.instanceName].updateGParticipant(update);
) {
logger.verbose(
'requested updateGParticipate from ' + instance.instanceName + ' instance',
);
return await this.waMonitor.waInstances[instance.instanceName].updateGParticipant(
update,
);
} }
public async updateGSetting(instance: InstanceDto, update: GroupUpdateSettingDto) { public async updateGSetting(instance: InstanceDto, update: GroupUpdateSettingDto) {
logger.verbose( logger.verbose('requested updateGSetting from ' + instance.instanceName + ' instance');
'requested updateGSetting from ' + instance.instanceName + ' instance',
);
return await this.waMonitor.waInstances[instance.instanceName].updateGSetting(update); return await this.waMonitor.waInstances[instance.instanceName].updateGSetting(update);
} }
public async toggleEphemeral(instance: InstanceDto, update: GroupToggleEphemeralDto) { public async toggleEphemeral(instance: InstanceDto, update: GroupToggleEphemeralDto) {
logger.verbose( logger.verbose('requested toggleEphemeral from ' + instance.instanceName + ' instance');
'requested toggleEphemeral from ' + instance.instanceName + ' instance', return await this.waMonitor.waInstances[instance.instanceName].toggleEphemeral(update);
);
return await this.waMonitor.waInstances[instance.instanceName].toggleEphemeral(
update,
);
} }
public async leaveGroup(instance: InstanceDto, groupJid: GroupJid) { public async leaveGroup(instance: InstanceDto, groupJid: GroupJid) {

View File

@@ -1,16 +1,20 @@
import { delay } from '@whiskeysockets/baileys'; import { delay } from '@whiskeysockets/baileys';
import { isURL } from 'class-validator';
import EventEmitter2 from 'eventemitter2'; import EventEmitter2 from 'eventemitter2';
import { Auth, ConfigService } from '../../config/env.config';
import { ConfigService, HttpServer } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { RedisCache } from '../../db/redis.client';
import { BadRequestException, InternalServerErrorException } from '../../exceptions'; import { BadRequestException, InternalServerErrorException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { RepositoryBroker } from '../repository/repository.manager'; import { RepositoryBroker } from '../repository/repository.manager';
import { AuthService, OldToken } from '../services/auth.service'; import { AuthService, OldToken } from '../services/auth.service';
import { ChatwootService } from '../services/chatwoot.service';
import { WAMonitoringService } from '../services/monitor.service'; import { WAMonitoringService } from '../services/monitor.service';
import { WAStartupService } from '../services/whatsapp.service'; import { SettingsService } from '../services/settings.service';
import { WebhookService } from '../services/webhook.service'; import { WebhookService } from '../services/webhook.service';
import { Logger } from '../../config/logger.config'; import { WAStartupService } from '../services/whatsapp.service';
import { wa } from '../types/wa.types'; import { wa } from '../types/wa.types';
import { RedisCache } from '../../db/redis.client';
export class InstanceController { export class InstanceController {
constructor( constructor(
@@ -20,6 +24,8 @@ export class InstanceController {
private readonly eventEmitter: EventEmitter2, private readonly eventEmitter: EventEmitter2,
private readonly authService: AuthService, private readonly authService: AuthService,
private readonly webhookService: WebhookService, private readonly webhookService: WebhookService,
private readonly chatwootService: ChatwootService,
private readonly settingsService: SettingsService,
private readonly cache: RedisCache, private readonly cache: RedisCache,
) {} ) {}
@@ -31,99 +37,29 @@ export class InstanceController {
webhook_by_events, webhook_by_events,
events, events,
qrcode, qrcode,
number,
token, token,
chatwoot_account_id,
chatwoot_token,
chatwoot_url,
chatwoot_sign_msg,
chatwoot_reopen_conversation,
chatwoot_conversation_pending,
reject_call,
msg_call,
groups_ignore,
always_online,
read_messages,
read_status,
}: InstanceDto) { }: InstanceDto) {
this.logger.verbose('requested createInstance from ' + instanceName + ' instance'); try {
this.logger.verbose('requested createInstance from ' + instanceName + ' instance');
const mode = this.configService.get<Auth>('AUTHENTICATION').INSTANCE.MODE;
if (mode === 'container') {
this.logger.verbose('container mode');
if (Object.keys(this.waMonitor.waInstances).length > 0) {
throw new BadRequestException([
'Instance already created',
'Only one instance can be created',
]);
}
this.logger.verbose('checking duplicate token'); this.logger.verbose('checking duplicate token');
await this.authService.checkDuplicateToken(token); await this.authService.checkDuplicateToken(token);
this.logger.verbose('creating instance'); this.logger.verbose('creating instance');
const instance = new WAStartupService( const instance = new WAStartupService(this.configService, this.eventEmitter, this.repository, this.cache);
this.configService,
this.eventEmitter,
this.repository,
this.cache,
);
instance.instanceName = instanceName;
this.logger.verbose('instance: ' + instance.instanceName + ' created');
this.waMonitor.waInstances[instance.instanceName] = instance;
this.waMonitor.delInstanceTime(instance.instanceName);
this.logger.verbose('generating hash');
const hash = await this.authService.generateHash(
{
instanceName: instance.instanceName,
},
token,
);
this.logger.verbose('hash: ' + hash + ' generated');
let getEvents: string[];
if (webhook) {
this.logger.verbose('creating webhook');
try {
this.webhookService.create(instance, {
enabled: true,
url: webhook,
events,
webhook_by_events,
});
getEvents = (await this.webhookService.find(instance)).events;
} catch (error) {
this.logger.log(error);
}
}
this.logger.verbose('instance created');
this.logger.verbose({
instance: {
instanceName: instance.instanceName,
status: 'created',
},
hash,
webhook,
events: getEvents,
});
return {
instance: {
instanceName: instance.instanceName,
status: 'created',
},
hash,
webhook,
events: getEvents,
};
} else {
this.logger.verbose('server mode');
this.logger.verbose('checking duplicate token');
await this.authService.checkDuplicateToken(token);
this.logger.verbose('creating instance');
const instance = new WAStartupService(
this.configService,
this.eventEmitter,
this.repository,
this.cache,
);
instance.instanceName = instanceName; instance.instanceName = instanceName;
this.logger.verbose('instance: ' + instance.instanceName + ' created'); this.logger.verbose('instance: ' + instance.instanceName + ' created');
@@ -144,6 +80,10 @@ export class InstanceController {
let getEvents: string[]; let getEvents: string[];
if (webhook) { if (webhook) {
if (!isURL(webhook, { require_tld: false })) {
throw new BadRequestException('Invalid "url" property in webhook');
}
this.logger.verbose('creating webhook'); this.logger.verbose('creating webhook');
try { try {
this.webhookService.create(instance, { this.webhookService.create(instance, {
@@ -159,27 +99,102 @@ export class InstanceController {
} }
} }
let getQrcode: wa.QrCode; this.logger.verbose('creating settings');
const settings: wa.LocalSettings = {
reject_call: reject_call || false,
msg_call: msg_call || '',
groups_ignore: groups_ignore || false,
always_online: always_online || false,
read_messages: read_messages || false,
read_status: read_status || false,
};
if (qrcode) { this.logger.verbose('settings: ' + JSON.stringify(settings));
this.logger.verbose('creating qrcode');
await instance.connectToWhatsapp(); this.settingsService.create(instance, settings);
await delay(2000);
getQrcode = instance.qrCode; if (!chatwoot_account_id || !chatwoot_token || !chatwoot_url) {
let getQrcode: wa.QrCode;
if (qrcode) {
this.logger.verbose('creating qrcode');
await instance.connectToWhatsapp(number);
await delay(5000);
getQrcode = instance.qrCode;
}
const result = {
instance: {
instanceName: instance.instanceName,
status: 'created',
},
hash,
webhook,
webhook_by_events,
events: getEvents,
settings,
qrcode: getQrcode,
};
this.logger.verbose('instance created');
this.logger.verbose(result);
return result;
} }
this.logger.verbose('instance created'); if (!chatwoot_account_id) {
this.logger.verbose({ throw new BadRequestException('account_id is required');
instance: { }
instanceName: instance.instanceName,
status: 'created', if (!chatwoot_token) {
}, throw new BadRequestException('token is required');
hash, }
webhook,
webhook_by_events, if (!chatwoot_url) {
events: getEvents, throw new BadRequestException('url is required');
qrcode: getQrcode, }
});
if (!isURL(chatwoot_url, { require_tld: false })) {
throw new BadRequestException('Invalid "url" property in chatwoot');
}
if (chatwoot_sign_msg !== true && chatwoot_sign_msg !== false) {
throw new BadRequestException('sign_msg is required');
}
if (chatwoot_reopen_conversation !== true && chatwoot_reopen_conversation !== false) {
throw new BadRequestException('reopen_conversation is required');
}
if (chatwoot_conversation_pending !== true && chatwoot_conversation_pending !== false) {
throw new BadRequestException('conversation_pending is required');
}
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
try {
this.chatwootService.create(instance, {
enabled: true,
account_id: chatwoot_account_id,
token: chatwoot_token,
url: chatwoot_url,
sign_msg: chatwoot_sign_msg || false,
name_inbox: instance.instanceName,
number,
reopen_conversation: chatwoot_reopen_conversation || false,
conversation_pending: chatwoot_conversation_pending || false,
});
this.chatwootService.initInstanceChatwoot(
instance,
instance.instanceName,
`${urlServer}/chatwoot/webhook/${instance.instanceName}`,
qrcode,
number,
);
} catch (error) {
this.logger.log(error);
}
return { return {
instance: { instance: {
@@ -190,33 +205,58 @@ export class InstanceController {
webhook, webhook,
webhook_by_events, webhook_by_events,
events: getEvents, events: getEvents,
qrcode: getQrcode, settings,
chatwoot: {
enabled: true,
account_id: chatwoot_account_id,
token: chatwoot_token,
url: chatwoot_url,
sign_msg: chatwoot_sign_msg || false,
reopen_conversation: chatwoot_reopen_conversation || false,
conversation_pending: chatwoot_conversation_pending || false,
number,
name_inbox: instance.instanceName,
webhook_url: `${urlServer}/chatwoot/webhook/${instance.instanceName}`,
},
}; };
} catch (error) {
console.log(error);
return { error: true, message: error.toString() };
} }
} }
public async connectToWhatsapp({ instanceName }: InstanceDto) { public async connectToWhatsapp({ instanceName, number = null }: InstanceDto) {
try { try {
this.logger.verbose( this.logger.verbose('requested connectToWhatsapp from ' + instanceName + ' instance');
'requested connectToWhatsapp from ' + instanceName + ' instance',
);
const instance = this.waMonitor.waInstances[instanceName]; const instance = this.waMonitor.waInstances[instanceName];
const state = instance?.connectionStatus?.state; const state = instance?.connectionStatus?.state;
this.logger.verbose('state: ' + state); this.logger.verbose('state: ' + state);
switch (state) { if (state == 'open') {
case 'close': return await this.connectionState({ instanceName });
this.logger.verbose('connecting');
await instance.connectToWhatsapp();
await delay(2000);
return instance.qrCode;
case 'connecting':
return instance.qrCode;
default:
return await this.connectionState({ instanceName });
} }
if (state == 'connecting') {
return instance.qrCode;
}
if (state == 'close') {
this.logger.verbose('connecting');
await instance.connectToWhatsapp(number);
await delay(5000);
return instance.qrCode;
}
return {
instance: {
instanceName: instanceName,
status: state,
},
qrcode: instance?.qrCode,
};
} catch (error) { } catch (error) {
this.logger.error(error); this.logger.error(error);
} }
@@ -226,24 +266,8 @@ export class InstanceController {
try { try {
this.logger.verbose('requested restartInstance from ' + instanceName + ' instance'); this.logger.verbose('requested restartInstance from ' + instanceName + ' instance');
this.logger.verbose('deleting instance: ' + instanceName); this.logger.verbose('logging out instance: ' + instanceName);
delete this.waMonitor.waInstances[instanceName]; this.waMonitor.waInstances[instanceName]?.client?.ws?.close();
this.logger.verbose('creating instance: ' + instanceName);
const instance = new WAStartupService(
this.configService,
this.eventEmitter,
this.repository,
this.cache,
);
instance.instanceName = instanceName;
this.logger.verbose('instance: ' + instance.instanceName + ' created');
this.logger.verbose('connecting instance: ' + instanceName);
await instance.connectToWhatsapp();
this.waMonitor.waInstances[instance.instanceName] = instance;
return { error: false, message: 'Instance restarted' }; return { error: false, message: 'Instance restarted' };
} catch (error) { } catch (error) {
@@ -253,7 +277,12 @@ export class InstanceController {
public async connectionState({ instanceName }: InstanceDto) { public async connectionState({ instanceName }: InstanceDto) {
this.logger.verbose('requested connectionState from ' + instanceName + ' instance'); this.logger.verbose('requested connectionState from ' + instanceName + ' instance');
return this.waMonitor.waInstances[instanceName]?.connectionStatus; return {
instance: {
instanceName: instanceName,
state: this.waMonitor.waInstances[instanceName]?.connectionStatus?.state,
},
};
} }
public async fetchInstances({ instanceName }: InstanceDto) { public async fetchInstances({ instanceName }: InstanceDto) {
@@ -268,11 +297,15 @@ export class InstanceController {
public async logout({ instanceName }: InstanceDto) { public async logout({ instanceName }: InstanceDto) {
this.logger.verbose('requested logout from ' + instanceName + ' instance'); this.logger.verbose('requested logout from ' + instanceName + ' instance');
const { instance } = await this.connectionState({ instanceName });
if (instance.state === 'close') {
throw new BadRequestException('The "' + instanceName + '" instance is not connected');
}
try { try {
this.logger.verbose('logging out instance: ' + instanceName); this.logger.verbose('logging out instance: ' + instanceName);
await this.waMonitor.waInstances[instanceName]?.client?.logout( await this.waMonitor.waInstances[instanceName]?.client?.logout('Log out instance: ' + instanceName);
'Log out instance: ' + instanceName,
);
this.logger.verbose('close connection instance: ' + instanceName); this.logger.verbose('close connection instance: ' + instanceName);
this.waMonitor.waInstances[instanceName]?.client?.ws?.close(); this.waMonitor.waInstances[instanceName]?.client?.ws?.close();
@@ -285,16 +318,13 @@ export class InstanceController {
public async deleteInstance({ instanceName }: InstanceDto) { public async deleteInstance({ instanceName }: InstanceDto) {
this.logger.verbose('requested deleteInstance from ' + instanceName + ' instance'); this.logger.verbose('requested deleteInstance from ' + instanceName + ' instance');
const stateConn = await this.connectionState({ instanceName }); const { instance } = await this.connectionState({ instanceName });
if (stateConn.state === 'open') { if (instance.state === 'open') {
throw new BadRequestException([ throw new BadRequestException('The "' + instanceName + '" instance needs to be disconnected');
'Deletion failed',
'The instance needs to be disconnected',
]);
} }
try { try {
if (stateConn.state === 'connecting') { if (instance.state === 'connecting') {
this.logger.verbose('logging out instance: ' + instanceName); this.logger.verbose('logging out instance: ' + instanceName);
await this.logout({ instanceName }); await this.logout({ instanceName });

View File

@@ -1,11 +1,12 @@
import { isBase64, isURL } from 'class-validator'; import { isBase64, isURL } from 'class-validator';
import { Logger } from '../../config/logger.config';
import { BadRequestException } from '../../exceptions'; import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { import {
SendAudioDto, SendAudioDto,
SendButtonDto, SendButtonDto,
SendContactDto, SendContactDto,
SendLinkPreviewDto,
SendListDto, SendListDto,
SendLocationDto, SendLocationDto,
SendMediaDto, SendMediaDto,
@@ -17,8 +18,6 @@ import {
} from '../dto/sendMessage.dto'; } from '../dto/sendMessage.dto';
import { WAMonitoringService } from '../services/monitor.service'; import { WAMonitoringService } from '../services/monitor.service';
import { Logger } from '../../config/logger.config';
const logger = new Logger('MessageRouter'); const logger = new Logger('MessageRouter');
export class SendMessageController { export class SendMessageController {
@@ -31,15 +30,16 @@ export class SendMessageController {
public async sendMedia({ instanceName }: InstanceDto, data: SendMediaDto) { public async sendMedia({ instanceName }: InstanceDto, data: SendMediaDto) {
logger.verbose('requested sendMedia from ' + instanceName + ' instance'); logger.verbose('requested sendMedia from ' + instanceName + ' instance');
if (isBase64(data?.mediaMessage?.media) && !data?.mediaMessage?.fileName) {
throw new BadRequestException('For bse64 the file name must be informed.'); if (
isBase64(data?.mediaMessage?.media) &&
!data?.mediaMessage?.fileName &&
data?.mediaMessage?.mediatype === 'document'
) {
throw new BadRequestException('For base64 the file name must be informed.');
} }
logger.verbose(
'isURL: ' + logger.verbose('isURL: ' + isURL(data?.mediaMessage?.media) + ', isBase64: ' + isBase64(data?.mediaMessage?.media));
isURL(data?.mediaMessage?.media) +
', isBase64: ' +
isBase64(data?.mediaMessage?.media),
);
if (isURL(data?.mediaMessage?.media) || isBase64(data?.mediaMessage?.media)) { if (isURL(data?.mediaMessage?.media) || isBase64(data?.mediaMessage?.media)) {
return await this.waMonitor.waInstances[instanceName].mediaMessage(data); return await this.waMonitor.waInstances[instanceName].mediaMessage(data);
} }
@@ -50,10 +50,7 @@ export class SendMessageController {
logger.verbose('requested sendSticker from ' + instanceName + ' instance'); logger.verbose('requested sendSticker from ' + instanceName + ' instance');
logger.verbose( logger.verbose(
'isURL: ' + 'isURL: ' + isURL(data?.stickerMessage?.image) + ', isBase64: ' + isBase64(data?.stickerMessage?.image),
isURL(data?.stickerMessage?.image) +
', isBase64: ' +
isBase64(data?.stickerMessage?.image),
); );
if (isURL(data.stickerMessage.image) || isBase64(data.stickerMessage.image)) { if (isURL(data.stickerMessage.image) || isBase64(data.stickerMessage.image)) {
return await this.waMonitor.waInstances[instanceName].mediaSticker(data); return await this.waMonitor.waInstances[instanceName].mediaSticker(data);
@@ -64,12 +61,7 @@ export class SendMessageController {
public async sendWhatsAppAudio({ instanceName }: InstanceDto, data: SendAudioDto) { public async sendWhatsAppAudio({ instanceName }: InstanceDto, data: SendAudioDto) {
logger.verbose('requested sendWhatsAppAudio from ' + instanceName + ' instance'); logger.verbose('requested sendWhatsAppAudio from ' + instanceName + ' instance');
logger.verbose( logger.verbose('isURL: ' + isURL(data?.audioMessage?.audio) + ', isBase64: ' + isBase64(data?.audioMessage?.audio));
'isURL: ' +
isURL(data?.audioMessage?.audio) +
', isBase64: ' +
isBase64(data?.audioMessage?.audio),
);
if (isURL(data.audioMessage.audio) || isBase64(data.audioMessage.audio)) { if (isURL(data.audioMessage.audio) || isBase64(data.audioMessage.audio)) {
return await this.waMonitor.waInstances[instanceName].audioWhatsapp(data); return await this.waMonitor.waInstances[instanceName].audioWhatsapp(data);
} }
@@ -78,10 +70,7 @@ export class SendMessageController {
public async sendButtons({ instanceName }: InstanceDto, data: SendButtonDto) { public async sendButtons({ instanceName }: InstanceDto, data: SendButtonDto) {
logger.verbose('requested sendButtons from ' + instanceName + ' instance'); logger.verbose('requested sendButtons from ' + instanceName + ' instance');
if ( if (isBase64(data.buttonMessage.mediaMessage?.media) && !data.buttonMessage.mediaMessage?.fileName) {
isBase64(data.buttonMessage.mediaMessage?.media) &&
!data.buttonMessage.mediaMessage?.fileName
) {
throw new BadRequestException('For bse64 the file name must be informed.'); throw new BadRequestException('For bse64 the file name must be informed.');
} }
return await this.waMonitor.waInstances[instanceName].buttonMessage(data); return await this.waMonitor.waInstances[instanceName].buttonMessage(data);
@@ -104,7 +93,7 @@ export class SendMessageController {
public async sendReaction({ instanceName }: InstanceDto, data: SendReactionDto) { public async sendReaction({ instanceName }: InstanceDto, data: SendReactionDto) {
logger.verbose('requested sendReaction from ' + instanceName + ' instance'); logger.verbose('requested sendReaction from ' + instanceName + ' instance');
if (!data.reactionMessage.reaction.match(/[^\(\)\w\sà-ú"-\+]+/)) { if (!data.reactionMessage.reaction.match(/[^()\w\sà-ú"-+]+/)) {
throw new BadRequestException('"reaction" must be an emoji'); throw new BadRequestException('"reaction" must be an emoji');
} }
return await this.waMonitor.waInstances[instanceName].reactionMessage(data); return await this.waMonitor.waInstances[instanceName].reactionMessage(data);
@@ -119,9 +108,4 @@ export class SendMessageController {
logger.verbose('requested sendStatus from ' + instanceName + ' instance'); logger.verbose('requested sendStatus from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].statusMessage(data); return await this.waMonitor.waInstances[instanceName].statusMessage(data);
} }
public async sendLinkPreview({ instanceName }: InstanceDto, data: SendLinkPreviewDto) {
logger.verbose('requested sendLinkPreview from ' + instanceName + ' instance');
return await this.waMonitor.waInstances[instanceName].linkPreview(data);
}
} }

View File

@@ -0,0 +1,24 @@
// import { isURL } from 'class-validator';
import { Logger } from '../../config/logger.config';
// import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto';
import { SettingsDto } from '../dto/settings.dto';
import { SettingsService } from '../services/settings.service';
const logger = new Logger('SettingsController');
export class SettingsController {
constructor(private readonly settingsService: SettingsService) {}
public async createSettings(instance: InstanceDto, data: SettingsDto) {
logger.verbose('requested createSettings from ' + instance.instanceName + ' instance');
return this.settingsService.create(instance, data);
}
public async findSettings(instance: InstanceDto) {
logger.verbose('requested findSettings from ' + instance.instanceName + ' instance');
return this.settingsService.find(instance);
}
}

View File

@@ -1,4 +1,5 @@
import { Request, Response } from 'express'; import { Request, Response } from 'express';
import { Auth, ConfigService } from '../../config/env.config'; import { Auth, ConfigService } from '../../config/env.config';
import { BadRequestException } from '../../exceptions'; import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
@@ -6,10 +7,7 @@ import { HttpStatus } from '../routers/index.router';
import { WAMonitoringService } from '../services/monitor.service'; import { WAMonitoringService } from '../services/monitor.service';
export class ViewsController { export class ViewsController {
constructor( constructor(private readonly waMonit: WAMonitoringService, private readonly configService: ConfigService) {}
private readonly waMonit: WAMonitoringService,
private readonly configService: ConfigService,
) {}
public async qrcode(request: Request, response: Response) { public async qrcode(request: Request, response: Response) {
try { try {

View File

@@ -1,9 +1,10 @@
import { isURL } from 'class-validator'; import { isURL } from 'class-validator';
import { Logger } from '../../config/logger.config';
import { BadRequestException } from '../../exceptions'; import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { WebhookDto } from '../dto/webhook.dto'; import { WebhookDto } from '../dto/webhook.dto';
import { WebhookService } from '../services/webhook.service'; import { WebhookService } from '../services/webhook.service';
import { Logger } from '../../config/logger.config';
const logger = new Logger('WebhookController'); const logger = new Logger('WebhookController');

View File

@@ -1,16 +1,7 @@
import { import { proto, WAPrivacyOnlineValue, WAPrivacyValue, WAReadReceiptsValue } from '@whiskeysockets/baileys';
WAPrivacyOnlineValue,
WAPrivacyValue,
WAReadReceiptsValue,
proto,
} from '@whiskeysockets/baileys';
export class OnWhatsAppDto { export class OnWhatsAppDto {
constructor( constructor(public readonly jid: string, public readonly exists: boolean, public readonly name?: string) {}
public readonly jid: string,
public readonly exists: boolean,
public readonly name?: string,
) {}
} }
export class getBase64FromMediaMessageDto { export class getBase64FromMediaMessageDto {
@@ -26,6 +17,19 @@ export class NumberDto {
number: string; number: string;
} }
export class NumberBusiness {
wid?: string;
jid?: string;
exists?: boolean;
isBusiness: boolean;
name?: string;
message?: string;
description?: string;
email?: string;
website?: string[];
address?: string;
}
export class ProfileNameDto { export class ProfileNameDto {
name: string; name: string;
} }
@@ -46,7 +50,7 @@ class Key {
remoteJid: string; remoteJid: string;
} }
export class ReadMessageDto { export class ReadMessageDto {
readMessages: Key[]; read_messages: Key[];
} }
class LastMessage { class LastMessage {

View File

@@ -0,0 +1,11 @@
export class ChatwootDto {
enabled?: boolean;
account_id?: string;
token?: string;
url?: string;
name_inbox?: string;
sign_msg?: boolean;
number?: string;
reopen_conversation?: boolean;
conversation_pending?: boolean;
}

View File

@@ -1,7 +1,8 @@
export class CreateGroupDto { export class CreateGroupDto {
subject: string; subject: string;
description?: string;
participants: string[]; participants: string[];
description?: string;
promoteParticipants?: boolean;
} }
export class GroupPictureDto { export class GroupPictureDto {
@@ -23,6 +24,10 @@ export class GroupJid {
groupJid: string; groupJid: string;
} }
export class GetParticipant {
getParticipants: string;
}
export class GroupInvite { export class GroupInvite {
inviteCode: string; inviteCode: string;
} }

View File

@@ -1,8 +1,21 @@
export class InstanceDto { export class InstanceDto {
instanceName: string; instanceName: string;
qrcode?: boolean;
number?: string;
token?: string;
webhook?: string; webhook?: string;
webhook_by_events?: boolean; webhook_by_events?: boolean;
events?: string[]; events?: string[];
qrcode?: boolean; reject_call?: boolean;
token?: string; msg_call?: string;
groups_ignore?: boolean;
always_online?: boolean;
read_messages?: boolean;
read_status?: boolean;
chatwoot_account_id?: string;
chatwoot_token?: string;
chatwoot_url?: string;
chatwoot_sign_msg?: boolean;
chatwoot_reopen_conversation?: boolean;
chatwoot_conversation_pending?: boolean;
} }

View File

@@ -15,6 +15,8 @@ export class Options {
presence?: WAPresence; presence?: WAPresence;
quoted?: Quoted; quoted?: Quoted;
mentions?: Mentions; mentions?: Mentions;
linkPreview?: boolean;
encoding?: boolean;
} }
class OptionsMessage { class OptionsMessage {
options: Options; options: Options;
@@ -28,10 +30,6 @@ class TextMessage {
text: string; text: string;
} }
class linkPreviewMessage {
text: string;
}
export class StatusMessage { export class StatusMessage {
type: string; type: string;
content: string; content: string;
@@ -52,10 +50,6 @@ export class SendTextDto extends Metadata {
textMessage: TextMessage; textMessage: TextMessage;
} }
export class SendLinkPreviewDto extends Metadata {
linkPreview: linkPreviewMessage;
}
export class SendStatusDto extends Metadata { export class SendStatusDto extends Metadata {
statusMessage: StatusMessage; statusMessage: StatusMessage;
} }

View File

@@ -0,0 +1,8 @@
export class SettingsDto {
reject_call?: boolean;
msg_call?: string;
groups_ignore?: boolean;
always_online?: boolean;
read_messages?: boolean;
read_status?: boolean;
}

View File

@@ -1,12 +1,13 @@
import { isJWT } from 'class-validator'; import { isJWT } from 'class-validator';
import { NextFunction, Request, Response } from 'express'; import { NextFunction, Request, Response } from 'express';
import jwt from 'jsonwebtoken'; import jwt from 'jsonwebtoken';
import { name } from '../../../package.json';
import { Auth, configService } from '../../config/env.config'; import { Auth, configService } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { name } from '../../../package.json'; import { ForbiddenException, UnauthorizedException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { JwtPayload } from '../services/auth.service'; import { JwtPayload } from '../services/auth.service';
import { ForbiddenException, UnauthorizedException } from '../../exceptions';
import { repository } from '../whatsapp.module'; import { repository } from '../whatsapp.module';
const logger = new Logger('GUARD'); const logger = new Logger('GUARD');
@@ -22,15 +23,8 @@ async function jwtGuard(req: Request, res: Response, next: NextFunction) {
return next(); return next();
} }
if ( if ((req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) && !key) {
(req.originalUrl.includes('/instance/create') || throw new ForbiddenException('Missing global api key', 'The global api key must be set');
req.originalUrl.includes('/instance/fetchInstances')) &&
!key
) {
throw new ForbiddenException(
'Missing global api key',
'The global api key must be set',
);
} }
const jwtOpts = configService.get<Auth>('AUTHENTICATION').JWT; const jwtOpts = configService.get<Auth>('AUTHENTICATION').JWT;
@@ -69,15 +63,8 @@ async function apikey(req: Request, res: Response, next: NextFunction) {
return next(); return next();
} }
if ( if ((req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) && !key) {
(req.originalUrl.includes('/instance/create') || throw new ForbiddenException('Missing global api key', 'The global api key must be set');
req.originalUrl.includes('/instance/fetchInstances')) &&
!key
) {
throw new ForbiddenException(
'Missing global api key',
'The global api key must be set',
);
} }
try { try {
@@ -86,7 +73,9 @@ async function apikey(req: Request, res: Response, next: NextFunction) {
if (instanceKey.apikey === key) { if (instanceKey.apikey === key) {
return next(); return next();
} }
} catch (error) {} } catch (error) {
logger.error(error);
}
throw new UnauthorizedException(); throw new UnauthorizedException();
} }

View File

@@ -1,17 +1,13 @@
import { NextFunction, Request, Response } from 'express'; import { NextFunction, Request, Response } from 'express';
import { existsSync } from 'fs'; import { existsSync } from 'fs';
import { join } from 'path'; import { join } from 'path';
import { configService, Database, Redis } from '../../config/env.config';
import { INSTANCE_DIR } from '../../config/path.config'; import { INSTANCE_DIR } from '../../config/path.config';
import { dbserver } from '../../db/db.connect'; import { dbserver } from '../../db/db.connect';
import { import { BadRequestException, ForbiddenException, NotFoundException } from '../../exceptions';
BadRequestException,
ForbiddenException,
NotFoundException,
} from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { cache, waMonitor } from '../whatsapp.module'; import { cache, waMonitor } from '../whatsapp.module';
import { Database, Redis, configService } from '../../config/env.config';
import { RedisCache } from '../../db/redis.client';
async function getInstance(instanceName: string) { async function getInstance(instanceName: string) {
const db = configService.get<Database>('DATABASE'); const db = configService.get<Database>('DATABASE');
@@ -36,10 +32,7 @@ async function getInstance(instanceName: string) {
} }
export async function instanceExistsGuard(req: Request, _: Response, next: NextFunction) { export async function instanceExistsGuard(req: Request, _: Response, next: NextFunction) {
if ( if (req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) {
req.originalUrl.includes('/instance/create') ||
req.originalUrl.includes('/instance/fetchInstances')
) {
return next(); return next();
} }
@@ -59,9 +52,7 @@ export async function instanceLoggedGuard(req: Request, _: Response, next: NextF
if (req.originalUrl.includes('/instance/create')) { if (req.originalUrl.includes('/instance/create')) {
const instance = req.body as InstanceDto; const instance = req.body as InstanceDto;
if (await getInstance(instance.instanceName)) { if (await getInstance(instance.instanceName)) {
throw new ForbiddenException( throw new ForbiddenException(`This name "${instance.instanceName}" is already in use.`);
`This name "${instance.instanceName}" is already in use.`,
);
} }
if (waMonitor.waInstances[instance.instanceName]) { if (waMonitor.waInstances[instance.instanceName]) {

View File

@@ -1,4 +1,5 @@
import { Schema } from 'mongoose'; import { Schema } from 'mongoose';
import { dbserver } from '../../db/db.connect'; import { dbserver } from '../../db/db.connect';
export class AuthRaw { export class AuthRaw {

View File

@@ -1,4 +1,5 @@
import { Schema } from 'mongoose'; import { Schema } from 'mongoose';
import { dbserver } from '../../db/db.connect'; import { dbserver } from '../../db/db.connect';
export class ChatRaw { export class ChatRaw {

View File

@@ -0,0 +1,30 @@
import { Schema } from 'mongoose';
import { dbserver } from '../../db/db.connect';
export class ChatwootRaw {
_id?: string;
enabled?: boolean;
account_id?: string;
token?: string;
url?: string;
name_inbox?: string;
sign_msg?: boolean;
number?: string;
reopen_conversation?: boolean;
conversation_pending?: boolean;
}
const chatwootSchema = new Schema<ChatwootRaw>({
_id: { type: String, _id: true },
enabled: { type: Boolean, required: true },
account_id: { type: String, required: true },
token: { type: String, required: true },
url: { type: String, required: true },
name_inbox: { type: String, required: true },
sign_msg: { type: Boolean, required: true },
number: { type: String, required: true },
});
export const ChatwootModel = dbserver?.model(ChatwootRaw.name, chatwootSchema, 'chatwoot');
export type IChatwootModel = typeof ChatwootModel;

View File

@@ -1,4 +1,5 @@
import { Schema } from 'mongoose'; import { Schema } from 'mongoose';
import { dbserver } from '../../db/db.connect'; import { dbserver } from '../../db/db.connect';
export class ContactRaw { export class ContactRaw {

View File

@@ -1,5 +1,7 @@
export * from './auth.model';
export * from './chat.model'; export * from './chat.model';
export * from './chatwoot.model';
export * from './contact.model'; export * from './contact.model';
export * from './message.model'; export * from './message.model';
export * from './auth.model'; export * from './settings.model';
export * from './webhook.model'; export * from './webhook.model';

View File

@@ -1,4 +1,5 @@
import { Schema } from 'mongoose'; import { Schema } from 'mongoose';
import { dbserver } from '../../db/db.connect'; import { dbserver } from '../../db/db.connect';
import { wa } from '../types/wa.types'; import { wa } from '../types/wa.types';
@@ -64,9 +65,5 @@ const messageUpdateSchema = new Schema<MessageUpdateRaw>({
owner: { type: String, required: true, min: 1 }, owner: { type: String, required: true, min: 1 },
}); });
export const MessageUpModel = dbserver?.model( export const MessageUpModel = dbserver?.model(MessageUpdateRaw.name, messageUpdateSchema, 'messageUpdate');
MessageUpdateRaw.name,
messageUpdateSchema,
'messageUpdate',
);
export type IMessageUpModel = typeof MessageUpModel; export type IMessageUpModel = typeof MessageUpModel;

View File

@@ -0,0 +1,26 @@
import { Schema } from 'mongoose';
import { dbserver } from '../../db/db.connect';
export class SettingsRaw {
_id?: string;
reject_call?: boolean;
msg_call?: string;
groups_ignore?: boolean;
always_online?: boolean;
read_messages?: boolean;
read_status?: boolean;
}
const settingsSchema = new Schema<SettingsRaw>({
_id: { type: String, _id: true },
reject_call: { type: Boolean, required: true },
msg_call: { type: String, required: true },
groups_ignore: { type: Boolean, required: true },
always_online: { type: Boolean, required: true },
read_messages: { type: Boolean, required: true },
read_status: { type: Boolean, required: true },
});
export const SettingsModel = dbserver?.model(SettingsRaw.name, settingsSchema, 'settings');
export type ISettingsModel = typeof SettingsModel;

View File

@@ -1,4 +1,5 @@
import { Schema } from 'mongoose'; import { Schema } from 'mongoose';
import { dbserver } from '../../db/db.connect'; import { dbserver } from '../../db/db.connect';
export class WebhookRaw { export class WebhookRaw {
@@ -14,6 +15,7 @@ const webhookSchema = new Schema<WebhookRaw>({
url: { type: String, required: true }, url: { type: String, required: true },
enabled: { type: Boolean, required: true }, enabled: { type: Boolean, required: true },
events: { type: [String], required: true }, events: { type: [String], required: true },
webhook_by_events: { type: Boolean, required: true },
}); });
export const WebhookModel = dbserver?.model(WebhookRaw.name, webhookSchema, 'webhook'); export const WebhookModel = dbserver?.model(WebhookRaw.name, webhookSchema, 'webhook');

View File

@@ -1,16 +1,14 @@
import { join } from 'path';
import { Auth, ConfigService } from '../../config/env.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { IAuthModel, AuthRaw } from '../models';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { AUTH_DIR } from '../../config/path.config'; import { join } from 'path';
import { Auth, ConfigService } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { AUTH_DIR } from '../../config/path.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { AuthRaw, IAuthModel } from '../models';
export class AuthRepository extends Repository { export class AuthRepository extends Repository {
constructor( constructor(private readonly authModel: IAuthModel, readonly configService: ConfigService) {
private readonly authModel: IAuthModel,
readonly configService: ConfigService,
) {
super(configService); super(configService);
this.auth = configService.get<Auth>('AUTHENTICATION'); this.auth = configService.get<Auth>('AUTHENTICATION');
} }
@@ -23,11 +21,7 @@ export class AuthRepository extends Repository {
this.logger.verbose('creating auth'); this.logger.verbose('creating auth');
if (this.dbSettings.ENABLED) { if (this.dbSettings.ENABLED) {
this.logger.verbose('saving auth to db'); this.logger.verbose('saving auth to db');
const insert = await this.authModel.replaceOne( const insert = await this.authModel.replaceOne({ _id: instance }, { ...data }, { upsert: true });
{ _id: instance },
{ ...data },
{ upsert: true },
);
this.logger.verbose('auth saved to db: ' + insert.modifiedCount + ' auth'); this.logger.verbose('auth saved to db: ' + insert.modifiedCount + ' auth');
return { insertCount: insert.modifiedCount }; return { insertCount: insert.modifiedCount };
@@ -40,9 +34,7 @@ export class AuthRepository extends Repository {
fileName: instance, fileName: instance,
data, data,
}); });
this.logger.verbose( this.logger.verbose('auth saved to store in path: ' + join(AUTH_DIR, this.auth.TYPE) + '/' + instance);
'auth saved to store in path: ' + join(AUTH_DIR, this.auth.TYPE) + '/' + instance,
);
this.logger.verbose('auth created'); this.logger.verbose('auth created');
return { insertCount: 1 }; return { insertCount: 1 };

View File

@@ -1,29 +1,23 @@
import { join } from 'path';
import { ConfigService, StoreConf } from '../../config/env.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { opendirSync, readFileSync, rmSync } from 'fs'; import { opendirSync, readFileSync, rmSync } from 'fs';
import { ChatRaw, IChatModel } from '../models'; import { join } from 'path';
import { ConfigService, StoreConf } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { ChatRaw, IChatModel } from '../models';
export class ChatQuery { export class ChatQuery {
where: ChatRaw; where: ChatRaw;
} }
export class ChatRepository extends Repository { export class ChatRepository extends Repository {
constructor( constructor(private readonly chatModel: IChatModel, private readonly configService: ConfigService) {
private readonly chatModel: IChatModel,
private readonly configService: ConfigService,
) {
super(configService); super(configService);
} }
private readonly logger = new Logger('ChatRepository'); private readonly logger = new Logger('ChatRepository');
public async insert( public async insert(data: ChatRaw[], instanceName: string, saveDb = false): Promise<IInsert> {
data: ChatRaw[],
instanceName: string,
saveDb = false,
): Promise<IInsert> {
this.logger.verbose('inserting chats'); this.logger.verbose('inserting chats');
if (data.length === 0) { if (data.length === 0) {
this.logger.verbose('no chats to insert'); this.logger.verbose('no chats to insert');
@@ -53,10 +47,7 @@ export class ChatRepository extends Repository {
data: chat, data: chat,
}); });
this.logger.verbose( this.logger.verbose(
'chats saved to store in path: ' + 'chats saved to store in path: ' + join(this.storePath, 'chats', instanceName) + '/' + chat.id,
join(this.storePath, 'chats', instanceName) +
'/' +
chat.id,
); );
}); });
@@ -89,10 +80,9 @@ export class ChatRepository extends Repository {
if (dirent.isFile()) { if (dirent.isFile()) {
chats.push( chats.push(
JSON.parse( JSON.parse(
readFileSync( readFileSync(join(this.storePath, 'chats', query.where.owner, dirent.name), {
join(this.storePath, 'chats', query.where.owner, dirent.name), encoding: 'utf-8',
{ encoding: 'utf-8' }, }),
),
), ),
); );
} }

View File

@@ -0,0 +1,62 @@
import { readFileSync } from 'fs';
import { join } from 'path';
import { ConfigService } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { ChatwootRaw, IChatwootModel } from '../models';
export class ChatwootRepository extends Repository {
constructor(private readonly chatwootModel: IChatwootModel, private readonly configService: ConfigService) {
super(configService);
}
private readonly logger = new Logger('ChatwootRepository');
public async create(data: ChatwootRaw, instance: string): Promise<IInsert> {
try {
this.logger.verbose('creating chatwoot');
if (this.dbSettings.ENABLED) {
this.logger.verbose('saving chatwoot to db');
const insert = await this.chatwootModel.replaceOne({ _id: instance }, { ...data }, { upsert: true });
this.logger.verbose('chatwoot saved to db: ' + insert.modifiedCount + ' chatwoot');
return { insertCount: insert.modifiedCount };
}
this.logger.verbose('saving chatwoot to store');
this.writeStore<ChatwootRaw>({
path: join(this.storePath, 'chatwoot'),
fileName: instance,
data,
});
this.logger.verbose('chatwoot saved to store in path: ' + join(this.storePath, 'chatwoot') + '/' + instance);
this.logger.verbose('chatwoot created');
return { insertCount: 1 };
} catch (error) {
return error;
}
}
public async find(instance: string): Promise<ChatwootRaw> {
try {
this.logger.verbose('finding chatwoot');
if (this.dbSettings.ENABLED) {
this.logger.verbose('finding chatwoot in db');
return await this.chatwootModel.findOne({ _id: instance });
}
this.logger.verbose('finding chatwoot in store');
return JSON.parse(
readFileSync(join(this.storePath, 'chatwoot', instance + '.json'), {
encoding: 'utf-8',
}),
) as ChatwootRaw;
} catch (error) {
return {};
}
}
}

View File

@@ -1,29 +1,23 @@
import { opendirSync, readFileSync } from 'fs'; import { opendirSync, readFileSync } from 'fs';
import { join } from 'path'; import { join } from 'path';
import { ConfigService, StoreConf } from '../../config/env.config'; import { ConfigService, StoreConf } from '../../config/env.config';
import { ContactRaw, IContactModel } from '../models';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { ContactRaw, IContactModel } from '../models';
export class ContactQuery { export class ContactQuery {
where: ContactRaw; where: ContactRaw;
} }
export class ContactRepository extends Repository { export class ContactRepository extends Repository {
constructor( constructor(private readonly contactModel: IContactModel, private readonly configService: ConfigService) {
private readonly contactModel: IContactModel,
private readonly configService: ConfigService,
) {
super(configService); super(configService);
} }
private readonly logger = new Logger('ContactRepository'); private readonly logger = new Logger('ContactRepository');
public async insert( public async insert(data: ContactRaw[], instanceName: string, saveDb = false): Promise<IInsert> {
data: ContactRaw[],
instanceName: string,
saveDb = false,
): Promise<IInsert> {
this.logger.verbose('inserting contacts'); this.logger.verbose('inserting contacts');
if (data.length === 0) { if (data.length === 0) {
@@ -54,10 +48,7 @@ export class ContactRepository extends Repository {
data: contact, data: contact,
}); });
this.logger.verbose( this.logger.verbose(
'contacts saved to store in path: ' + 'contacts saved to store in path: ' + join(this.storePath, 'contacts', instanceName) + '/' + contact.id,
join(this.storePath, 'contacts', instanceName) +
'/' +
contact.id,
); );
}); });
@@ -74,11 +65,7 @@ export class ContactRepository extends Repository {
} }
} }
public async update( public async update(data: ContactRaw[], instanceName: string, saveDb = false): Promise<IInsert> {
data: ContactRaw[],
instanceName: string,
saveDb = false,
): Promise<IInsert> {
try { try {
this.logger.verbose('updating contacts'); this.logger.verbose('updating contacts');
@@ -119,10 +106,7 @@ export class ContactRepository extends Repository {
data: contact, data: contact,
}); });
this.logger.verbose( this.logger.verbose(
'contacts updated in store in path: ' + 'contacts updated in store in path: ' + join(this.storePath, 'contacts', instanceName) + '/' + contact.id,
join(this.storePath, 'contacts', instanceName) +
'/' +
contact.id,
); );
}); });
@@ -154,15 +138,9 @@ export class ContactRepository extends Repository {
this.logger.verbose('finding contacts in store by id'); this.logger.verbose('finding contacts in store by id');
contacts.push( contacts.push(
JSON.parse( JSON.parse(
readFileSync( readFileSync(join(this.storePath, 'contacts', query.where.owner, query.where.id + '.json'), {
join( encoding: 'utf-8',
this.storePath, }),
'contacts',
query.where.owner,
query.where.id + '.json',
),
{ encoding: 'utf-8' },
),
), ),
); );
} else { } else {
@@ -175,10 +153,9 @@ export class ContactRepository extends Repository {
if (dirent.isFile()) { if (dirent.isFile()) {
contacts.push( contacts.push(
JSON.parse( JSON.parse(
readFileSync( readFileSync(join(this.storePath, 'contacts', query.where.owner, dirent.name), {
join(this.storePath, 'contacts', query.where.owner, dirent.name), encoding: 'utf-8',
{ encoding: 'utf-8' }, }),
),
), ),
); );
} }

View File

@@ -1,9 +1,10 @@
import { ConfigService, StoreConf } from '../../config/env.config';
import { join } from 'path';
import { IMessageModel, MessageRaw } from '../models';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { opendirSync, readFileSync } from 'fs'; import { opendirSync, readFileSync } from 'fs';
import { join } from 'path';
import { ConfigService, StoreConf } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { IMessageModel, MessageRaw } from '../models';
export class MessageQuery { export class MessageQuery {
where: MessageRaw; where: MessageRaw;
@@ -11,20 +12,13 @@ export class MessageQuery {
} }
export class MessageRepository extends Repository { export class MessageRepository extends Repository {
constructor( constructor(private readonly messageModel: IMessageModel, private readonly configService: ConfigService) {
private readonly messageModel: IMessageModel,
private readonly configService: ConfigService,
) {
super(configService); super(configService);
} }
private readonly logger = new Logger('MessageRepository'); private readonly logger = new Logger('MessageRepository');
public async insert( public async insert(data: MessageRaw[], instanceName: string, saveDb = false): Promise<IInsert> {
data: MessageRaw[],
instanceName: string,
saveDb = false,
): Promise<IInsert> {
this.logger.verbose('inserting messages'); this.logger.verbose('inserting messages');
if (!Array.isArray(data) || data.length === 0) { if (!Array.isArray(data) || data.length === 0) {
@@ -74,10 +68,7 @@ export class MessageRepository extends Repository {
data: message, data: message,
}); });
this.logger.verbose( this.logger.verbose(
'messages saved to store in path: ' + 'messages saved to store in path: ' + join(this.storePath, 'messages', instanceName) + '/' + message.key.id,
join(this.storePath, 'messages', instanceName) +
'/' +
message.key.id,
); );
}); });
@@ -119,15 +110,9 @@ export class MessageRepository extends Repository {
this.logger.verbose('finding messages in store by id'); this.logger.verbose('finding messages in store by id');
messages.push( messages.push(
JSON.parse( JSON.parse(
readFileSync( readFileSync(join(this.storePath, 'messages', query.where.owner, query.where.key.id + '.json'), {
join( encoding: 'utf-8',
this.storePath, }),
'messages',
query.where.owner,
query.where.key.id + '.json',
),
{ encoding: 'utf-8' },
),
), ),
); );
} else { } else {
@@ -140,10 +125,9 @@ export class MessageRepository extends Repository {
if (dirent.isFile()) { if (dirent.isFile()) {
messages.push( messages.push(
JSON.parse( JSON.parse(
readFileSync( readFileSync(join(this.storePath, 'messages', query.where.owner, dirent.name), {
join(this.storePath, 'messages', query.where.owner, dirent.name), encoding: 'utf-8',
{ encoding: 'utf-8' }, }),
),
), ),
); );
} }

View File

@@ -1,9 +1,10 @@
import { ConfigService, StoreConf } from '../../config/env.config';
import { IMessageUpModel, MessageUpdateRaw } from '../models';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { join } from 'path';
import { opendirSync, readFileSync } from 'fs'; import { opendirSync, readFileSync } from 'fs';
import { join } from 'path';
import { ConfigService, StoreConf } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { IMessageUpModel, MessageUpdateRaw } from '../models';
export class MessageUpQuery { export class MessageUpQuery {
where: MessageUpdateRaw; where: MessageUpdateRaw;
@@ -11,20 +12,13 @@ export class MessageUpQuery {
} }
export class MessageUpRepository extends Repository { export class MessageUpRepository extends Repository {
constructor( constructor(private readonly messageUpModel: IMessageUpModel, private readonly configService: ConfigService) {
private readonly messageUpModel: IMessageUpModel,
private readonly configService: ConfigService,
) {
super(configService); super(configService);
} }
private readonly logger = new Logger('MessageUpRepository'); private readonly logger = new Logger('MessageUpRepository');
public async insert( public async insert(data: MessageUpdateRaw[], instanceName: string, saveDb?: boolean): Promise<IInsert> {
data: MessageUpdateRaw[],
instanceName: string,
saveDb?: boolean,
): Promise<IInsert> {
this.logger.verbose('inserting message up'); this.logger.verbose('inserting message up');
if (data.length === 0) { if (data.length === 0) {
@@ -54,10 +48,7 @@ export class MessageUpRepository extends Repository {
data: update, data: update,
}); });
this.logger.verbose( this.logger.verbose(
'message up saved to store in path: ' + 'message up saved to store in path: ' + join(this.storePath, 'message-up', instanceName) + '/' + update.id,
join(this.storePath, 'message-up', instanceName) +
'/' +
update.id,
); );
}); });
@@ -91,42 +82,32 @@ export class MessageUpRepository extends Repository {
messageUpdate.push( messageUpdate.push(
JSON.parse( JSON.parse(
readFileSync( readFileSync(join(this.storePath, 'message-up', query.where.owner, query.where.id + '.json'), {
join( encoding: 'utf-8',
this.storePath, }),
'message-up',
query.where.owner,
query.where.id + '.json',
),
{ encoding: 'utf-8' },
),
), ),
); );
} else { } else {
this.logger.verbose('finding message up in store by owner'); this.logger.verbose('finding message up in store by owner');
const openDir = opendirSync( const openDir = opendirSync(join(this.storePath, 'message-up', query.where.owner), {
join(this.storePath, 'message-up', query.where.owner), encoding: 'utf-8',
{ encoding: 'utf-8' }, });
);
for await (const dirent of openDir) { for await (const dirent of openDir) {
if (dirent.isFile()) { if (dirent.isFile()) {
messageUpdate.push( messageUpdate.push(
JSON.parse( JSON.parse(
readFileSync( readFileSync(join(this.storePath, 'message-up', query.where.owner, dirent.name), {
join(this.storePath, 'message-up', query.where.owner, dirent.name), encoding: 'utf-8',
{ encoding: 'utf-8' }, }),
),
), ),
); );
} }
} }
} }
this.logger.verbose( this.logger.verbose('message up found in store: ' + messageUpdate.length + ' message up');
'message up found in store: ' + messageUpdate.length + ' message up',
);
return messageUpdate return messageUpdate
.sort((x, y) => { .sort((x, y) => {
return y.datetime - x.datetime; return y.datetime - x.datetime;

View File

@@ -1,15 +1,17 @@
import { MessageRepository } from './message.repository'; import fs from 'fs';
import { ChatRepository } from './chat.repository';
import { ContactRepository } from './contact.repository';
import { MessageUpRepository } from './messageUp.repository';
import { MongoClient } from 'mongodb'; import { MongoClient } from 'mongodb';
import { WebhookRepository } from './webhook.repository';
import { AuthRepository } from './auth.repository';
import { Auth, ConfigService, Database } from '../../config/env.config';
import { execSync } from 'child_process';
import { join } from 'path'; import { join } from 'path';
import { Logger } from '../../config/logger.config';
import { Auth, ConfigService, Database } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { AuthRepository } from './auth.repository';
import { ChatRepository } from './chat.repository';
import { ChatwootRepository } from './chatwoot.repository';
import { ContactRepository } from './contact.repository';
import { MessageRepository } from './message.repository';
import { MessageUpRepository } from './messageUp.repository';
import { SettingsRepository } from './settings.repository';
import { WebhookRepository } from './webhook.repository';
export class RepositoryBroker { export class RepositoryBroker {
constructor( constructor(
public readonly message: MessageRepository, public readonly message: MessageRepository,
@@ -17,11 +19,12 @@ export class RepositoryBroker {
public readonly contact: ContactRepository, public readonly contact: ContactRepository,
public readonly messageUpdate: MessageUpRepository, public readonly messageUpdate: MessageUpRepository,
public readonly webhook: WebhookRepository, public readonly webhook: WebhookRepository,
public readonly chatwoot: ChatwootRepository,
public readonly settings: SettingsRepository,
public readonly auth: AuthRepository, public readonly auth: AuthRepository,
private configService: ConfigService, private configService: ConfigService,
dbServer?: MongoClient, dbServer?: MongoClient,
) { ) {
this.logger.verbose('initializing repository broker');
this.dbClient = dbServer; this.dbClient = dbServer;
this.__init_repo_without_db__(); this.__init_repo_without_db__();
} }
@@ -36,36 +39,79 @@ export class RepositoryBroker {
private __init_repo_without_db__() { private __init_repo_without_db__() {
this.logger.verbose('initializing repository without db'); this.logger.verbose('initializing repository without db');
if (!this.configService.get<Database>('DATABASE').ENABLED) { if (!this.configService.get<Database>('DATABASE').ENABLED) {
this.logger.verbose('database is disabled');
const storePath = join(process.cwd(), 'store'); const storePath = join(process.cwd(), 'store');
this.logger.verbose('creating store path: ' + storePath); this.logger.verbose('creating store path: ' + storePath);
execSync( try {
`mkdir -p ${join( const authDir = join(storePath, 'auth', this.configService.get<Auth>('AUTHENTICATION').TYPE);
storePath, const chatsDir = join(storePath, 'chats');
'auth', const contactsDir = join(storePath, 'contacts');
this.configService.get<Auth>('AUTHENTICATION').TYPE, const messagesDir = join(storePath, 'messages');
)}`, const messageUpDir = join(storePath, 'message-up');
); const webhookDir = join(storePath, 'webhook');
const chatwootDir = join(storePath, 'chatwoot');
const settingsDir = join(storePath, 'settings');
const tempDir = join(storePath, 'temp');
this.logger.verbose('creating chats path: ' + join(storePath, 'chats')); if (!fs.existsSync(authDir)) {
execSync(`mkdir -p ${join(storePath, 'chats')}`); this.logger.verbose('creating auth dir: ' + authDir);
fs.mkdirSync(authDir, { recursive: true });
}
if (!fs.existsSync(chatsDir)) {
this.logger.verbose('creating chats dir: ' + chatsDir);
fs.mkdirSync(chatsDir, { recursive: true });
}
if (!fs.existsSync(contactsDir)) {
this.logger.verbose('creating contacts dir: ' + contactsDir);
fs.mkdirSync(contactsDir, { recursive: true });
}
if (!fs.existsSync(messagesDir)) {
this.logger.verbose('creating messages dir: ' + messagesDir);
fs.mkdirSync(messagesDir, { recursive: true });
}
if (!fs.existsSync(messageUpDir)) {
this.logger.verbose('creating message-up dir: ' + messageUpDir);
fs.mkdirSync(messageUpDir, { recursive: true });
}
if (!fs.existsSync(webhookDir)) {
this.logger.verbose('creating webhook dir: ' + webhookDir);
fs.mkdirSync(webhookDir, { recursive: true });
}
if (!fs.existsSync(chatwootDir)) {
this.logger.verbose('creating chatwoot dir: ' + chatwootDir);
fs.mkdirSync(chatwootDir, { recursive: true });
}
if (!fs.existsSync(settingsDir)) {
this.logger.verbose('creating settings dir: ' + settingsDir);
fs.mkdirSync(settingsDir, { recursive: true });
}
if (!fs.existsSync(tempDir)) {
this.logger.verbose('creating temp dir: ' + tempDir);
fs.mkdirSync(tempDir, { recursive: true });
}
} catch (error) {
this.logger.error(error);
}
} else {
try {
const storePath = join(process.cwd(), 'store');
this.logger.verbose('creating contacts path: ' + join(storePath, 'contacts')); this.logger.verbose('creating store path: ' + storePath);
execSync(`mkdir -p ${join(storePath, 'contacts')}`);
this.logger.verbose('creating messages path: ' + join(storePath, 'messages')); const tempDir = join(storePath, 'temp');
execSync(`mkdir -p ${join(storePath, 'messages')}`); const chatwootDir = join(storePath, 'chatwoot');
this.logger.verbose('creating message-up path: ' + join(storePath, 'message-up')); if (!fs.existsSync(chatwootDir)) {
execSync(`mkdir -p ${join(storePath, 'message-up')}`); this.logger.verbose('creating chatwoot dir: ' + chatwootDir);
fs.mkdirSync(chatwootDir, { recursive: true });
this.logger.verbose('creating webhook path: ' + join(storePath, 'webhook')); }
execSync(`mkdir -p ${join(storePath, 'webhook')}`); if (!fs.existsSync(tempDir)) {
this.logger.verbose('creating temp dir: ' + tempDir);
this.logger.verbose('creating temp path: ' + join(storePath, 'temp')); fs.mkdirSync(tempDir, { recursive: true });
execSync(`mkdir -p ${join(storePath, 'temp')}`); }
} catch (error) {
this.logger.error(error);
}
} }
} }
} }

View File

@@ -0,0 +1,62 @@
import { readFileSync } from 'fs';
import { join } from 'path';
import { ConfigService } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { ISettingsModel, SettingsRaw } from '../models';
export class SettingsRepository extends Repository {
constructor(private readonly settingsModel: ISettingsModel, private readonly configService: ConfigService) {
super(configService);
}
private readonly logger = new Logger('SettingsRepository');
public async create(data: SettingsRaw, instance: string): Promise<IInsert> {
try {
this.logger.verbose('creating settings');
if (this.dbSettings.ENABLED) {
this.logger.verbose('saving settings to db');
const insert = await this.settingsModel.replaceOne({ _id: instance }, { ...data }, { upsert: true });
this.logger.verbose('settings saved to db: ' + insert.modifiedCount + ' settings');
return { insertCount: insert.modifiedCount };
}
this.logger.verbose('saving settings to store');
this.writeStore<SettingsRaw>({
path: join(this.storePath, 'settings'),
fileName: instance,
data,
});
this.logger.verbose('settings saved to store in path: ' + join(this.storePath, 'settings') + '/' + instance);
this.logger.verbose('settings created');
return { insertCount: 1 };
} catch (error) {
return error;
}
}
public async find(instance: string): Promise<SettingsRaw> {
try {
this.logger.verbose('finding settings');
if (this.dbSettings.ENABLED) {
this.logger.verbose('finding settings in db');
return await this.settingsModel.findOne({ _id: instance });
}
this.logger.verbose('finding settings in store');
return JSON.parse(
readFileSync(join(this.storePath, 'settings', instance + '.json'), {
encoding: 'utf-8',
}),
) as SettingsRaw;
} catch (error) {
return {};
}
}
}

View File

@@ -1,15 +1,13 @@
import { IInsert, Repository } from '../abstract/abstract.repository';
import { ConfigService } from '../../config/env.config';
import { join } from 'path';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { IWebhookModel, WebhookRaw } from '../models'; import { join } from 'path';
import { ConfigService } from '../../config/env.config';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { IWebhookModel, WebhookRaw } from '../models';
export class WebhookRepository extends Repository { export class WebhookRepository extends Repository {
constructor( constructor(private readonly webhookModel: IWebhookModel, private readonly configService: ConfigService) {
private readonly webhookModel: IWebhookModel,
private readonly configService: ConfigService,
) {
super(configService); super(configService);
} }
@@ -20,11 +18,7 @@ export class WebhookRepository extends Repository {
this.logger.verbose('creating webhook'); this.logger.verbose('creating webhook');
if (this.dbSettings.ENABLED) { if (this.dbSettings.ENABLED) {
this.logger.verbose('saving webhook to db'); this.logger.verbose('saving webhook to db');
const insert = await this.webhookModel.replaceOne( const insert = await this.webhookModel.replaceOne({ _id: instance }, { ...data }, { upsert: true });
{ _id: instance },
{ ...data },
{ upsert: true },
);
this.logger.verbose('webhook saved to db: ' + insert.modifiedCount + ' webhook'); this.logger.verbose('webhook saved to db: ' + insert.modifiedCount + ' webhook');
return { insertCount: insert.modifiedCount }; return { insertCount: insert.modifiedCount };
@@ -38,12 +32,7 @@ export class WebhookRepository extends Repository {
data, data,
}); });
this.logger.verbose( this.logger.verbose('webhook saved to store in path: ' + join(this.storePath, 'webhook') + '/' + instance);
'webhook saved to store in path: ' +
join(this.storePath, 'webhook') +
'/' +
instance,
);
this.logger.verbose('webhook created'); this.logger.verbose('webhook created');
return { insertCount: 1 }; return { insertCount: 1 };

View File

@@ -1,4 +1,6 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
import { import {
archiveChatSchema, archiveChatSchema,
contactValidateSchema, contactValidateSchema,
@@ -8,13 +10,16 @@ import {
privacySettingsSchema, privacySettingsSchema,
profileNameSchema, profileNameSchema,
profilePictureSchema, profilePictureSchema,
profileSchema,
profileStatusSchema, profileStatusSchema,
readMessageSchema, readMessageSchema,
whatsappNumberSchema, whatsappNumberSchema,
} from '../../validate/validate.schema'; } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router';
import { import {
ArchiveChatDto, ArchiveChatDto,
DeleteMessage, DeleteMessage,
getBase64FromMediaMessageDto,
NumberDto, NumberDto,
PrivacySettingDto, PrivacySettingDto,
ProfileNameDto, ProfileNameDto,
@@ -22,17 +27,13 @@ import {
ProfileStatusDto, ProfileStatusDto,
ReadMessageDto, ReadMessageDto,
WhatsAppNumberDto, WhatsAppNumberDto,
getBase64FromMediaMessageDto,
} from '../dto/chat.dto'; } from '../dto/chat.dto';
import { InstanceDto } from '../dto/instance.dto';
import { ContactQuery } from '../repository/contact.repository'; import { ContactQuery } from '../repository/contact.repository';
import { MessageQuery } from '../repository/message.repository'; import { MessageQuery } from '../repository/message.repository';
import { chatController } from '../whatsapp.module';
import { RouterBroker } from '../abstract/abstract.router';
import { HttpStatus } from './index.router';
import { MessageUpQuery } from '../repository/messageUp.repository'; import { MessageUpQuery } from '../repository/messageUp.repository';
import { proto } from '@whiskeysockets/baileys'; import { chatController } from '../whatsapp.module';
import { InstanceDto } from '../dto/instance.dto'; import { HttpStatus } from './index.router';
import { Logger } from '../../config/logger.config';
const logger = new Logger('ChatRouter'); const logger = new Logger('ChatRouter');
@@ -91,27 +92,23 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.delete( .delete(this.routerPath('deleteMessageForEveryone'), ...guards, async (req, res) => {
this.routerPath('deleteMessageForEveryone'), logger.verbose('request received in deleteMessageForEveryone');
...guards, logger.verbose('request body: ');
async (req, res) => { logger.verbose(req.body);
logger.verbose('request received in deleteMessageForEveryone');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: '); logger.verbose('request query: ');
logger.verbose(req.query); logger.verbose(req.query);
const response = await this.dataValidate<DeleteMessage>({ const response = await this.dataValidate<DeleteMessage>({
request: req, request: req,
schema: deleteMessageSchema, schema: deleteMessageSchema,
ClassRef: DeleteMessage, ClassRef: DeleteMessage,
execute: (instance, data) => chatController.deleteMessage(instance, data), execute: (instance, data) => chatController.deleteMessage(instance, data),
}); });
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}, })
)
.post(this.routerPath('fetchProfilePictureUrl'), ...guards, async (req, res) => { .post(this.routerPath('fetchProfilePictureUrl'), ...guards, async (req, res) => {
logger.verbose('request received in fetchProfilePictureUrl'); logger.verbose('request received in fetchProfilePictureUrl');
logger.verbose('request body: '); logger.verbose('request body: ');
@@ -129,6 +126,23 @@ export class ChatRouter extends RouterBroker {
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
}) })
.post(this.routerPath('fetchProfile'), ...guards, async (req, res) => {
logger.verbose('request received in fetchProfile');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<NumberDto>({
request: req,
schema: profileSchema,
ClassRef: NumberDto,
execute: (instance, data) => chatController.fetchProfile(instance, data),
});
return res.status(HttpStatus.OK).json(response);
})
.post(this.routerPath('findContacts'), ...guards, async (req, res) => { .post(this.routerPath('findContacts'), ...guards, async (req, res) => {
logger.verbose('request received in findContacts'); logger.verbose('request received in findContacts');
logger.verbose('request body: '); logger.verbose('request body: ');
@@ -158,8 +172,7 @@ export class ChatRouter extends RouterBroker {
request: req, request: req,
schema: null, schema: null,
ClassRef: getBase64FromMediaMessageDto, ClassRef: getBase64FromMediaMessageDto,
execute: (instance, data) => execute: (instance, data) => chatController.getBase64FromMediaMessage(instance, data),
chatController.getBase64FromMediaMessage(instance, data),
}); });
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
@@ -245,8 +258,7 @@ export class ChatRouter extends RouterBroker {
request: req, request: req,
schema: privacySettingsSchema, schema: privacySettingsSchema,
ClassRef: PrivacySettingDto, ClassRef: PrivacySettingDto,
execute: (instance, data) => execute: (instance, data) => chatController.updatePrivacySettings(instance, data),
chatController.updatePrivacySettings(instance, data),
}); });
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
@@ -263,8 +275,7 @@ export class ChatRouter extends RouterBroker {
request: req, request: req,
schema: profilePictureSchema, schema: profilePictureSchema,
ClassRef: ProfilePictureDto, ClassRef: ProfilePictureDto,
execute: (instance, data) => execute: (instance, data) => chatController.fetchBusinessProfile(instance, data),
chatController.fetchBusinessProfile(instance, data),
}); });
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
@@ -315,8 +326,7 @@ export class ChatRouter extends RouterBroker {
request: req, request: req,
schema: profilePictureSchema, schema: profilePictureSchema,
ClassRef: ProfilePictureDto, ClassRef: ProfilePictureDto,
execute: (instance, data) => execute: (instance, data) => chatController.updateProfilePicture(instance, data),
chatController.updateProfilePicture(instance, data),
}); });
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);
@@ -333,8 +343,7 @@ export class ChatRouter extends RouterBroker {
request: req, request: req,
schema: profilePictureSchema, schema: profilePictureSchema,
ClassRef: ProfilePictureDto, ClassRef: ProfilePictureDto,
execute: (instance, data) => execute: (instance) => chatController.removeProfilePicture(instance),
chatController.removeProfilePicture(instance, data),
}); });
return res.status(HttpStatus.OK).json(response); return res.status(HttpStatus.OK).json(response);

View File

@@ -0,0 +1,69 @@
import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
import { chatwootSchema, instanceNameSchema } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router';
import { ChatwootDto } from '../dto/chatwoot.dto';
import { InstanceDto } from '../dto/instance.dto';
// import { ChatwootService } from '../services/chatwoot.service';
import { chatwootController } from '../whatsapp.module';
import { HttpStatus } from './index.router';
const logger = new Logger('ChatwootRouter');
export class ChatwootRouter extends RouterBroker {
constructor(...guards: RequestHandler[]) {
super();
this.router
.post(this.routerPath('set'), ...guards, async (req, res) => {
logger.verbose('request received in setChatwoot');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<ChatwootDto>({
request: req,
schema: chatwootSchema,
ClassRef: ChatwootDto,
execute: (instance, data) => chatwootController.createChatwoot(instance, data),
});
res.status(HttpStatus.CREATED).json(response);
})
.get(this.routerPath('find'), ...guards, async (req, res) => {
logger.verbose('request received in findChatwoot');
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: instanceNameSchema,
ClassRef: InstanceDto,
execute: (instance) => chatwootController.findChatwoot(instance),
});
res.status(HttpStatus.OK).json(response);
})
.post(this.routerPath('webhook'), async (req, res) => {
logger.verbose('request received in findChatwoot');
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: instanceNameSchema,
ClassRef: InstanceDto,
execute: (instance, data) => chatwootController.receiveWebhook(instance, data),
});
res.status(HttpStatus.OK).json(response);
});
}
public readonly router = Router();
}

View File

@@ -1,32 +1,35 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
import { import {
createGroupSchema, createGroupSchema,
getParticipantsSchema,
groupInviteSchema,
groupJidSchema, groupJidSchema,
updateParticipantsSchema, groupSendInviteSchema,
updateSettingsSchema,
toggleEphemeralSchema, toggleEphemeralSchema,
updateGroupDescriptionSchema,
updateGroupPictureSchema, updateGroupPictureSchema,
updateGroupSubjectSchema, updateGroupSubjectSchema,
updateGroupDescriptionSchema, updateParticipantsSchema,
groupInviteSchema, updateSettingsSchema,
groupSendInviteSchema,
} from '../../validate/validate.schema'; } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router'; import { RouterBroker } from '../abstract/abstract.router';
import { import {
CreateGroupDto, CreateGroupDto,
GetParticipant,
GroupDescriptionDto,
GroupInvite, GroupInvite,
GroupJid, GroupJid,
GroupPictureDto, GroupPictureDto,
GroupSendInvite,
GroupSubjectDto, GroupSubjectDto,
GroupDescriptionDto, GroupToggleEphemeralDto,
GroupUpdateParticipantDto, GroupUpdateParticipantDto,
GroupUpdateSettingDto, GroupUpdateSettingDto,
GroupToggleEphemeralDto,
GroupSendInvite,
} from '../dto/group.dto'; } from '../dto/group.dto';
import { groupController } from '../whatsapp.module'; import { groupController } from '../whatsapp.module';
import { HttpStatus } from './index.router'; import { HttpStatus } from './index.router';
import { Logger } from '../../config/logger.config';
const logger = new Logger('GroupRouter'); const logger = new Logger('GroupRouter');
@@ -94,8 +97,7 @@ export class GroupRouter extends RouterBroker {
request: req, request: req,
schema: updateGroupDescriptionSchema, schema: updateGroupDescriptionSchema,
ClassRef: GroupDescriptionDto, ClassRef: GroupDescriptionDto,
execute: (instance, data) => execute: (instance, data) => groupController.updateGroupDescription(instance, data),
groupController.updateGroupDescription(instance, data),
}); });
res.status(HttpStatus.CREATED).json(response); res.status(HttpStatus.CREATED).json(response);
@@ -123,11 +125,11 @@ export class GroupRouter extends RouterBroker {
logger.verbose('request query: '); logger.verbose('request query: ');
logger.verbose(req.query); logger.verbose(req.query);
const response = await this.groupNoValidate<GroupJid>({ const response = await this.getParticipantsValidate<GetParticipant>({
request: req, request: req,
schema: {}, schema: getParticipantsSchema,
ClassRef: GroupJid, ClassRef: GetParticipant,
execute: (instance) => groupController.fetchAllGroups(instance), execute: (instance, data) => groupController.fetchAllGroups(instance, data),
}); });
res.status(HttpStatus.OK).json(response); res.status(HttpStatus.OK).json(response);

View File

@@ -1,11 +1,15 @@
import { Router } from 'express'; import { Router } from 'express';
import fs from 'fs';
import { Auth, configService } from '../../config/env.config'; import { Auth, configService } from '../../config/env.config';
import { instanceExistsGuard, instanceLoggedGuard } from '../guards/instance.guard';
import { authGuard } from '../guards/auth.guard'; import { authGuard } from '../guards/auth.guard';
import { instanceExistsGuard, instanceLoggedGuard } from '../guards/instance.guard';
import { ChatRouter } from './chat.router'; import { ChatRouter } from './chat.router';
import { ChatwootRouter } from './chatwoot.router';
import { GroupRouter } from './group.router'; import { GroupRouter } from './group.router';
import { InstanceRouter } from './instance.router'; import { InstanceRouter } from './instance.router';
import { MessageRouter } from './sendMessage.router'; import { MessageRouter } from './sendMessage.router';
import { SettingsRouter } from './settings.router';
import { ViewsRouter } from './view.router'; import { ViewsRouter } from './view.router';
import { WebhookRouter } from './webhook.router'; import { WebhookRouter } from './webhook.router';
@@ -23,15 +27,22 @@ const router = Router();
const authType = configService.get<Auth>('AUTHENTICATION').TYPE; const authType = configService.get<Auth>('AUTHENTICATION').TYPE;
const guards = [instanceExistsGuard, instanceLoggedGuard, authGuard[authType]]; const guards = [instanceExistsGuard, instanceLoggedGuard, authGuard[authType]];
const packageJson = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
router router
.use( .get('/', (req, res) => {
'/instance', res.status(HttpStatus.OK).json({
new InstanceRouter(configService, ...guards).router, status: HttpStatus.OK,
new ViewsRouter(instanceExistsGuard).router, message: 'Welcome to the Evolution API, it is working!',
) version: packageJson.version,
});
})
.use('/instance', new InstanceRouter(configService, ...guards).router, new ViewsRouter(instanceExistsGuard).router)
.use('/message', new MessageRouter(...guards).router) .use('/message', new MessageRouter(...guards).router)
.use('/chat', new ChatRouter(...guards).router) .use('/chat', new ChatRouter(...guards).router)
.use('/group', new GroupRouter(...guards).router) .use('/group', new GroupRouter(...guards).router)
.use('/webhook', new WebhookRouter(...guards).router); .use('/webhook', new WebhookRouter(...guards).router)
.use('/chatwoot', new ChatwootRouter(...guards).router)
.use('/settings', new SettingsRouter(...guards).router);
export { router, HttpStatus }; export { HttpStatus, router };

View File

@@ -1,13 +1,14 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { instanceNameSchema, oldTokenSchema } from '../../validate/validate.schema';
import { InstanceDto } from '../dto/instance.dto';
import { instanceController } from '../whatsapp.module';
import { RouterBroker } from '../abstract/abstract.router';
import { HttpStatus } from './index.router';
import { OldToken } from '../services/auth.service';
import { Auth, ConfigService, Database } from '../../config/env.config'; import { Auth, ConfigService, Database } from '../../config/env.config';
import { dbserver } from '../../db/db.connect';
import { Logger } from '../../config/logger.config'; import { Logger } from '../../config/logger.config';
import { dbserver } from '../../db/db.connect';
import { instanceNameSchema, oldTokenSchema } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router';
import { InstanceDto } from '../dto/instance.dto';
import { OldToken } from '../services/auth.service';
import { instanceController } from '../whatsapp.module';
import { HttpStatus } from './index.router';
const logger = new Logger('InstanceRouter'); const logger = new Logger('InstanceRouter');
@@ -23,6 +24,7 @@ export class InstanceRouter extends RouterBroker {
logger.verbose('request query: '); logger.verbose('request query: ');
logger.verbose(req.query); logger.verbose(req.query);
const response = await this.dataValidate<InstanceDto>({ const response = await this.dataValidate<InstanceDto>({
request: req, request: req,
schema: instanceNameSchema, schema: instanceNameSchema,
@@ -159,19 +161,13 @@ export class InstanceRouter extends RouterBroker {
if (db.ENABLED) { if (db.ENABLED) {
try { try {
await dbserver.dropDatabase(); await dbserver.dropDatabase();
return res return res.status(HttpStatus.CREATED).json({ error: false, message: 'Database deleted' });
.status(HttpStatus.CREATED)
.json({ error: false, message: 'Database deleted' });
} catch (error) { } catch (error) {
return res return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ error: true, message: error.message });
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ error: true, message: error.message });
} }
} }
return res return res.status(HttpStatus.INTERNAL_SERVER_ERROR).json({ error: true, message: 'Database is not enabled' });
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.json({ error: true, message: 'Database is not enabled' });
}); });
} }

View File

@@ -1,9 +1,10 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
import { import {
audioMessageSchema, audioMessageSchema,
buttonMessageSchema, buttonMessageSchema,
contactMessageSchema, contactMessageSchema,
linkPreviewSchema,
listMessageSchema, listMessageSchema,
locationMessageSchema, locationMessageSchema,
mediaMessageSchema, mediaMessageSchema,
@@ -13,11 +14,11 @@ import {
stickerMessageSchema, stickerMessageSchema,
textMessageSchema, textMessageSchema,
} from '../../validate/validate.schema'; } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router';
import { import {
SendAudioDto, SendAudioDto,
SendButtonDto, SendButtonDto,
SendContactDto, SendContactDto,
SendLinkPreviewDto,
SendListDto, SendListDto,
SendLocationDto, SendLocationDto,
SendMediaDto, SendMediaDto,
@@ -28,9 +29,7 @@ import {
SendTextDto, SendTextDto,
} from '../dto/sendMessage.dto'; } from '../dto/sendMessage.dto';
import { sendMessageController } from '../whatsapp.module'; import { sendMessageController } from '../whatsapp.module';
import { RouterBroker } from '../abstract/abstract.router';
import { HttpStatus } from './index.router'; import { HttpStatus } from './index.router';
import { Logger } from '../../config/logger.config';
const logger = new Logger('MessageRouter'); const logger = new Logger('MessageRouter');
@@ -81,8 +80,7 @@ export class MessageRouter extends RouterBroker {
request: req, request: req,
schema: audioMessageSchema, schema: audioMessageSchema,
ClassRef: SendMediaDto, ClassRef: SendMediaDto,
execute: (instance, data) => execute: (instance, data) => sendMessageController.sendWhatsAppAudio(instance, data),
sendMessageController.sendWhatsAppAudio(instance, data),
}); });
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
@@ -199,23 +197,6 @@ export class MessageRouter extends RouterBroker {
return res.status(HttpStatus.CREATED).json(response); return res.status(HttpStatus.CREATED).json(response);
}) })
.post(this.routerPath('sendLinkPreview'), ...guards, async (req, res) => {
logger.verbose('request received in sendLinkPreview');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<SendLinkPreviewDto>({
request: req,
schema: linkPreviewSchema,
ClassRef: SendLinkPreviewDto,
execute: (instance, data) =>
sendMessageController.sendLinkPreview(instance, data),
});
return res.status(HttpStatus.CREATED).json(response);
})
.post(this.routerPath('sendSticker'), ...guards, async (req, res) => { .post(this.routerPath('sendSticker'), ...guards, async (req, res) => {
logger.verbose('request received in sendSticker'); logger.verbose('request received in sendSticker');
logger.verbose('request body: '); logger.verbose('request body: ');

View File

@@ -0,0 +1,53 @@
import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
import { instanceNameSchema, settingsSchema } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router';
import { InstanceDto } from '../dto/instance.dto';
import { SettingsDto } from '../dto/settings.dto';
// import { SettingsService } from '../services/settings.service';
import { settingsController } from '../whatsapp.module';
import { HttpStatus } from './index.router';
const logger = new Logger('SettingsRouter');
export class SettingsRouter extends RouterBroker {
constructor(...guards: RequestHandler[]) {
super();
this.router
.post(this.routerPath('set'), ...guards, async (req, res) => {
logger.verbose('request received in setSettings');
logger.verbose('request body: ');
logger.verbose(req.body);
logger.verbose('request query: ');
logger.verbose(req.query);
const response = await this.dataValidate<SettingsDto>({
request: req,
schema: settingsSchema,
ClassRef: SettingsDto,
execute: (instance, data) => settingsController.createSettings(instance, data),
});
res.status(HttpStatus.CREATED).json(response);
})
.get(this.routerPath('find'), ...guards, async (req, res) => {
logger.verbose('request received in findSettings');
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: instanceNameSchema,
ClassRef: InstanceDto,
execute: (instance) => settingsController.findSettings(instance),
});
res.status(HttpStatus.OK).json(response);
});
}
public readonly router = Router();
}

View File

@@ -1,4 +1,5 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { RouterBroker } from '../abstract/abstract.router'; import { RouterBroker } from '../abstract/abstract.router';
import { viewsController } from '../whatsapp.module'; import { viewsController } from '../whatsapp.module';

View File

@@ -1,11 +1,12 @@
import { RequestHandler, Router } from 'express'; import { RequestHandler, Router } from 'express';
import { Logger } from '../../config/logger.config';
import { instanceNameSchema, webhookSchema } from '../../validate/validate.schema'; import { instanceNameSchema, webhookSchema } from '../../validate/validate.schema';
import { RouterBroker } from '../abstract/abstract.router'; import { RouterBroker } from '../abstract/abstract.router';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { WebhookDto } from '../dto/webhook.dto'; import { WebhookDto } from '../dto/webhook.dto';
import { webhookController } from '../whatsapp.module'; import { webhookController } from '../whatsapp.module';
import { HttpStatus } from './index.router'; import { HttpStatus } from './index.router';
import { Logger } from '../../config/logger.config';
const logger = new Logger('WebhookRouter'); const logger = new Logger('WebhookRouter');

View File

@@ -1,14 +1,15 @@
import { Auth, ConfigService, Webhook } from '../../config/env.config';
import { InstanceDto } from '../dto/instance.dto';
import { name as apiName } from '../../../package.json';
import { verify, sign } from 'jsonwebtoken';
import { Logger } from '../../config/logger.config';
import { v4 } from 'uuid';
import { isJWT } from 'class-validator';
import { BadRequestException } from '../../exceptions';
import axios from 'axios'; import axios from 'axios';
import { WAMonitoringService } from './monitor.service'; import { isJWT } from 'class-validator';
import { sign, verify } from 'jsonwebtoken';
import { v4 } from 'uuid';
import { name as apiName } from '../../../package.json';
import { Auth, ConfigService, Webhook } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { BadRequestException } from '../../exceptions';
import { InstanceDto } from '../dto/instance.dto';
import { RepositoryBroker } from '../repository/repository.manager'; import { RepositoryBroker } from '../repository/repository.manager';
import { WAMonitoringService } from './monitor.service';
export type JwtPayload = { export type JwtPayload = {
instanceName: string; instanceName: string;
@@ -63,9 +64,7 @@ export class AuthService {
private async apikey(instance: InstanceDto, token?: string) { private async apikey(instance: InstanceDto, token?: string) {
const apikey = token ? token : v4().toUpperCase(); const apikey = token ? token : v4().toUpperCase();
this.logger.verbose( this.logger.verbose(token ? 'APIKEY defined: ' + apikey : 'APIKEY created: ' + apikey);
token ? 'APIKEY defined: ' + apikey : 'APIKEY created: ' + apikey,
);
const auth = await this.repository.auth.create({ apikey }, instance.instanceName); const auth = await this.repository.auth.create({ apikey }, instance.instanceName);
@@ -101,13 +100,9 @@ export class AuthService {
public async generateHash(instance: InstanceDto, token?: string) { public async generateHash(instance: InstanceDto, token?: string) {
const options = this.configService.get<Auth>('AUTHENTICATION'); const options = this.configService.get<Auth>('AUTHENTICATION');
this.logger.verbose( this.logger.verbose('generating hash ' + options.TYPE + ' to instance: ' + instance.instanceName);
'generating hash ' + options.TYPE + ' to instance: ' + instance.instanceName,
);
return (await this[options.TYPE](instance, token)) as return (await this[options.TYPE](instance, token)) as { jwt: string } | { apikey: string };
| { jwt: string }
| { apikey: string };
} }
public async refreshToken({ oldToken }: OldToken) { public async refreshToken({ oldToken }: OldToken) {
@@ -150,10 +145,7 @@ export class AuthService {
try { try {
this.logger.verbose('checking webhook'); this.logger.verbose('checking webhook');
const webhook = await this.repository.webhook.find(decode.instanceName); const webhook = await this.repository.webhook.find(decode.instanceName);
if ( if (webhook?.enabled && this.configService.get<Webhook>('WEBHOOK').EVENTS.NEW_JWT_TOKEN) {
webhook?.enabled &&
this.configService.get<Webhook>('WEBHOOK').EVENTS.NEW_JWT_TOKEN
) {
this.logger.verbose('sending webhook'); this.logger.verbose('sending webhook');
const httpService = axios.create({ baseURL: webhook.url }); const httpService = axios.create({ baseURL: webhook.url });

File diff suppressed because it is too large Load Diff

View File

@@ -1,22 +1,26 @@
import { opendirSync, readdirSync, rmSync } from 'fs';
import { WAStartupService } from './whatsapp.service';
import { INSTANCE_DIR, STORE_DIR } from '../../config/path.config';
import EventEmitter2 from 'eventemitter2';
import { join } from 'path';
import { Logger } from '../../config/logger.config';
import {
Auth,
ConfigService,
Database,
DelInstance,
Redis,
} from '../../config/env.config';
import { RepositoryBroker } from '../repository/repository.manager';
import { NotFoundException } from '../../exceptions';
import { Db } from 'mongodb';
import { initInstance } from '../whatsapp.module';
import { RedisCache } from '../../db/redis.client';
import { execSync } from 'child_process'; import { execSync } from 'child_process';
import EventEmitter2 from 'eventemitter2';
import { opendirSync, readdirSync, rmSync } from 'fs';
import { Db } from 'mongodb';
import { join } from 'path';
import { Auth, ConfigService, Database, DelInstance, HttpServer, Redis } from '../../config/env.config';
import { Logger } from '../../config/logger.config';
import { INSTANCE_DIR, STORE_DIR } from '../../config/path.config';
import { dbserver } from '../../db/db.connect';
import { RedisCache } from '../../db/redis.client';
import { NotFoundException } from '../../exceptions';
import {
AuthModel,
ChatwootModel,
ContactModel,
MessageModel,
MessageUpModel,
SettingsModel,
WebhookModel,
} from '../models';
import { RepositoryBroker } from '../repository/repository.manager';
import { WAStartupService } from './whatsapp.service';
export class WAMonitoringService { export class WAMonitoringService {
constructor( constructor(
@@ -44,22 +48,20 @@ export class WAMonitoringService {
private dbInstance: Db; private dbInstance: Db;
private dbStore = dbserver;
private readonly logger = new Logger(WAMonitoringService.name); private readonly logger = new Logger(WAMonitoringService.name);
public readonly waInstances: Record<string, WAStartupService> = {}; public readonly waInstances: Record<string, WAStartupService> = {};
public delInstanceTime(instance: string) { public delInstanceTime(instance: string) {
const time = this.configService.get<DelInstance>('DEL_INSTANCE'); const time = this.configService.get<DelInstance>('DEL_INSTANCE');
if (typeof time === 'number' && time > 0) { if (typeof time === 'number' && time > 0) {
this.logger.verbose( this.logger.verbose(`Instance "${instance}" don't have connection, will be removed in ${time} minutes`);
`Instance "${instance}" don't have connection, will be removed in ${time} minutes`,
);
setTimeout(async () => { setTimeout(async () => {
if (this.waInstances[instance]?.connectionStatus?.state !== 'open') { if (this.waInstances[instance]?.connectionStatus?.state !== 'open') {
if (this.waInstances[instance]?.connectionStatus?.state === 'connecting') { if (this.waInstances[instance]?.connectionStatus?.state === 'connecting') {
await this.waInstances[instance]?.client?.logout( await this.waInstances[instance]?.client?.logout('Log out instance: ' + instance);
'Log out instance: ' + instance,
);
this.waInstances[instance]?.client?.ws?.close(); this.waInstances[instance]?.client?.ws?.close();
this.waInstances[instance]?.client?.end(undefined); this.waInstances[instance]?.client?.end(undefined);
delete this.waInstances[instance]; delete this.waInstances[instance];
@@ -83,70 +85,61 @@ export class WAMonitoringService {
for await (const [key, value] of Object.entries(this.waInstances)) { for await (const [key, value] of Object.entries(this.waInstances)) {
if (value) { if (value) {
this.logger.verbose('get instance info: ' + key); this.logger.verbose('get instance info: ' + key);
let chatwoot: any;
const urlServer = this.configService.get<HttpServer>('SERVER').URL;
const findChatwoot = await this.waInstances[key].findChatwoot();
if (findChatwoot && findChatwoot.enabled) {
chatwoot = {
...findChatwoot,
webhook_url: `${urlServer}/chatwoot/webhook/${key}`,
};
}
if (value.connectionStatus.state === 'open') { if (value.connectionStatus.state === 'open') {
this.logger.verbose('instance: ' + key + ' - connectionStatus: open'); this.logger.verbose('instance: ' + key + ' - connectionStatus: open');
let apikey: string;
if (this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES) {
this.logger.verbose(
'instance: ' + key + ' - hash exposed in fetch instances',
);
const tokenStore = await this.repository.auth.find(key);
apikey = tokenStore.apikey || 'Apikey not found';
instances.push({ const instanceData = {
instance: { instance: {
instanceName: key, instanceName: key,
owner: value.wuid, owner: value.wuid,
profileName: (await value.getProfileName()) || 'not loaded', profileName: (await value.getProfileName()) || 'not loaded',
profilePictureUrl: value.profilePictureUrl, profilePictureUrl: value.profilePictureUrl,
status: (await value.getProfileStatus()) || '', profileStatus: (await value.getProfileStatus()) || '',
apikey, status: value.connectionStatus.state,
}, },
}); };
} else {
this.logger.verbose( if (this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES) {
'instance: ' + key + ' - hash not exposed in fetch instances', instanceData.instance['serverUrl'] = this.configService.get<HttpServer>('SERVER').URL;
);
instances.push({ instanceData.instance['apikey'] = (await this.repository.auth.find(key)).apikey;
instance: {
instanceName: key, instanceData.instance['chatwoot'] = chatwoot;
owner: value.wuid,
profileName: (await value.getProfileName()) || 'not loaded',
profilePictureUrl: value.profilePictureUrl,
status: (await value.getProfileStatus()) || '',
},
});
} }
instances.push(instanceData);
} else { } else {
this.logger.verbose( this.logger.verbose('instance: ' + key + ' - connectionStatus: ' + value.connectionStatus.state);
'instance: ' + key + ' - connectionStatus: ' + value.connectionStatus.state,
);
let apikey: string;
if (this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES) {
this.logger.verbose(
'instance: ' + key + ' - hash exposed in fetch instances',
);
const tokenStore = await this.repository.auth.find(key);
apikey = tokenStore.apikey || 'Apikey not found';
instances.push({ const instanceData = {
instance: { instance: {
instanceName: key, instanceName: key,
status: value.connectionStatus.state, status: value.connectionStatus.state,
apikey, },
}, };
});
} else { if (this.configService.get<Auth>('AUTHENTICATION').EXPOSE_IN_FETCH_INSTANCES) {
this.logger.verbose( instanceData.instance['serverUrl'] = this.configService.get<HttpServer>('SERVER').URL;
'instance: ' + key + ' - hash not exposed in fetch instances',
); instanceData.instance['apikey'] = (await this.repository.auth.find(key)).apikey;
instances.push({
instance: { instanceData.instance['chatwoot'] = chatwoot;
instanceName: key,
status: value.connectionStatus.state,
},
});
} }
instances.push(instanceData);
} }
} }
} }
@@ -164,14 +157,11 @@ export class WAMonitoringService {
collections.forEach(async (collection) => { collections.forEach(async (collection) => {
const name = collection.namespace.replace(/^[\w-]+./, ''); const name = collection.namespace.replace(/^[\w-]+./, '');
await this.dbInstance.collection(name).deleteMany({ await this.dbInstance.collection(name).deleteMany({
$or: [ $or: [{ _id: { $regex: /^app.state.*/ } }, { _id: { $regex: /^session-.*/ } }],
{ _id: { $regex: /^app.state.*/ } },
{ _id: { $regex: /^session-.*/ } },
],
}); });
this.logger.verbose('instance files deleted: ' + name); this.logger.verbose('instance files deleted: ' + name);
}); });
} else if (this.redis.ENABLED) { // } else if (this.redis.ENABLED) {
} else { } else {
const dir = opendirSync(INSTANCE_DIR, { encoding: 'utf-8' }); const dir = opendirSync(INSTANCE_DIR, { encoding: 'utf-8' });
for await (const dirent of dir) { for await (const dirent of dir) {
@@ -218,11 +208,8 @@ export class WAMonitoringService {
} }
public async cleaningStoreFiles(instanceName: string) { public async cleaningStoreFiles(instanceName: string) {
this.logger.verbose('cleaning store files instance: ' + instanceName);
if (!this.db.ENABLED) { if (!this.db.ENABLED) {
const instance = this.waInstances[instanceName]; this.logger.verbose('cleaning store files instance: ' + instanceName);
rmSync(join(INSTANCE_DIR, instanceName), { recursive: true, force: true }); rmSync(join(INSTANCE_DIR, instanceName), { recursive: true, force: true });
execSync(`rm -rf ${join(STORE_DIR, 'chats', instanceName)}`); execSync(`rm -rf ${join(STORE_DIR, 'chats', instanceName)}`);
@@ -232,18 +219,30 @@ export class WAMonitoringService {
execSync(`rm -rf ${join(STORE_DIR, 'auth', 'apikey', instanceName + '.json')}`); execSync(`rm -rf ${join(STORE_DIR, 'auth', 'apikey', instanceName + '.json')}`);
execSync(`rm -rf ${join(STORE_DIR, 'webhook', instanceName + '.json')}`); execSync(`rm -rf ${join(STORE_DIR, 'webhook', instanceName + '.json')}`);
execSync(`rm -rf ${join(STORE_DIR, 'chatwoot', instanceName + '*')}`);
execSync(`rm -rf ${join(STORE_DIR, 'settings', instanceName + '*')}`);
return;
} }
this.logger.verbose('cleaning store database instance: ' + instanceName);
await AuthModel.deleteMany({ owner: instanceName });
await ContactModel.deleteMany({ owner: instanceName });
await MessageModel.deleteMany({ owner: instanceName });
await MessageUpModel.deleteMany({ owner: instanceName });
await AuthModel.deleteMany({ _id: instanceName });
await WebhookModel.deleteMany({ _id: instanceName });
await ChatwootModel.deleteMany({ _id: instanceName });
await SettingsModel.deleteMany({ _id: instanceName });
return;
} }
public async loadInstance() { public async loadInstance() {
this.logger.verbose('load instances'); this.logger.verbose('load instances');
const set = async (name: string) => { const set = async (name: string) => {
const instance = new WAStartupService( const instance = new WAStartupService(this.configService, this.eventEmitter, this.repository, this.cache);
this.configService,
this.eventEmitter,
this.repository,
this.cache,
);
instance.instanceName = name; instance.instanceName = name;
this.logger.verbose('instance loaded: ' + name); this.logger.verbose('instance loaded: ' + name);
@@ -263,7 +262,6 @@ export class WAMonitoringService {
keys.forEach(async (k) => await set(k.split(':')[1])); keys.forEach(async (k) => await set(k.split(':')[1]));
} else { } else {
this.logger.verbose('no instance keys found'); this.logger.verbose('no instance keys found');
initInstance();
} }
return; return;
} }
@@ -274,12 +272,9 @@ export class WAMonitoringService {
const collections: any[] = await this.dbInstance.collections(); const collections: any[] = await this.dbInstance.collections();
if (collections.length > 0) { if (collections.length > 0) {
this.logger.verbose('reading collections and setting instances'); this.logger.verbose('reading collections and setting instances');
collections.forEach( collections.forEach(async (coll) => await set(coll.namespace.replace(/^[\w-]+\./, '')));
async (coll) => await set(coll.namespace.replace(/^[\w-]+\./, '')),
);
} else { } else {
this.logger.verbose('no collections found'); this.logger.verbose('no collections found');
initInstance();
} }
return; return;
} }
@@ -300,7 +295,6 @@ export class WAMonitoringService {
await set(dirent.name); await set(dirent.name);
} else { } else {
this.logger.verbose('no instance files found'); this.logger.verbose('no instance files found');
initInstance();
} }
} }
} catch (error) { } catch (error) {
@@ -314,7 +308,9 @@ export class WAMonitoringService {
try { try {
this.logger.verbose('instance: ' + instanceName + ' - removing from memory'); this.logger.verbose('instance: ' + instanceName + ' - removing from memory');
this.waInstances[instanceName] = undefined; this.waInstances[instanceName] = undefined;
} catch {} } catch (error) {
this.logger.error(error);
}
try { try {
this.logger.verbose('request cleaning up instance: ' + instanceName); this.logger.verbose('request cleaning up instance: ' + instanceName);

View File

@@ -0,0 +1,32 @@
import { Logger } from '../../config/logger.config';
import { InstanceDto } from '../dto/instance.dto';
import { SettingsDto } from '../dto/settings.dto';
import { WAMonitoringService } from './monitor.service';
export class SettingsService {
constructor(private readonly waMonitor: WAMonitoringService) {}
private readonly logger = new Logger(SettingsService.name);
public create(instance: InstanceDto, data: SettingsDto) {
this.logger.verbose('create settings: ' + instance.instanceName);
this.waMonitor.waInstances[instance.instanceName].setSettings(data);
return { settings: { ...instance, settings: data } };
}
public async find(instance: InstanceDto): Promise<SettingsDto> {
try {
this.logger.verbose('find settings: ' + instance.instanceName);
const result = await this.waMonitor.waInstances[instance.instanceName].findSettings();
if (Object.keys(result).length === 0) {
throw new Error('Settings not found');
}
return result;
} catch (error) {
return { reject_call: false, msg_call: '', groups_ignore: false };
}
}
}

View File

@@ -1,7 +1,7 @@
import { Logger } from '../../config/logger.config';
import { InstanceDto } from '../dto/instance.dto'; import { InstanceDto } from '../dto/instance.dto';
import { WebhookDto } from '../dto/webhook.dto'; import { WebhookDto } from '../dto/webhook.dto';
import { WAMonitoringService } from './monitor.service'; import { WAMonitoringService } from './monitor.service';
import { Logger } from '../../config/logger.config';
export class WebhookService { export class WebhookService {
constructor(private readonly waMonitor: WAMonitoringService) {} constructor(private readonly waMonitor: WAMonitoringService) {}
@@ -18,9 +18,15 @@ export class WebhookService {
public async find(instance: InstanceDto): Promise<WebhookDto> { public async find(instance: InstanceDto): Promise<WebhookDto> {
try { try {
this.logger.verbose('find webhook: ' + instance.instanceName); this.logger.verbose('find webhook: ' + instance.instanceName);
return await this.waMonitor.waInstances[instance.instanceName].findWebhook(); const result = await this.waMonitor.waInstances[instance.instanceName].findWebhook();
if (Object.keys(result).length === 0) {
throw new Error('Webhook not found');
}
return result;
} catch (error) { } catch (error) {
return { enabled: null, url: '' }; return { enabled: false, url: '', events: [], webhook_by_events: false };
} }
} }
} }

File diff suppressed because it is too large Load Diff

View File

@@ -6,10 +6,11 @@ export enum Events {
QRCODE_UPDATED = 'qrcode.updated', QRCODE_UPDATED = 'qrcode.updated',
CONNECTION_UPDATE = 'connection.update', CONNECTION_UPDATE = 'connection.update',
STATUS_INSTANCE = 'status.instance', STATUS_INSTANCE = 'status.instance',
SEND_MESSAGE = 'send.message',
MESSAGES_SET = 'messages.set', MESSAGES_SET = 'messages.set',
MESSAGES_UPSERT = 'messages.upsert', MESSAGES_UPSERT = 'messages.upsert',
MESSAGES_UPDATE = 'messages.update', MESSAGES_UPDATE = 'messages.update',
MESSAGES_DELETE = 'messages.delete',
SEND_MESSAGE = 'send.message',
CONTACTS_SET = 'contacts.set', CONTACTS_SET = 'contacts.set',
CONTACTS_UPSERT = 'contacts.upsert', CONTACTS_UPSERT = 'contacts.upsert',
CONTACTS_UPDATE = 'contacts.update', CONTACTS_UPDATE = 'contacts.update',
@@ -21,12 +22,19 @@ export enum Events {
GROUPS_UPSERT = 'groups.upsert', GROUPS_UPSERT = 'groups.upsert',
GROUPS_UPDATE = 'groups.update', GROUPS_UPDATE = 'groups.update',
GROUP_PARTICIPANTS_UPDATE = 'group-participants.update', GROUP_PARTICIPANTS_UPDATE = 'group-participants.update',
CALL = 'call',
} }
export declare namespace wa { export declare namespace wa {
export type QrCode = { count?: number; base64?: string; code?: string }; export type QrCode = {
count?: number;
pairingCode?: string;
base64?: string;
code?: string;
};
export type Instance = { export type Instance = {
qrcode?: QrCode; qrcode?: QrCode;
pairingCode?: string;
authState?: { state: AuthenticationState; saveCreds: () => void }; authState?: { state: AuthenticationState; saveCreds: () => void };
name?: string; name?: string;
wuid?: string; wuid?: string;
@@ -41,28 +49,37 @@ export declare namespace wa {
webhook_by_events?: boolean; webhook_by_events?: boolean;
}; };
export type LocalChatwoot = {
enabled?: boolean;
account_id?: string;
token?: string;
url?: string;
name_inbox?: string;
sign_msg?: boolean;
number?: string;
reopen_conversation?: boolean;
conversation_pending?: boolean;
};
export type LocalSettings = {
reject_call?: boolean;
msg_call?: string;
groups_ignore?: boolean;
always_online?: boolean;
read_messages?: boolean;
read_status?: boolean;
};
export type StateConnection = { export type StateConnection = {
instance?: string; instance?: string;
state?: WAConnectionState | 'refused'; state?: WAConnectionState | 'refused';
statusReason?: number; statusReason?: number;
}; };
export type StatusMessage = export type StatusMessage = 'ERROR' | 'PENDING' | 'SERVER_ACK' | 'DELIVERY_ACK' | 'READ' | 'DELETED' | 'PLAYED';
| 'ERROR'
| 'PENDING'
| 'SERVER_ACK'
| 'DELIVERY_ACK'
| 'READ'
| 'PLAYED';
} }
export const TypeMediaMessage = [ export const TypeMediaMessage = ['imageMessage', 'documentMessage', 'audioMessage', 'videoMessage', 'stickerMessage'];
'imageMessage',
'documentMessage',
'audioMessage',
'videoMessage',
'stickerMessage',
];
export const MessageSubtype = [ export const MessageSubtype = [
'ephemeralMessage', 'ephemeralMessage',

View File

@@ -1,35 +1,40 @@
import { Auth, configService } from '../config/env.config'; import { configService } from '../config/env.config';
import { Logger } from '../config/logger.config';
import { eventEmitter } from '../config/event.config'; import { eventEmitter } from '../config/event.config';
import { MessageRepository } from './repository/message.repository'; import { Logger } from '../config/logger.config';
import { WAMonitoringService } from './services/monitor.service'; import { dbserver } from '../db/db.connect';
import { ChatRepository } from './repository/chat.repository'; import { RedisCache } from '../db/redis.client';
import { ContactRepository } from './repository/contact.repository';
import { MessageUpRepository } from './repository/messageUp.repository';
import { ChatController } from './controllers/chat.controller'; import { ChatController } from './controllers/chat.controller';
import { ChatwootController } from './controllers/chatwoot.controller';
import { GroupController } from './controllers/group.controller';
import { InstanceController } from './controllers/instance.controller'; import { InstanceController } from './controllers/instance.controller';
import { SendMessageController } from './controllers/sendMessage.controller'; import { SendMessageController } from './controllers/sendMessage.controller';
import { AuthService } from './services/auth.service'; import { SettingsController } from './controllers/settings.controller';
import { GroupController } from './controllers/group.controller';
import { ViewsController } from './controllers/views.controller'; import { ViewsController } from './controllers/views.controller';
import { WebhookService } from './services/webhook.service';
import { WebhookController } from './controllers/webhook.controller'; import { WebhookController } from './controllers/webhook.controller';
import { RepositoryBroker } from './repository/repository.manager';
import { import {
AuthModel, AuthModel,
ChatModel, ChatModel,
ChatwootModel,
ContactModel, ContactModel,
MessageModel, MessageModel,
MessageUpModel, MessageUpModel,
SettingsModel,
WebhookModel,
} from './models'; } from './models';
import { dbserver } from '../db/db.connect';
import { WebhookRepository } from './repository/webhook.repository';
import { WebhookModel } from './models/webhook.model';
import { AuthRepository } from './repository/auth.repository'; import { AuthRepository } from './repository/auth.repository';
import { WAStartupService } from './services/whatsapp.service'; import { ChatRepository } from './repository/chat.repository';
import { delay } from '@whiskeysockets/baileys'; import { ChatwootRepository } from './repository/chatwoot.repository';
import { Events } from './types/wa.types'; import { ContactRepository } from './repository/contact.repository';
import { RedisCache } from '../db/redis.client'; import { MessageRepository } from './repository/message.repository';
import { MessageUpRepository } from './repository/messageUp.repository';
import { RepositoryBroker } from './repository/repository.manager';
import { SettingsRepository } from './repository/settings.repository';
import { WebhookRepository } from './repository/webhook.repository';
import { AuthService } from './services/auth.service';
import { ChatwootService } from './services/chatwoot.service';
import { WAMonitoringService } from './services/monitor.service';
import { SettingsService } from './services/settings.service';
import { WebhookService } from './services/webhook.service';
const logger = new Logger('WA MODULE'); const logger = new Logger('WA MODULE');
@@ -38,6 +43,8 @@ const chatRepository = new ChatRepository(ChatModel, configService);
const contactRepository = new ContactRepository(ContactModel, configService); const contactRepository = new ContactRepository(ContactModel, configService);
const messageUpdateRepository = new MessageUpRepository(MessageUpModel, configService); const messageUpdateRepository = new MessageUpRepository(MessageUpModel, configService);
const webhookRepository = new WebhookRepository(WebhookModel, configService); const webhookRepository = new WebhookRepository(WebhookModel, configService);
const chatwootRepository = new ChatwootRepository(ChatwootModel, configService);
const settingsRepository = new SettingsRepository(SettingsModel, configService);
const authRepository = new AuthRepository(AuthModel, configService); const authRepository = new AuthRepository(AuthModel, configService);
export const repository = new RepositoryBroker( export const repository = new RepositoryBroker(
@@ -46,6 +53,8 @@ export const repository = new RepositoryBroker(
contactRepository, contactRepository,
messageUpdateRepository, messageUpdateRepository,
webhookRepository, webhookRepository,
chatwootRepository,
settingsRepository,
authRepository, authRepository,
configService, configService,
dbserver?.getClient(), dbserver?.getClient(),
@@ -53,12 +62,7 @@ export const repository = new RepositoryBroker(
export const cache = new RedisCache(); export const cache = new RedisCache();
export const waMonitor = new WAMonitoringService( export const waMonitor = new WAMonitoringService(eventEmitter, configService, repository, cache);
eventEmitter,
configService,
repository,
cache,
);
const authService = new AuthService(configService, waMonitor, repository); const authService = new AuthService(configService, waMonitor, repository);
@@ -66,6 +70,14 @@ const webhookService = new WebhookService(waMonitor);
export const webhookController = new WebhookController(webhookService); export const webhookController = new WebhookController(webhookService);
const chatwootService = new ChatwootService(waMonitor, configService);
export const chatwootController = new ChatwootController(chatwootService, configService);
const settingsService = new SettingsService(waMonitor);
export const settingsController = new SettingsController(settingsService);
export const instanceController = new InstanceController( export const instanceController = new InstanceController(
waMonitor, waMonitor,
configService, configService,
@@ -73,6 +85,8 @@ export const instanceController = new InstanceController(
eventEmitter, eventEmitter,
authService, authService,
webhookService, webhookService,
chatwootService,
settingsService,
cache, cache,
); );
export const viewsController = new ViewsController(waMonitor, configService); export const viewsController = new ViewsController(waMonitor, configService);
@@ -80,84 +94,4 @@ export const sendMessageController = new SendMessageController(waMonitor);
export const chatController = new ChatController(waMonitor); export const chatController = new ChatController(waMonitor);
export const groupController = new GroupController(waMonitor); export const groupController = new GroupController(waMonitor);
export async function initInstance() {
const instance = new WAStartupService(configService, eventEmitter, repository, cache);
const mode = configService.get<Auth>('AUTHENTICATION').INSTANCE.MODE;
logger.verbose('Sending data webhook for event: ' + Events.APPLICATION_STARTUP);
instance.sendDataWebhook(
Events.APPLICATION_STARTUP,
{
message: 'Application startup',
mode,
},
false,
);
if (mode === 'container') {
logger.verbose('Application startup in container mode');
const instanceName = configService.get<Auth>('AUTHENTICATION').INSTANCE.NAME;
logger.verbose('Instance name: ' + instanceName);
const instanceWebhook =
configService.get<Auth>('AUTHENTICATION').INSTANCE.WEBHOOK_URL;
logger.verbose('Instance webhook: ' + instanceWebhook);
instance.instanceName = instanceName;
waMonitor.waInstances[instance.instanceName] = instance;
waMonitor.delInstanceTime(instance.instanceName);
const hash = await authService.generateHash({
instanceName: instance.instanceName,
token: configService.get<Auth>('AUTHENTICATION').API_KEY.KEY,
});
logger.verbose('Hash generated: ' + hash);
if (instanceWebhook) {
logger.verbose('Creating webhook for instance: ' + instanceName);
try {
webhookService.create(instance, { enabled: true, url: instanceWebhook });
logger.verbose('Webhook created');
} catch (error) {
logger.log(error);
}
}
try {
const state = instance.connectionStatus?.state;
switch (state) {
case 'close':
await instance.connectToWhatsapp();
await delay(2000);
return instance.qrCode;
case 'connecting':
return instance.qrCode;
default:
return await this.connectionState({ instanceName });
}
} catch (error) {
logger.log(error);
}
const result = {
instance: {
instanceName: instance.instanceName,
status: 'created',
},
hash,
webhook: instanceWebhook,
};
logger.info(result);
return result;
}
return null;
}
logger.info('Module - ON'); logger.info('Module - ON');

View File

@@ -6,6 +6,7 @@ then
echo "DOCKER_ENV=$DOCKER_ENV" echo "DOCKER_ENV=$DOCKER_ENV"
echo echo
else else
mkdir -p ./dist/src
cp ./src/env.yml ./dist/src cp ./src/env.yml ./dist/src
fi fi
echo "> removing dist" echo "> removing dist"