Skip to content

Commit

Permalink
Whatsapp API Dashboard Completed
Browse files Browse the repository at this point in the history
  • Loading branch information
keyurboss committed Apr 15, 2024
1 parent b0e245c commit 58f0da0
Show file tree
Hide file tree
Showing 6 changed files with 58 additions and 145 deletions.
3 changes: 2 additions & 1 deletion .env_template
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
APP_ENV="LOCAL"
# APP_ENV="PRODUCTION"
# "LOCAL" || "PRODUCTION" || "CI"
PORT="4000"
PORT="4000"
ALLOW_LOCAL_NO_AUTH="true"
11 changes: 11 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [

{
"name": "Run Main",
"type": "go",
Expand All @@ -13,6 +14,16 @@
"--dev"
],
"program": "${workspaceFolder}/main.go"
},
{
"name": "Jwelly Main",
"type": "go",
"request": "launch",
"mode": "auto",
"args": [
"--dev"
],
"program": "${workspaceFolder}/jwelly/main.go"
}
]
}
4 changes: 2 additions & 2 deletions apis/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,12 +94,12 @@ func SendMediaFile(c *fiber.Ctx) error {
runHeadLess = false
}
if runHeadLess {
go connection.SendMediaFile(body.To, destination, file.Filename, body.Msg)
go connection.SendMediaFileWithPath(body.To, destination, file.Filename, body.Msg)
return c.JSON(fiber.Map{
"success": true,
})
} else {
return c.JSON(connection.SendMediaFile(body.To, destination, file.Filename, body.Msg))
return c.JSON(connection.SendMediaFileWithPath(body.To, destination, file.Filename, body.Msg))
}
}
func SendMediaFileWithBase64(c *fiber.Ctx) error {
Expand Down
51 changes: 34 additions & 17 deletions jwelly/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,13 @@ func ReadConfigFileAndReturnIt(currentDir string) *JwellyWhatsappConfig {
panic(fmt.Errorf("failed to read config file: %w", err))
}
config := &JwellyWhatsappConfig{}
_, err = fmt.Sscanln(string(dat), &config.ServerUrl, &config.DoNotWaitForResponse)
if err != nil {
panic(fmt.Errorf("failed to parse config file: %w", err))
dataArray := strings.Split(string(dat), "\n")
if len(dataArray) < 2 {
panic(fmt.Errorf("expected dataArray to have length 2, got %d", len(dataArray)))
}
config.ServerUrl = strings.TrimSpace(dataArray[0])
config.DoNotWaitForResponse = strings.TrimSpace(dataArray[1]) == "true"

if errs := validator.Validator.Validate(config); len(errs) > 0 {
panic(fmt.Errorf("CONFIG_ERROR %#v", errs))
}
Expand All @@ -71,37 +74,43 @@ func ReadConfigFileAndReturnIt(currentDir string) *JwellyWhatsappConfig {
func AfterWhatsappConfigFile(data string) {
// Check that config is not null
if config == nil {
AppendToOutPutFile("Config is null")
go AppendToOutPutFile("Config is null")
return
}

dataToBeSend := strings.SplitN(data, "\n", 4)
dataToBeSend := strings.SplitN(data, "\n", 5)

// Check that dataToBeSend is the expected length
if len(dataToBeSend) != 4 {
AppendToOutPutFile(fmt.Sprintf("Expected dataToBeSend to have length 4, got %d", len(dataToBeSend)))
if len(dataToBeSend) < 5 {
go AppendToOutPutFile(fmt.Sprintf("Expected dataToBeSend to have length 5, got %d", len(dataToBeSend)))
return
}

number, key, filePathToBeSend := dataToBeSend[1], dataToBeSend[0], dataToBeSend[3]

number = strings.TrimSpace(number)
key = strings.TrimSpace(key)
filePathToBeSend = strings.TrimSpace(filePathToBeSend)
// Check that filePathToBeSend is not empty
if filePathToBeSend == "" {
AppendToOutPutFile("filePathToBeSend is empty")
go AppendToOutPutFile("filePathToBeSend is empty")
return
}

// Check that key is not empty
if key == "" {
AppendToOutPutFile("key is empty")
go AppendToOutPutFile("key is empty")
return
}

reqUrl := config.ServerUrl + "/send_media_64"

if _, err := os.Stat(filePathToBeSend); err != nil {
go AppendToOutPutFile(err.Error())
return
}
go AppendToOutPutFile("File Read Successfully")
fileBytes, err := os.ReadFile(filePathToBeSend)
if err != nil {
AppendToOutPutFile(err.Error())
go AppendToOutPutFile(err.Error())
return
}

Expand All @@ -110,32 +119,40 @@ func AfterWhatsappConfigFile(data string) {
postBody := fmt.Sprintf(`{"msg":"","fileName":"%s","to":["%s"],"base64":"%s"}`,
filepath.Base(filePathToBeSend), number, base64File)

// Send the POST request
go AppendToOutPutFile("Sending Request To " + reqUrl)
req, err := http.NewRequest("POST", reqUrl, strings.NewReader(postBody))
if err != nil {
AppendToOutPutFile(err.Error())
go AppendToOutPutFile(err.Error())
return
}

req.Header.Add("headless", "true")
if config.DoNotWaitForResponse {
req.Header.Add("headless", "true")
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("X-Api-Token", key)

res, err := http.DefaultClient.Do(req)
if err != nil {
AppendToOutPutFile(err.Error())
go AppendToOutPutFile(err.Error())
return
}

defer res.Body.Close()

_, err = io.ReadAll(res.Body)
body, err := io.ReadAll(res.Body)
if err != nil {
AppendToOutPutFile(err.Error())
go AppendToOutPutFile(err.Error())
return
}
go AppendToOutPutFile("Response " + string(body))
}

func AppendToOutPutFile(text string) {
text = text + "\n"
println(text)

f, err := os.OpenFile("./rps_whatsapp.logs.txt", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
panic(err)
Expand Down
15 changes: 7 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package main

import (
"bufio"
"encoding/json"
"errors"
"fmt"
Expand All @@ -26,13 +25,13 @@ var version string
func main() {
println(version)
// println(time.Now().Unix())
if time.Now().Unix() > 1713262858 {
println("Please Update The Binary From Keyur Shah")
println("Press Any Key To Close")
input := bufio.NewScanner(os.Stdin)
input.Scan()
return
}
// if time.Now().Unix() > 1713262858 {
// println("Please Update The Binary From Keyur Shah")
// println("Press Any Key To Close")
// input := bufio.NewScanner(os.Stdin)
// input.Scan()
// return
// }
env.CurrentDirectory = FindAndReturnCurrentDir()
go func() {
os.RemoveAll("./tmp")
Expand Down
119 changes: 2 additions & 117 deletions whatsapp/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ func (connection *WhatsappConnection) SendTextMessage(to []string, msg string) *
// return
}
targetJID := NumberOnWhatsapp.JID
fmt.Printf("sending File To %s\n", number)
fmt.Printf("sending Text To %s\n", number)
response[number] = false
if len(msg) > 0 {
resp, err := connection.Client.SendMessage(context.Background(), targetJID, &waProto.Message{
Expand All @@ -137,121 +137,6 @@ func (connection *WhatsappConnection) SendTextMessage(to []string, msg string) *
}
return &response
}
func (connection *WhatsappConnection) SendMediaFile(to []string, filePath string, fileName string, msg string) *map[string]interface{} {
response := make(map[string]interface{})
var docProto *waProto.Message
for _, number := range to {
IsOnWhatsappCheck, err := connection.Client.IsOnWhatsApp([]string{"+" + number})
if err != nil {
AppendToOutPutFile(fmt.Sprintf("%s,false,Something Went Wrong %#v\n", number, err))
// return
response[number] = false
continue
}
NumberOnWhatsapp := IsOnWhatsappCheck[0]
if !NumberOnWhatsapp.IsIn {
AppendToOutPutFile(fmt.Sprintf("%s,false,Number %s Not On Whatsapp\n", number, number))
response[number] = false
continue
// return
}
targetJID := NumberOnWhatsapp.JID
fmt.Printf("sending File To %s\n", number)
if docProto == nil {
extensionName := utility.GetMime(fileName)
fileByte, err := os.ReadFile(filePath)
if err != nil {
AppendToOutPutFile(fmt.Sprintf("false,Error While Reading File %#v\n", err))
continue
}
if strings.Contains(extensionName, "image") {
resp, err := connection.Client.Upload(context.Background(), fileByte, whatsmeow.MediaImage)
if err != nil {
AppendToOutPutFile(fmt.Sprintf("%s,false,Error While Uploading %#v\n", number, err))
continue
}
docProto = &waProto.Message{
ImageMessage: &waProto.ImageMessage{
Caption: proto.String(msg),
Url: &resp.URL,
Mimetype: proto.String(extensionName),
// FileName: &fileName,
DirectPath: &resp.DirectPath,
MediaKey: resp.MediaKey,
FileEncSha256: resp.FileEncSHA256,
FileSha256: resp.FileSHA256,
FileLength: &resp.FileLength,
},
}
} else if strings.Contains(extensionName, "audio") {
resp, err := connection.Client.Upload(context.Background(), fileByte, whatsmeow.MediaAudio)
if err != nil {
AppendToOutPutFile(fmt.Sprintf("%s,false,Error While Uploading %#v\n", number, err))
continue
}
docProto = &waProto.Message{
AudioMessage: &waProto.AudioMessage{
// Caption: proto.String(msg),
Url: &resp.URL,
Mimetype: proto.String(extensionName),
// FileName: &fileName,
DirectPath: &resp.DirectPath,
MediaKey: resp.MediaKey,
FileEncSha256: resp.FileEncSHA256,
FileSha256: resp.FileSHA256,
FileLength: &resp.FileLength,
},
}
} else if strings.Contains(extensionName, "video") {
resp, err := connection.Client.Upload(context.Background(), fileByte, whatsmeow.MediaVideo)
if err != nil {
AppendToOutPutFile(fmt.Sprintf("%s,false,Error While Uploading %#v\n", number, err))
continue
}
docProto = &waProto.Message{
VideoMessage: &waProto.VideoMessage{
Caption: proto.String(msg),
Url: &resp.URL,
Mimetype: proto.String(extensionName),
DirectPath: &resp.DirectPath,
MediaKey: resp.MediaKey,
FileEncSha256: resp.FileEncSHA256,
FileSha256: resp.FileSHA256,
FileLength: &resp.FileLength,
},
}
} else {
resp, err := connection.Client.Upload(context.Background(), fileByte, whatsmeow.MediaDocument)
if err != nil {
AppendToOutPutFile(fmt.Sprintf("%s,false,Error While Uploading %#v\n", number, err))
continue
}
docProto = &waProto.Message{
DocumentMessage: &waProto.DocumentMessage{
Caption: proto.String(msg),
Url: &resp.URL,
Mimetype: proto.String(extensionName),
FileName: &fileName,
DirectPath: &resp.DirectPath,
MediaKey: resp.MediaKey,
FileEncSha256: resp.FileEncSHA256,
FileSha256: resp.FileSHA256,
FileLength: &resp.FileLength,
},
}
}
}
response[number] = false
if len(msg) > 0 {
resp, err := connection.Client.SendMessage(context.Background(), targetJID, docProto)
if err == nil {
response[number] = resp
}
}
}
return &response
}

func (connection *WhatsappConnection) SendMediaFileBase64(to []string, base64Data string, fileName string, msg string) *map[string]bool {
// pdfBytes, err := os.ReadFile(filePath)
bytesData, err := base64.StdEncoding.DecodeString(base64Data)
Expand Down Expand Up @@ -369,7 +254,7 @@ func (connection *WhatsappConnection) sendMediaFile(to []string, fileByte []byte
}
}
response[number] = false
if len(msg) > 0 {
if docProto != nil {
_, err := connection.Client.SendMessage(context.Background(), targetJID, docProto)
if err == nil {
response[number] = true
Expand Down

0 comments on commit 58f0da0

Please sign in to comment.