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
from random import shuffle
import threading
from time import sleep
from time import sleep, time
from gevent import monkey; monkey.patch_all(); del monkey # noqa
import gevent
@ -75,7 +75,7 @@ from user_data.backup_service import BackupService
import styles.style # TODO: dynamic loading
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
import logging
@ -846,10 +846,10 @@ class App:
sleep(interval / 1000.0)
def _test_tox(self):
self.test_net()
self.test_net(iMax=8)
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)
# bootstrap
@ -906,7 +906,7 @@ class App:
self.loop(2)
global iLAST_CONN
iLAST_CONN = time.time()
iLAST_CONN = time()
def _test_env(self):
_settings = self._settings
@ -961,7 +961,7 @@ class App:
lElts = self._settings['current_nodes_tcp']
shuffle(lElts)
try:
bootstrap_iNodeInfo(lElts)
test_bootstrap_iNmapInfo(lElts)
except Exception as e:
# json.decoder.JSONDecodeError
LOG.error(f"test_tox ' +' : {e}")

View file

@ -21,6 +21,8 @@ LOG = logging.getLogger('app.'+'bootstrap')
def download_nodes_list(settings, oArgs):
if not settings['download_nodes_list']:
return ''
if not ts.bAreWeConnected():
return ''
url = settings['download_nodes_url']
path = _get_nodes_path(oArgs=oArgs)
# 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")
return False
if self._active_contact not in self._contacts:
LOG.debug(f"_active_contact={self._active_contact} len={len(self._contacts)}")
return False
if not self._contacts[self._active_contact]:
LOG.debug(f"{self._contacts[self._active_contact]} {contact.tox_id}")
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
# -----------------------------------------------------------------------------------------------------------------
@ -296,7 +299,7 @@ class ContactsManager(ToxSave):
def get_or_create_group_peer_contact(self, group_number, peer_id):
group = self.get_group_by_number(group_number)
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:
LOG.error(f'no peer public_key ' + repr(dir(peer)))
else:
@ -304,7 +307,7 @@ class ContactsManager(ToxSave):
self.add_group_peer(group, peer)
return self.get_contact_by_tox_id(peer.public_key)
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):
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
def add_incoming_transfer_message(self, friend, accepted, size, file_name, file_number):
assert friend
author = MessageAuthor(friend.name, MESSAGE_AUTHOR['FRIEND'])
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)
@ -36,6 +37,7 @@ class FileTransfersMessagesService:
return tm
def add_outgoing_transfer_message(self, friend, size, file_name, file_number):
assert friend
author = MessageAuthor(self._profile.name, MESSAGE_AUTHOR['ME'])
status = FILE_TRANSFER_STATE['OUTGOING_NOT_STARTED']
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)
def add_unsent_file_message(self, friend, file_path, data):
assert friend
author = MessageAuthor(self._profile.name, MESSAGE_AUTHOR['ME'])
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)

View file

@ -1,7 +1,10 @@
# -*- mode: python; indent-tabs-mode: nil; py-indent-offset: 4; coding: utf-8 -*-
import common.tox_save as tox_save
import utils.ui as util_ui
from messenger.messages import *
from wrapper_tests.support_testing import assert_main_thread
from wrapper.toxcore_enums_and_consts import TOX_MAX_MESSAGE_LENGTH
global LOG
import logging
@ -60,34 +63,54 @@ class Messenger(tox_save.ToxSave):
self._screen.messageEdit.clear()
return
action_message_prefix = '/me '
if text.startswith(action_message_prefix):
message_type = TOX_MESSAGE_TYPE['ACTION']
text = text[len(action_message_prefix):]
else:
message_type = TOX_MESSAGE_TYPE['NORMAL']
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)
message_type = TOX_MESSAGE_TYPE['NORMAL']
if False: # undocumented
action_message_prefix = '/me '
if text.startswith(action_message_prefix):
message_type = TOX_MESSAGE_TYPE['ACTION']
text = text[len(action_message_prefix):]
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):
"""
Send message
:param text: message text
:param friend_number: number of friend
from Qt callback
"""
if friend_number is None:
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:
return
assert_main_thread()
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'))
t = util.get_unix_time()
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_number = group.number
if not text or group_number < 0 or peer_id < 0:
if not text:
return
if group.number < 0:
return
if peer_id and peer_id < 0:
return
assert_main_thread()
# FixMe: peer_id is None?
group_peer_contact = self._contacts_manager.get_or_create_group_peer_contact(group_number, peer_id)
# group_peer_contact now may be None
@ -309,6 +336,7 @@ class Messenger(tox_save.ToxSave):
self._add_info_message(friend_number, text)
def _add_info_message(self, friend_number, text):
assert friend
friend = self._get_friend_by_number(friend_number)
message = InfoMessage(text, util.get_unix_time())
friend.append_message(message)
@ -330,6 +358,7 @@ class Messenger(tox_save.ToxSave):
self._screen.messages.scrollToBottom()
self._contacts_manager.get_curr_contact().append_message(text_message)
else:
LOG.debug("_add_message not is_contact_active(contact)")
contact.inc_messages()
contact.append_message(text_message)
if not contact.visibility:

View file

@ -103,26 +103,14 @@ class InitThread(BaseThread):
def run(self):
LOG_DEBUG('InitThread run: ')
try:
if self._is_first_start:
if self._is_first_start and ts.bAreWeConnected():
if self._settings['download_nodes_list']:
LOG_INFO('downloading list of nodes')
download_nodes_list(self._settings, oArgs=self._app._args)
if False:
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:
if ts.bAreWeConnected():
LOG_INFO(f"calling test_net nodes")
threading.Timer(1.0,
self._app.test_net,
args=list(),
kwargs=dict(oThread=self, iMax=4)
).start()
self._app.test_net(oThread=self, iMax=4)
if self._is_first_start:
LOG_INFO('starting plugins')
@ -170,15 +158,8 @@ class ToxIterateThread(BaseQThread):
self._tox.self_get_connection_status() == TOX_CONNECTION['NONE']:
iLAST_CONN = time.time()
LOG_INFO(f"ToxIterateThread calling test_net")
if True:
invoke_in_main_thread(
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()
invoke_in_main_thread(
self._app.test_net, oThread=self, iMax=2)
class ToxAVIterateThread(BaseQThread):

View file

@ -9,9 +9,6 @@ import os
global LOG
import logging
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 utils import util
@ -30,6 +27,7 @@ def LOG_DEBUG(a):
def LOG_TRACE(a):
bVERBOSE = hasattr(__builtins__, 'app') and app.oArgs.loglevel < 10
if bVERBOSE: print('TRAC> '+a)
def LOG_LOG(a): print('TRAC> '+a)
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 user_data The user data pointer passed to tox_new in options.
"""
file = str(file, 'UTF-8')
func = str(func, 'UTF-8')
message = str(message, 'UTF-8')
if file == 'network.c' and line == 660: return
# 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
message = f"{file}#{line}:{func} {message}"
LOG_LOG(message)
try:
if type(file) == bytes:
file = str(file, 'UTF-8')
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
if type(func) == bytes:
func = str(func, 'UTF-8')
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):
"""
: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.self_logger_cb)
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)
except Exception as e:

View file

@ -733,8 +733,8 @@ class MainWindow(QtWidgets.QMainWindow):
def test_tox(self):
self._app._test_tox()
def test_socks(self):
self._app._test_socks()
def test_nmap(self):
self._app._test_nmap()
def quit_program(self):
try:
@ -904,9 +904,13 @@ class MainWindow(QtWidgets.QMainWindow):
def show_search_field(self):
if hasattr(self, 'search_field') and self.search_field.isVisible():
#?
self.search_field.show()
return
if self._contacts_manager.get_curr_friend() is None:
return
if not hasattr(self._contacts_manager, 'get_curr_friend') or \
self._contacts_manager.get_curr_friend() is None:
#? return
pass
self.search_field = self._widget_factory.create_search_screen(self.messages)
x, y = self.messages.x(), self.messages.y() + self.messages.height() - 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_message()
except Exception as e:
LOG.error(f"keyPressEvent ERROR send_message to {self._messenger}")
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():
self.appendPlainText(self._messenger.get_last_message())