Skip to content

Commit

Permalink
fix: goneonize
Browse files Browse the repository at this point in the history
  • Loading branch information
krypton-byte committed Aug 20, 2024
1 parent a21d3b8 commit d58c561
Show file tree
Hide file tree
Showing 72 changed files with 18,434 additions and 3,707 deletions.
6 changes: 1 addition & 5 deletions examples/multisession.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,12 @@ def interrupted(*_):
signal.signal(signal.SIGINT, interrupted)



client_factory = ClientFactory("db.sqlite3")

# create clients from preconfigured sessions
sessions = client_factory.get_all_devices()
for device in sessions:
client_factory.new_client(
device.JID
)
client_factory.new_client(device.JID)
# if new_client jid parameter is not passed, it will create a new client

# or create a new client
Expand Down Expand Up @@ -71,7 +68,6 @@ def on_message(client: NewClient, message: MessageEv):
handler(client, message)



def handler(client: NewClient, message: MessageEv):
text = message.Message.conversation or message.Message.extendedTextMessage.text
chat = message.Info.MessageSource.Chat
Expand Down
8 changes: 8 additions & 0 deletions goneonize/Neonize.proto
Original file line number Diff line number Diff line change
Expand Up @@ -869,4 +869,12 @@ message ReturnFunctionWithError {
LocalChatSettings LocalChatSettings = 2;
}

}

message SendRequestExtra {
required string ID = 1;
required JID InlineBotJID = 2;
required bool Peer = 3;
required int64 Timeout = 4;
required string MediaHandle = 5;
}
193 changes: 148 additions & 45 deletions goneonize/defproto/Neonize.pb.go

Large diffs are not rendered by default.

8 changes: 8 additions & 0 deletions goneonize/defproto/Neonize.proto
Original file line number Diff line number Diff line change
Expand Up @@ -869,4 +869,12 @@ message ReturnFunctionWithError {
LocalChatSettings LocalChatSettings = 2;
}

}

message SendRequestExtra {
required string ID = 1;
required JID InlineBotJID = 2;
required bool Peer = 3;
required int64 Timeout = 4;
required string MediaHandle = 5;
}
68 changes: 67 additions & 1 deletion goneonize/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import (
"github.com/krypton-byte/neonize/utils"
_ "github.com/mattn/go-sqlite3"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/proto/waConsumerApplication"
"go.mau.fi/whatsmeow/proto/waMsgApplication"
"go.mau.fi/whatsmeow/store"
"go.mau.fi/whatsmeow/store/sqlstore"
"go.mau.fi/whatsmeow/types"
Expand Down Expand Up @@ -159,7 +161,7 @@ func Neonize(db *C.char, id *C.char, JIDByte *C.uchar, JIDSize C.int, logLevel *
}
deviceStore, err_device = container.GetDevice(utils.DecodeJidProto(&JID))
} else {
deviceStore, err_device = container.GetFirstDevice(), nil
deviceStore, err_device = container.GetFirstDevice()
}
if err_device != nil {
panic(err)
Expand Down Expand Up @@ -1969,6 +1971,70 @@ func GetAllDevices(db *C.char) *C.char {
return C.CString(result.String())
}

//export SendFBMessage
func SendFBMessage(id *C.char, to *C.uchar, toSize C.int, message *C.uchar, messageSize C.int, metadata *C.uchar, metadataSize C.int, extra *C.uchar, extraSize C.int) C.struct_BytesReturn {
var toJID defproto.JID
var waConsumerApp waConsumerApplication.ConsumerApplication
var waConsumerAppMetadata waMsgApplication.MessageApplication_Metadata
var SendRequestExtra defproto.SendRequestExtra
err := proto.Unmarshal(
getByteByAddr(
to,
toSize,
),
&toJID,
)
if err != nil {
panic(err)
}
err_1 := proto.Unmarshal(
getByteByAddr(
message,
messageSize,
),
&waConsumerApp,
)
if err_1 != nil {
panic(err_1)
}
err_2 := proto.Unmarshal(
getByteByAddr(metadata, metadataSize),
&waConsumerAppMetadata,
)
if err != nil {
panic(err_2)
}
err_3 := proto.Unmarshal(
getByteByAddr(extra, extraSize),
&SendRequestExtra,
)
if err_3 != nil {
panic(err_3)
}
resp, err_fbmessage := clients[C.GoString(id)].SendFBMessage(
context.Background(),
utils.DecodeJidProto(&toJID),
&waConsumerApp,
&waConsumerAppMetadata,
utils.DecodeSendRequestExtra(
&SendRequestExtra,
),
)
if err_fbmessage != nil {
panic(err_fbmessage)
}
response := defproto.SendResponse{
Timestamp: proto.Int64(resp.Timestamp.UnixNano()),
ID: proto.String(resp.ID),
ServerID: proto.Int64(int64(resp.ServerID)),
DebugTimings: utils.EncodeMessageDebugTimings(resp.DebugTimings),
}
response_bytes, err_marshal := proto.Marshal(&response)
if err_marshal != nil {
panic(err_marshal)
}
return ReturnBytes(response_bytes)
}
func main() {

}
9 changes: 9 additions & 0 deletions goneonize/utils/decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,3 +162,12 @@ func DecodeContactEntry(entry *defproto.ContactEntry) *store.ContactEntry {
FullName: *entry.FullName,
}
}

func DecodeSendRequestExtra(extra *defproto.SendRequestExtra) whatsmeow.SendRequestExtra {
return whatsmeow.SendRequestExtra{
ID: *extra.ID,
InlineBotJID: DecodeJidProto(extra.InlineBotJID),
Peer: *extra.Peer,
Timeout: time.Duration(*extra.Timeout),
}
}
12 changes: 12 additions & 0 deletions neonize/_binder.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,5 +454,17 @@ def get_bytes(self):
gocode.GetChatSettings.restype = Bytes
gocode.GetAllDevices.argtypes = [ctypes.c_char_p]
gocode.GetAllDevices.restype = ctypes.c_char_p
gocode.SendFBMessage.argtypes = [
ctypes.c_char_p,
ctypes.c_char_p,
ctypes.c_int,
ctypes.c_char_p,
ctypes.c_int,
ctypes.c_char_p,
ctypes.c_int,
ctypes.c_char_p,
ctypes.c_int,
]
gocode.SendFBMessage.restype = Bytes
else:
gocode: Any = object()
58 changes: 46 additions & 12 deletions neonize/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@
NewsletterMetadata,
PrivacySettings,
ProfilePictureInfo,
SendRequestExtra,
StatusPrivacy,
UploadReturnFunction,
GroupInfo,
Expand Down Expand Up @@ -134,6 +135,8 @@
DocumentMessage,
ContactMessage,
)
from .proto.waConsumerApplication.WAConsumerApplication_pb2 import ConsumerApplication
from .proto.waMsgApplication.WAMsgApplication_pb2 import MessageApplication
from .types import MessageServerID, MessageWithContextInfo
from .utils import add_exif, gen_vcard, log, validate_link
from .utils.enum import (
Expand Down Expand Up @@ -2494,6 +2497,30 @@ def get_message_for_retry(
if not model.isEmpty:
return model.Message

def send_fb_message(
self,
to: JID,
message: ConsumerApplication,
metadata: MessageApplication.Metadata,
extra: SendRequestExtra,
):
to_buff = to.SerializeToString()
message_buff = message.SerializeToString()
metadata_buff = metadata.SerializeToString()
extra_buff = extra.SerializeToString()
response = self.__client.SendFBMessage(
self.uuid,
to_buff,
len(to_buff),
message_buff,
len(message_buff),
metadata_buff,
len(metadata_buff),
extra_buff,
len(extra_buff),
)
return SendResponse.FromString(response.get_bytes())

def connect(self):
"""Establishes a connection to the WhatsApp servers."""
# Convert the list of functions to a bytearray
Expand Down Expand Up @@ -2538,9 +2565,8 @@ def disconnect(self) -> None:
self.__client.Disconnect(self.uuid)



class ClientFactory:
def __init__(self, database_name: str = 'neonize.db') -> None:
def __init__(self, database_name: str = "neonize.db") -> None:
"""
This class is used to create new instances of the client.
"""
Expand All @@ -2559,31 +2585,39 @@ def get_all_devices_from_db(db: str) -> List["Device"]:
c_string = gocode.GetAllDevices(db.encode()).decode()
if not c_string:
return []

class Device:
def __init__(self, JID: JID, PushName: str, BussinessName: str = None, Initialized: bool = None):
def __init__(
self,
JID: JID,
PushName: str,
BussinessName: str = None,
Initialized: bool = None,
):
self.JID = JID
self.PushName = PushName
self.BusinessName = BussinessName
self.Initialized = Initialized

devices: list[Device] = []

for device_str in c_string.split('|\u0001|'):
id, push_name, bussniess_name, initialized = device_str.split(',')
id, server = id.split('@')
for device_str in c_string.split("|\u0001|"):
id, push_name, bussniess_name, initialized = device_str.split(",")
id, server = id.split("@")
jid = build_jid(id, server)

device = Device(jid, push_name, bussniess_name, initialized == 'true')
device = Device(jid, push_name, bussniess_name, initialized == "true")
devices.append(device)

return devices

def get_all_devices(self) -> List["Device"]:
"""Retrieves all devices associated with the current account from the database."""
return self.get_all_devices_from_db(self.database_name)

def new_client(self, jid: JID = None, uuid: str = None, props: Optional[DeviceProps] = None) -> NewClient:
def new_client(
self, jid: JID = None, uuid: str = None, props: Optional[DeviceProps] = None
) -> NewClient:
"""
This function creates a new instance of the client. If the jid parameter is not provided, a new client will be created.
:param name: The name of the client.
Expand All @@ -2601,7 +2635,7 @@ def new_client(self, jid: JID = None, uuid: str = None, props: Optional[DevicePr
raise Exception("JID and UUID cannot be none")

client = NewClient(self.database_name, jid, props, uuid)
self.clients.append(client)
self.clients.append(client)
return client

def run(self):
Expand All @@ -2612,4 +2646,4 @@ def run(self):
name=client.uuid,
).start()

Event.default_blocking(None)
Event.default_blocking(None)
4 changes: 3 additions & 1 deletion neonize/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@

event = EventThread()


class EventsManager:
def __init__(self, client_factory: ClientFactory):
self.client_factory = client_factory
Expand All @@ -116,6 +117,7 @@ def __call__(
:return: A decorator that registers the callback function.
:rtype: Callable[[Callable[[NewClient, EventType], None]], None]
"""

def callback(func: Callable[[NewClient, EventType], None]) -> None:
for client in self.client_factory.clients:
wrapped_func = client.event.wrap(func, event)
Expand Down Expand Up @@ -227,4 +229,4 @@ def callback(func: Callable[[NewClient, EventType], None]) -> None:
wrapped_func = self.wrap(func, event)
self.list_func.update({EVENT_TO_INT[event]: wrapped_func})

return callback
return callback
621 changes: 319 additions & 302 deletions neonize/proto/Neonize_pb2.py

Large diffs are not rendered by default.

Loading

0 comments on commit d58c561

Please sign in to comment.