This commit is contained in:
Tulir Asokan
2018-08-26 17:29:51 +03:00
parent 941ab724c6
commit a6ebc50f6d
499 changed files with 462188 additions and 2 deletions

2
vendor/github.com/Rhymen/go-whatsapp/.gitignore generated vendored Normal file
View File

@ -0,0 +1,2 @@
.idea/
docs/

21
vendor/github.com/Rhymen/go-whatsapp/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

104
vendor/github.com/Rhymen/go-whatsapp/README.md generated vendored Normal file
View File

@ -0,0 +1,104 @@
# go-whatsapp
Package rhymen/go-whatsapp implements the WhatsApp Web API to provide a clean interface for developers. Big thanks to all contributors of the [sigalor/whatsapp-web-reveng](https://github.com/sigalor/whatsapp-web-reveng) project. The official WhatsApp Business API was released in August 2018. You can check it out [here](https://www.whatsapp.com/business/api).
## Installation
```sh
go get github.com/rhymen/go-whatsapp
```
## Usage
### Creating a connection
```go
import (
whatsapp "github.com/Rhymen/go-whatsapp"
)
wac, err := whatsapp.NewConn(20 * time.Second)
```
The duration passed to the NewConn function is used to timeout login requests. If you have a bad internet connection use a higher timeout value. This function only creates a websocket connection, it does not handle authentication.
### Login
```go
qrChan := make(chan string)
go func() {
fmt.Printf("qr code: %v\n", <-qrChan)
//show qr code or save it somewhere to scan
}
sess, err := wac.Login(qrChan)
```
The authentication process requires you to scan the qr code, that is send through the channel, with the device you are using whatsapp on. The session struct that is returned can be saved and used to restore the login without scanning the qr code again. The qr code has a ttl of 20 seconds and the login function throws a timeout err if the time has passed or any other request fails.
### Restore
```go
newSess, err := wac.RestoreSession(sess)
```
The restore function needs a valid session and returns the new session that was created.
### Add message handlers
```go
type myHandler struct{}
func (myHandler) HandleError(err error) {
fmt.Fprintf(os.Stderr, "%v", err)
}
func (myHandler) HandleTextMessage(message whatsapp.TextMessage) {
fmt.Println(message)
}
func (myHandler) HandleImageMessage(message whatsapp.ImageMessage) {
fmt.Println(message)
}
func (myHandler) HandleVideoMessage(message whatsapp.VideoMessage) {
fmt.Println(message)
}
func (myHandler) HandleJsonMessage(message string) {
fmt.Println(message)
}
wac.AddHandler(myHandler{})
```
The message handlers are all optional, you don't need to implement anything but the error handler to implement the interface. The ImageMessage and VideoMessage provide a Download function to get the media data.
### Sending text messages
```go
text := whatsapp.TextMessage{
Info: whatsapp.MessageInfo{
RemoteJid: "0123456789@s.whatsapp.net",
},
Text: "Hello Whatsapp",
}
err := wac.Send(text)
```
The message will be send over the websocket. The attributes seen above are the required ones. All other relevant attributes (id, timestamp, fromMe, status) are set if they are missing in the struct. For the time being we only support text messages, but other types are planned for the near future.
## Legal
This code is in no way affiliated with, authorized, maintained, sponsored or endorsed by WhatsApp or any of its
affiliates or subsidiaries. This is an independent and unofficial software. Use at your own risk.
## License
The MIT License (MIT)
Copyright (c) 2018
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

388
vendor/github.com/Rhymen/go-whatsapp/binary/decoder.go generated vendored Normal file
View File

@ -0,0 +1,388 @@
package binary
import (
"fmt"
"github.com/Rhymen/go-whatsapp/binary/token"
"io"
"strconv"
)
type binaryDecoder struct {
data []byte
index int
}
func NewDecoder(data []byte) *binaryDecoder {
return &binaryDecoder{data, 0}
}
func (r *binaryDecoder) checkEOS(length int) error {
if r.index+length > len(r.data) {
return io.EOF
}
return nil
}
func (r *binaryDecoder) readByte() (byte, error) {
if err := r.checkEOS(1); err != nil {
return 0, err
}
b := r.data[r.index]
r.index++
return b, nil
}
func (r *binaryDecoder) readIntN(n int, littleEndian bool) (int, error) {
if err := r.checkEOS(n); err != nil {
return 0, err
}
var ret int
for i := 0; i < n; i++ {
var curShift int
if littleEndian {
curShift = i
} else {
curShift = n - i - 1
}
ret |= int(r.data[r.index+i]) << uint(curShift*8)
}
r.index += n
return ret, nil
}
func (r *binaryDecoder) readInt8(littleEndian bool) (int, error) {
return r.readIntN(1, littleEndian)
}
func (r *binaryDecoder) readInt16(littleEndian bool) (int, error) {
return r.readIntN(2, littleEndian)
}
func (r *binaryDecoder) readInt20() (int, error) {
if err := r.checkEOS(3); err != nil {
return 0, err
}
ret := ((int(r.data[r.index]) & 15) << 16) + (int(r.data[r.index+1]) << 8) + int(r.data[r.index+2])
r.index += 3
return ret, nil
}
func (r *binaryDecoder) readInt32(littleEndian bool) (int, error) {
return r.readIntN(4, littleEndian)
}
func (r *binaryDecoder) readInt64(littleEndian bool) (int, error) {
return r.readIntN(8, littleEndian)
}
func (r *binaryDecoder) readPacked8(tag int) (string, error) {
startByte, err := r.readByte()
if err != nil {
return "", err
}
ret := ""
for i := 0; i < int(startByte&127); i++ {
currByte, err := r.readByte()
if err != nil {
return "", err
}
lower, err := unpackByte(tag, currByte&0xF0>>4)
if err != nil {
return "", err
}
upper, err := unpackByte(tag, currByte&0x0F)
if err != nil {
return "", err
}
ret += lower + upper
}
if startByte>>7 != 0 {
ret = ret[:len(ret)-1]
}
return ret, nil
}
func unpackByte(tag int, value byte) (string, error) {
switch tag {
case token.NIBBLE_8:
return unpackNibble(value)
case token.HEX_8:
return unpackHex(value)
default:
return "", fmt.Errorf("unpackByte with unknown tag %d", tag)
}
}
func unpackNibble(value byte) (string, error) {
switch {
case value < 0 || value > 15:
return "", fmt.Errorf("unpackNibble with value %d", value)
case value == 10:
return "-", nil
case value == 11:
return ".", nil
case value == 15:
return "\x00", nil
default:
return strconv.Itoa(int(value)), nil
}
}
func unpackHex(value byte) (string, error) {
switch {
case value < 0 || value > 15:
return "", fmt.Errorf("unpackHex with value %d", value)
case value < 10:
return strconv.Itoa(int(value)), nil
default:
return string('A' + value - 10), nil
}
}
func (r *binaryDecoder) readListSize(tag int) (int, error) {
switch tag {
case token.LIST_EMPTY:
return 0, nil
case token.LIST_8:
return r.readInt8(false)
case token.LIST_16:
return r.readInt16(false)
default:
return 0, fmt.Errorf("readListSize with unknown tag %d at position %d", tag, r.index)
}
}
func (r *binaryDecoder) readString(tag int) (string, error) {
switch {
case tag >= 3 && tag <= len(token.SingleByteTokens):
tok, err := token.GetSingleToken(tag)
if err != nil {
return "", err
}
if tok == "s.whatsapp.net" {
tok = "c.us"
}
return tok, nil
case tag == token.DICTIONARY_0 || tag == token.DICTIONARY_1 || tag == token.DICTIONARY_2 || tag == token.DICTIONARY_3:
i, err := r.readInt8(false)
if err != nil {
return "", err
}
return token.GetDoubleToken(tag-token.DICTIONARY_0, i)
case tag == token.LIST_EMPTY:
return "", nil
case tag == token.BINARY_8:
length, err := r.readInt8(false)
if err != nil {
return "", err
}
return r.readStringFromChars(length)
case tag == token.BINARY_20:
length, err := r.readInt20()
if err != nil {
return "", err
}
return r.readStringFromChars(length)
case tag == token.BINARY_32:
length, err := r.readInt32(false)
if err != nil {
return "", err
}
return r.readStringFromChars(length)
case tag == token.JID_PAIR:
b, err := r.readByte()
if err != nil {
return "", err
}
i, err := r.readString(int(b))
if err != nil {
return "", err
}
b, err = r.readByte()
if err != nil {
return "", err
}
j, err := r.readString(int(b))
if err != nil {
return "", err
}
if i == "" || j == "" {
return "", fmt.Errorf("invalid jid pair: %s - %s", i, j)
}
return i + "@" + j, nil
case tag == token.NIBBLE_8 || tag == token.HEX_8:
return r.readPacked8(tag)
default:
return "", fmt.Errorf("invalid string with tag %d", tag)
}
}
func (r *binaryDecoder) readStringFromChars(length int) (string, error) {
if err := r.checkEOS(length); err != nil {
return "", err
}
ret := r.data[r.index : r.index+length]
r.index += length
return string(ret), nil
}
func (r *binaryDecoder) readAttributes(n int) (map[string]string, error) {
if n == 0 {
return nil, nil
}
ret := make(map[string]string)
for i := 0; i < n; i++ {
idx, err := r.readInt8(false)
if err != nil {
return nil, err
}
index, err := r.readString(idx)
if err != nil {
return nil, err
}
idx, err = r.readInt8(false)
if err != nil {
return nil, err
}
ret[index], err = r.readString(idx)
if err != nil {
return nil, err
}
}
return ret, nil
}
func (r *binaryDecoder) readList(tag int) ([]Node, error) {
size, err := r.readListSize(tag)
if err != nil {
return nil, err
}
ret := make([]Node, size)
for i := 0; i < size; i++ {
n, err := r.ReadNode()
if err != nil {
return nil, err
}
ret[i] = *n
}
return ret, nil
}
func (r *binaryDecoder) ReadNode() (*Node, error) {
ret := &Node{}
size, err := r.readInt8(false)
if err != nil {
return nil, err
}
listSize, err := r.readListSize(size)
if err != nil {
return nil, err
}
descrTag, err := r.readInt8(false)
if descrTag == token.STREAM_END {
return nil, fmt.Errorf("unexpected stream end")
}
ret.Description, err = r.readString(descrTag)
if err != nil {
return nil, err
}
if listSize == 0 || ret.Description == "" {
return nil, fmt.Errorf("invalid Node")
}
ret.Attributes, err = r.readAttributes((listSize - 1) >> 1)
if err != nil {
return nil, err
}
if listSize%2 == 1 {
return ret, nil
}
tag, err := r.readInt8(false)
if err != nil {
return nil, err
}
switch tag {
case token.LIST_EMPTY, token.LIST_8, token.LIST_16:
ret.Content, err = r.readList(tag)
case token.BINARY_8:
size, err = r.readInt8(false)
if err != nil {
return nil, err
}
ret.Content, err = r.readBytes(size)
case token.BINARY_20:
size, err = r.readInt20()
if err != nil {
return nil, err
}
ret.Content, err = r.readBytes(size)
case token.BINARY_32:
size, err = r.readInt32(false)
if err != nil {
return nil, err
}
ret.Content, err = r.readBytes(size)
default:
ret.Content, err = r.readString(tag)
}
if err != nil {
return nil, err
}
return ret, nil
}
func (r *binaryDecoder) readBytes(n int) ([]byte, error) {
ret := make([]byte, n)
var err error
for i := range ret {
ret[i], err = r.readByte()
if err != nil {
return nil, err
}
}
return ret, nil
}

351
vendor/github.com/Rhymen/go-whatsapp/binary/encoder.go generated vendored Normal file
View File

@ -0,0 +1,351 @@
package binary
import (
"fmt"
"github.com/Rhymen/go-whatsapp/binary/token"
"math"
"strconv"
"strings"
)
type binaryEncoder struct {
data []byte
}
func NewEncoder() *binaryEncoder {
return &binaryEncoder{make([]byte, 0)}
}
func (w *binaryEncoder) GetData() []byte {
return w.data
}
func (w *binaryEncoder) pushByte(b byte) {
w.data = append(w.data, b)
}
func (w *binaryEncoder) pushBytes(bytes []byte) {
w.data = append(w.data, bytes...)
}
func (w *binaryEncoder) pushIntN(value, n int, littleEndian bool) {
for i := 0; i < n; i++ {
var curShift int
if littleEndian {
curShift = i
} else {
curShift = n - i - 1
}
w.pushByte(byte((value >> uint(curShift*8)) & 0xFF))
}
}
func (w *binaryEncoder) pushInt20(value int) {
w.pushBytes([]byte{byte((value >> 16) & 0x0F), byte((value >> 8) & 0xFF), byte(value & 0xFF)})
}
func (w *binaryEncoder) pushInt8(value int) {
w.pushIntN(value, 1, false)
}
func (w *binaryEncoder) pushInt16(value int) {
w.pushIntN(value, 2, false)
}
func (w *binaryEncoder) pushInt32(value int) {
w.pushIntN(value, 4, false)
}
func (w *binaryEncoder) pushInt64(value int) {
w.pushIntN(value, 8, false)
}
func (w *binaryEncoder) pushString(value string) {
w.pushBytes([]byte(value))
}
func (w *binaryEncoder) writeByteLength(length int) error {
if length > math.MaxInt32 {
return fmt.Errorf("length is too large: %d", length)
} else if length >= (1 << 20) {
w.pushByte(token.BINARY_32)
w.pushInt32(length)
} else if length >= 256 {
w.pushByte(token.BINARY_20)
w.pushInt20(length)
} else {
w.pushByte(token.BINARY_8)
w.pushInt8(length)
}
return nil
}
func (w *binaryEncoder) WriteNode(n Node) error {
numAttributes := 0
if n.Attributes != nil {
numAttributes = len(n.Attributes)
}
hasContent := 0
if n.Content != nil {
hasContent = 1
}
w.writeListStart(2*numAttributes + 1 + hasContent)
if err := w.writeString(n.Description, false); err != nil {
return err
}
if err := w.writeAttributes(n.Attributes); err != nil {
return err
}
if err := w.writeChildren(n.Content); err != nil {
return err
}
return nil
}
func (w *binaryEncoder) writeString(tok string, i bool) error {
if !i && tok == "c.us" {
if err := w.writeToken(token.IndexOfSingleToken("s.whatsapp.net")); err != nil {
return err
}
return nil
}
tokenIndex := token.IndexOfSingleToken(tok)
if tokenIndex == -1 {
jidSepIndex := strings.Index(tok, "@")
if jidSepIndex < 1 {
w.writeStringRaw(tok)
} else {
w.writeJid(tok[:jidSepIndex], tok[jidSepIndex+1:])
}
} else {
if tokenIndex < token.SINGLE_BYTE_MAX {
if err := w.writeToken(tokenIndex); err != nil {
return err
}
} else {
singleByteOverflow := tokenIndex - token.SINGLE_BYTE_MAX
dictionaryIndex := singleByteOverflow >> 8
if dictionaryIndex < 0 || dictionaryIndex > 3 {
return fmt.Errorf("double byte dictionary token out of range: %v", tok)
}
if err := w.writeToken(token.DICTIONARY_0 + dictionaryIndex); err != nil {
return err
}
if err := w.writeToken(singleByteOverflow % 256); err != nil {
return err
}
}
}
return nil
}
func (w *binaryEncoder) writeStringRaw(value string) error {
if err := w.writeByteLength(len(value)); err != nil {
return err
}
w.pushString(value)
return nil
}
func (w *binaryEncoder) writeJid(jidLeft, jidRight string) error {
w.pushByte(token.JID_PAIR)
if jidLeft != "" {
if err := w.writePackedBytes(jidLeft); err != nil {
return err
}
} else {
if err := w.writeToken(token.LIST_EMPTY); err != nil {
return err
}
}
if err := w.writeString(jidRight, false); err != nil {
return err
}
return nil
}
func (w *binaryEncoder) writeToken(tok int) error {
if tok < len(token.SingleByteTokens) {
w.pushByte(byte(tok))
} else if tok <= 500 {
return fmt.Errorf("invalid token: %d", tok)
}
return nil
}
func (w *binaryEncoder) writeAttributes(attributes map[string]string) error {
if attributes == nil {
return nil
}
for key, val := range attributes {
if val == "" {
continue
}
if err := w.writeString(key, false); err != nil {
return err
}
if err := w.writeString(val, false); err != nil {
return err
}
}
return nil
}
func (w *binaryEncoder) writeChildren(children interface{}) error {
if children == nil {
return nil
}
switch childs := children.(type) {
case string:
if err := w.writeString(childs, true); err != nil {
return err
}
case []byte:
if err := w.writeByteLength(len(childs)); err != nil {
return err
}
w.pushBytes(childs)
case []Node:
w.writeListStart(len(childs))
for _, n := range childs {
if err := w.WriteNode(n); err != nil {
return err
}
}
default:
return fmt.Errorf("cannot write child of type: %T", children)
}
return nil
}
func (w *binaryEncoder) writeListStart(listSize int) {
if listSize == 0 {
w.pushByte(byte(token.LIST_EMPTY))
} else if listSize < 256 {
w.pushByte(byte(token.LIST_8))
w.pushInt8(listSize)
} else {
w.pushByte(byte(token.LIST_16))
w.pushInt16(listSize)
}
}
func (w *binaryEncoder) writePackedBytes(value string) error {
if err := w.writePackedBytesImpl(value, token.NIBBLE_8); err != nil {
if err := w.writePackedBytesImpl(value, token.HEX_8); err != nil {
return err
}
}
return nil
}
func (w *binaryEncoder) writePackedBytesImpl(value string, dataType int) error {
numBytes := len(value)
if numBytes > token.PACKED_MAX {
return fmt.Errorf("too many bytes to pack: %d", numBytes)
}
w.pushByte(byte(dataType))
x := 0
if numBytes%2 != 0 {
x = 128
}
w.pushByte(byte(x | int(math.Ceil(float64(numBytes)/2.0))))
for i, l := 0, numBytes/2; i < l; i++ {
b, err := w.packBytePair(dataType, value[2*i:2*i+1], value[2*i+1:2*i+2])
if err != nil {
return err
}
w.pushByte(byte(b))
}
if (numBytes % 2) != 0 {
b, err := w.packBytePair(dataType, value[numBytes-1:], "\x00")
if err != nil {
return err
}
w.pushByte(byte(b))
}
return nil
}
func (w *binaryEncoder) packBytePair(packType int, part1, part2 string) (int, error) {
if packType == token.NIBBLE_8 {
n1, err := packNibble(part1)
if err != nil {
return 0, err
}
n2, err := packNibble(part2)
if err != nil {
return 0, err
}
return (n1 << 4) | n2, nil
} else if packType == token.HEX_8 {
n1, err := packHex(part1)
if err != nil {
return 0, err
}
n2, err := packHex(part2)
if err != nil {
return 0, err
}
return (n1 << 4) | n2, nil
} else {
return 0, fmt.Errorf("invalid pack type (%d) for byte pair: %s / %s", packType, part1, part2)
}
}
func packNibble(value string) (int, error) {
if value >= "0" && value <= "9" {
return strconv.Atoi(value)
} else if value == "-" {
return 10, nil
} else if value == "." {
return 11, nil
} else if value == "\x00" {
return 15, nil
}
return 0, fmt.Errorf("invalid string to pack as nibble: %v", value)
}
func packHex(value string) (int, error) {
if (value >= "0" && value <= "9") || (value >= "A" && value <= "F") || (value >= "a" && value <= "f") {
d, err := strconv.ParseInt(value, 16, 0)
return int(d), err
} else if value == "\x00" {
return 15, nil
}
return 0, fmt.Errorf("invalid string to pack as hex: %v", value)
}

103
vendor/github.com/Rhymen/go-whatsapp/binary/node.go generated vendored Normal file
View File

@ -0,0 +1,103 @@
package binary
import (
"fmt"
pb "github.com/Rhymen/go-whatsapp/binary/proto"
"github.com/golang/protobuf/proto"
)
type Node struct {
Description string
Attributes map[string]string
Content interface{}
}
func Marshal(n Node) ([]byte, error) {
if n.Attributes != nil && n.Content != nil {
a, err := marshalMessageArray(n.Content.([]interface{}))
if err != nil {
return nil, err
}
n.Content = a
}
w := NewEncoder()
if err := w.WriteNode(n); err != nil {
return nil, err
}
return w.GetData(), nil
}
func marshalMessageArray(messages []interface{}) ([]Node, error) {
ret := make([]Node, len(messages))
for i, m := range messages {
if wmi, ok := m.(*pb.WebMessageInfo); ok {
b, err := marshalWebMessageInfo(wmi)
if err != nil {
return nil, nil
}
ret[i] = Node{"message", nil, b}
} else {
ret[i], ok = m.(Node)
if !ok {
return nil, fmt.Errorf("invalid Node")
}
}
}
return ret, nil
}
func marshalWebMessageInfo(p *pb.WebMessageInfo) ([]byte, error) {
b, err := proto.Marshal(p)
if err != nil {
return nil, err
}
return b, nil
}
func Unmarshal(data []byte) (*Node, error) {
r := NewDecoder(data)
n, err := r.ReadNode()
if err != nil {
return nil, err
}
if n != nil && n.Attributes != nil && n.Content != nil {
n.Content, err = unmarshalMessageArray(n.Content.([]Node))
if err != nil {
return nil, err
}
}
return n, nil
}
func unmarshalMessageArray(messages []Node) ([]interface{}, error) {
ret := make([]interface{}, len(messages))
for i, msg := range messages {
if msg.Description == "message" {
info, err := unmarshalWebMessageInfo(msg.Content.([]byte))
if err != nil {
return nil, err
}
ret[i] = info
} else {
ret[i] = msg
}
}
return ret, nil
}
func unmarshalWebMessageInfo(msg []byte) (*pb.WebMessageInfo, error) {
message := &pb.WebMessageInfo{}
err := proto.Unmarshal(msg, message)
if err != nil {
return nil, err
}
return message, nil
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,417 @@
syntax = "proto2";
package proto;
message FingerprintData {
optional string publicKey = 1;
optional string identifier = 2;
}
message CombinedFingerprint {
optional uint32 version = 1;
optional FingerprintData localFingerprint = 2;
optional FingerprintData remoteFingerprint = 3;
}
message MessageKey {
optional string remoteJid = 1;
optional bool fromMe = 2;
optional string id = 3;
optional string participant = 4;
}
message SenderKeyDistributionMessage {
optional string groupId = 1;
optional bytes axolotlSenderKeyDistributionMessage = 2;
}
message ImageMessage {
optional string url = 1;
optional string mimetype = 2;
optional string caption = 3;
optional bytes fileSha256 = 4;
optional uint64 fileLength = 5;
optional uint32 height = 6;
optional uint32 width = 7;
optional bytes mediaKey = 8;
optional bytes fileEncSha256 = 9;
repeated InteractiveAnnotation interactiveAnnotations = 10;
optional string directPath = 11;
optional bytes jpegThumbnail = 16;
optional ContextInfo contextInfo = 17;
optional bytes firstScanSidecar = 18;
optional uint32 firstScanLength = 19;
}
message ContactMessage {
optional string displayName = 1;
optional string vcard = 16;
optional ContextInfo contextInfo = 17;
}
message LocationMessage {
optional double degreesLatitude = 1;
optional double degreesLongitude = 2;
optional string name = 3;
optional string address = 4;
optional string url = 5;
optional bytes jpegThumbnail = 16;
optional ContextInfo contextInfo = 17;
}
message ExtendedTextMessage {
optional string text = 1;
optional string matchedText = 2;
optional string canonicalUrl = 4;
optional string description = 5;
optional string title = 6;
optional fixed32 textArgb = 7;
optional fixed32 backgroundArgb = 8;
enum FONTTYPE {
SANS_SERIF = 0;
SERIF = 1;
NORICAN_REGULAR = 2;
BRYNDAN_WRITE = 3;
BEBASNEUE_REGULAR = 4;
OSWALD_HEAVY = 5;
}
optional FONTTYPE font = 9;
optional bytes jpegThumbnail = 16;
optional ContextInfo contextInfo = 17;
}
message DocumentMessage {
optional string url = 1;
optional string mimetype = 2;
optional string title = 3;
optional bytes fileSha256 = 4;
optional uint64 fileLength = 5;
optional uint32 pageCount = 6;
optional bytes mediaKey = 7;
optional string fileName = 8;
optional bytes fileEncSha256 = 9;
optional string directPath = 10;
optional bytes jpegThumbnail = 16;
optional ContextInfo contextInfo = 17;
}
message AudioMessage {
optional string url = 1;
optional string mimetype = 2;
optional bytes fileSha256 = 3;
optional uint64 fileLength = 4;
optional uint32 seconds = 5;
optional bool ptt = 6;
optional bytes mediaKey = 7;
optional bytes fileEncSha256 = 8;
optional string directPath = 9;
optional ContextInfo contextInfo = 17;
optional bytes streamingSidecar = 18;
}
message VideoMessage {
optional string url = 1;
optional string mimetype = 2;
optional bytes fileSha256 = 3;
optional uint64 fileLength = 4;
optional uint32 seconds = 5;
optional bytes mediaKey = 6;
optional string caption = 7;
optional bool gifPlayback = 8;
optional uint32 height = 9;
optional uint32 width = 10;
optional bytes fileEncSha256 = 11;
repeated InteractiveAnnotation interactiveAnnotations = 12;
optional string directPath = 13;
optional bytes jpegThumbnail = 16;
optional ContextInfo contextInfo = 17;
optional bytes streamingSidecar = 18;
enum ATTRIBUTION {
NONE = 0;
GIPHY = 1;
TENOR = 2;
}
optional ATTRIBUTION gifAttribution = 19;
}
message Call {
optional bytes callKey = 1;
}
message Chat {
optional string displayName = 1;
optional string id = 2;
}
message ProtocolMessage {
optional MessageKey key = 1;
enum TYPE {
REVOKE = 0;
}
optional TYPE type = 2;
}
message ContactsArrayMessage {
optional string displayName = 1;
repeated ContactMessage contacts = 2;
optional ContextInfo contextInfo = 17;
}
message HSMCurrency {
optional string currencyCode = 1;
optional int64 amount1000 = 2;
}
message HSMDateTimeComponent {
enum DAYOFWEEKTYPE {
MONDAY = 1;
TUESDAY = 2;
WEDNESDAY = 3;
THURSDAY = 4;
FRIDAY = 5;
SATURDAY = 6;
SUNDAY = 7;
}
optional DAYOFWEEKTYPE dayOfWeek = 1;
optional uint32 year = 2;
optional uint32 month = 3;
optional uint32 dayOfMonth = 4;
optional uint32 hour = 5;
optional uint32 minute = 6;
enum CALENDARTYPE {
GREGORIAN = 1;
SOLAR_HIJRI = 2;
}
optional CALENDARTYPE calendar = 7;
}
message HSMDateTimeUnixEpoch {
optional int64 timestamp = 1;
}
message HSMDateTime {
oneof datetimeOneof {
HSMDateTimeComponent component = 1;
HSMDateTimeUnixEpoch unixEpoch = 2;
}
}
message HSMLocalizableParameter {
optional string default = 1;
oneof paramOneof {
HSMCurrency currency = 2;
HSMDateTime dateTime = 3;
}
}
message HighlyStructuredMessage {
optional string namespace = 1;
optional string elementName = 2;
repeated string params = 3;
optional string fallbackLg = 4;
optional string fallbackLc = 5;
repeated HSMLocalizableParameter localizableParams = 6;
}
message SendPaymentMessage {
optional Message noteMessage = 2;
}
message RequestPaymentMessage {
optional string currencyCodeIso4217 = 1;
optional uint64 amount1000 = 2;
optional string requestFrom = 3;
optional Message noteMessage = 4;
}
message LiveLocationMessage {
optional double degreesLatitude = 1;
optional double degreesLongitude = 2;
optional uint32 accuracyInMeters = 3;
optional float speedInMps = 4;
optional uint32 degreesClockwiseFromMagneticNorth = 5;
optional string caption = 6;
optional int64 sequenceNumber = 7;
optional bytes jpegThumbnail = 16;
optional ContextInfo contextInfo = 17;
}
message StickerMessage {
optional string url = 1;
optional bytes fileSha256 = 2;
optional bytes fileEncSha256 = 3;
optional bytes mediaKey = 4;
optional string mimetype = 5;
optional uint32 height = 6;
optional uint32 width = 7;
optional string directPath = 8;
optional uint64 fileLength = 9;
optional bytes pngThumbnail = 16;
optional ContextInfo contextInfo = 17;
}
message Message {
optional string conversation = 1;
optional SenderKeyDistributionMessage senderKeyDistributionMessage = 2;
optional ImageMessage imageMessage = 3;
optional ContactMessage contactMessage = 4;
optional LocationMessage locationMessage = 5;
optional ExtendedTextMessage extendedTextMessage = 6;
optional DocumentMessage documentMessage = 7;
optional AudioMessage audioMessage = 8;
optional VideoMessage videoMessage = 9;
optional Call call = 10;
optional Chat chat = 11;
optional ProtocolMessage protocolMessage = 12;
optional ContactsArrayMessage contactsArrayMessage = 13;
optional HighlyStructuredMessage highlyStructuredMessage = 14;
optional SenderKeyDistributionMessage fastRatchetKeySenderKeyDistributionMessage = 15;
optional SendPaymentMessage sendPaymentMessage = 16;
optional RequestPaymentMessage requestPaymentMessage = 17;
optional LiveLocationMessage liveLocationMessage = 18;
optional StickerMessage stickerMessage = 20;
}
message ContextInfo {
optional string stanzaId = 1;
optional string participant = 2;
repeated Message quotedMessage = 3;
optional string remoteJid = 4;
repeated string mentionedJid = 15;
optional string conversionSource = 18;
optional bytes conversionData = 19;
optional uint32 conversionDelaySeconds = 20;
optional bool isForwarded = 22;
reserved 16, 17;
}
message InteractiveAnnotation {
repeated Point polygonVertices = 1;
oneof action {
Location location = 2;
}
}
message Point {
optional double x = 3;
optional double y = 4;
}
message Location {
optional double degreesLatitude = 1;
optional double degreesLongitude = 2;
optional string name = 3;
}
message WebMessageInfo {
required MessageKey key = 1;
optional Message message = 2;
optional uint64 messageTimestamp = 3;
enum STATUS {
ERROR = 0;
PENDING = 1;
SERVER_ACK = 2;
DELIVERY_ACK = 3;
READ = 4;
PLAYED = 5;
}
optional STATUS status = 4 [default=PENDING];
optional string participant = 5;
optional bool ignore = 16;
optional bool starred = 17;
optional bool broadcast = 18;
optional string pushName = 19;
optional bytes mediaCiphertextSha256 = 20;
optional bool multicast = 21;
optional bool urlText = 22;
optional bool urlNumber = 23;
enum STUBTYPE {
UNKNOWN = 0;
REVOKE = 1;
CIPHERTEXT = 2;
FUTUREPROOF = 3;
NON_VERIFIED_TRANSITION = 4;
UNVERIFIED_TRANSITION = 5;
VERIFIED_TRANSITION = 6;
VERIFIED_LOW_UNKNOWN = 7;
VERIFIED_HIGH = 8;
VERIFIED_INITIAL_UNKNOWN = 9;
VERIFIED_INITIAL_LOW = 10;
VERIFIED_INITIAL_HIGH = 11;
VERIFIED_TRANSITION_ANY_TO_NONE = 12;
VERIFIED_TRANSITION_ANY_TO_HIGH = 13;
VERIFIED_TRANSITION_HIGH_TO_LOW = 14;
VERIFIED_TRANSITION_HIGH_TO_UNKNOWN = 15;
VERIFIED_TRANSITION_UNKNOWN_TO_LOW = 16;
VERIFIED_TRANSITION_LOW_TO_UNKNOWN = 17;
VERIFIED_TRANSITION_NONE_TO_LOW = 18;
VERIFIED_TRANSITION_NONE_TO_UNKNOWN = 19;
GROUP_CREATE = 20;
GROUP_CHANGE_SUBJECT = 21;
GROUP_CHANGE_ICON = 22;
GROUP_CHANGE_INVITE_LINK = 23;
GROUP_CHANGE_DESCRIPTION = 24;
GROUP_CHANGE_RESTRICT = 25;
GROUP_CHANGE_ANNOUNCE = 26;
GROUP_PARTICIPANT_ADD = 27;
GROUP_PARTICIPANT_REMOVE = 28;
GROUP_PARTICIPANT_PROMOTE = 29;
GROUP_PARTICIPANT_DEMOTE = 30;
GROUP_PARTICIPANT_INVITE = 31;
GROUP_PARTICIPANT_LEAVE = 32;
GROUP_PARTICIPANT_CHANGE_NUMBER = 33;
BROADCAST_CREATE = 34;
BROADCAST_ADD = 35;
BROADCAST_REMOVE = 36;
GENERIC_NOTIFICATION = 37;
E2E_IDENTITY_CHANGED = 38;
E2E_ENCRYPTED = 39;
CALL_MISSED_VOICE = 40;
CALL_MISSED_VIDEO = 41;
INDIVIDUAL_CHANGE_NUMBER = 42;
GROUP_DELETE = 43;
}
optional STUBTYPE messageStubType = 24;
optional bool clearMedia = 25;
repeated string messageStubParameters = 26;
optional uint32 duration = 27;
repeated string labels = 28;
}
message WebNotificationsInfo {
optional uint64 timestamp = 2;
optional uint32 unreadChats = 3;
optional uint32 notifyMessageCount = 4;
repeated Message notifyMessages = 5;
}
message NotificationMessageInfo {
optional MessageKey key = 1;
optional Message message = 2;
optional uint64 messageTimestamp = 3;
optional string participant = 4;
}
message TabletNotificationsInfo {
optional uint64 timestamp = 2;
optional uint32 unreadChats = 3;
optional uint32 notifyMessageCount = 4;
repeated Message notifyMessage = 5;
}
message WebFeatures {
enum FLAG {
NOT_IMPLEMENTED = 0;
IMPLEMENTED = 1;
OPTIONAL = 2;
}
optional FLAG labelsDisplay = 1;
optional FLAG voipIndividualOutgoing = 2;
optional FLAG groupsV3 = 3;
optional FLAG groupsV3Create = 4;
optional FLAG changeNumberV2 = 5;
optional FLAG queryStatusV3Thumbnail = 6;
optional FLAG liveLocations = 7;
optional FLAG queryVname = 8;
optional FLAG voipIndividualIncoming = 9;
optional FLAG quickRepliesQuery = 10;
}

View File

@ -0,0 +1,78 @@
package token
import "fmt"
var SingleByteTokens = [...]string{"", "", "", "200", "400", "404", "500", "501", "502", "action", "add",
"after", "archive", "author", "available", "battery", "before", "body",
"broadcast", "chat", "clear", "code", "composing", "contacts", "count",
"create", "debug", "delete", "demote", "duplicate", "encoding", "error",
"false", "filehash", "from", "g.us", "group", "groups_v2", "height", "id",
"image", "in", "index", "invis", "item", "jid", "kind", "last", "leave",
"live", "log", "media", "message", "mimetype", "missing", "modify", "name",
"notification", "notify", "out", "owner", "participant", "paused",
"picture", "played", "presence", "preview", "promote", "query", "raw",
"read", "receipt", "received", "recipient", "recording", "relay",
"remove", "response", "resume", "retry", "s.whatsapp.net", "seconds",
"set", "size", "status", "subject", "subscribe", "t", "text", "to", "true",
"type", "unarchive", "unavailable", "url", "user", "value", "web", "width",
"mute", "read_only", "admin", "creator", "short", "update", "powersave",
"checksum", "epoch", "block", "previous", "409", "replaced", "reason",
"spam", "modify_tag", "message_info", "delivery", "emoji", "title",
"description", "canonical-url", "matched-text", "star", "unstar",
"media_key", "filename", "identity", "unread", "page", "page_count",
"search", "media_message", "security", "call_log", "profile", "ciphertext",
"invite", "gif", "vcard", "frequent", "privacy", "blacklist", "whitelist",
"verify", "location", "document", "elapsed", "revoke_invite", "expiration",
"unsubscribe", "disable", "vname", "old_jid", "new_jid", "announcement",
"locked", "prop", "label", "color", "call", "offer", "call-id"}
var doubleByteTokens = [...]string{}
func GetSingleToken(i int) (string, error) {
if i < 3 || i >= len(SingleByteTokens) {
return "", fmt.Errorf("index out of single byte token bounds %d", i)
}
return SingleByteTokens[i], nil
}
func GetDoubleToken(index1 int, index2 int) (string, error) {
n := 256*index1 + index2
if n < 0 || n >= len(doubleByteTokens) {
return "", fmt.Errorf("index out of double byte token bounds %d", n)
}
return doubleByteTokens[n], nil
}
func IndexOfSingleToken(token string) int {
for i, t := range SingleByteTokens {
if t == token {
return i
}
}
return -1
}
const (
LIST_EMPTY = 0
STREAM_END = 2
DICTIONARY_0 = 236
DICTIONARY_1 = 237
DICTIONARY_2 = 238
DICTIONARY_3 = 239
LIST_8 = 248
LIST_16 = 249
JID_PAIR = 250
HEX_8 = 251
BINARY_8 = 252
BINARY_20 = 253
BINARY_32 = 254
NIBBLE_8 = 255
)
const (
PACKED_MAX = 254
SINGLE_BYTE_MAX = 256
)

284
vendor/github.com/Rhymen/go-whatsapp/conn.go generated vendored Normal file
View File

@ -0,0 +1,284 @@
//Package whatsapp provides a developer API to interact with the WhatsAppWeb-Servers.
package whatsapp
import (
"crypto/hmac"
"crypto/sha256"
"encoding/json"
"fmt"
"github.com/Rhymen/go-whatsapp/binary"
"github.com/Rhymen/go-whatsapp/crypto/cbc"
"github.com/gorilla/websocket"
"math/rand"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
)
type metric byte
const (
debugLog metric = iota + 1
queryResume
queryReceipt
queryMedia
queryChat
queryContacts
queryMessages
presence
presenceSubscribe
group
read
chat
received
pic
status
message
queryActions
block
queryGroup
queryPreview
queryEmoji
queryMessageInfo
spam
querySearch
queryIdentity
queryUrl
profile
contact
queryVcard
queryStatus
queryStatusUpdate
privacyStatus
queryLiveLocations
liveLocation
queryVname
queryLabels
call
queryCall
queryQuickReplies
)
type flag byte
const (
ignore flag = 1 << (7 - iota)
ackRequest
available
notAvailable
expires
skipOffline
)
/*
Conn is created by NewConn. Interacting with the initialized Conn is the main way of interacting with our package.
It holds all necessary information to make the package work internally.
*/
type Conn struct {
wsConn *websocket.Conn
session *Session
listener map[string]chan string
listenerMutex sync.RWMutex
writeChan chan wsMsg
handler []Handler
msgCount int
msgTimeout time.Duration
Info *Info
Store *Store
ServerLastSeen time.Time
}
type wsMsg struct {
messageType int
data []byte
}
/*
Creates a new connection with a given timeout. The websocket connection to the WhatsAppWeb servers get´s established.
The goroutine for handling incoming messages is started
*/
func NewConn(timeout time.Duration) (*Conn, error) {
dialer := &websocket.Dialer{
ReadBufferSize: 25 * 1024 * 1024,
WriteBufferSize: 10 * 1024 * 1024,
HandshakeTimeout: timeout,
}
headers := http.Header{"Origin": []string{"https://web.whatsapp.com"}}
wsConn, _, err := dialer.Dial("wss://w3.web.whatsapp.com/ws", headers)
if err != nil {
return nil, fmt.Errorf("couldn't dial whatsapp web websocket: %v", err)
}
wac := &Conn{
wsConn: wsConn,
listener: make(map[string]chan string),
listenerMutex: sync.RWMutex{},
writeChan: make(chan wsMsg),
handler: make([]Handler, 0),
msgCount: 0,
msgTimeout: timeout,
Store: newStore(),
}
go wac.readPump()
go wac.writePump()
go wac.keepAlive(20000, 90000)
return wac, nil
}
func (wac *Conn) write(data []interface{}) (<-chan string, error) {
d, err := json.Marshal(data)
if err != nil {
return nil, err
}
ts := time.Now().Unix()
messageTag := fmt.Sprintf("%d.--%d", ts, wac.msgCount)
msg := fmt.Sprintf("%s,%s", messageTag, d)
ch := make(chan string, 1)
wac.listenerMutex.Lock()
wac.listener[messageTag] = ch
wac.listenerMutex.Unlock()
wac.writeChan <- wsMsg{websocket.TextMessage, []byte(msg)}
wac.msgCount++
return ch, nil
}
func (wac *Conn) writeBinary(node binary.Node, metric metric, flag flag, tag string) (<-chan string, error) {
if len(tag) < 2 {
return nil, fmt.Errorf("no tag specified or to short")
}
b, err := binary.Marshal(node)
if err != nil {
return nil, err
}
cipher, err := cbc.Encrypt(wac.session.EncKey, nil, b)
if err != nil {
return nil, err
}
h := hmac.New(sha256.New, wac.session.MacKey)
h.Write(cipher)
hash := h.Sum(nil)
data := []byte(tag + ",")
data = append(data, byte(metric), byte(flag))
data = append(data, hash[:32]...)
data = append(data, cipher...)
ch := make(chan string, 1)
wac.listenerMutex.Lock()
wac.listener[tag] = ch
wac.listenerMutex.Unlock()
msg := wsMsg{websocket.BinaryMessage, data}
wac.writeChan <- msg
wac.msgCount++
return ch, nil
}
func (wac *Conn) readPump() {
defer wac.wsConn.Close()
for {
msgType, msg, err := wac.wsConn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
wac.handle(fmt.Errorf("unexpected websocket close: %v", err))
}
break
}
data := strings.SplitN(string(msg), ",", 2)
//Kepp-Alive Timestmap
if data[0][0] == '!' {
msecs, err := strconv.ParseInt(data[0][1:], 10, 64)
if err != nil {
fmt.Fprintf(os.Stderr, "Error converting time string to uint: %v\n", err)
continue
}
wac.ServerLastSeen = time.Unix(msecs/1000, (msecs%1000)*int64(time.Millisecond))
continue
}
wac.listenerMutex.RLock()
listener, hasListener := wac.listener[data[0]]
wac.listenerMutex.RUnlock()
if hasListener && len(data[1]) > 0 {
listener <- data[1]
wac.listenerMutex.Lock()
delete(wac.listener, data[0])
wac.listenerMutex.Unlock()
} else if msgType == 2 && wac.session != nil && wac.session.EncKey != nil {
message, err := wac.decryptBinaryMessage([]byte(data[1]))
if err != nil {
wac.handle(fmt.Errorf("error decoding binary: %v", err))
continue
}
wac.dispatch(message)
} else {
if len(data[1]) > 0 {
wac.handle(string(data[1]))
}
}
}
}
func (wac *Conn) writePump() {
for msg := range wac.writeChan {
if err := wac.wsConn.WriteMessage(msg.messageType, msg.data); err != nil {
fmt.Fprintf(os.Stderr, "error writing to socket: %v", err)
}
}
}
func (wac *Conn) keepAlive(minIntervalMs int, maxIntervalMs int) {
for {
wac.writeChan <- wsMsg{
messageType: websocket.TextMessage,
data: []byte("?,,"),
}
interval := rand.Intn(maxIntervalMs-minIntervalMs) + minIntervalMs
<-time.After(time.Duration(interval) * time.Millisecond)
}
}
func (wac *Conn) decryptBinaryMessage(msg []byte) (*binary.Node, error) {
//message validation
h2 := hmac.New(sha256.New, wac.session.MacKey)
h2.Write([]byte(msg[32:]))
if !hmac.Equal(h2.Sum(nil), msg[:32]) {
return nil, fmt.Errorf("message received with invalid hmac")
}
// message decrypt
d, err := cbc.Decrypt(wac.session.EncKey, nil, msg[32:])
if err != nil {
return nil, fmt.Errorf("error decrypting message with AES: %v", err)
}
// message unmarshal
message, err := binary.Unmarshal(d)
if err != nil {
return nil, fmt.Errorf("error decoding binary: %v", err)
}
return message, nil
}

250
vendor/github.com/Rhymen/go-whatsapp/contact.go generated vendored Normal file
View File

@ -0,0 +1,250 @@
package whatsapp
import (
"fmt"
"github.com/Rhymen/go-whatsapp/binary"
"strconv"
"time"
)
type Presence string
const (
PresenceAvailable = "available"
PresenceUnavailable = "unavailable"
PresenceComposing = "composing"
)
//TODO: filename? WhatsApp uses Store.Contacts for these functions
//TODO: functions probably shouldn't return a string, maybe build a struct / return json
//TODO: check for further queries
func (wac *Conn) GetProfilePicThumb(jid string) (<-chan string, error) {
data := []interface{}{"query", "ProfilePicThumb", jid}
return wac.write(data)
}
func (wac *Conn) GetStatus(jid string) (<-chan string, error) {
data := []interface{}{"query", "Status", jid}
return wac.write(data)
}
func (wac *Conn) GetGroupMetaData(jid string) (<-chan string, error) {
data := []interface{}{"query", "GroupMetadata", jid}
return wac.write(data)
}
func (wac *Conn) SubscribePresence(jid string) (<-chan string, error) {
data := []interface{}{"action", "presence", "subscribe", jid}
return wac.write(data)
}
func (wac *Conn) CreateGroup(subject string, participants []string) (<-chan string, error) {
return wac.setGroup("create", "", subject, participants)
}
func (wac *Conn) UpdateGroupSubject(subject string, jid string) (<-chan string, error) {
return wac.setGroup("subject", jid, subject, nil)
}
func (wac *Conn) SetAdmin(jid string, participants []string) (<-chan string, error) {
return wac.setGroup("promote", jid, "", participants)
}
func (wac *Conn) RemoveAdmin(jid string, participants []string) (<-chan string, error) {
return wac.setGroup("demote", jid, "", participants)
}
func (wac *Conn) AddMember(jid string, participants []string) (<-chan string, error) {
return wac.setGroup("add", jid, "", participants)
}
func (wac *Conn) RemoveMember(jid string, participants []string) (<-chan string, error) {
return wac.setGroup("remove", jid, "", participants)
}
func (wac *Conn) LeaveGroup(jid string) (<-chan string, error) {
return wac.setGroup("leave", jid, "", nil)
}
func (wac *Conn) Search(search string, count, page int) (*binary.Node, error) {
return wac.query("search", "", "", "", "", search, count, page)
}
func (wac *Conn) LoadMessages(jid, messageId string, count int) (*binary.Node, error) {
return wac.query("message", jid, "", "before", "true", "", count, 0)
}
func (wac *Conn) LoadMessagesBefore(jid, messageId string, count int) (*binary.Node, error) {
return wac.query("message", jid, messageId, "before", "true", "", count, 0)
}
func (wac *Conn) LoadMessagesAfter(jid, messageId string, count int) (*binary.Node, error) {
return wac.query("message", jid, messageId, "after", "true", "", count, 0)
}
func (wac *Conn) Presence(jid string, presence Presence) (<-chan string, error) {
ts := time.Now().Unix()
tag := fmt.Sprintf("%d.--%d", ts, wac.msgCount)
n := binary.Node{
Description: "action",
Attributes: map[string]string{
"type": "set",
"epoch": strconv.Itoa(wac.msgCount),
},
Content: []interface{}{binary.Node{
Description: "presence",
Attributes: map[string]string{
"type": string(presence),
},
}},
}
return wac.writeBinary(n, group, ignore, tag)
}
func (wac *Conn) Emoji() (*binary.Node, error) {
return wac.query("emoji", "", "", "", "", "", 0, 0)
}
func (wac *Conn) Contacts() (*binary.Node, error) {
return wac.query("contacts", "", "", "", "", "", 0, 0)
}
func (wac *Conn) Chats() (*binary.Node, error) {
return wac.query("chat", "", "", "", "", "", 0, 0)
}
func (wac *Conn) Read(jid, id string) (<-chan string, error) {
ts := time.Now().Unix()
tag := fmt.Sprintf("%d.--%d", ts, wac.msgCount)
n := binary.Node{
Description: "action",
Attributes: map[string]string{
"type": "set",
"epoch": strconv.Itoa(wac.msgCount),
},
Content: []interface{}{binary.Node{
Description: "read",
Attributes: map[string]string{
"count": "1",
"index": id,
"jid": jid,
"owner": "false",
},
}},
}
return wac.writeBinary(n, group, ignore, tag)
}
func (wac *Conn) query(t, jid, messageId, kind, owner, search string, count, page int) (*binary.Node, error) {
ts := time.Now().Unix()
tag := fmt.Sprintf("%d.--%d", ts, wac.msgCount)
n := binary.Node{
Description: "query",
Attributes: map[string]string{
"type": t,
"epoch": strconv.Itoa(wac.msgCount),
},
}
if jid != "" {
n.Attributes["jid"] = jid
}
if messageId != "" {
n.Attributes["index"] = messageId
}
if kind != "" {
n.Attributes["kind"] = kind
}
if owner != "" {
n.Attributes["owner"] = owner
}
if search != "" {
n.Attributes["search"] = search
}
if count != 0 {
n.Attributes["count"] = strconv.Itoa(count)
}
if page != 0 {
n.Attributes["page"] = strconv.Itoa(page)
}
ch, err := wac.writeBinary(n, group, ignore, tag)
if err != nil {
return nil, err
}
msg, err := wac.decryptBinaryMessage([]byte(<-ch))
if err != nil {
return nil, err
}
//TODO: use parseProtoMessage
return msg, nil
}
func (wac *Conn) setGroup(t, jid, subject string, participants []string) (<-chan string, error) {
ts := time.Now().Unix()
tag := fmt.Sprintf("%d.--%d", ts, wac.msgCount)
//TODO: get proto or improve encoder to handle []interface{}
p := buildParticipantNodes(participants)
g := binary.Node{
Description: "group",
Attributes: map[string]string{
"author": wac.session.Wid,
"id": tag,
"type": t,
},
Content: p,
}
if jid != "" {
g.Attributes["jid"] = jid
}
if subject != "" {
g.Attributes["subject"] = subject
}
n := binary.Node{
Description: "action",
Attributes: map[string]string{
"type": "set",
"epoch": strconv.Itoa(wac.msgCount),
},
Content: []interface{}{g},
}
return wac.writeBinary(n, group, ignore, tag)
}
func buildParticipantNodes(participants []string) []binary.Node {
l := len(participants)
if participants == nil || l == 0 {
return nil
}
p := make([]binary.Node, len(participants))
for i, participant := range participants {
p[i] = binary.Node{
Description: "participant",
Attributes: map[string]string{
"jid": participant,
},
}
}
return p
}

101
vendor/github.com/Rhymen/go-whatsapp/crypto/cbc/cbc.go generated vendored Normal file
View File

@ -0,0 +1,101 @@
/*
CBC describes a block cipher mode. In cryptography, a block cipher mode of operation is an algorithm that uses a
block cipher to provide an information service such as confidentiality or authenticity. A block cipher by itself
is only suitable for the secure cryptographic transformation (encryption or decryption) of one fixed-length group of
bits called a block. A mode of operation describes how to repeatedly apply a cipher's single-block operation to
securely transform amounts of data larger than a block.
This package simplifies the usage of AES-256-CBC.
*/
package cbc
/*
Some code is provided by the GitHub user locked (github.com/locked):
https://gist.github.com/locked/b066aa1ddeb2b28e855e
Thanks!
*/
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
)
/*
Decrypt is a function that decrypts a given cipher text with a provided key and initialization vector(iv).
*/
func Decrypt(key, iv, ciphertext []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
if len(ciphertext) < aes.BlockSize {
return nil, fmt.Errorf("ciphertext is shorter then block size: %d / %d", len(ciphertext), aes.BlockSize)
}
if iv == nil {
iv = ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
}
cbc := cipher.NewCBCDecrypter(block, iv)
cbc.CryptBlocks(ciphertext, ciphertext)
return unpad(ciphertext)
}
/*
Encrypt is a function that encrypts plaintext with a given key and an optional initialization vector(iv).
*/
func Encrypt(key, iv, plaintext []byte) ([]byte, error) {
plaintext = pad(plaintext, aes.BlockSize)
if len(plaintext)%aes.BlockSize != 0 {
return nil, fmt.Errorf("plaintext is not a multiple of the block size: %d / %d", len(plaintext), aes.BlockSize)
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
var ciphertext []byte
if iv == nil {
ciphertext = make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
cbc := cipher.NewCBCEncrypter(block, iv)
cbc.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
} else {
ciphertext = make([]byte, len(plaintext))
cbc := cipher.NewCBCEncrypter(block, iv)
cbc.CryptBlocks(ciphertext, plaintext)
}
return ciphertext, nil
}
func pad(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext)%blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func unpad(src []byte) ([]byte, error) {
length := len(src)
padLen := int(src[length-1])
if padLen > length {
return nil, fmt.Errorf("padding is greater then the length: %d / %d", padLen, length)
}
return src[:(length - padLen)], nil
}

View File

@ -0,0 +1,44 @@
/*
In cryptography, Curve25519 is an elliptic curve offering 128 bits of security and designed for use with the elliptic
curve DiffieHellman (ECDH) key agreement scheme. It is one of the fastest ECC curves and is not covered by any known
patents. The reference implementation is public domain software. The original Curve25519 paper defined it
as a DiffieHellman (DH) function.
*/
package curve25519
import (
"crypto/rand"
"golang.org/x/crypto/curve25519"
"io"
)
/*
GenerateKey generates a public private key pair using Curve25519.
*/
func GenerateKey() (privateKey *[32]byte, publicKey *[32]byte, err error) {
var pub, priv [32]byte
_, err = io.ReadFull(rand.Reader, priv[:])
if err != nil {
return nil, nil, err
}
priv[0] &= 248
priv[31] &= 127
priv[31] |= 64
curve25519.ScalarBaseMult(&pub, &priv)
return &priv, &pub, nil
}
/*
GenerateSharedSecret generates the shared secret with a given public private key pair.
*/
func GenerateSharedSecret(priv, pub [32]byte) []byte {
var secret [32]byte
curve25519.ScalarMult(&secret, &priv, &pub)
return secret[:]
}

View File

@ -0,0 +1,52 @@
/*
HKDF is a simple key derivation function (KDF) based on
a hash-based message authentication code (HMAC). It was initially proposed by its authors as a building block in
various protocols and applications, as well as to discourage the proliferation of multiple KDF mechanisms.
The main approach HKDF follows is the "extract-then-expand" paradigm, where the KDF logically consists of two modules:
the first stage takes the input keying material and "extracts" from it a fixed-length pseudorandom key, and then the
second stage "expands" this key into several additional pseudorandom keys (the output of the KDF).
*/
package hkdf
import (
"crypto/hmac"
"crypto/sha256"
"fmt"
"golang.org/x/crypto/hkdf"
"io"
)
/*
Expand expands a given key with the HKDF algorithm.
*/
func Expand(key []byte, length int, info string) ([]byte, error) {
if info == "" {
keyBlock := hmac.New(sha256.New, key)
var out, last []byte
var blockIndex byte = 1
for i := 0; len(out) < length; i++ {
keyBlock.Reset()
//keyBlock.Write(append(append(last, []byte(info)...), blockIndex))
keyBlock.Write(last)
keyBlock.Write([]byte(info))
keyBlock.Write([]byte{blockIndex})
last = keyBlock.Sum(nil)
blockIndex += 1
out = append(out, last...)
}
return out[:length], nil
} else {
h := hkdf.New(sha256.New, key, nil, []byte(info))
out := make([]byte, length)
n, err := io.ReadAtLeast(h, out, length)
if err != nil {
return nil, err
}
if n != length {
return nil, fmt.Errorf("new key to short")
}
return out[:length], nil
}
}

181
vendor/github.com/Rhymen/go-whatsapp/handler.go generated vendored Normal file
View File

@ -0,0 +1,181 @@
package whatsapp
import (
"fmt"
"github.com/Rhymen/go-whatsapp/binary"
"github.com/Rhymen/go-whatsapp/binary/proto"
"os"
)
/*
The Handler interface is the minimal interface that needs to be implemented
to be accepted as a valid handler for our dispatching system.
The minimal handler is used to dispatch error messages. These errors occur on unexpected behavior by the websocket
connection or if we are unable to handle or interpret an incoming message. Error produced by user actions are not
dispatched through this handler. They are returned as an error on the specific function call.
*/
type Handler interface {
HandleError(err error)
}
/*
The TextMessageHandler interface needs to be implemented to receive text messages dispatched by the dispatcher.
*/
type TextMessageHandler interface {
Handler
HandleTextMessage(message TextMessage)
}
/*
The ImageMessageHandler interface needs to be implemented to receive image messages dispatched by the dispatcher.
*/
type ImageMessageHandler interface {
Handler
HandleImageMessage(message ImageMessage)
}
/*
The VideoMessageHandler interface needs to be implemented to receive video messages dispatched by the dispatcher.
*/
type VideoMessageHandler interface {
Handler
HandleVideoMessage(message VideoMessage)
}
/*
The AudioMessageHandler interface needs to be implemented to receive audio messages dispatched by the dispatcher.
*/
type AudioMessageHandler interface {
Handler
HandleAudioMessage(message AudioMessage)
}
/*
The DocumentMessageHandler interface needs to be implemented to receive document messages dispatched by the dispatcher.
*/
type DocumentMessageHandler interface {
Handler
HandleDocumentMessage(message DocumentMessage)
}
/*
The JsonMessageHandler interface needs to be implemented to receive json messages dispatched by the dispatcher.
These json messages contain status updates of every kind sent by WhatsAppWeb servers. WhatsAppWeb uses these messages
to built a Store, which is used to save these "secondary" information. These messages may contain
presence (available, last see) information, or just the battery status of your phone.
*/
type JsonMessageHandler interface {
Handler
HandleJsonMessage(message string)
}
/**
The RawMessageHandler interface needs to be implemented to receive raw messages dispatched by the dispatcher.
Raw messages are the raw protobuf structs instead of the easy-to-use structs in TextMessageHandler, ImageMessageHandler, etc..
*/
type RawMessageHandler interface {
Handler
HandleRawMessage(message *proto.WebMessageInfo)
}
/*
AddHandler adds an handler to the list of handler that receive dispatched messages.
The provided handler must at least implement the Handler interface. Additionally implemented
handlers(TextMessageHandler, ImageMessageHandler) are optional. At runtime it is checked if they are implemented
and they are called if so and needed.
*/
func (wac *Conn) AddHandler(handler Handler) {
wac.handler = append(wac.handler, handler)
}
func (wac *Conn) handle(message interface{}) {
switch m := message.(type) {
case error:
for _, h := range wac.handler {
go h.HandleError(m)
}
case string:
for _, h := range wac.handler {
x, ok := h.(JsonMessageHandler)
if !ok {
continue
}
go x.HandleJsonMessage(m)
}
case TextMessage:
for _, h := range wac.handler {
x, ok := h.(TextMessageHandler)
if !ok {
continue
}
go x.HandleTextMessage(m)
}
case ImageMessage:
for _, h := range wac.handler {
x, ok := h.(ImageMessageHandler)
if !ok {
continue
}
go x.HandleImageMessage(m)
}
case VideoMessage:
for _, h := range wac.handler {
x, ok := h.(VideoMessageHandler)
if !ok {
continue
}
go x.HandleVideoMessage(m)
}
case AudioMessage:
for _, h := range wac.handler {
x, ok := h.(AudioMessageHandler)
if !ok {
continue
}
go x.HandleAudioMessage(m)
}
case DocumentMessage:
for _, h := range wac.handler {
x, ok := h.(DocumentMessageHandler)
if !ok {
continue
}
go x.HandleDocumentMessage(m)
}
}
}
func (wac *Conn) dispatch(msg interface{}) {
if msg == nil {
return
}
switch message := msg.(type) {
case *binary.Node:
if message.Description == "action" {
if con, ok := message.Content.([]interface{}); ok {
for a := range con {
if v, ok := con[a].(*proto.WebMessageInfo); ok {
for _, h := range wac.handler {
x, ok := h.(RawMessageHandler)
if !ok {
continue
}
go x.HandleRawMessage(v)
}
wac.handle(parseProtoMessage(v))
}
}
}
} else if message.Description == "response" && message.Attributes["type"] == "contacts" {
wac.updateContacts(message.Content)
}
case error:
wac.handle(message)
case string:
wac.handle(message)
default:
fmt.Fprintf(os.Stderr, "unknown type in dipatcher chan: %T", msg)
}
}

199
vendor/github.com/Rhymen/go-whatsapp/media.go generated vendored Normal file
View File

@ -0,0 +1,199 @@
package whatsapp
import (
"bytes"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/Rhymen/go-whatsapp/crypto/cbc"
"github.com/Rhymen/go-whatsapp/crypto/hkdf"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"strings"
"time"
)
func Download(url string, mediaKey []byte, appInfo MediaType, fileLength int) ([]byte, error) {
if url == "" {
return nil, fmt.Errorf("no url present")
}
file, mac, err := downloadMedia(url)
if err != nil {
return nil, err
}
iv, cipherKey, macKey, _, err := getMediaKeys(mediaKey, appInfo)
if err != nil {
return nil, err
}
if err = validateMedia(iv, file, macKey, mac); err != nil {
return nil, err
}
data, err := cbc.Decrypt(cipherKey, iv, file)
if err != nil {
return nil, err
}
if len(data) != fileLength {
return nil, fmt.Errorf("file length does not match")
}
return data, nil
}
func validateMedia(iv []byte, file []byte, macKey []byte, mac []byte) error {
h := hmac.New(sha256.New, macKey)
n, err := h.Write(append(iv, file...))
if err != nil {
return err
}
if n < 10 {
return fmt.Errorf("hash to short")
}
if !hmac.Equal(h.Sum(nil)[:10], mac) {
return fmt.Errorf("invalid media hmac")
}
return nil
}
func getMediaKeys(mediaKey []byte, appInfo MediaType) (iv, cipherKey, macKey, refKey []byte, err error) {
mediaKeyExpanded, err := hkdf.Expand(mediaKey, 112, string(appInfo))
if err != nil {
return nil, nil, nil, nil, err
}
return mediaKeyExpanded[:16], mediaKeyExpanded[16:48], mediaKeyExpanded[48:80], mediaKeyExpanded[80:], nil
}
func downloadMedia(url string) (file []byte, mac []byte, err error) {
resp, err := http.Get(url)
if err != nil {
return nil, nil, err
}
if resp.StatusCode != 200 {
return nil, nil, fmt.Errorf("download failed")
}
defer resp.Body.Close()
if resp.ContentLength <= 10 {
return nil, nil, fmt.Errorf("file to short")
}
data, err := ioutil.ReadAll(resp.Body)
n := len(data)
if err != nil {
return nil, nil, err
}
return data[:n-10], data[n-10 : n], nil
}
func (wac *Conn) Upload(reader io.Reader, appInfo MediaType) (url string, mediaKey []byte, fileEncSha256 []byte, fileSha256 []byte, fileLength uint64, err error) {
data, err := ioutil.ReadAll(reader)
if err != nil {
return "", nil, nil, nil, 0, err
}
mediaKey = make([]byte, 32)
rand.Read(mediaKey)
iv, cipherKey, macKey, _, err := getMediaKeys(mediaKey, appInfo)
if err != nil {
return "", nil, nil, nil, 0, err
}
enc, err := cbc.Encrypt(cipherKey, iv, data)
if err != nil {
return "", nil, nil, nil, 0, err
}
fileLength = uint64(len(data))
h := hmac.New(sha256.New, macKey)
h.Write(append(iv, enc...))
mac := h.Sum(nil)[:10]
sha := sha256.New()
sha.Write(data)
fileSha256 = sha.Sum(nil)
sha.Reset()
sha.Write(append(enc, mac...))
fileEncSha256 = sha.Sum(nil)
var filetype string
switch appInfo {
case MediaImage:
filetype = "image"
case MediaAudio:
filetype = "audio"
case MediaDocument:
filetype = "document"
case MediaVideo:
filetype = "video"
}
uploadReq := []interface{}{"action", "encr_upload", filetype, base64.StdEncoding.EncodeToString(fileEncSha256)}
ch, err := wac.write(uploadReq)
if err != nil {
return "", nil, nil, nil, 0, err
}
var resp map[string]interface{}
select {
case r := <-ch:
if err = json.Unmarshal([]byte(r), &resp); err != nil {
return "", nil, nil, nil, 0, fmt.Errorf("error decoding upload response: %v\n", err)
}
case <-time.After(wac.msgTimeout):
return "", nil, nil, nil, 0, fmt.Errorf("restore session init timed out")
}
if int(resp["status"].(float64)) != 200 {
return "", nil, nil, nil, 0, fmt.Errorf("upload responsed with %d", resp["status"])
}
var b bytes.Buffer
w := multipart.NewWriter(&b)
hashWriter, err := w.CreateFormField("hash")
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
}
io.Copy(hashWriter, strings.NewReader(base64.StdEncoding.EncodeToString(fileEncSha256)))
fileWriter, err := w.CreateFormFile("file", "blob")
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
}
io.Copy(fileWriter, bytes.NewReader(append(enc, mac...)))
err = w.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
}
req, err := http.NewRequest("POST", resp["url"].(string), &b)
if err != nil {
return "", nil, nil, nil, 0, err
}
req.Header.Set("Content-Type", w.FormDataContentType())
req.Header.Set("Origin", "https://web.whatsapp.com")
req.Header.Set("Referer", "https://web.whatsapp.com/")
req.URL.Query().Set("f", "j")
client := &http.Client{}
// Submit the request
res, err := client.Do(req)
if err != nil {
return "", nil, nil, nil, 0, err
}
if res.StatusCode != http.StatusOK {
return "", nil, nil, nil, 0, fmt.Errorf("upload failed with status code %d", res.StatusCode)
}
var jsonRes map[string]string
json.NewDecoder(res.Body).Decode(&jsonRes)
return jsonRes["url"], mediaKey, fileEncSha256, fileSha256, fileLength, nil
}

442
vendor/github.com/Rhymen/go-whatsapp/message.go generated vendored Normal file
View File

@ -0,0 +1,442 @@
package whatsapp
import (
"encoding/hex"
"encoding/json"
"fmt"
"github.com/Rhymen/go-whatsapp/binary"
"github.com/Rhymen/go-whatsapp/binary/proto"
"io"
"math/rand"
"strconv"
"strings"
"time"
)
type MediaType string
const (
MediaImage MediaType = "WhatsApp Image Keys"
MediaVideo MediaType = "WhatsApp Video Keys"
MediaAudio MediaType = "WhatsApp Audio Keys"
MediaDocument MediaType = "WhatsApp Document Keys"
)
func (wac *Conn) Send(msg interface{}) error {
var err error
var ch <-chan string
switch m := msg.(type) {
case *proto.WebMessageInfo:
ch, err = wac.sendProto(m)
case TextMessage:
ch, err = wac.sendProto(getTextProto(m))
case ImageMessage:
m.url, m.mediaKey, m.fileEncSha256, m.fileSha256, m.fileLength, err = wac.Upload(m.Content, MediaImage)
if err != nil {
return fmt.Errorf("image upload failed: %v", err)
}
ch, err = wac.sendProto(getImageProto(m))
case VideoMessage:
m.url, m.mediaKey, m.fileEncSha256, m.fileSha256, m.fileLength, err = wac.Upload(m.Content, MediaVideo)
if err != nil {
return fmt.Errorf("video upload failed: %v", err)
}
ch, err = wac.sendProto(getVideoProto(m))
case DocumentMessage:
m.url, m.mediaKey, m.fileEncSha256, m.fileSha256, m.fileLength, err = wac.Upload(m.Content, MediaDocument)
if err != nil {
return fmt.Errorf("document upload failed: %v", err)
}
ch, err = wac.sendProto(getDocumentProto(m))
case AudioMessage:
m.url, m.mediaKey, m.fileEncSha256, m.fileSha256, m.fileLength, err = wac.Upload(m.Content, MediaAudio)
if err != nil {
return fmt.Errorf("audio upload failed: %v", err)
}
ch, err = wac.sendProto(getAudioProto(m))
default:
return fmt.Errorf("cannot match type %T, use message types declared in the package", msg)
}
if err != nil {
return fmt.Errorf("could not send proto: %v", err)
}
select {
case response := <-ch:
var resp map[string]interface{}
if err = json.Unmarshal([]byte(response), &resp); err != nil {
return fmt.Errorf("error decoding sending response: %v\n", err)
}
if int(resp["status"].(float64)) != 200 {
return fmt.Errorf("message sending responded with %d", resp["status"])
}
case <-time.After(wac.msgTimeout):
return fmt.Errorf("sending message timed out")
}
return nil
}
func (wac *Conn) sendProto(p *proto.WebMessageInfo) (<-chan string, error) {
n := binary.Node{
Description: "action",
Attributes: map[string]string{
"type": "relay",
"epoch": strconv.Itoa(wac.msgCount),
},
Content: []interface{}{p},
}
return wac.writeBinary(n, message, ignore, p.Key.GetId())
}
func init() {
rand.Seed(time.Now().UTC().UnixNano())
}
/*
MessageInfo contains general message information. It is part of every of every message type.
*/
type MessageInfo struct {
Id string
RemoteJid string
SenderJid string
FromMe bool
Timestamp uint64
PushName string
Status MessageStatus
QuotedMessageID string
Source *proto.WebMessageInfo
}
type MessageStatus int
const (
Error MessageStatus = 0
Pending = 1
ServerAck = 2
DeliveryAck = 3
Read = 4
Played = 5
)
func getMessageInfo(msg *proto.WebMessageInfo) MessageInfo {
return MessageInfo{
Id: msg.GetKey().GetId(),
RemoteJid: msg.GetKey().GetRemoteJid(),
SenderJid: msg.GetKey().GetParticipant(),
FromMe: msg.GetKey().GetFromMe(),
Timestamp: msg.GetMessageTimestamp(),
Status: MessageStatus(msg.GetStatus()),
PushName: msg.GetPushName(),
Source: msg,
}
}
func getInfoProto(info *MessageInfo) *proto.WebMessageInfo {
if info.Id == "" || len(info.Id) < 2 {
b := make([]byte, 10)
rand.Read(b)
info.Id = strings.ToUpper(hex.EncodeToString(b))
}
if info.Timestamp == 0 {
info.Timestamp = uint64(time.Now().Unix())
}
info.FromMe = true
status := proto.WebMessageInfo_STATUS(info.Status)
return &proto.WebMessageInfo{
Key: &proto.MessageKey{
FromMe: &info.FromMe,
RemoteJid: &info.RemoteJid,
Id: &info.Id,
},
MessageTimestamp: &info.Timestamp,
Status: &status,
}
}
/*
TextMessage represents a text message.
*/
type TextMessage struct {
Info MessageInfo
Text string
}
func getTextMessage(msg *proto.WebMessageInfo) TextMessage {
text := TextMessage{Info: getMessageInfo(msg)}
if m := msg.GetMessage().GetExtendedTextMessage(); m != nil {
text.Text = m.GetText()
text.Info.QuotedMessageID = m.GetContextInfo().GetStanzaId()
} else {
text.Text = msg.GetMessage().GetConversation()
}
return text
}
func getTextProto(msg TextMessage) *proto.WebMessageInfo {
p := getInfoProto(&msg.Info)
p.Message = &proto.Message{
Conversation: &msg.Text,
}
return p
}
/*
ImageMessage represents a image message. Unexported fields are needed for media up/downloading and media validation.
Provide a io.Reader as Content for message sending.
*/
type ImageMessage struct {
Info MessageInfo
Caption string
Thumbnail []byte
Type string
Content io.Reader
url string
mediaKey []byte
fileEncSha256 []byte
fileSha256 []byte
fileLength uint64
}
func getImageMessage(msg *proto.WebMessageInfo) ImageMessage {
image := msg.GetMessage().GetImageMessage()
return ImageMessage{
Info: getMessageInfo(msg),
Caption: image.GetCaption(),
Thumbnail: image.GetJpegThumbnail(),
url: image.GetUrl(),
mediaKey: image.GetMediaKey(),
Type: image.GetMimetype(),
fileEncSha256: image.GetFileEncSha256(),
fileSha256: image.GetFileSha256(),
fileLength: image.GetFileLength(),
}
}
func getImageProto(msg ImageMessage) *proto.WebMessageInfo {
p := getInfoProto(&msg.Info)
p.Message = &proto.Message{
ImageMessage: &proto.ImageMessage{
Caption: &msg.Caption,
JpegThumbnail: msg.Thumbnail,
Url: &msg.url,
MediaKey: msg.mediaKey,
Mimetype: &msg.Type,
FileEncSha256: msg.fileEncSha256,
FileSha256: msg.fileSha256,
FileLength: &msg.fileLength,
},
}
return p
}
/*
Download is the function to retrieve media data. The media gets downloaded, validated and returned.
*/
func (m *ImageMessage) Download() ([]byte, error) {
return Download(m.url, m.mediaKey, MediaImage, int(m.fileLength))
}
/*
VideoMessage represents a video message. Unexported fields are needed for media up/downloading and media validation.
Provide a io.Reader as Content for message sending.
*/
type VideoMessage struct {
Info MessageInfo
Caption string
Thumbnail []byte
Length uint32
Type string
Content io.Reader
url string
mediaKey []byte
fileEncSha256 []byte
fileSha256 []byte
fileLength uint64
}
func getVideoMessage(msg *proto.WebMessageInfo) VideoMessage {
vid := msg.GetMessage().GetVideoMessage()
return VideoMessage{
Info: getMessageInfo(msg),
Caption: vid.GetCaption(),
Thumbnail: vid.GetJpegThumbnail(),
url: vid.GetUrl(),
mediaKey: vid.GetMediaKey(),
Length: vid.GetSeconds(),
Type: vid.GetMimetype(),
fileEncSha256: vid.GetFileEncSha256(),
fileSha256: vid.GetFileSha256(),
fileLength: vid.GetFileLength(),
}
}
func getVideoProto(msg VideoMessage) *proto.WebMessageInfo {
p := getInfoProto(&msg.Info)
p.Message = &proto.Message{
VideoMessage: &proto.VideoMessage{
Caption: &msg.Caption,
JpegThumbnail: msg.Thumbnail,
Url: &msg.url,
MediaKey: msg.mediaKey,
Seconds: &msg.Length,
FileEncSha256: msg.fileEncSha256,
FileSha256: msg.fileSha256,
FileLength: &msg.fileLength,
Mimetype: &msg.Type,
},
}
return p
}
/*
Download is the function to retrieve media data. The media gets downloaded, validated and returned.
*/
func (m *VideoMessage) Download() ([]byte, error) {
return Download(m.url, m.mediaKey, MediaVideo, int(m.fileLength))
}
/*
AudioMessage represents a audio message. Unexported fields are needed for media up/downloading and media validation.
Provide a io.Reader as Content for message sending.
*/
type AudioMessage struct {
Info MessageInfo
Length uint32
Type string
Content io.Reader
url string
mediaKey []byte
fileEncSha256 []byte
fileSha256 []byte
fileLength uint64
}
func getAudioMessage(msg *proto.WebMessageInfo) AudioMessage {
aud := msg.GetMessage().GetAudioMessage()
return AudioMessage{
Info: getMessageInfo(msg),
url: aud.GetUrl(),
mediaKey: aud.GetMediaKey(),
Length: aud.GetSeconds(),
Type: aud.GetMimetype(),
fileEncSha256: aud.GetFileEncSha256(),
fileSha256: aud.GetFileSha256(),
fileLength: aud.GetFileLength(),
}
}
func getAudioProto(msg AudioMessage) *proto.WebMessageInfo {
p := getInfoProto(&msg.Info)
p.Message = &proto.Message{
AudioMessage: &proto.AudioMessage{
Url: &msg.url,
MediaKey: msg.mediaKey,
Seconds: &msg.Length,
FileEncSha256: msg.fileEncSha256,
FileSha256: msg.fileSha256,
FileLength: &msg.fileLength,
Mimetype: &msg.Type,
},
}
return p
}
/*
Download is the function to retrieve media data. The media gets downloaded, validated and returned.
*/
func (m *AudioMessage) Download() ([]byte, error) {
return Download(m.url, m.mediaKey, MediaAudio, int(m.fileLength))
}
/*
DocumentMessage represents a document message. Unexported fields are needed for media up/downloading and media
validation. Provide a io.Reader as Content for message sending.
*/
type DocumentMessage struct {
Info MessageInfo
Title string
PageCount uint32
Type string
Thumbnail []byte
Content io.Reader
url string
mediaKey []byte
fileEncSha256 []byte
fileSha256 []byte
fileLength uint64
}
func getDocumentMessage(msg *proto.WebMessageInfo) DocumentMessage {
doc := msg.GetMessage().GetDocumentMessage()
return DocumentMessage{
Info: getMessageInfo(msg),
Thumbnail: doc.GetJpegThumbnail(),
url: doc.GetUrl(),
mediaKey: doc.GetMediaKey(),
fileEncSha256: doc.GetFileEncSha256(),
fileSha256: doc.GetFileSha256(),
fileLength: doc.GetFileLength(),
PageCount: doc.GetPageCount(),
Title: doc.GetTitle(),
Type: doc.GetMimetype(),
}
}
func getDocumentProto(msg DocumentMessage) *proto.WebMessageInfo {
p := getInfoProto(&msg.Info)
p.Message = &proto.Message{
DocumentMessage: &proto.DocumentMessage{
JpegThumbnail: msg.Thumbnail,
Url: &msg.url,
MediaKey: msg.mediaKey,
FileEncSha256: msg.fileEncSha256,
FileSha256: msg.fileSha256,
FileLength: &msg.fileLength,
PageCount: &msg.PageCount,
Title: &msg.Title,
Mimetype: &msg.Type,
},
}
return p
}
/*
Download is the function to retrieve media data. The media gets downloaded, validated and returned.
*/
func (m *DocumentMessage) Download() ([]byte, error) {
return Download(m.url, m.mediaKey, MediaDocument, int(m.fileLength))
}
func parseProtoMessage(msg *proto.WebMessageInfo) interface{} {
switch {
case msg.GetMessage().GetAudioMessage() != nil:
return getAudioMessage(msg)
case msg.GetMessage().GetImageMessage() != nil:
return getImageMessage(msg)
case msg.GetMessage().GetVideoMessage() != nil:
return getVideoMessage(msg)
case msg.GetMessage().GetDocumentMessage() != nil:
return getDocumentMessage(msg)
case msg.GetMessage().GetConversation() != "":
return getTextMessage(msg)
case msg.GetMessage().GetExtendedTextMessage() != nil:
return getTextMessage(msg)
default:
//cannot match message
}
return nil
}

377
vendor/github.com/Rhymen/go-whatsapp/session.go generated vendored Normal file
View File

@ -0,0 +1,377 @@
package whatsapp
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"time"
"github.com/Rhymen/go-whatsapp/crypto/cbc"
"github.com/Rhymen/go-whatsapp/crypto/curve25519"
"github.com/Rhymen/go-whatsapp/crypto/hkdf"
)
/*
Session contains session individual information. To be able to resume the connection without scanning the qr code
every time you should save the Session returned by Login and use RestoreSession the next time you want to login.
Every successful created connection returns a new Session. The Session(ClientToken, ServerToken) is altered after
every re-login and should be saved every time.
*/
type Session struct {
ClientId string
ClientToken string
ServerToken string
EncKey []byte
MacKey []byte
Wid string
}
type Info struct {
Battery int
Platform string
Connected bool
Pushname string
Wid string
Lc string
Phone *PhoneInfo
Plugged bool
Tos int
Lg string
Is24h bool
}
type PhoneInfo struct {
Mcc string
Mnc string
OsVersion string
DeviceManufacturer string
DeviceModel string
OsBuildNumber string
WaVersion string
}
func newInfoFromReq(info map[string]interface{}) *Info {
phoneInfo := info["phone"].(map[string]interface{})
ret := &Info{
Battery: int(info["battery"].(float64)),
Platform: info["platform"].(string),
Connected: info["connected"].(bool),
Pushname: info["pushname"].(string),
Wid: info["wid"].(string),
Lc: info["lc"].(string),
Phone: &PhoneInfo{
phoneInfo["mcc"].(string),
phoneInfo["mnc"].(string),
phoneInfo["os_version"].(string),
phoneInfo["device_manufacturer"].(string),
phoneInfo["device_model"].(string),
phoneInfo["os_build_number"].(string),
phoneInfo["wa_version"].(string),
},
Plugged: info["plugged"].(bool),
Lg: info["lg"].(string),
Tos: int(info["tos"].(float64)),
}
if is24h, ok := info["is24h"]; ok {
ret.Is24h = is24h.(bool)
}
return ret
}
/*
Login is the function that creates a new whatsapp session and logs you in. If you do not want to scan the qr code
every time, you should save the returned session and use RestoreSession the next time. Login takes a writable channel
as an parameter. This channel is used to push the data represented by the qr code back to the user. The received data
should be displayed as an qr code in a way you prefer. To print a qr code to console you can use:
github.com/Baozisoftware/qrcode-terminal-go Example login procedure:
wac, err := whatsapp.NewConn(5 * time.Second)
if err != nil {
panic(err)
}
qr := make(chan string)
go func() {
terminal := qrcodeTerminal.New()
terminal.Get(<-qr).Print()
}()
session, err := wac.Login(qr)
if err != nil {
fmt.Fprintf(os.Stderr, "error during login: %v\n", err)
}
fmt.Printf("login successful, session: %v\n", session)
*/
func (wac *Conn) Login(qrChan chan<- string) (Session, error) {
session := Session{}
if wac.session != nil && (wac.session.EncKey != nil || wac.session.MacKey != nil) {
return session, fmt.Errorf("already logged in")
}
clientId := make([]byte, 16)
_, err := rand.Read(clientId)
if err != nil {
return session, fmt.Errorf("error creating random ClientId: %v", err)
}
session.ClientId = base64.StdEncoding.EncodeToString(clientId)
//oldVersion=8691
login := []interface{}{"admin", "init", []int{0, 3, 225}, []string{"github.com/rhymen/go-whatsapp", "go-whatsapp"}, session.ClientId, true}
loginChan, err := wac.write(login)
if err != nil {
return session, fmt.Errorf("error writing login: %v\n", err)
}
var r string
select {
case r = <-loginChan:
case <-time.After(wac.msgTimeout):
return session, fmt.Errorf("login connection timed out")
}
var resp map[string]interface{}
if err = json.Unmarshal([]byte(r), &resp); err != nil {
return session, fmt.Errorf("error decoding login resp: %v\n", err)
}
ref := resp["ref"].(string)
priv, pub, err := curve25519.GenerateKey()
if err != nil {
return session, fmt.Errorf("error generating keys: %v\n", err)
}
//listener for Login response
messageTag := "s1"
wac.listener[messageTag] = make(chan string, 1)
qrChan <- fmt.Sprintf("%v,%v,%v", ref, base64.StdEncoding.EncodeToString(pub[:]), session.ClientId)
var resp2 []interface{}
select {
case r1 := <-wac.listener[messageTag]:
if err := json.Unmarshal([]byte(r1), &resp2); err != nil {
return session, fmt.Errorf("error decoding qr code resp: %v", err)
}
case <-time.After(time.Duration(resp["ttl"].(float64)) * time.Millisecond):
return session, fmt.Errorf("qr code scan timed out")
}
info := resp2[1].(map[string]interface{})
wac.Info = newInfoFromReq(info)
session.ClientToken = info["clientToken"].(string)
session.ServerToken = info["serverToken"].(string)
session.Wid = info["wid"].(string)
s := info["secret"].(string)
decodedSecret, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return session, fmt.Errorf("error decoding secret: %v", err)
}
var pubKey [32]byte
copy(pubKey[:], decodedSecret[:32])
sharedSecret := curve25519.GenerateSharedSecret(*priv, pubKey)
hash := sha256.New
nullKey := make([]byte, 32)
h := hmac.New(hash, nullKey)
h.Write(sharedSecret)
sharedSecretExtended, err := hkdf.Expand(h.Sum(nil), 80, "")
if err != nil {
return session, fmt.Errorf("hkdf error: %v", err)
}
//login validation
checkSecret := make([]byte, 112)
copy(checkSecret[:32], decodedSecret[:32])
copy(checkSecret[32:], decodedSecret[64:])
h2 := hmac.New(hash, sharedSecretExtended[32:64])
h2.Write(checkSecret)
if !hmac.Equal(h2.Sum(nil), decodedSecret[32:64]) {
return session, fmt.Errorf("abort login")
}
keysEncrypted := make([]byte, 96)
copy(keysEncrypted[:16], sharedSecretExtended[64:])
copy(keysEncrypted[16:], decodedSecret[64:])
keyDecrypted, err := cbc.Decrypt(sharedSecretExtended[:32], nil, keysEncrypted)
if err != nil {
return session, fmt.Errorf("error decryptAes: %v", err)
}
session.EncKey = keyDecrypted[:32]
session.MacKey = keyDecrypted[32:64]
wac.session = &session
return session, nil
}
/*
RestoreSession is the function that restores a given session. It will try to reestablish the connection to the
WhatsAppWeb servers with the provided session. If it succeeds it will return a new session. This new session has to be
saved because the Client and Server-Token will change after every login. Logging in with old tokens is possible, but not
suggested. If so, a challenge has to be resolved which is just another possible point of failure.
*/
func (wac *Conn) RestoreSession(session Session) (Session, error) {
if wac.session != nil && (wac.session.EncKey != nil || wac.session.MacKey != nil) {
return Session{}, fmt.Errorf("already logged in")
}
wac.session = &session
//listener for Conn or challenge; s1 is not allowed to drop
wac.listener["s1"] = make(chan string, 1)
//admin init
init := []interface{}{"admin", "init", []int{0, 3, 225}, []string{"github.com/rhymen/go-whatsapp", "go-whatsapp"}, session.ClientId, true}
initChan, err := wac.write(init)
if err != nil {
wac.session = nil
return Session{}, fmt.Errorf("error writing admin init: %v\n", err)
}
//admin login with takeover
login := []interface{}{"admin", "login", session.ClientToken, session.ServerToken, session.ClientId, "takeover"}
loginChan, err := wac.write(login)
if err != nil {
wac.session = nil
return Session{}, fmt.Errorf("error writing admin login: %v\n", err)
}
select {
case r := <-initChan:
var resp map[string]interface{}
if err = json.Unmarshal([]byte(r), &resp); err != nil {
wac.session = nil
return Session{}, fmt.Errorf("error decoding login connResp: %v\n", err)
}
if int(resp["status"].(float64)) != 200 {
wac.session = nil
return Session{}, fmt.Errorf("init responded with %d", resp["status"])
}
case <-time.After(wac.msgTimeout):
wac.session = nil
return Session{}, fmt.Errorf("restore session init timed out")
}
//wait for s1
var connResp []interface{}
select {
case r1 := <-wac.listener["s1"]:
if err := json.Unmarshal([]byte(r1), &connResp); err != nil {
wac.session = nil
return Session{}, fmt.Errorf("error decoding s1 message: %v\n", err)
}
case <-time.After(wac.msgTimeout):
wac.session = nil
return Session{}, fmt.Errorf("restore session connection timed out")
}
//check if challenge is present
if len(connResp) == 2 && connResp[0] == "Cmd" && connResp[1].(map[string]interface{})["type"] == "challenge" {
wac.listener["s2"] = make(chan string, 1)
if err := wac.resolveChallenge(connResp[1].(map[string]interface{})["challenge"].(string)); err != nil {
wac.session = nil
return Session{}, fmt.Errorf("error resolving challenge: %v\n", err)
}
select {
case r := <-wac.listener["s2"]:
if err := json.Unmarshal([]byte(r), &connResp); err != nil {
wac.session = nil
return Session{}, fmt.Errorf("error decoding s2 message: %v\n", err)
}
case <-time.After(wac.msgTimeout):
wac.session = nil
return Session{}, fmt.Errorf("restore session challenge timed out")
}
}
//check for login 200 --> login success
select {
case r := <-loginChan:
var resp map[string]interface{}
if err = json.Unmarshal([]byte(r), &resp); err != nil {
wac.session = nil
return Session{}, fmt.Errorf("error decoding login connResp: %v\n", err)
}
if int(resp["status"].(float64)) != 200 {
wac.session = nil
return Session{}, fmt.Errorf("admin login responded with %d", resp["status"])
}
case <-time.After(wac.msgTimeout):
wac.session = nil
return Session{}, fmt.Errorf("restore session login timed out")
}
info := connResp[1].(map[string]interface{})
wac.Info = newInfoFromReq(info)
//set new tokens
session.ClientToken = info["clientToken"].(string)
session.ServerToken = info["serverToken"].(string)
session.Wid = info["wid"].(string)
return *wac.session, nil
}
func (wac *Conn) resolveChallenge(challenge string) error {
decoded, err := base64.StdEncoding.DecodeString(challenge)
if err != nil {
return err
}
h2 := hmac.New(sha256.New, wac.session.MacKey)
h2.Write([]byte(decoded))
ch := []interface{}{"admin", "challenge", base64.StdEncoding.EncodeToString(h2.Sum(nil)), wac.session.ServerToken, wac.session.ClientId}
challengeChan, err := wac.write(ch)
if err != nil {
return fmt.Errorf("error writing challenge: %v\n", err)
}
select {
case r := <-challengeChan:
var resp map[string]interface{}
if err := json.Unmarshal([]byte(r), &resp); err != nil {
return fmt.Errorf("error decoding login resp: %v\n", err)
}
if int(resp["status"].(float64)) != 200 {
return fmt.Errorf("challenge responded with %d\n", resp["status"])
}
case <-time.After(wac.msgTimeout):
return fmt.Errorf("connection timed out")
}
return nil
}
/*
Logout is the function to logout from a WhatsApp session. Logging out means invalidating the current session.
The session can not be resumed and will disappear on your phone in the WhatsAppWeb client list.
*/
func (wac *Conn) Logout() error {
login := []interface{}{"admin", "Conn", "disconnect"}
_, err := wac.write(login)
if err != nil {
return fmt.Errorf("error writing logout: %v\n", err)
}
return nil
}

45
vendor/github.com/Rhymen/go-whatsapp/store.go generated vendored Normal file
View File

@ -0,0 +1,45 @@
package whatsapp
import (
"github.com/Rhymen/go-whatsapp/binary"
"strings"
)
type Store struct {
Contacts map[string]Contact
}
type Contact struct {
Jid string
Notify string
Name string
Short string
}
func newStore() *Store {
return &Store{
make(map[string]Contact),
}
}
func (wac *Conn) updateContacts(contacts interface{}) {
c, ok := contacts.([]interface{})
if !ok {
return
}
for _, contact := range c {
contactNode, ok := contact.(binary.Node)
if !ok {
continue
}
jid := strings.Replace(contactNode.Attributes["jid"], "@c.us", "@s.whatsapp.net", 1)
wac.Store.Contacts[jid] = Contact{
jid,
contactNode.Attributes["notify"],
contactNode.Attributes["name"],
contactNode.Attributes["short"],
}
}
}