This commit is contained in:
emdee 2022-10-13 13:55:56 +00:00
parent a92bbbbcbf
commit 90e379a6de
9 changed files with 92 additions and 66 deletions

View File

@ -4,7 +4,7 @@ import sys
import traceback import traceback
from random import shuffle from random import shuffle
import threading import threading
from time import sleep from time import sleep, time
from gevent import monkey; monkey.patch_all(); del monkey # noqa from gevent import monkey; monkey.patch_all(); del monkey # noqa
import gevent import gevent
@ -75,7 +75,7 @@ from user_data.backup_service import BackupService
import styles.style # TODO: dynamic loading import styles.style # TODO: dynamic loading
import wrapper_tests.support_testing as ts import wrapper_tests.support_testing as ts
from wrapper_tests.tests_wrapper import bootstrap_iNodeInfo from wrapper_tests.tests_wrapper import test_bootstrap_iNmapInfo
global LOG global LOG
import logging import logging
@ -846,10 +846,10 @@ class App:
sleep(interval / 1000.0) sleep(interval / 1000.0)
def _test_tox(self): def _test_tox(self):
self.test_net() self.test_net(iMax=8)
self._ms.log_console() self._ms.log_console()
def test_net(self, oThread=None, iMax=4): def test_net(self, oThread=None, iMax=6):
LOG.debug("test_net " +self._oArgs.network) LOG.debug("test_net " +self._oArgs.network)
# bootstrap # bootstrap
@ -906,7 +906,7 @@ class App:
self.loop(2) self.loop(2)
global iLAST_CONN global iLAST_CONN
iLAST_CONN = time.time() iLAST_CONN = time()
def _test_env(self): def _test_env(self):
_settings = self._settings _settings = self._settings
@ -961,7 +961,7 @@ class App:
lElts = self._settings['current_nodes_tcp'] lElts = self._settings['current_nodes_tcp']
shuffle(lElts) shuffle(lElts)
try: try:
bootstrap_iNodeInfo(lElts) test_bootstrap_iNmapInfo(lElts)
except Exception as e: except Exception as e:
# json.decoder.JSONDecodeError # json.decoder.JSONDecodeError
LOG.error(f"test_tox ' +' : {e}") LOG.error(f"test_tox ' +' : {e}")

View File

@ -21,6 +21,8 @@ LOG = logging.getLogger('app.'+'bootstrap')
def download_nodes_list(settings, oArgs): def download_nodes_list(settings, oArgs):
if not settings['download_nodes_list']: if not settings['download_nodes_list']:
return '' return ''
if not ts.bAreWeConnected():
return ''
url = settings['download_nodes_url'] url = settings['download_nodes_url']
path = _get_nodes_path(oArgs=oArgs) path = _get_nodes_path(oArgs=oArgs)
# dont download blindly so we can edit the file and not block on startup # dont download blindly so we can edit the file and not block on startup

View File

@ -96,10 +96,13 @@ class ContactsManager(ToxSave):
LOG.warn("No self._active_contact") LOG.warn("No self._active_contact")
return False return False
if self._active_contact not in self._contacts: if self._active_contact not in self._contacts:
LOG.debug(f"_active_contact={self._active_contact} len={len(self._contacts)}")
return False return False
if not self._contacts[self._active_contact]: if not self._contacts[self._active_contact]:
LOG.debug(f"{self._contacts[self._active_contact]} {contact.tox_id}")
return False return False
LOG.debug(f"{self._contacts[self._active_contact].tox_id} == {contact.tox_id}")
return self._contacts[self._active_contact].tox_id == contact.tox_id return self._contacts[self._active_contact].tox_id == contact.tox_id
# ----------------------------------------------------------------------------------------------------------------- # -----------------------------------------------------------------------------------------------------------------
@ -296,7 +299,7 @@ class ContactsManager(ToxSave):
def get_or_create_group_peer_contact(self, group_number, peer_id): def get_or_create_group_peer_contact(self, group_number, peer_id):
group = self.get_group_by_number(group_number) group = self.get_group_by_number(group_number)
peer = group.get_peer_by_id(peer_id) peer = group.get_peer_by_id(peer_id)
if peer: # broken if peer: # broken?
if not hasattr(peer, 'public_key') or not peer.public_key: if not hasattr(peer, 'public_key') or not peer.public_key:
LOG.error(f'no peer public_key ' + repr(dir(peer))) LOG.error(f'no peer public_key ' + repr(dir(peer)))
else: else:
@ -304,7 +307,7 @@ class ContactsManager(ToxSave):
self.add_group_peer(group, peer) self.add_group_peer(group, peer)
return self.get_contact_by_tox_id(peer.public_key) return self.get_contact_by_tox_id(peer.public_key)
else: else:
LOG.warn(f'no peer group_number={group_number}') LOG.warn(f'no peer group_number={group_number} peer_id={peer_id}')
def check_if_contact_exists(self, tox_id): def check_if_contact_exists(self, tox_id):
return any(filter(lambda c: c.tox_id == tox_id, self._contacts)) return any(filter(lambda c: c.tox_id == tox_id, self._contacts))

View File

@ -21,6 +21,7 @@ class FileTransfersMessagesService:
self._messages = main_screen.messages self._messages = main_screen.messages
def add_incoming_transfer_message(self, friend, accepted, size, file_name, file_number): def add_incoming_transfer_message(self, friend, accepted, size, file_name, file_number):
assert friend
author = MessageAuthor(friend.name, MESSAGE_AUTHOR['FRIEND']) author = MessageAuthor(friend.name, MESSAGE_AUTHOR['FRIEND'])
status = FILE_TRANSFER_STATE['RUNNING'] if accepted else FILE_TRANSFER_STATE['INCOMING_NOT_STARTED'] status = FILE_TRANSFER_STATE['RUNNING'] if accepted else FILE_TRANSFER_STATE['INCOMING_NOT_STARTED']
tm = TransferMessage(author, util.get_unix_time(), status, size, file_name, friend.number, file_number) tm = TransferMessage(author, util.get_unix_time(), status, size, file_name, friend.number, file_number)
@ -36,6 +37,7 @@ class FileTransfersMessagesService:
return tm return tm
def add_outgoing_transfer_message(self, friend, size, file_name, file_number): def add_outgoing_transfer_message(self, friend, size, file_name, file_number):
assert friend
author = MessageAuthor(self._profile.name, MESSAGE_AUTHOR['ME']) author = MessageAuthor(self._profile.name, MESSAGE_AUTHOR['ME'])
status = FILE_TRANSFER_STATE['OUTGOING_NOT_STARTED'] status = FILE_TRANSFER_STATE['OUTGOING_NOT_STARTED']
tm = TransferMessage(author, util.get_unix_time(), status, size, file_name, friend.number, file_number) tm = TransferMessage(author, util.get_unix_time(), status, size, file_name, friend.number, file_number)
@ -61,6 +63,7 @@ class FileTransfersMessagesService:
self._create_inline_item(transfer.data, count + index + 1) self._create_inline_item(transfer.data, count + index + 1)
def add_unsent_file_message(self, friend, file_path, data): def add_unsent_file_message(self, friend, file_path, data):
assert friend
author = MessageAuthor(self._profile.name, MESSAGE_AUTHOR['ME']) author = MessageAuthor(self._profile.name, MESSAGE_AUTHOR['ME'])
size = os.path.getsize(file_path) if data is None else len(data) size = os.path.getsize(file_path) if data is None else len(data)
tm = UnsentFileMessage(file_path, data, util.get_unix_time(), author, size, friend.number) tm = UnsentFileMessage(file_path, data, util.get_unix_time(), author, size, friend.number)

View File

@ -1,7 +1,10 @@
# -*- mode: python; indent-tabs-mode: nil; py-indent-offset: 4; coding: utf-8 -*- # -*- mode: python; indent-tabs-mode: nil; py-indent-offset: 4; coding: utf-8 -*-
import common.tox_save as tox_save import common.tox_save as tox_save
import utils.ui as util_ui
from messenger.messages import * from messenger.messages import *
from wrapper_tests.support_testing import assert_main_thread from wrapper_tests.support_testing import assert_main_thread
from wrapper.toxcore_enums_and_consts import TOX_MAX_MESSAGE_LENGTH
global LOG global LOG
import logging import logging
@ -60,34 +63,54 @@ class Messenger(tox_save.ToxSave):
self._screen.messageEdit.clear() self._screen.messageEdit.clear()
return return
action_message_prefix = '/me ' message_type = TOX_MESSAGE_TYPE['NORMAL']
if text.startswith(action_message_prefix): if False: # undocumented
message_type = TOX_MESSAGE_TYPE['ACTION'] action_message_prefix = '/me '
text = text[len(action_message_prefix):] if text.startswith(action_message_prefix):
else: message_type = TOX_MESSAGE_TYPE['ACTION']
message_type = TOX_MESSAGE_TYPE['NORMAL'] text = text[len(action_message_prefix):]
if self._contacts_manager.is_active_a_friend():
self.send_message_to_friend(text, message_type)
elif self._contacts_manager.is_active_a_group():
self.send_message_to_group('~'+text, message_type)
elif self._contacts_manager.is_active_a_group_chat_peer():
self.send_message_to_group_peer(text, message_type)
if len(text) > TOX_MAX_MESSAGE_LENGTH:
text = text[:TOX_MAX_MESSAGE_LENGTH] # 1372
try:
if self._contacts_manager.is_active_a_friend():
self.send_message_to_friend(text, message_type)
elif self._contacts_manager.is_active_a_group():
self.send_message_to_group('~'+text, message_type)
elif self._contacts_manager.is_active_a_group_chat_peer():
self.send_message_to_group_peer(text, message_type)
else:
LOG.warn(f'Unknown friend type for Messenger send_message')
except Exception as e:
LOG.error(f'Messenger send_message {e}')
import traceback
LOG.warn(traceback.format_exc())
title = 'Messenger send_message Error'
text = 'Error: ' + str(e)
assert_main_thread()
util_ui.message_box(text, title)
def send_message_to_friend(self, text, message_type, friend_number=None): def send_message_to_friend(self, text, message_type, friend_number=None):
""" """
Send message Send message
:param text: message text :param text: message text
:param friend_number: number of friend :param friend_number: number of friend
from Qt callback
""" """
if friend_number is None: if friend_number is None:
friend_number = self._contacts_manager.get_active_number() friend_number = self._contacts_manager.get_active_number()
if friend_number is None:
LOG.error(f"No _contacts_manager.get_active_number")
return
if not text or friend_number < 0: if not text or friend_number < 0:
return return
assert_main_thread() assert_main_thread()
friend = self._get_friend_by_number(friend_number) friend = self._get_friend_by_number(friend_number)
if not friend:
LOG.error(f"No self._get_friend_by_number")
return
assert friend
messages = self._split_message(text.encode('utf-8')) messages = self._split_message(text.encode('utf-8'))
t = util.get_unix_time() t = util.get_unix_time()
for message in messages: for message in messages:
@ -172,10 +195,14 @@ class Messenger(tox_save.ToxSave):
group = self._get_group_by_public_key(group_peer_contact.group_pk) group = self._get_group_by_public_key(group_peer_contact.group_pk)
group_number = group.number group_number = group.number
if not text or group_number < 0 or peer_id < 0: if not text:
return return
if group.number < 0:
return
if peer_id and peer_id < 0:
return
assert_main_thread() assert_main_thread()
# FixMe: peer_id is None? # FixMe: peer_id is None?
group_peer_contact = self._contacts_manager.get_or_create_group_peer_contact(group_number, peer_id) group_peer_contact = self._contacts_manager.get_or_create_group_peer_contact(group_number, peer_id)
# group_peer_contact now may be None # group_peer_contact now may be None
@ -309,6 +336,7 @@ class Messenger(tox_save.ToxSave):
self._add_info_message(friend_number, text) self._add_info_message(friend_number, text)
def _add_info_message(self, friend_number, text): def _add_info_message(self, friend_number, text):
assert friend
friend = self._get_friend_by_number(friend_number) friend = self._get_friend_by_number(friend_number)
message = InfoMessage(text, util.get_unix_time()) message = InfoMessage(text, util.get_unix_time())
friend.append_message(message) friend.append_message(message)
@ -330,6 +358,7 @@ class Messenger(tox_save.ToxSave):
self._screen.messages.scrollToBottom() self._screen.messages.scrollToBottom()
self._contacts_manager.get_curr_contact().append_message(text_message) self._contacts_manager.get_curr_contact().append_message(text_message)
else: else:
LOG.debug("_add_message not is_contact_active(contact)")
contact.inc_messages() contact.inc_messages()
contact.append_message(text_message) contact.append_message(text_message)
if not contact.visibility: if not contact.visibility:

View File

@ -103,26 +103,14 @@ class InitThread(BaseThread):
def run(self): def run(self):
LOG_DEBUG('InitThread run: ') LOG_DEBUG('InitThread run: ')
try: try:
if self._is_first_start: if self._is_first_start and ts.bAreWeConnected():
if self._settings['download_nodes_list']: if self._settings['download_nodes_list']:
LOG_INFO('downloading list of nodes') LOG_INFO('downloading list of nodes')
download_nodes_list(self._settings, oArgs=self._app._args) download_nodes_list(self._settings, oArgs=self._app._args)
if False: if ts.bAreWeConnected():
lNodes = ts.generate_nodes()
LOG_INFO(f"bootstrapping {len(lNodes)!s} nodes")
for data in lNodes:
if self._stop_thread:
return
self._tox.bootstrap(*data)
self._tox.add_tcp_relay(*data)
else:
LOG_INFO(f"calling test_net nodes") LOG_INFO(f"calling test_net nodes")
threading.Timer(1.0, self._app.test_net(oThread=self, iMax=4)
self._app.test_net,
args=list(),
kwargs=dict(oThread=self, iMax=4)
).start()
if self._is_first_start: if self._is_first_start:
LOG_INFO('starting plugins') LOG_INFO('starting plugins')
@ -170,15 +158,8 @@ class ToxIterateThread(BaseQThread):
self._tox.self_get_connection_status() == TOX_CONNECTION['NONE']: self._tox.self_get_connection_status() == TOX_CONNECTION['NONE']:
iLAST_CONN = time.time() iLAST_CONN = time.time()
LOG_INFO(f"ToxIterateThread calling test_net") LOG_INFO(f"ToxIterateThread calling test_net")
if True: invoke_in_main_thread(
invoke_in_main_thread( self._app.test_net, oThread=self, iMax=2)
self._app.test_net, oThread=self, iMax=2)
else:
threading.Timer(1.0,
self._app.test_net,
args=list(),
kwargs=dict(lElts=None, oThread=self, iMax=2)
).start()
class ToxAVIterateThread(BaseQThread): class ToxAVIterateThread(BaseQThread):

View File

@ -9,9 +9,6 @@ import os
global LOG global LOG
import logging import logging
LOG = logging.getLogger('app.'+'tox_factory') LOG = logging.getLogger('app.'+'tox_factory')
def LOG_INFO(l): print('DBUG> '+l)
def LOG_DEBUG(l): print('DBUG> '+l)
def LOG_LOG(l): print('TRAC> '+l)
from ctypes import * from ctypes import *
from utils import util from utils import util
@ -30,6 +27,7 @@ def LOG_DEBUG(a):
def LOG_TRACE(a): def LOG_TRACE(a):
bVERBOSE = hasattr(__builtins__, 'app') and app.oArgs.loglevel < 10 bVERBOSE = hasattr(__builtins__, 'app') and app.oArgs.loglevel < 10
if bVERBOSE: print('TRAC> '+a) if bVERBOSE: print('TRAC> '+a)
def LOG_LOG(a): print('TRAC> '+a)
def tox_log_cb(iTox, level, file, line, func, message, *args): def tox_log_cb(iTox, level, file, line, func, message, *args):
""" """
@ -40,15 +38,20 @@ def tox_log_cb(iTox, level, file, line, func, message, *args):
* @param message The log message. * @param message The log message.
* @param user_data The user data pointer passed to tox_new in options. * @param user_data The user data pointer passed to tox_new in options.
""" """
file = str(file, 'UTF-8') try:
func = str(func, 'UTF-8') if type(file) == bytes:
message = str(message, 'UTF-8') file = str(file, 'UTF-8')
if file == 'network.c' and line == 660: return if file == 'network.c' and line in [944, 660]: return
# root WARNING 3network.c#944:b'send_packet'attempted to send message with network family 10 (probably IPv6) on IPv4 socket # root WARNING 3network.c#944:b'send_packet'attempted to send message with network family 10 (probably IPv6) on IPv4 socket
if file == 'network.c' and line == 944: return if type(func) == bytes:
message = f"{file}#{line}:{func} {message}" func = str(func, 'UTF-8')
LOG_LOG(message) if type(message) == bytes:
message = str(message, 'UTF-8')
message = f"{file}#{line}:{func} {message}"
LOG_LOG(message)
except Exception as e:
LOG_ERROR("tox_log_cb {e}")
def tox_factory(data=None, settings=None, args=None, app=None): def tox_factory(data=None, settings=None, args=None, app=None):
""" """
:param data: user data from .tox file. None = no saved data, create new profile :param data: user data from .tox file. None = no saved data, create new profile
@ -102,7 +105,7 @@ def tox_factory(data=None, settings=None, args=None, app=None):
tox_options._options_pointer, tox_options._options_pointer,
tox_options.self_logger_cb) tox_options.self_logger_cb)
else: else:
logging_WARN("No tox_options._options_pointer to add self_logger_cb" ) LOG_WARN("No tox_options._options_pointer to add self_logger_cb" )
retval = wrapper.tox.Tox(tox_options) retval = wrapper.tox.Tox(tox_options)
except Exception as e: except Exception as e:

View File

@ -733,8 +733,8 @@ class MainWindow(QtWidgets.QMainWindow):
def test_tox(self): def test_tox(self):
self._app._test_tox() self._app._test_tox()
def test_socks(self): def test_nmap(self):
self._app._test_socks() self._app._test_nmap()
def quit_program(self): def quit_program(self):
try: try:
@ -904,9 +904,13 @@ class MainWindow(QtWidgets.QMainWindow):
def show_search_field(self): def show_search_field(self):
if hasattr(self, 'search_field') and self.search_field.isVisible(): if hasattr(self, 'search_field') and self.search_field.isVisible():
#?
self.search_field.show()
return return
if self._contacts_manager.get_curr_friend() is None: if not hasattr(self._contacts_manager, 'get_curr_friend') or \
return self._contacts_manager.get_curr_friend() is None:
#? return
pass
self.search_field = self._widget_factory.create_search_screen(self.messages) self.search_field = self._widget_factory.create_search_screen(self.messages)
x, y = self.messages.x(), self.messages.y() + self.messages.height() - 40 x, y = self.messages.x(), self.messages.y() + self.messages.height() - 40
self.search_field.setGeometry(x, y, self.messages.width(), 40) self.search_field.setGeometry(x, y, self.messages.width(), 40)

View File

@ -48,8 +48,9 @@ class MessageArea(QtWidgets.QPlainTextEdit):
self._messenger.send_typing(False) self._messenger.send_typing(False)
self._messenger.send_message() self._messenger.send_message()
except Exception as e: except Exception as e:
LOG.error(f"keyPressEvent ERROR send_message to {self._messenger}")
util_ui.message_box(str(e), util_ui.message_box(str(e),
util_ui.tr(f"ERROR send_message to {self._messenger}")) util_ui.tr(f"keyPressEvent ERROR send_message to {self._messenger}"))
elif event.key() == QtCore.Qt.Key_Up and not self.toPlainText(): elif event.key() == QtCore.Qt.Key_Up and not self.toPlainText():
self.appendPlainText(self._messenger.get_last_message()) self.appendPlainText(self._messenger.get_last_message())