cwtchbot/bot.go

83 lines
2.2 KiB
Go
Raw Normal View History

2019-10-28 02:09:02 +00:00
package bot
import (
2020-11-09 21:45:13 +00:00
"crypto/rand"
2019-10-28 02:09:02 +00:00
"cwtch.im/cwtch/app"
2019-10-28 21:17:38 +00:00
"cwtch.im/cwtch/app/plugins"
2019-10-28 02:09:02 +00:00
"cwtch.im/cwtch/event"
"cwtch.im/cwtch/peer"
2020-11-09 21:45:13 +00:00
"encoding/base64"
"git.openprivacy.ca/openprivacy/connectivity"
"git.openprivacy.ca/openprivacy/connectivity/tor"
"git.openprivacy.ca/openprivacy/log"
"os"
2019-10-28 02:09:02 +00:00
"path"
2020-11-09 21:45:13 +00:00
"path/filepath"
2019-10-28 02:09:02 +00:00
"time"
2020-11-09 21:45:13 +00:00
mrand "math/rand"
2019-10-28 02:09:02 +00:00
)
type CwtchBot struct {
dir string
Peer peer.CwtchPeer
Queue event.Queue
acn connectivity.ACN
peername string
}
func NewCwtchBot(userdir string, peername string) *CwtchBot {
cb := new(CwtchBot)
cb.dir = userdir
cb.peername = peername
return cb
}
func (cb *CwtchBot) Launch() {
2020-11-09 21:45:13 +00:00
mrand.Seed(int64(time.Now().Nanosecond()))
port := mrand.Intn(1000) + 9600
controlPort := port + 1
// generate a random password (actually random, stored in memory, for the control port)
key := make([]byte, 64)
_, err := rand.Read(key)
if err != nil {
panic(err)
}
log.Infof("making directory %v", cb.dir)
os.MkdirAll(path.Join(cb.dir, "/.tor","tor"),0700)
tor.NewTorrc().WithSocksPort(port).WithOnionTrafficOnly().WithControlPort(controlPort).WithHashedPassword(base64.StdEncoding.EncodeToString(key)).Build(filepath.Join(cb.dir, ".tor", "tor", "torrc"))
cb.acn, err = tor.NewTorACNWithAuth(path.Join(cb.dir, "/.tor"), "", controlPort, tor.HashedPasswordAuthenticator{base64.StdEncoding.EncodeToString(key)})
2019-10-28 02:09:02 +00:00
if err != nil {
log.Errorf("\nError connecting to Tor: %v\n", err)
}
cb.acn.WaitTillBootstrapped()
2020-11-09 21:45:13 +00:00
app := app.NewApp(cb.acn, cb.dir)
2019-10-28 02:09:02 +00:00
2019-10-28 21:17:38 +00:00
2019-10-28 02:09:02 +00:00
app.LoadProfiles("")
if len(app.ListPeers()) == 0 {
app.CreatePeer(cb.peername, "")
}
peers := app.ListPeers()
for onion, _ := range peers {
2019-10-28 21:17:38 +00:00
app.AddPeerPlugin(onion, plugins.CONNECTIONRETRY)
2019-10-28 02:09:02 +00:00
cb.Peer = app.GetPeer(onion)
log.Infof("Running %v", onion)
cb.Queue = event.NewQueue()
eb := app.GetEventBus(onion)
eb.Subscribe(event.NewMessageFromPeer, cb.Queue)
eb.Subscribe(event.PeerAcknowledgement, cb.Queue)
eb.Subscribe(event.NewMessageFromGroup, cb.Queue)
eb.Subscribe(event.NewGroupInvite, cb.Queue)
eb.Subscribe(event.SendMessageToGroupError, cb.Queue)
eb.Subscribe(event.SendMessageToPeerError, cb.Queue)
eb.Subscribe(event.ServerStateChange, cb.Queue)
eb.Subscribe(event.PeerStateChange, cb.Queue)
time.Sleep(time.Second * 4)
}
app.LaunchPeers()
}