cwtch/app/app.go

99 lines
2.0 KiB
Go

package app
import (
"cwtch.im/cwtch/connectivity/tor"
"cwtch.im/cwtch/peer"
"fmt"
"log"
"os"
"os/user"
"path"
)
// Application is a facade over a cwtchPeer that provides some wrapping logic.
type Application struct {
Peer peer.CwtchPeerInterface
TorManager *tor.Manager
}
// NewProfile creates a new cwtchPeer with a given name.
func (app *Application) NewProfile(name string, filename string, password string) error {
profile := peer.NewCwtchPeer(name, password)
app.Peer = profile
err := profile.Save(filename)
if err == nil {
err := app.startTor()
if err != nil {
return err
}
go func() {
err := app.Peer.Listen()
if err != nil {
log.Panic(err)
}
}()
}
return err
}
func (app *Application) startTor() error {
// Creating a local cwtch tor server config for the user
usr, err := user.Current()
if err != nil {
return err
}
// creating /home/<usr>/.cwtch/torrc file
// SOCKSPort socksPort
// ControlPort controlPort
torrc := path.Join(usr.HomeDir, ".cwtch", "torrc")
if _, err := os.Stat(torrc); os.IsNotExist(err) {
os.MkdirAll(path.Join(usr.HomeDir, ".cwtch"), 0700)
file, err := os.Create(torrc)
if err != nil {
return err
}
fmt.Fprintf(file, "SOCKSPort %d\nControlPort %d\n", 9050, 9051)
file.Close()
}
tm, err := tor.NewTorManager(9050, 9051, torrc)
if err != nil {
return err
}
app.TorManager = tm
return nil
}
// SetProfile loads an existing profile from the given filename.
func (app *Application) SetProfile(filename string, password string) error {
profile, err := peer.LoadCwtchPeer(filename, password)
if err != nil {
return err
}
app.Peer = profile
if err == nil {
err := app.startTor()
if err != nil {
return err
}
go func() {
err := app.Peer.Listen()
if err != nil {
log.Panic(err)
}
}()
}
return err
}
// PeerRequest attempts to setup peer relationship with the given onion address.`
func (app *Application) PeerRequest(onion string) {
app.Peer.PeerWithOnion(onion)
}