refactor: code cleanup

This commit is contained in:
Richard Ramos 2020-06-03 16:33:36 -04:00 committed by Iuri Matias
parent 2641986bbe
commit dd0e9de324
12 changed files with 56 additions and 63 deletions

View File

@ -1,5 +1,5 @@
import NimQml
import json, eventemitter, chronicles
import eventemitter, chronicles
import ../../status/chat as chat_model
import ../../status/mailservers as mailserver_model
import ../../signals/types
@ -29,11 +29,11 @@ proc delete*(self: ChatController) =
delete self.variant
proc handleChatEvents(self: ChatController) =
# Display already saved messages
self.status.events.on("messagesLoaded") do(e:Args):
for message in MsgsLoadedArgs(e).messages:
self.view.pushMessage(message.chatId, message.toChatMessage())
self.status.events.on("messageSent") do(e: Args):
var sentMessage = MsgArgs(e)
var chatMessage = sentMessage.payload.toChatMessage()
@ -62,7 +62,6 @@ proc handleMailserverEvents(self: ChatController) =
self.status.events.on("mailserverAvailable") do(e:Args):
self.status.mailservers.requestMessages()
proc init*(self: ChatController) =
self.handleMailserverEvents()
self.handleChatEvents()
@ -72,24 +71,20 @@ proc init*(self: ChatController) =
self.view.setActiveChannelByIndex(0)
proc handleMessage(self: ChatController, data: Signal) =
var messageSignal = cast[MessageSignal](data)
proc handleMessage(self: ChatController, data: MessageSignal) =
for c in data.chats:
self.view.updateChat(c.toChatItem())
for c in messageSignal.chats:
let channel = c.toChatItem()
self.view.updateChat(channel)
for message in data.messages:
self.view.pushMessage(message.localChatId, message.toChatMessage())
for message in messageSignal.messages:
let chatMessage = message.toChatMessage()
self.view.pushMessage(message.localChatId, chatMessage)
proc handleDiscoverySummary(self: ChatController, data: Signal) =
var discovery = DiscoverySummarySignal(data)
self.status.mailservers.peerSummaryChange(discovery.enodes)
proc handleDiscoverySummary(self: ChatController, data: DiscoverySummarySignal) =
## Handle mailserver peers being added and removed
self.status.mailservers.peerSummaryChange(data.enodes)
method onSignal(self: ChatController, data: Signal) =
case data.signalType:
of SignalType.Message: handleMessage(self, data)
of SignalType.DiscoverySummary: handleDiscoverySummary(self, data)
of SignalType.Message: handleMessage(self, MessageSignal(data))
of SignalType.DiscoverySummary: handleDiscoverySummary(self, DiscoverySummarySignal(data))
else:
warn "Unhandled signal received", signalType = data.signalType

View File

@ -32,7 +32,7 @@ QtObject:
result.setup()
proc getChatsList(self: ChatsView): QVariant {.slot.} =
return newQVariant(self.chats)
newQVariant(self.chats)
QtProperty[QVariant] chats:
read = getChatsList
@ -53,7 +53,7 @@ QtObject:
self.activeChannelChanged()
proc getActiveChannelIdx(self: ChatsView): QVariant {.slot.} =
return newQVariant(self.chats.chats.findById(self.activeChannel.id))
newQVariant(self.chats.chats.findById(self.activeChannel.id))
QtProperty[QVariant] activeChannelIndex:
read = getActiveChannelIdx
@ -65,7 +65,7 @@ QtObject:
self.activeChannelChanged()
proc getActiveChannel*(self: ChatsView): QVariant {.slot.} =
result = newQVariant(self.activeChannel)
newQVariant(self.activeChannel)
QtProperty[QVariant] activeChannel:
read = getActiveChannel

View File

@ -21,14 +21,17 @@ QtObject:
self.chatItem = chatItem
proc id*(self: ChatItemView): string {.slot.} = result = ?.self.chatItem.id
QtProperty[string] id:
read = id
proc name*(self: ChatItemView): string {.slot.} = result = ?.self.chatItem.name
QtProperty[string] name:
read = name
proc identicon*(self: ChatItemView): string {.slot.} = result = ?.self.chatItem.identicon
QtProperty[string] identicon:
read = identicon
@ -37,5 +40,6 @@ QtObject:
result = self.chatItem.chatType.int
else:
result = 0
QtProperty[int] chatType:
read = chatType

View File

@ -98,3 +98,4 @@ QtObject:
read = statusSignal
write = receiveSignal
notify = signalReceived

View File

@ -1,36 +1,34 @@
import eventemitter, sets, json, strutils
import eventemitter, sets, json
import sequtils
import libstatus/utils
import libstatus/core as status_core
import libstatus/chat as status_chat
import libstatus/mailservers as status_mailservers
import chronicles
import ../signals/types
import chat/chat_item
import chat/chat_message
import tables
export chat_item
export chat_message
type MsgArgs* = ref object of Args
type
MsgArgs* = ref object of Args
message*: string
chatId*: string
payload*: JsonNode
type ChannelArgs* = ref object of Args
ChannelArgs* = ref object of Args
channel*: string
chatTypeInt*: ChatType
type ChatArgs* = ref object of Args
chats*: seq[Chat]
ChatArgs* = ref object of Args
chats*: seq[Chat]
type TopicArgs* = ref object of Args
topics*: seq[string]
TopicArgs* = ref object of Args
topics*: seq[string]
type MsgsLoadedArgs* = ref object of Args
messages*: seq[Message]
MsgsLoadedArgs* = ref object of Args
messages*: seq[Message]
type
ChatModel* = ref object
events*: EventEmitter
channels*: HashSet[string]
@ -69,12 +67,9 @@ proc join*(self: ChatModel, chatId: string, chatType: ChatType) =
else:
self.events.emit("mailserverTopics", TopicArgs(topics: topics));
self.events.emit("channelJoined", ChannelArgs(channel: chatId, chatTypeInt: chatType))
self.events.emit("activeChannelChanged", ChannelArgs(channel: self.getActiveChannel()))
proc init*(self: ChatModel) =
let chatList = status_chat.loadChats()
@ -103,7 +98,6 @@ proc init*(self: ChatModel) =
else:
self.events.emit("mailserverTopics", TopicArgs(topics: topics));
proc leave*(self: ChatModel, chatId: string) =
status_chat.removeFilters(chatId, self.filters[chatId])
status_chat.deactivateChat(chatId)

View File

@ -73,7 +73,7 @@ proc loadChats*(): seq[Chat] =
proc chatMessages*(chatId: string): seq[Message] =
result = @[]
let rpcResult = parseJson(callPrivateRPC("chatMessages".prefix, %* [chatId, nil, 5]))["result"]
let rpcResult = parseJson(callPrivateRPC("chatMessages".prefix, %* [chatId, nil, 1000]))["result"]
if rpcResult["messages"].kind != JNull:
for jsonMsg in rpcResult["messages"]:
result.add(jsonMsg.toMessage)
@ -85,20 +85,6 @@ proc generateSymKeyFromPassword*(): string =
"status-offline-inbox"
]))["result"]).strip(chars = {'"'})
proc requestMessages*(topics: seq[string], symKeyID: string, peer: string, numberOfMessages: int) =
echo callPrivateRPC("requestMessages".prefix, %* [
{
"topics": topics,
"mailServerPeer": peer,
"symKeyID": symKeyID,
"timeout": 30,
"limit": numberOfMessages,
"cursor": nil,
"from": (times.toUnix(times.getTime()) - 86400) # Unhardcode this. Need to keep the last fetch in a DB
}
])
proc sendChatMessage*(chatId: string, msg: string): string =
callPrivateRPC("sendChatMessage".prefix, %* [
{

View File

@ -39,7 +39,7 @@ proc addPeer*(peer: string) =
discard callPrivateRPC("admin_addPeer", %* [peer])
proc removePeer*(peer: string) =
echo "TODO: removePeer"
discard callPrivateRPC("admin_removePeer", %* [peer])
proc markTrustedPeer*(peer: string) =
discard callPrivateRPC("markTrustedPeer".prefix(false), %* [peer])

View File

@ -1,6 +1,7 @@
import core
import json
import utils
import times
proc getMailservers*(): array[0..8, (string, string)] =
result = [
@ -58,3 +59,17 @@ proc update*(peer: string) =
proc delete*(peer: string) =
discard callPrivateRPC("mailservers_deleteMailserver".prefix, %* [[peer]])
proc requestMessages*(topics: seq[string], symKeyID: string, peer: string, numberOfMessages: int) =
echo callPrivateRPC("requestMessages".prefix, %* [
{
"topics": topics,
"mailServerPeer": peer,
"symKeyID": symKeyID,
"timeout": 30,
"limit": numberOfMessages,
"cursor": nil,
"from": (times.toUnix(times.getTime()) - 86400) # Unhardcode this. Need to keep the last fetch in a DB
}
])

View File

@ -83,7 +83,7 @@ proc connect*(self: MailserverModel, enode: string) =
return
self.selectedMailserver = enode
if self.nodes.hasKey(enode):
if self.nodes.hasKey(enode) and self.nodes[enode] == MailserverStatus.Connecting:
if self.nodes[enode] == MailserverStatus.Connected:
self.trustPeer(enode)
else:
@ -94,12 +94,9 @@ proc connect*(self: MailserverModel, enode: string) =
status_mailservers.update(enode)
proc peerSummaryChange*(self: MailserverModel, peers: seq[string]) =
for p in peers:
debug "Peer summary", p
for peer in self.nodes.keys:
if not peers.contains(peer):
self.nodes[peer] = MailserverStatus.Disconnected
warn "Peer disconnected", peer
self.events.emit("peerDisconnected", MailserverArg(peer: peer))
# TODO: reconnect peer up to N times on 'peerDisconnected'
@ -117,15 +114,17 @@ proc peerSummaryChange*(self: MailserverModel, peers: seq[string]) =
proc requestMessages*(self: MailserverModel) =
debug "Requesting messages from", mailserver=self.selectedMailserver
let generatedSymKey = status_chat.generateSymKeyFromPassword()
status_chat.requestMessages(toSeq(self.topics), generatedSymKey, self.selectedMailserver, 1000)
status_mailservers.requestMessages(toSeq(self.topics), generatedSymKey, self.selectedMailserver, 1000)
proc autoConnect(self: MailserverModel) =
let mailserversReply = parseJson(status_mailservers.ping(500))["result"]
var availableMailservers:seq[(string, int)] = @[]
for reply in mailserversReply:
if(reply["error"].kind != JNull): continue # The results with error are ignored
availableMailservers.add((reply["address"].getStr, reply["rttMs"].getInt))
availableMailservers.sort(cmpMailserverReply)
# Picks a random mailserver amongs the ones with the lowest latency
# The pool size is 1/4 of the mailservers were pinged successfully
randomize()
@ -158,4 +157,3 @@ proc init*(self: MailserverModel) =
#TODO: connect to current mailserver from the settings
# or setup a random one:
self.autoConnect()

View File

@ -18,7 +18,7 @@ ModalPopup {
id: chatKeyBox
height: 44
color: Theme.grey
anchors.top: separator.bottom
anchors.top: parent.top
anchors.topMargin: 16
radius: 8
anchors.right: parent.right

View File

@ -50,7 +50,7 @@ Popup {
Image {
id: closeModalImg
source: "../../../img/close.svg"
source: "./img/close.svg"
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
}

View File

Before

Width:  |  Height:  |  Size: 664 B

After

Width:  |  Height:  |  Size: 664 B