Get email websocket connection working
This commit is contained in:
parent
17c6bf8d50
commit
085935fa66
2 changed files with 28 additions and 14 deletions
|
|
@ -2,8 +2,10 @@ package email
|
|||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
|
|
@ -12,11 +14,11 @@ import (
|
|||
|
||||
var FORWARDEMAIL_WS_API = "wss://api.forwardemail.net/v1/ws"
|
||||
|
||||
func StartWebsocket(ctx context.Context, api_token string) {
|
||||
|
||||
func StartWebsocket(ctx context.Context, username, password string) {
|
||||
var err error
|
||||
var conn *websocket.Conn
|
||||
for {
|
||||
err := ensureConnected(conn, api_token)
|
||||
conn, err = ensureConnected(conn, username, password)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("Bailing on email websocket")
|
||||
return
|
||||
|
|
@ -40,23 +42,28 @@ func StartWebsocket(ctx context.Context, api_token string) {
|
|||
}
|
||||
}
|
||||
|
||||
func ensureConnected(conn *websocket.Conn, api_token string) error {
|
||||
func ensureConnected(conn *websocket.Conn, username, password string) (*websocket.Conn, error) {
|
||||
if conn != nil {
|
||||
return nil
|
||||
return conn, nil
|
||||
}
|
||||
url := FORWARDEMAIL_WS_API + "?token=" + api_token
|
||||
url := FORWARDEMAIL_WS_API
|
||||
for {
|
||||
new_conn, _, err := websocket.DefaultDialer.Dial(url, nil)
|
||||
encoded := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
|
||||
h := http.Header{}
|
||||
h.Add("Authorization", "Basic "+encoded)
|
||||
new_conn, _, err := websocket.DefaultDialer.Dial(url, h)
|
||||
if err == nil {
|
||||
if new_conn == nil {
|
||||
log.Error().Msg("new connection is nil.")
|
||||
return nil, fmt.Errorf("nil new connection")
|
||||
}
|
||||
log.Info().Msg("Connected to mail websocket")
|
||||
*conn = *new_conn
|
||||
return nil
|
||||
return new_conn, nil
|
||||
}
|
||||
if errors.Is(err, websocket.ErrBadHandshake) {
|
||||
return fmt.Errorf("Bad handshake connecting to email websocket, bailing.")
|
||||
return nil, fmt.Errorf("Bad handshake connecting to email websocket, bailing.")
|
||||
}
|
||||
log.Error().Err(err).Str("url", url).Msg("Error connecting to WebSocket")
|
||||
time.Sleep(3 * time.Second)
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue