This repository has been archived on 2021-06-24. You can view files and clone it, but cannot push or open issues or pull requests.
ui/go/ui/gcd.go

664 lines
22 KiB
Go

package ui
import (
"cwtch.im/cwtch/app"
"cwtch.im/cwtch/event"
"cwtch.im/cwtch/model/attr"
"cwtch.im/cwtch/protocol/connections"
"cwtch.im/ui/go/constants"
"github.com/therecipe/qt/qml"
"sync"
"cwtch.im/ui/go/the"
"encoding/base32"
"git.openprivacy.ca/openprivacy/log"
"github.com/therecipe/qt/core"
"strings"
"time"
)
type GrandCentralDispatcher struct {
core.QObject
QMLEngine *qml.QQmlApplicationEngine
Translator, OpaqueTranslator *core.QTranslator
uIManagers map[string]Manager // profile-onion : Manager
profileLock sync.Mutex
conversationLock sync.Mutex
m_selectedProfile string
m_selectedConversation string
_ string `property:"os"`
_ float32 `property:"themeScale"`
_ string `property:"version"`
_ string `property:"buildDate"`
_ string `property:"assetPath"`
_ string `property:"selectedProfile,auto"`
_ string `property:"selectedConversation,auto"`
// profile management stuff
_ func() `signal:"Loaded"`
_ func(handle, displayname, image, tag string) `signal:"AddProfile"`
_ func() `signal:"ErrorLoaded0"`
_ func() `signal:"ResetProfile"`
_ func() `signal:"ResetProfileList"`
_ func(failed bool) `signal:"ChangePasswordResponse"`
// contact list stuff
_ func(handle, displayName, image string, badge, status int, blocked bool, loading bool, lastMsgTime int) `signal:"AddContact"`
_ func(handle, displayName string) `signal:"UpdateContactDisplayName"`
_ func(handle, image string) `signal:"UpdateContactPicture"`
_ func(handle string, status int, loading bool) `signal:"UpdateContactStatus"`
_ func(handle string, blocked bool) `signal:"UpdateContactBlocked"`
_ func(handle string) `signal:"IncContactUnreadCount"`
_ func(handle string) `signal:"RemoveContact"`
_ func(handle, key, value string) `signal:"UpdateContactAttribute"`
// messages pane stuff
_ func(handle, from, displayName, message, image string, mID string, fromMe bool, ts string, ackd bool, error bool) `signal:"AppendMessage"`
_ func(handle, from, displayName, message, image string, mID string, fromMe bool, ts string, ackd bool, error bool) `signal:"PrependMessage"`
_ func() `signal:"ClearMessages"`
_ func() `signal:"ResetMessagePane"`
_ func(mID string) `signal:"Acknowledged"`
_ func(title string) `signal:"SetToolbarTitle"`
_ func(signature string, err string) `signal:"GroupSendError"`
_ func(loading bool) `signal:"SetLoadingState"`
// profile-area stuff
_ func(name, onion, image, tag string) `signal:"UpdateMyProfile"`
_ func(status int) `signal:"TorStatus"`
// settings helpers
_ func(str string) `signal:"InvokePopup"`
_ func(zoom, locale string, blockunknownpeers bool) `signal:"SupplySettings"`
_ func(groupID, name, server, invitation string, accepted bool, addrbooknames, addrbookaddrs []string) `signal:"SupplyGroupSettings"`
_ func(onion, nick string, blocked bool) `signal:"SupplyPeerSettings"`
// signals emitted from the ui (written in go, below)
// ui
_ func() `signal:"onActivate,auto"`
_ func(locale string) `signal:"setLocale,auto"`
// profile managemenet
_ func(onion, nick string) `signal:"updateNick,auto"`
_ func(handle string) `signal:"loadProfile,auto"`
_ func(nick string, defaultPass bool, password string) `signal:"createProfile,auto"`
_ func(password string) `signal:"unlockProfiles,auto"`
_ func() `signal:"reloadProfileList,auto"`
_ func(onion string) `signal:"deleteProfile,auto"`
_ func(onion, currentPassword, newPassword string, defaultPass bool) `signal:"changePassword,auto""`
// operating a profile
_ func(message string, mid string) `signal:"sendMessage,auto"`
_ func(onion string) `signal:"blockPeer,auto"`
_ func(onion string) `signal:"unblockPeer,auto"`
_ func(onion string) `signal:"loadMessagesPane,auto"`
_ func(signal string) `signal:"broadcast,auto"` // convenience relay signal
_ func(str string) `signal:"importString,auto"`
_ func(str string) `signal:"createContact,auto"`
_ func(str string) `signal:"popup,auto"`
_ func(server, groupName string) `signal:"createGroup,auto"`
_ func(groupID string) `signal:"leaveGroup,auto"`
_ func(groupID string) `signal:"acceptGroup,auto"`
_ func() `signal:"requestSettings,auto"`
_ func(zoom, locale string) `signal:"saveSettings,auto"`
_ func(groupID string) `signal:"requestGroupSettings,auto"`
_ func(groupID, nick string) `signal:"saveGroupSettings,auto"`
_ func() `signal:"requestPeerSettings,auto"`
_ func(onion, nick string) `signal:"savePeerSettings,auto"`
_ func(onion, groupID string) `signal:"inviteToGroup,auto"`
_ func(onion string) `signal:"deleteContact,auto"`
_ func() `signal:"allowUnknownPeers,auto"`
_ func() `signal:"blockUnknownPeers,auto"`
_ func() `constructor:"init"`
}
func (this *GrandCentralDispatcher) init() {
this.uIManagers = make(map[string]Manager)
}
// GetUiManager gets (and creates if required) a ui Manager for the supplied profile id
func (this *GrandCentralDispatcher) GetUiManager(profile string) Manager {
this.profileLock.Lock()
defer this.profileLock.Unlock()
if manager, exists := this.uIManagers[profile]; exists {
return manager
} else {
this.uIManagers[profile] = NewManager(profile, this)
return this.uIManagers[profile]
}
}
func (this *GrandCentralDispatcher) selectedProfile() string {
this.profileLock.Lock()
defer this.profileLock.Unlock()
return this.m_selectedProfile
}
func (this *GrandCentralDispatcher) setSelectedProfile(onion string) {
this.profileLock.Lock()
defer this.profileLock.Unlock()
this.m_selectedProfile = onion
}
func (this *GrandCentralDispatcher) selectedProfileChanged(onion string) {
this.SelectedProfileChanged(onion)
}
// DoIfProfile performs a gcd action for a profile IF it is the currently selected profile in the UI
// otherwise it does nothing. it also locks profile switching for the duration of the action
func (this *GrandCentralDispatcher) DoIfProfile(profile string, fn func()) {
this.profileLock.Lock()
defer this.profileLock.Unlock()
if this.m_selectedProfile == profile {
fn()
}
}
func (this *GrandCentralDispatcher) selectedConversation() string {
this.conversationLock.Lock()
defer this.conversationLock.Unlock()
return this.m_selectedConversation
}
func (this *GrandCentralDispatcher) setSelectedConversation(handle string) {
this.conversationLock.Lock()
defer this.conversationLock.Unlock()
this.m_selectedConversation = handle
}
func (this *GrandCentralDispatcher) selectedConversationChanged(handle string) {
this.SelectedConversationChanged(handle)
}
// DoIfConversation performs a gcd action for a conversation IF it is the currently selected conversation in the UI
// otherwise it does nothing. it also locks conversation switching for the duration of the action
func (this *GrandCentralDispatcher) DoIfConversation(conversation string, fn func()) {
this.conversationLock.Lock()
defer this.conversationLock.Unlock()
if this.m_selectedConversation == conversation {
fn()
}
}
func (this *GrandCentralDispatcher) sendMessage(message string, mID string) {
if len(message) > 65530 {
this.InvokePopup("message is too long")
return
}
if this.SelectedConversation() == "" {
this.InvokePopup("ui error")
return
}
if isGroup(this.SelectedConversation()) {
if !the.Peer.GetGroup(this.SelectedConversation()).Accepted {
err := the.Peer.AcceptInvite(this.SelectedConversation())
if err != nil {
log.Errorf("tried to mark a nonexistent group as existed. bad!")
return
}
}
var err error
mID, err = the.Peer.SendMessageToGroupTracked(this.SelectedConversation(), message)
this.GetUiManager(this.selectedProfile()).AddMessage(this.SelectedConversation(), "me", message, true, mID, time.Now(), false)
if err != nil {
this.InvokePopup("failed to send message " + err.Error())
return
}
} else {
to := this.SelectedConversation()
mID = the.Peer.SendMessageToPeer(to, message)
this.GetUiManager(this.selectedProfile()).AddMessage(to, "me", message, true, mID, time.Now(), false)
}
}
func (this *GrandCentralDispatcher) loadMessagesPane(handle string) {
go this.loadMessagesPaneHelper(handle)
}
func (this *GrandCentralDispatcher) loadMessagesPaneHelper(handle string) {
if handle == the.Peer.GetOnion() {
return
}
this.ClearMessages()
this.SetSelectedConversation(handle)
if isGroup(handle) { // LOAD GROUP
group := the.Peer.GetGroup(handle)
loading := false
state := connections.ConnectionStateToType[group.State]
if state == connections.AUTHENTICATED {
loading = true
}
this.UpdateContactStatus(group.GroupID, int(state), loading)
tl := group.GetTimeline()
nick := getNick(handle)
updateLastReadTime(group.GroupID)
if nick == "" {
this.SetToolbarTitle(handle)
} else {
this.SetToolbarTitle(nick)
}
for i := len(tl) - 1; i >= 0; i-- {
if tl[i].PeerID == the.Peer.GetOnion() {
handle = "me"
} else {
handle = tl[i].PeerID
}
name := getNick(tl[i].PeerID)
image := getProfilePic(tl[i].PeerID)
this.PrependMessage(
handle,
tl[i].PeerID,
name,
tl[i].Message,
image,
string(tl[i].Signature),
tl[i].PeerID == the.Peer.GetOnion(),
tl[i].Timestamp.Format(constants.TIME_FORMAT),
tl[i].Received.Equal(time.Unix(0, 0)) == false, // If the received timestamp is epoch, we have not yet received this message through an active server
false,
)
}
return
} // ELSE LOAD CONTACT
contact := the.Peer.GetContact(handle)
this.UpdateContactStatus(handle, int(connections.ConnectionStateToType[contact.State]), false)
var nick string
if contact != nil {
nick = getNick(contact.Onion)
}
updateLastReadTime(contact.Onion)
this.SetToolbarTitle(nick)
peer := the.Peer.GetContact(handle)
messages := peer.Timeline.GetMessages()
for i := range messages {
from := messages[i].PeerID
fromMe := messages[i].PeerID == the.Peer.GetOnion()
if fromMe {
from = "me"
}
displayname := getNick(messages[i].PeerID)
image := getProfilePic(messages[i].PeerID)
this.AppendMessage(
from,
messages[i].PeerID,
displayname,
messages[i].Message,
image,
string(messages[i].Signature),
fromMe,
messages[i].Timestamp.Format(constants.TIME_FORMAT),
messages[i].Acknowledged,
messages[i].Error != "",
)
}
}
func (this *GrandCentralDispatcher) requestSettings() {
zoom, exists := the.Peer.GetAttribute(attr.GetSettingsScope(constants.ZoomSetting))
if !exists {
zoom = "1.0"
}
locale, exists := the.Peer.GetAttribute(attr.GetSettingsScope(constants.LocaleSetting))
if !exists {
// TODO: pull env locale
locale = ""
}
blockunkownpeers, exists := the.Peer.GetAttribute(attr.GetSettingsScope(constants.BlockUnknownPeersSetting))
if !exists {
blockunkownpeers = "false"
}
this.SupplySettings(zoom, locale, blockunkownpeers == "true")
}
func (this *GrandCentralDispatcher) saveSettings(zoom, locale string) {
// saveSettings accidentally gets called once when the app first starts but before the app has been prepared
// so let's just ignore that one
if the.CwtchApp == nil {
return
}
the.Peer.SetAttribute(attr.GetSettingsScope(constants.ZoomSetting), zoom)
}
func (this *GrandCentralDispatcher) requestPeerSettings() {
contact := the.Peer.GetContact(this.SelectedConversation())
if contact == nil {
log.Errorf("error: requested settings for unknown contact %v?", this.SelectedConversation())
this.SupplyPeerSettings(this.SelectedConversation(), this.SelectedConversation(), false)
return
}
name := getNick(contact.Onion)
this.SupplyPeerSettings(contact.Onion, name, contact.Blocked)
}
func (this *GrandCentralDispatcher) savePeerSettings(onion, nick string) {
the.Peer.SetContactAttribute(onion, attr.GetLocalScope(constants.Name), nick)
this.UpdateContactDisplayName(onion, nick)
}
func (this *GrandCentralDispatcher) requestGroupSettings(groupID string) {
group := the.Peer.GetGroup(groupID)
if group == nil {
log.Errorf("couldn't find group %v", groupID)
return
}
nick := getNick(groupID)
invite, _ := the.Peer.ExportGroup(groupID)
contactaddrs := the.Peer.GetContacts()
contactnames := make([]string, len(contactaddrs))
for i, contact := range contactaddrs {
contactnames[i] = getNick(contact)
}
this.SupplyGroupSettings(group.GroupID, nick, group.GroupServer, invite, group.Accepted, contactnames, contactaddrs)
}
func (this *GrandCentralDispatcher) saveGroupSettings(groupID, nick string) {
the.Peer.SetGroupAttribute(groupID, attr.GetLocalScope(constants.Name), nick)
this.UpdateContactDisplayName(groupID, nick)
}
func (this *GrandCentralDispatcher) broadcast(signal string) {
switch signal {
default:
log.Debugf("unhandled broadcast signal: %v", signal)
case "ResetMessagePane":
this.ResetMessagePane()
case "ResetProfile":
this.ResetProfile()
}
}
func (this *GrandCentralDispatcher) createContact(onion string) {
if contact := the.Peer.GetContact(onion); contact != nil {
return
}
the.Peer.AddContact(onion, onion, false)
the.Peer.PeerWithOnion(onion)
}
func (this *GrandCentralDispatcher) importString(str string) {
if len(str) < 5 {
log.Debugf("ignoring short string")
return
}
log.Debugf("importing: %s\n", str)
onion := str
name := onion
str = strings.TrimSpace(str)
//eg: torv3JFDWkXExBsZLkjvfkkuAxHsiLGZBk0bvoeJID9ItYnU=EsEBCiBhOWJhZDU1OTQ0NWI3YmM2N2YxYTM5YjkzMTNmNTczNRIgpHeNaG+6jy750eDhwLO39UX4f2xs0irK/M3P6mDSYQIaOTJjM2ttb29ibnlnaGoyenc2cHd2N2Q1N3l6bGQ3NTNhdW8zdWdhdWV6enB2ZmFrM2FoYzRiZHlkCiJAdVSSVgsksceIfHe41OJu9ZFHO8Kwv3G6F5OK3Hw4qZ6hn6SiZjtmJlJezoBH0voZlCahOU7jCOg+dsENndZxAA==
if str[0:5] == "torv3" { // GROUP INVITE
err := the.Peer.ImportGroup(str)
if err != nil {
this.InvokePopup("not a valid group invite")
return
}
return
}
if strings.Contains(str, " ") { // usually people prepend spaces and we don't want it going into the name (use ~ for that)
parts := strings.Split(strings.TrimSpace(str), " ")
str = parts[len(parts)-1]
}
if strings.Contains(str, "~") {
parts := strings.Split(str, "~")
onion = parts[len(parts)-1]
name = strings.Join(parts[:len(parts)-1], " ")
}
if len(onion) != 56 {
this.InvokePopup("invalid format")
return
}
name = strings.TrimSpace(name)
if name == "" {
this.InvokePopup("empty name")
return
}
if len(name) > 32 {
name = name[:32] //TODO: better strategy for long names?
}
_, err := base32.StdEncoding.DecodeString(strings.ToUpper(onion[:56]))
if err != nil {
log.Debugln(err)
this.InvokePopup("bad format. missing handlers?")
return
}
checkc := the.Peer.GetContact(onion)
if checkc != nil {
this.InvokePopup("already have this contact")
return //TODO: bring them to the duplicate
} else {
the.Peer.AddContact(name, onion, false)
the.Peer.PeerWithOnion(onion)
}
this.GetUiManager(this.selectedProfile()).AddContact(onion)
}
func (this *GrandCentralDispatcher) popup(str string) {
this.InvokePopup(str)
}
func (this *GrandCentralDispatcher) updateNick(onion, nick string) {
p := the.CwtchApp.GetPeer(onion)
if p != nil {
p.SetName(nick)
p.SetAttribute(attr.GetPublicScope(constants.Name), nick)
the.CwtchApp.GetEventBus(onion).Publish(event.NewEvent(event.SetProfileName, map[event.Field]string{
event.ProfileName: nick,
}))
}
}
func (this *GrandCentralDispatcher) createGroup(server, groupName string) {
groupID, _, err := the.Peer.StartGroup(server)
if err != nil {
this.popup("group creation failed :(")
return
}
this.GetUiManager(this.selectedProfile()).AddContact(groupID)
the.Peer.SetGroupAttribute(groupID, attr.GetLocalScope(constants.Name), groupName)
the.Peer.JoinServer(server)
}
func (this *GrandCentralDispatcher) blockPeer(onion string) {
err := the.Peer.BlockPeer(onion)
if err != nil {
this.InvokePopup("Error Blocking Peer: " + err.Error())
}
this.UpdateContactBlocked(onion, true)
}
func (this *GrandCentralDispatcher) unblockPeer(onion string) {
err := the.Peer.UnblockPeer(onion)
if err != nil {
this.InvokePopup("Error Unblocking Peer: " + err.Error())
}
the.Peer.PeerWithOnion(onion)
this.UpdateContactBlocked(onion, false)
}
func (this *GrandCentralDispatcher) inviteToGroup(onion, groupID string) {
err := the.Peer.InviteOnionToGroup(onion, groupID)
if err != nil {
log.Errorf("inviting %v to %v: %v", onion, groupID, err)
}
}
func (this *GrandCentralDispatcher) leaveGroup(groupID string) {
the.Peer.DeleteGroup(groupID)
this.RemoveContact(groupID)
}
func (this *GrandCentralDispatcher) deleteContact(onion string) {
the.Peer.DeleteContact(onion)
this.RemoveContact(onion)
}
func (this *GrandCentralDispatcher) acceptGroup(groupID string) {
if the.Peer.GetGroup(groupID) != nil {
the.Peer.AcceptInvite(groupID)
}
}
func (this *GrandCentralDispatcher) blockUnknownPeers() {
the.Peer.SetAttribute(attr.GetSettingsScope(constants.BlockUnknownPeersSetting), "true")
the.EventBus.Publish(event.NewEvent(event.BlockUnknownPeers, map[event.Field]string{}))
}
func (this *GrandCentralDispatcher) allowUnknownPeers() {
the.Peer.SetAttribute(attr.GetSettingsScope(constants.BlockUnknownPeersSetting), "false")
the.EventBus.Publish(event.NewEvent(event.AllowUnknownPeers, map[event.Field]string{}))
}
func (this *GrandCentralDispatcher) setLocale(locale string) {
this.SetLocale_helper(locale)
the.Peer.SetAttribute(attr.GetSettingsScope(constants.LocaleSetting), locale)
zoom, _ := the.Peer.GetAttribute(attr.GetSettingsScope(constants.ZoomSetting))
blockunkownpeers, _ := the.Peer.GetAttribute(attr.GetPeerScope(constants.BlockUnknownPeersSetting))
this.SupplySettings(zoom, locale, blockunkownpeers == "true")
}
func (this *GrandCentralDispatcher) onActivate() {
log.Debugln("onActivate")
if the.CwtchApp != nil {
go the.CwtchApp.QueryACNStatus()
}
}
func (this *GrandCentralDispatcher) SetLocale_helper(locale string) {
core.QCoreApplication_RemoveTranslator(this.Translator)
this.Translator = core.NewQTranslator(nil)
this.Translator.Load("translation_"+locale, ":/i18n/", "", "")
core.QCoreApplication_InstallTranslator(this.Translator)
this.QMLEngine.Retranslate()
}
func (this *GrandCentralDispatcher) unlockProfiles(password string) {
the.CwtchApp.LoadProfiles(password)
}
func (this *GrandCentralDispatcher) loadProfile(onion string) {
the.Peer = the.CwtchApp.GetPeer(onion)
if the.Peer == nil {
return
}
the.EventBus = the.CwtchApp.GetEventBus(onion)
picVal, exists := the.Peer.GetAttribute(attr.GetPublicScope(constants.Picture))
if !exists {
picVal = ImageToString(NewImage(RandomProfileImage(onion), TypeImageDistro))
the.Peer.SetAttribute(attr.GetPublicScope(constants.Picture), picVal)
}
pic, err := StringToImage(picVal)
if err != nil {
pic = NewImage(RandomProfileImage(onion), TypeImageDistro)
the.Peer.SetAttribute(attr.GetPublicScope(constants.Picture), ImageToString(pic))
}
tag, _ := the.Peer.GetAttribute(app.AttributeTag)
this.UpdateMyProfile(the.Peer.GetName(), the.Peer.GetOnion(), getPicturePath(pic), tag)
contacts := the.Peer.GetContacts()
for i := range contacts {
this.GetUiManager(this.selectedProfile()).AddContact(contacts[i])
}
groups := the.Peer.GetGroups()
for i := range groups {
// Only join servers for active and explicitly accepted groups.
this.GetUiManager(this.selectedProfile()).AddContact(groups[i])
}
// load ui preferences
this.RequestSettings()
locale, exists := the.Peer.GetAttribute(attr.GetSettingsScope(constants.LocaleSetting))
if exists {
this.SetLocale_helper(locale)
}
}
func (this *GrandCentralDispatcher) createProfile(nick string, defaultPass bool, password string) {
if defaultPass {
the.CwtchApp.CreateTaggedPeer(nick, the.AppPassword, constants.ProfileTypeV1DefaultPassword)
} else {
the.CwtchApp.CreateTaggedPeer(nick, password, constants.ProfileTypeV1Password)
}
}
func (this *GrandCentralDispatcher) changePassword(onion, currentPassword, newPassword string, defaultPass bool) {
tag, _ := the.CwtchApp.GetPeer(onion).GetAttribute(app.AttributeTag)
if tag == constants.ProfileTypeV1DefaultPassword {
currentPassword = the.AppPassword
}
if defaultPass {
newPassword = the.AppPassword
}
the.CwtchApp.ChangePeerPassword(onion, currentPassword, newPassword)
}
func (this *GrandCentralDispatcher) reloadProfileList() {
this.ResetProfileList()
for onion, _ := range the.CwtchApp.ListPeers() {
AddProfile(this, onion)
}
}
func (this *GrandCentralDispatcher) deleteProfile(onion string) {
log.Infof("deleteProfile %v\n", onion)
the.CwtchApp.DeletePeer(onion)
}