Skip to content

Commit

Permalink
Merge pull request #483 from SchulteMK/feature/loginoptions
Browse files Browse the repository at this point in the history
Add NewConnWIthOptions
  • Loading branch information
SchulteMK authored Nov 18, 2020
2 parents 79ad714 + c8076aa commit 459e3de
Show file tree
Hide file tree
Showing 16 changed files with 175 additions and 52 deletions.
58 changes: 43 additions & 15 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,31 +116,59 @@ Creates a new connection with a given timeout. The websocket connection to the W
The goroutine for handling incoming messages is started
*/
func NewConn(timeout time.Duration) (*Conn, error) {
wac := &Conn{
handler: make([]Handler, 0),
msgCount: 0,
msgTimeout: timeout,
Store: newStore(),

longClientName: "github.com/rhymen/go-whatsapp",
shortClientName: "go-whatsapp",
clientVersion: "0.1.0",
}
return wac, wac.connect()
return NewConnWithOptions(&Options{
Timeout: timeout,
})
}

// NewConnWithProxy Create a new connect with a given timeout and a http proxy.
func NewConnWithProxy(timeout time.Duration, proxy func(*http.Request) (*url.URL, error)) (*Conn, error) {
return NewConnWithOptions(&Options{
Timeout: timeout,
Proxy: proxy,
})
}

// NewConnWithOptions Create a new connect with a given options.
type Options struct {
Proxy func(*http.Request) (*url.URL, error)
Timeout time.Duration
Handler []Handler
ShortClientName string
LongClientName string
ClientVersion string
Store *Store
}
func NewConnWithOptions(opt *Options) (*Conn, error) {
if opt == nil {
return nil, ErrOptionsNotProvided
}
wac := &Conn{
handler: make([]Handler, 0),
msgCount: 0,
msgTimeout: timeout,
msgTimeout: opt.Timeout,
Store: newStore(),

longClientName: "github.com/rhymen/go-whatsapp",
longClientName: "github.com/Rhymen/go-whatsapp",
shortClientName: "go-whatsapp",
clientVersion: "0.1.0",
Proxy: proxy,
}
if opt.Handler != nil {
wac.handler = opt.Handler
}
if opt.Store != nil {
wac.Store = opt.Store
}
if opt.Proxy != nil {
wac.Proxy = opt.Proxy
}
if len(opt.ShortClientName) != 0 {
wac.shortClientName = opt.ShortClientName
}
if len(opt.LongClientName) != 0 {
wac.longClientName = opt.LongClientName
}
if len(opt.ClientVersion) != 0 {
wac.clientVersion = opt.ClientVersion
}
return wac, wac.connect()
}
Expand Down
2 changes: 2 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ var (
ErrMediaDownloadFailedWith404 = errors.New("download failed with status code 404")
ErrMediaDownloadFailedWith410 = errors.New("download failed with status code 410")
ErrInvalidWebsocket = errors.New("invalid websocket")

ErrOptionsNotProvided = errors.New("new conn options not provided")
)

type ErrConnectionFailed struct {
Expand Down
3 changes: 2 additions & 1 deletion examples/chatHistory/history.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package main

import (
"fmt"
"github.com/Rhymen/go-whatsapp"
"log"
"time"

"github.com/Rhymen/go-whatsapp"
)

// historyHandler for acquiring chat history
Expand Down
5 changes: 3 additions & 2 deletions examples/chatHistory/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ package main
import (
"encoding/gob"
"fmt"
"github.com/Rhymen/go-whatsapp/binary/proto"
"log"
"os"
"os/signal"
"syscall"
"time"

"github.com/Baozisoftware/qrcode-terminal-go"
"github.com/Rhymen/go-whatsapp/binary/proto"

qrcodeTerminal "github.com/Baozisoftware/qrcode-terminal-go"
"github.com/Rhymen/go-whatsapp"
)

Expand Down
5 changes: 3 additions & 2 deletions examples/echo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ package main
import (
"encoding/gob"
"fmt"
"github.com/Baozisoftware/qrcode-terminal-go"
"github.com/Rhymen/go-whatsapp"
"os"
"strings"
"time"

qrcodeTerminal "github.com/Baozisoftware/qrcode-terminal-go"
"github.com/Rhymen/go-whatsapp"
)

type waHandler struct {
Expand Down
2 changes: 2 additions & 0 deletions examples/login/go.mod
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
module github.com/Rhymen/go-whatsapp/examples/login

go 1.14

require (
github.com/Baozisoftware/qrcode-terminal-go v0.0.0-20170407111555-c0650d8dff0f
github.com/Rhymen/go-whatsapp v0.0.0
Expand Down
2 changes: 2 additions & 0 deletions examples/login/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ github.com/golang/protobuf v1.3.0 h1:kbxbvI4Un1LUWKxufD+BiE6AEExYYgkQLQmLFqA1LFk
github.com/golang/protobuf v1.3.0/go.mod h1:Qd/q+1AKNOZr9uGQzbzCmRO6sUih6GTPZv6a1/R87v0=
github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q=
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM=
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/mattn/go-colorable v0.1.1 h1:G1f5SKeVxmagw/IyvzvtZE4Gybcc4Tr1tf7I8z0XgOg=
github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ=
github.com/mattn/go-isatty v0.0.5 h1:tHXDdz1cpzGaovsTB+TVB8q90WEokoVmfMqoVcrLUgw=
Expand Down
6 changes: 4 additions & 2 deletions examples/login/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ package main

import (
"fmt"
"github.com/Baozisoftware/qrcode-terminal-go"
"github.com/Rhymen/go-whatsapp"
"os"
"time"

qrcodeTerminal "github.com/Baozisoftware/qrcode-terminal-go"
"github.com/Rhymen/go-whatsapp"
)

func main() {
Expand All @@ -23,6 +24,7 @@ func main() {
session, err := wac.Login(qr)
if err != nil {
fmt.Fprintf(os.Stderr, "error during login: %v\n", err)
return
}
fmt.Printf("login successful, session: %v\n", session)
}
10 changes: 10 additions & 0 deletions examples/loginWithOptions/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module github.com/Rhymen/go-whatsapp/examples/loginWithOptions

go 1.14

require (
github.com/Baozisoftware/qrcode-terminal-go v0.0.0-20170407111555-c0650d8dff0f
github.com/Rhymen/go-whatsapp v0.0.0
)

replace github.com/Rhymen/go-whatsapp => ../../
25 changes: 25 additions & 0 deletions examples/loginWithOptions/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
github.com/Baozisoftware/qrcode-terminal-go v0.0.0-20170407111555-c0650d8dff0f h1:2dk3eOnYllh+wUOuDhOoC2vUVoJF/5z478ryJ+wzEII=
github.com/Baozisoftware/qrcode-terminal-go v0.0.0-20170407111555-c0650d8dff0f/go.mod h1:4a58ifQTEe2uwwsaqbh3i2un5/CBPg+At/qHpt18Tmk=
github.com/Rhymen/go-whatsapp/examples/echo v0.0.0-20190325075644-cc2581bbf24d/go.mod h1:zgCiQtBtZ4P4gFWvwl9aashsdwOcbb/EHOGRmSzM8ME=
github.com/Rhymen/go-whatsapp/examples/restoreSession v0.0.0-20190325075644-cc2581bbf24d/go.mod h1:5sCUSpG616ZoSJhlt9iBNI/KXBqrVLcNUJqg7J9+8pU=
github.com/Rhymen/go-whatsapp/examples/sendImage v0.0.0-20190325075644-cc2581bbf24d/go.mod h1:RdiyhanVEGXTam+mZ3k6Y3VDCCvXYCwReOoxGozqhHw=
github.com/Rhymen/go-whatsapp/examples/sendTextMessages v0.0.0-20190325075644-cc2581bbf24d/go.mod h1:suwzklatySS3Q0+NCxCDh5hYfgXdQUWU1DNcxwAxStM=
github.com/golang/protobuf v1.3.0 h1:kbxbvI4Un1LUWKxufD+BiE6AEExYYgkQLQmLFqA1LFk=
github.com/golang/protobuf v1.3.0/go.mod h1:Qd/q+1AKNOZr9uGQzbzCmRO6sUih6GTPZv6a1/R87v0=
github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM=
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/mattn/go-colorable v0.1.1 h1:G1f5SKeVxmagw/IyvzvtZE4Gybcc4Tr1tf7I8z0XgOg=
github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ=
github.com/mattn/go-isatty v0.0.5 h1:tHXDdz1cpzGaovsTB+TVB8q90WEokoVmfMqoVcrLUgw=
github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/skip2/go-qrcode v0.0.0-20190110000554-dc11ecdae0a9 h1:lpEzuenPuO1XNTeikEmvqYFcU37GVLl8SRNblzyvGBE=
github.com/skip2/go-qrcode v0.0.0-20190110000554-dc11ecdae0a9/go.mod h1:PLPIyL7ikehBD1OAjmKKiOEhbvWyHGaNDjquXMcYABo=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
50 changes: 50 additions & 0 deletions examples/loginWithOptions/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package main

import (
"fmt"
"net/http"
"net/url"
"os"
"time"

qrcodeTerminal "github.com/Baozisoftware/qrcode-terminal-go"
"github.com/Rhymen/go-whatsapp"
)

func main() {
// set proxy
// or you can use *url.URL directly like loginWithProxy example
purl, err := url.Parse("socks5://127.0.0.1/")
if err != nil {
panic(err)
}
proxy := http.ProxyURL(purl)

// or just left it empty
proxy = nil

wac, err := whatsapp.NewConnWithOptions(&whatsapp.Options{
// timeout
Timeout: 20 * time.Second,
Proxy: proxy,
// set custom client name
ShortClientName: "My-WhatsApp-Client",
LongClientName: "My-WhatsApp-Clientttttttttttttt",
})
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)
return
}
fmt.Printf("login successful, session: %v\n", session)
}
1 change: 1 addition & 0 deletions examples/loginWithProxy/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func main() {
session, err := wac.Login(qr)
if err != nil {
fmt.Fprintf(os.Stderr, "error during login: %v\n", err)
return
}
fmt.Printf("login successful, session: %v\n", session)
}
5 changes: 3 additions & 2 deletions examples/restoreSession/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ package main
import (
"encoding/gob"
"fmt"
"github.com/Baozisoftware/qrcode-terminal-go"
"github.com/Rhymen/go-whatsapp"
"os"
"time"

qrcodeTerminal "github.com/Baozisoftware/qrcode-terminal-go"
"github.com/Rhymen/go-whatsapp"
)

func main() {
Expand Down
11 changes: 6 additions & 5 deletions examples/sendImage/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ package main
import (
"encoding/gob"
"fmt"
"github.com/Baozisoftware/qrcode-terminal-go"
"github.com/Rhymen/go-whatsapp"
"os"
"time"

qrcodeTerminal "github.com/Baozisoftware/qrcode-terminal-go"
"github.com/Rhymen/go-whatsapp"
)

func main() {
Expand Down Expand Up @@ -40,12 +41,12 @@ func main() {
Content: img,
}

msgId,err := wac.Send(msg)
msgId, err := wac.Send(msg)
if err != nil {
fmt.Fprintf(os.Stderr, "error sending message: %v", err)
os.Exit(1)
os.Exit(1)
} else {
fmt.Println("Message Sent -> ID : "+msgId)
fmt.Println("Message Sent -> ID : " + msgId)
}
}

Expand Down
31 changes: 14 additions & 17 deletions media.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,21 +93,18 @@ func downloadMedia(url string) (file []byte, mac []byte, err error) {
return data[:n-10], data[n-10 : n], nil
}


type MediaConn struct {
Status int `json:"status"`
MediaConn struct {
Auth string `json:"auth"`
TTL int `json:"ttl"`
Hosts []struct {
Hostname string `json:"hostname"`
IPs []interface{} `json:"ips"`
} `json:"hosts"`
} `json:"media_conn"`
type MediaConn struct {
Status int `json:"status"`
MediaConn struct {
Auth string `json:"auth"`
TTL int `json:"ttl"`
Hosts []struct {
Hostname string `json:"hostname"`
IPs []interface{} `json:"ips"`
} `json:"hosts"`
} `json:"media_conn"`
}



func (wac *Conn) queryMediaConn() (hostname, auth string, ttl int, err error) {
queryReq := []interface{}{"query", "mediaConn"}
ch, err := wac.writeJson(queryReq)
Expand All @@ -131,7 +128,7 @@ func (wac *Conn) queryMediaConn() (hostname, auth string, ttl int, err error) {

var host string
for _, h := range resp.MediaConn.Hosts {
if h.Hostname!="" {
if h.Hostname != "" {
host = h.Hostname
break
}
Expand All @@ -143,10 +140,10 @@ func (wac *Conn) queryMediaConn() (hostname, auth string, ttl int, err error) {
}

var mediaTypeMap = map[MediaType]string{
MediaImage: "/mms/image",
MediaVideo: "/mms/video",
MediaImage: "/mms/image",
MediaVideo: "/mms/video",
MediaDocument: "/mms/document",
MediaAudio: "/mms/audio",
MediaAudio: "/mms/audio",
}

func (wac *Conn) Upload(reader io.Reader, appInfo MediaType) (downloadURL string, mediaKey []byte, fileEncSha256 []byte, fileSha256 []byte, fileLength uint64, err error) {
Expand Down
11 changes: 5 additions & 6 deletions message.go
Original file line number Diff line number Diff line change
Expand Up @@ -844,13 +844,12 @@ func ParseProtoMessage(msg *proto.WebMessageInfo) interface{} {
return nil
}


/*
BatteryMessage represents a battery level and charging state.
*/
type BatteryMessage struct {
Plugged bool
Powersave bool
Plugged bool
Powersave bool
Percentage int
}

Expand All @@ -859,8 +858,8 @@ func getBatteryMessage(msg map[string]string) BatteryMessage {
powersave, _ := strconv.ParseBool(msg["powersave"])
percentage, _ := strconv.Atoi(msg["value"])
batteryMessage := BatteryMessage{
Plugged: plugged,
Powersave: powersave,
Plugged: plugged,
Powersave: powersave,
Percentage: percentage,
}

Expand All @@ -869,7 +868,7 @@ func getBatteryMessage(msg map[string]string) BatteryMessage {

func getNewContact(msg map[string]string) Contact {
contact := Contact{
Jid: msg["jid"],
Jid: msg["jid"],
Notify: msg["notify"],
}

Expand Down

0 comments on commit 459e3de

Please sign in to comment.