From a2e5f652da9a4bc45a6ca26056cd4526d2095b35 Mon Sep 17 00:00:00 2001 From: "Schimon Jehudah, Adv." Date: Thu, 21 Nov 2024 13:40:43 +0200 Subject: [PATCH] Improve reference to bot; Add more handlers instead of repeatedly processing for data. --- kaikout/__main__.py | 17 +- kaikout/database.py | 432 +----------------------------------- kaikout/utilities.py | 31 +-- kaikout/xmpp/chat.py | 18 +- kaikout/xmpp/client.py | 69 +++--- kaikout/xmpp/commands.py | 32 +-- kaikout/xmpp/moderation.py | 6 +- kaikout/xmpp/muc.py | 19 -- kaikout/xmpp/observation.py | 4 +- kaikout/xmpp/status.py | 6 +- 10 files changed, 95 insertions(+), 539 deletions(-) diff --git a/kaikout/__main__.py b/kaikout/__main__.py index bb4d44b..4482f82 100644 --- a/kaikout/__main__.py +++ b/kaikout/__main__.py @@ -86,15 +86,14 @@ def main(): Toml.save_file(file_settings, data_settings) # Try configuration file - account_xmpp = Config.get_values('accounts.toml', 'xmpp') - if 'client' in account_xmpp: - account_xmpp_client = account_xmpp['client'] - jid = account_xmpp_client['jid'] - password = account_xmpp_client['password'] - alias = account_xmpp_client['alias'] if 'alias' in account_xmpp_client else None - hostname = account_xmpp_client['hostname'] if 'hostname' in account_xmpp_client else None - port = account_xmpp_client['port'] if 'port' in account_xmpp_client else None - XmppClient(jid, password, hostname, port, alias) + jid = data_settings_account['jid'] + password = data_settings_account['password'] + alias = data_settings_account['alias'] + # TODO + #hostname = account_xmpp_client['hostname'] if 'hostname' in account_xmpp_client else None + #port = account_xmpp_client['port'] if 'port' in account_xmpp_client else None + hostname = port = None + XmppClient(jid, password, hostname, port, alias) if __name__ == '__main__': main() diff --git a/kaikout/database.py b/kaikout/database.py index a1bceb2..ba4a32d 100644 --- a/kaikout/database.py +++ b/kaikout/database.py @@ -3,7 +3,6 @@ from asyncio import Lock from kaikout.log import Logger -from sqlite3 import connect, Error, IntegrityError import os import sys import time @@ -18,429 +17,10 @@ import tomllib # # with start_action(action_type="search_entries()", query=query): # # with start_action(action_type="check_entry()", link=link): -CURSORS = {} - -# aiosqlite -DBLOCK = Lock() - logger = Logger(__name__) -class SQLite: - - - def create_connection(db_file): - """ - Create a database connection to the SQLite database - specified by db_file. - - Parameters - ---------- - db_file : str - Path to database file. - - Returns - ------- - conn : object - Connection object or None. - """ - time_begin = time.time() - function_name = sys._getframe().f_code.co_name - message_log = '{}' - logger.debug(message_log.format(function_name)) - conn = None - try: - conn = connect(db_file) - conn.execute("PRAGMA foreign_keys = ON") - # return conn - except Error as e: - logger.warning('Error creating a connection to database {}.'.format(db_file)) - logger.error(e) - time_end = time.time() - difference = time_end - time_begin - if difference > 1: logger.warning('{} (time: {})'.format(function_name, - difference)) - return conn - - - def create_tables(db_file): - """ - Create SQLite tables. - - Parameters - ---------- - db_file : str - Path to database file. - """ - function_name = sys._getframe().f_code.co_name - logger.debug('{}: db_file: {}' - .format(function_name, db_file)) - with SQLite.create_connection(db_file) as conn: - activity_table_sql = ( - """ - CREATE TABLE IF NOT EXISTS activity ( - id INTEGER NOT NULL, - stanza_id TEXT, - alias TEXT, - jid TEXT, - body TEXT, - thread TEXT, - PRIMARY KEY ("id") - ); - """ - ) - filters_table_sql = ( - """ - CREATE TABLE IF NOT EXISTS filters ( - id INTEGER NOT NULL, - key TEXT NOT NULL, - value TEXT NOT NULL, - PRIMARY KEY ("id") - ); - """ - ) - outcast_table_sql = ( - """ - CREATE TABLE IF NOT EXISTS outcast ( - id INTEGER NOT NULL, - alias TEXT, - jid TEXT, - reason TEXT, - PRIMARY KEY ("id") - ); - """ - ) - settings_table_sql = ( - """ - CREATE TABLE IF NOT EXISTS settings ( - id INTEGER NOT NULL, - key TEXT NOT NULL, - value INTEGER, - PRIMARY KEY ("id") - ); - """ - ) - cur = conn.cursor() - # cur = get_cursor(db_file) - cur.execute(activity_table_sql) - cur.execute(filters_table_sql) - cur.execute(outcast_table_sql) - cur.execute(settings_table_sql) - - - def get_cursor(db_file): - """ - Allocate a cursor to connection per database. - - Parameters - ---------- - db_file : str - Path to database file. - - Returns - ------- - CURSORS[db_file] : object - Cursor. - """ - function_name = sys._getframe().f_code.co_name - logger.debug('{}: db_file: {}' - .format(function_name, db_file)) - if db_file in CURSORS: - return CURSORS[db_file] - else: - with SQLite.create_connection(db_file) as conn: - cur = conn.cursor() - CURSORS[db_file] = cur - return CURSORS[db_file] - - - async def import_feeds(db_file, feeds): - """ - Insert a new feed into the feeds table. - - Parameters - ---------- - db_file : str - Path to database file. - feeds : list - Set of feeds (Title and URL). - """ - function_name = sys._getframe().f_code.co_name - logger.debug('{}: db_file: {}' - .format(function_name, db_file)) - async with DBLOCK: - with SQLite.create_connection(db_file) as conn: - cur = conn.cursor() - for feed in feeds: - logger.debug('{}: feed: {}' - .format(function_name, feed)) - url = feed['url'] - title = feed['title'] - sql = ( - """ - INSERT - INTO feeds_properties( - title, url) - VALUES( - ?, ?) - """ - ) - par = (title, url) - try: - cur.execute(sql, par) - except IntegrityError as e: - logger.warning("Skipping: " + str(url)) - logger.error(e) - - - async def add_metadata(db_file): - """ - Insert a new feed into the feeds table. - - Parameters - ---------- - db_file : str - Path to database file. - """ - function_name = sys._getframe().f_code.co_name - logger.debug('{}: db_file: {}' - .format(function_name, db_file)) - async with DBLOCK: - with SQLite.create_connection(db_file) as conn: - cur = conn.cursor() - sql = ( - """ - SELECT id - FROM feeds_properties - ORDER BY id ASC - """ - ) - ixs = cur.execute(sql).fetchall() - for ix in ixs: - feed_id = ix[0] - # Set feed status - sql = ( - """ - INSERT - INTO feeds_state( - feed_id) - VALUES( - ?) - """ - ) - par = (feed_id,) - try: - cur.execute(sql, par) - except IntegrityError as e: - logger.warning( - "Skipping feed_id {} for table feeds_state".format(feed_id)) - logger.error(e) - # Set feed preferences. - sql = ( - """ - INSERT - INTO feeds_preferences( - feed_id) - VALUES( - ?) - """ - ) - par = (feed_id,) - try: - cur.execute(sql, par) - except IntegrityError as e: - logger.warning( - "Skipping feed_id {} for table feeds_preferences".format(feed_id)) - logger.error(e) - - - async def insert_feed(db_file, url, title, identifier, entries=None, version=None, - encoding=None, language=None, status_code=None, - updated=None): - """ - Insert a new feed into the feeds table. - - Parameters - ---------- - db_file : str - Path to database file. - url : str - URL. - title : str - Feed title. - identifier : str - Feed identifier. - entries : int, optional - Number of entries. The default is None. - version : str, optional - Type of feed. The default is None. - encoding : str, optional - Encoding of feed. The default is None. - language : str, optional - Language code of feed. The default is None. - status : str, optional - HTTP status code. The default is None. - updated : ???, optional - Date feed was last updated. The default is None. - """ - function_name = sys._getframe().f_code.co_name - logger.debug('{}: db_file: {} url: {}' - .format(function_name, db_file, url)) - async with DBLOCK: - with SQLite.create_connection(db_file) as conn: - cur = conn.cursor() - sql = ( - """ - INSERT - INTO feeds_properties( - url, title, identifier, entries, version, encoding, language, updated) - VALUES( - ?, ?, ?, ?, ?, ?, ?, ?) - """ - ) - par = (url, title, identifier, entries, version, encoding, language, updated) - cur.execute(sql, par) - sql = ( - """ - SELECT id - FROM feeds_properties - WHERE url = :url - """ - ) - par = (url,) - feed_id = cur.execute(sql, par).fetchone()[0] - sql = ( - """ - INSERT - INTO feeds_state( - feed_id, status_code, valid) - VALUES( - ?, ?, ?) - """ - ) - par = (feed_id, status_code, 1) - cur.execute(sql, par) - sql = ( - """ - INSERT - INTO feeds_preferences( - feed_id) - VALUES( - ?) - """ - ) - par = (feed_id,) - cur.execute(sql, par) - - - async def remove_feed_by_url(db_file, url): - """ - Delete a feed by feed URL. - - Parameters - ---------- - db_file : str - Path to database file. - url : str - URL of feed. - """ - function_name = sys._getframe().f_code.co_name - logger.debug('{}: db_file: {} url: {}' - .format(function_name, db_file, url)) - with SQLite.create_connection(db_file) as conn: - async with DBLOCK: - cur = conn.cursor() - sql = ( - """ - DELETE - FROM feeds_properties - WHERE url = ? - """ - ) - par = (url,) - cur.execute(sql, par) - - - async def remove_feed_by_index(db_file, ix): - """ - Delete a feed by feed ID. - - Parameters - ---------- - db_file : str - Path to database file. - ix : str - Index of feed. - """ - function_name = sys._getframe().f_code.co_name - logger.debug('{}: db_file: {} ix: {}' - .format(function_name, db_file, ix)) - with SQLite.create_connection(db_file) as conn: - async with DBLOCK: - cur = conn.cursor() - # # NOTE Should we move DBLOCK to this line? 2022-12-23 - # sql = ( - # "DELETE " - # "FROM entries " - # "WHERE feed_id = ?" - # ) - # par = (url,) - # cur.execute(sql, par) # Error? 2024-01-05 - # sql = ( - # "DELETE " - # "FROM archive " - # "WHERE feed_id = ?" - # ) - # par = (url,) - # cur.execute(sql, par) - sql = ( - """ - DELETE - FROM feeds_properties - WHERE id = ? - """ - ) - par = (ix,) - cur.execute(sql, par) - - - def get_feeds_by_tag_id(db_file, tag_id): - """ - Get feeds of given tag. - - Parameters - ---------- - db_file : str - Path to database file. - tag_id : str - Tag ID. - - Returns - ------- - result : tuple - List of tags. - """ - function_name = sys._getframe().f_code.co_name - logger.debug('{}: db_file: {} tag_id: {}' - .format(function_name, db_file, tag_id)) - with SQLite.create_connection(db_file) as conn: - cur = conn.cursor() - sql = ( - """ - SELECT feeds_properties.* - FROM feeds_properties - INNER JOIN tagged_feeds ON feeds_properties.id = tagged_feeds.feed_id - INNER JOIN tags ON tags.id = tagged_feeds.tag_id - WHERE tags.id = ? - ORDER BY feeds_properties.title; - """ - ) - par = (tag_id,) - result = cur.execute(sql, par).fetchall() - return result - - -class Toml: +class DatabaseToml: def instantiate(self, room): @@ -462,7 +42,7 @@ class Toml: object Coroutine object. """ - data_dir = Toml.get_default_data_directory() + data_dir = DatabaseToml.get_default_data_directory() if not os.path.isdir(data_dir): os.mkdir(data_dir) data_dir_toml = os.path.join(data_dir, 'toml') @@ -470,8 +50,8 @@ class Toml: os.mkdir(data_dir_toml) filename = os.path.join(data_dir_toml, f'{room}.toml') if not os.path.exists(filename): - Toml.create_settings_file(self, filename) - Toml.load_jid_settings(self, room, filename) + DatabaseToml.create_settings_file(self, filename) + DatabaseToml.load_jid_settings(self, room, filename) return filename @@ -499,8 +79,8 @@ class Toml: def load_jid_settings(self, room, filename): - # data_dir = Toml.get_default_data_directory() - # filename = Toml.get_data_file(data_dir, room) + # data_dir = DatabaseToml.get_default_data_directory() + # filename = DatabaseToml.get_data_file(data_dir, room) with open(filename, 'rb') as f: self.settings[room] = tomllib.load(f) diff --git a/kaikout/utilities.py b/kaikout/utilities.py index 190d63a..d481d05 100644 --- a/kaikout/utilities.py +++ b/kaikout/utilities.py @@ -4,7 +4,7 @@ import csv from email.utils import parseaddr import hashlib -from kaikout.database import Toml +from kaikout.database import DatabaseToml from kaikout.log import Logger #import kaikout.sqlite as sqlite import os @@ -79,25 +79,6 @@ class Config: return os.path.join(directory_config_home, 'kaikout') - def get_setting_value(db_file, key): - value = sqlite.get_setting_value(db_file, key) - if value: - value = value[0] - else: - value = Config.get_value('settings', 'Settings', key) - return value - - - def get_values(filename, key=None): - config_dir = Config.get_default_config_directory() - if not os.path.isdir(config_dir): config_dir = os.path.join('usr', 'share', 'kaikout') - if not os.path.isdir(config_dir): config_dir = os.path.join(os.path.dirname(__file__), 'assets') - config_file = os.path.join(config_dir, filename) - with open(config_file, mode="rb") as f: result = tomllib.load(f) - values = result[key] if key else result - return values - - class Documentation: @@ -270,8 +251,8 @@ class Log: None. """ alias, content, identifier, timestamp = fields - data_dir = Toml.get_default_data_directory() - filename = Toml.get_data_file(data_dir, room) + data_dir = DatabaseToml.get_default_data_directory() + filename = DatabaseToml.get_data_file(data_dir, room) # filename = room + '.toml' entry = {} entry['alias'] = alias @@ -315,12 +296,6 @@ class BlockList: return filename - def load_blocklist(self): - filename = BlockList.get_filename() - with open(filename, 'rb') as f: - self.blocklist = tomllib.load(f) - - def add_entry_to_blocklist(self, jabber_id, node_id, item_id): """ Update blocklist file. diff --git a/kaikout/xmpp/chat.py b/kaikout/xmpp/chat.py index 31fd53c..184bf9c 100644 --- a/kaikout/xmpp/chat.py +++ b/kaikout/xmpp/chat.py @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- # from slixmpp import JID -from kaikout.database import Toml +from kaikout.database import DatabaseToml from kaikout.log import Logger from kaikout.utilities import Documentation from kaikout.xmpp.commands import XmppCommands @@ -52,13 +52,19 @@ class XmppChat: if message_type == 'groupchat': alias = message['mucnick'] room = message['mucroom'] - alias_of_kaikout = XmppUtilities.get_self_alias(self, jid_bare) + self_alias = XmppUtilities.get_self_alias(self, jid_bare) + if (message['mucnick'] == self.alias or not XmppUtilities.is_moderator(self, room, alias) or - not message_body.startswith(alias_of_kaikout)): + (not message_body.startswith(self_alias + ' ') and + not message_body.startswith(self_alias + ',') and + not message_body.startswith(self_alias + ':'))): return - alias_of_kaikout_length = len(alias_of_kaikout) + 1 - command = message_body[alias_of_kaikout_length:].lstrip() + + # Adding one to the length because of + # assumption that a comma or a dot is added + self_alias_length = len(self_alias) + 1 + command = message_body[self_alias_length:].lstrip() elif message_type in ('chat', 'normal'): command = message_body jid_full = jid.full @@ -177,7 +183,7 @@ class XmppChat: print(message) return - db_file = Toml.instantiate(self, room) + db_file = DatabaseToml.instantiate(self, room) # # Support private message via groupchat # # See https://codeberg.org/poezio/slixmpp/issues/3506 diff --git a/kaikout/xmpp/client.py b/kaikout/xmpp/client.py index be9f93f..09c44b3 100644 --- a/kaikout/xmpp/client.py +++ b/kaikout/xmpp/client.py @@ -4,9 +4,9 @@ import asyncio from datetime import datetime from kaikout.about import Documentation -from kaikout.database import Toml +from kaikout.database import DatabaseToml from kaikout.log import Logger -from kaikout.utilities import Config, Log, BlockList +from kaikout.utilities import Config, Log, BlockList, Toml from kaikout.xmpp.bookmark import XmppBookmark from kaikout.xmpp.chat import XmppChat from kaikout.xmpp.commands import XmppCommands @@ -16,6 +16,7 @@ from kaikout.xmpp.muc import XmppMuc from kaikout.xmpp.observation import XmppObservation from kaikout.xmpp.pubsub import XmppPubsub from kaikout.xmpp.status import XmppStatus +import os import slixmpp import time @@ -39,23 +40,35 @@ class XmppClient(slixmpp.ClientXMPP): def __init__(self, jid, password, hostname, port, alias): slixmpp.ClientXMPP.__init__(self, jid, password, hostname, port, alias) + self.directory_config = Config.get_default_config_directory() + self.directory_shared = Config.get_default_data_directory() + # A handler for accounts. + filename_accounts = os.path.join(self.directory_config, 'accounts.toml') + self.data_accounts = Toml.open_file(filename_accounts) + self.data_accounts_xmpp = self.data_accounts['xmpp'] + # A handler for blocklist. + filename_blocklist = os.path.join(self.directory_shared, 'blocklist.toml') + self.blocklist = Toml.open_file(filename_blocklist) + # A handler for blocklist. + filename_rtbl = os.path.join(self.directory_config, 'rtbl.toml') + self.data_rtbl = Toml.open_file(filename_rtbl) + # A handler for settings. + filename_settings = os.path.join(self.directory_config, 'settings.toml') + self.data_settings = Toml.open_file(filename_settings) # Handlers for action messages. self.actions = {} self.action_count = 0 # A handler for alias. self.alias = alias # A handler for configuration. - self.defaults = Config.get_values('settings.toml', 'defaults') + self.defaults = self.data_settings['defaults'] # Handlers for connectivity. self.connection_attempts = 0 self.max_connection_attempts = 10 self.task_ping_instance = {} - self.reconnect_timeout = Config.get_values('accounts.toml', 'xmpp')['settings']['reconnect_timeout'] + self.reconnect_timeout = self.data_accounts_xmpp['settings']['reconnect_timeout'] # A handler for operators. - self.operators = Config.get_values('accounts.toml', 'xmpp')['operators'] - # A handler for blocklist. - #self.blocklist = {} - BlockList.load_blocklist(self) + self.operators = self.data_accounts_xmpp['operators'] # A handler for sessions. self.sessions = {} # A handler for settings. @@ -186,24 +199,26 @@ class XmppClient(slixmpp.ClientXMPP): fields = ['message', timestamp_iso, alias, message_body, lang, identifier] filename = datetime.today().strftime('%Y-%m-%d') + '_' + room Log.csv(filename, fields) - db_file = Toml.instantiate(self, room) + db_file = DatabaseToml.instantiate(self, room) timestamp = time.time() - jid_bare = XmppMuc.get_full_jid(self, room, alias).split('/')[0] - XmppCommands.update_last_activity(self, room, jid_bare, db_file, timestamp) - # Toml.load_jid_settings(self, room) - # await XmppChat.process_message(self, message) - if (XmppMuc.is_moderator(self, room, self.alias) and - self.settings[room]['enabled'] and - alias != self.alias and - jid_bare and - jid_bare not in self.settings[room]['jid_whitelist']): - identifier = message['id'] - fields = [alias, message_body, identifier, timestamp] - Log.toml(self, room, fields, 'message') - # Check for message - await XmppObservation.observe_message(self, db_file, alias, message_body, room) - # Check for inactivity - await XmppObservation.observe_inactivity(self, db_file, room) + jid_full = XmppMuc.get_full_jid(self, room, alias) + if jid_full and '/' in jid_full: + jid_bare = jid_full.split('/')[0] + XmppCommands.update_last_activity(self, room, jid_bare, db_file, timestamp) + # DatabaseToml.load_jid_settings(self, room) + # await XmppChat.process_message(self, message) + if (XmppMuc.is_moderator(self, room, self.alias) and + self.settings[room]['enabled'] and + alias != self.alias and + jid_bare and + jid_bare not in self.settings[room]['jid_whitelist']): + identifier = message['id'] + fields = [alias, message_body, identifier, timestamp] + Log.toml(self, room, fields, 'message') + # Check for message + await XmppObservation.observe_message(self, db_file, alias, message_body, room) + # Check for inactivity + await XmppObservation.observe_inactivity(self, db_file, room) async def on_muc_got_online(self, presence): @@ -257,7 +272,7 @@ class XmppClient(slixmpp.ClientXMPP): filename = datetime.today().strftime('%Y-%m-%d') + '_' + room # if identifier and presence_body: Log.csv(filename, fields) - db_file = Toml.instantiate(self, room) + db_file = DatabaseToml.instantiate(self, room) if (XmppMuc.is_moderator(self, room, self.alias) and self.settings[room]['enabled'] and alias != self.alias): @@ -322,7 +337,7 @@ class XmppClient(slixmpp.ClientXMPP): """ # self.command_list() # await self.get_roster() - rtbl_sources = Config.get_values('rtbl.toml')['sources'] + rtbl_sources = self.data_rtbl['sources'] for source in rtbl_sources: jabber_id = source['jabber_id'] node_id = source['node_id'] diff --git a/kaikout/xmpp/commands.py b/kaikout/xmpp/commands.py index 421762a..a9f0583 100644 --- a/kaikout/xmpp/commands.py +++ b/kaikout/xmpp/commands.py @@ -5,7 +5,7 @@ import asyncio import kaikout.config as config from kaikout.config import Config from kaikout.log import Logger -from kaikout.database import Toml +from kaikout.database import DatabaseToml from kaikout.utilities import Documentation, Url from kaikout.version import __version__ from kaikout.xmpp.bookmark import XmppBookmark @@ -37,7 +37,7 @@ class XmppCommands: async def clear_filter(self, room, db_file, key): value = [] self.settings[room][key] = value - Toml.update_jid_settings(self, room, db_file, key, value) + DatabaseToml.update_jid_settings(self, room, db_file, key, value) message = 'Filter {} has been purged.'.format(key) return message @@ -327,7 +327,7 @@ class XmppCommands: if jid_full: jid_bare = jid_full.split('/')[0] scores[jid_bare] = scores[jid_bare] + 1 if jid_bare in scores else 1 - Toml.update_jid_settings(self, room, db_file, 'scores', scores) + DatabaseToml.update_jid_settings(self, room, db_file, 'scores', scores) time.sleep(5) del self.actions[room][task_number] XmppStatus.send_status_message(self, room) @@ -355,7 +355,7 @@ class XmppCommands: """ scores = self.settings[room]['score_ban'] if 'score_ban' in self.settings[room] else {} scores[jid_bare] = scores[jid_bare] + 1 if jid_bare in scores else 1 - Toml.update_jid_settings(self, room, db_file, 'score_ban', scores) + DatabaseToml.update_jid_settings(self, room, db_file, 'score_ban', scores) # result = scores[jid_bare] # return result @@ -380,7 +380,7 @@ class XmppCommands: """ scores = self.settings[room]['score_kick'] if 'score_kick' in self.settings[room] else {} scores[jid_bare] = scores[jid_bare] + 1 if jid_bare in scores else 1 - Toml.update_jid_settings(self, room, db_file, 'score_kick', scores) + DatabaseToml.update_jid_settings(self, room, db_file, 'score_kick', scores) # result = scores[jid_bare] # return result @@ -407,7 +407,7 @@ class XmppCommands: """ activity = self.settings[room]['last_activity'] if 'last_activity' in self.settings[room] else {} activity[jid_bare] = timestamp - Toml.update_jid_settings(self, room, db_file, 'last_activity', activity) + DatabaseToml.update_jid_settings(self, room, db_file, 'last_activity', activity) def remove_last_activity(self, room, jid_bare, db_file): @@ -430,7 +430,7 @@ class XmppCommands: """ activity = self.settings[room]['last_activity'] if 'last_activity' in self.settings[room] else {} del activity[jid_bare] - Toml.update_jid_settings(self, room, db_file, 'last_activity', activity) + DatabaseToml.update_jid_settings(self, room, db_file, 'last_activity', activity) def raise_score_inactivity(self, room, alias, db_file): @@ -462,7 +462,7 @@ class XmppCommands: if jid_full: jid_bare = jid_full.split('/')[0] scores_inactivity[jid_bare] = scores_inactivity[jid_bare] + 1 if jid_bare in scores_inactivity else 1 - Toml.update_jid_settings(self, room, db_file, 'scores_inactivity', scores_inactivity) + DatabaseToml.update_jid_settings(self, room, db_file, 'scores_inactivity', scores_inactivity) time.sleep(5) del self.actions[room][task_number] XmppStatus.send_status_message(self, room) @@ -474,16 +474,16 @@ class XmppCommands: if key: value = self.defaults[key] self.settings[room][key] = value - # data_dir = Toml.get_default_data_directory() - # db_file = Toml.get_data_file(data_dir, jid_bare) - Toml.update_jid_settings(self, room, db_file, key, value) + # data_dir = DatabaseToml.get_default_data_directory() + # db_file = DatabaseToml.get_data_file(data_dir, jid_bare) + DatabaseToml.update_jid_settings(self, room, db_file, key, value) message = ('Setting {} has been restored to default value.' .format(key)) else: self.settings = self.defaults - data_dir = Toml.get_default_data_directory() - db_file = Toml.get_data_file(data_dir, room) - Toml.create_settings_file(self, db_file) + data_dir = DatabaseToml.get_default_data_directory() + db_file = DatabaseToml.get_data_file(data_dir, room) + DatabaseToml.create_settings_file(self, db_file) message = 'Default settings have been restored.' return message @@ -524,7 +524,7 @@ class XmppCommands: string_trim = string.strip() string_list.remove(string_trim) processed_strings.append(string_trim) - Toml.update_jid_settings(self, room, db_file, filter, string_list) + DatabaseToml.update_jid_settings(self, room, db_file, filter, string_list) processed_strings.sort() if processed_strings: message = 'Strings "{}" have been {} list "{}".'.format( @@ -551,4 +551,4 @@ class XmppCommands: def update_setting_value(self, room, db_file, key, value): - Toml.update_jid_settings(self, room, db_file, key, value) + DatabaseToml.update_jid_settings(self, room, db_file, key, value) diff --git a/kaikout/xmpp/moderation.py b/kaikout/xmpp/moderation.py index fcd61a0..bd91c95 100644 --- a/kaikout/xmpp/moderation.py +++ b/kaikout/xmpp/moderation.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -from kaikout.database import Toml +from kaikout.database import DatabaseToml from kaikout.log import Logger from kaikout.xmpp.commands import XmppCommands @@ -17,8 +17,8 @@ class XmppModeration: if jid_bare not in self.settings[room]['last_activity']: # self.settings[room]['last_activity'][jid_bare] = timestamp # last_activity_for_jid = self.settings[room]['last_activity'][jid_bare] - db_file = Toml.instantiate(self, room) - # Toml.update_jid_settings(self, room, db_file, 'last_activity', last_activity_for_jid) + db_file = DatabaseToml.instantiate(self, room) + # DatabaseToml.update_jid_settings(self, room, db_file, 'last_activity', last_activity_for_jid) XmppCommands.update_last_activity(self, room, jid_bare, db_file, timestamp) else: jid_last_activity = self.settings[room]['last_activity'][jid_bare] diff --git a/kaikout/xmpp/muc.py b/kaikout/xmpp/muc.py index 9c79b5e..5512967 100644 --- a/kaikout/xmpp/muc.py +++ b/kaikout/xmpp/muc.py @@ -101,25 +101,6 @@ class XmppMuc: async def join(self, jid, alias=None, password=None): - # token = await initdb( - # muc_jid, - # sqlite.get_setting_value, - # "token" - # ) - # if token != "accepted": - # token = randrange(10000, 99999) - # await initdb( - # muc_jid, - # sqlite.update_setting_value, - # ["token", token] - # ) - # self.send_message( - # mto=inviter, - # mfrom=self.boundjid.bare, - # mbody=( - # "Send activation token {} to groupchat xmpp:{}?join." - # ).format(token, muc_jid) - # ) logger.info('Joining groupchat\nJID : {}\n'.format(jid)) jid_from = str(self.boundjid) if self.is_component else None if not alias: alias = self.alias diff --git a/kaikout/xmpp/observation.py b/kaikout/xmpp/observation.py index 66efdc4..3646410 100644 --- a/kaikout/xmpp/observation.py +++ b/kaikout/xmpp/observation.py @@ -3,7 +3,7 @@ import asyncio from hashlib import sha256 -from kaikout.database import Toml +from kaikout.database import DatabaseToml from kaikout.log import Logger from kaikout.xmpp.commands import XmppCommands from kaikout.xmpp.message import XmppMessage @@ -70,7 +70,7 @@ class XmppObservation: 'You are expected to be expelled from ' 'groupchat {} within {} hour time.' .format(room, int(span) or 'an')) - Toml.update_jid_settings( + DatabaseToml.update_jid_settings( self, room, db_file, 'inactivity_notice', noticed_jids) if message_to_participant: XmppMessage.send( diff --git a/kaikout/xmpp/status.py b/kaikout/xmpp/status.py index 8aa2709..2d9a23e 100644 --- a/kaikout/xmpp/status.py +++ b/kaikout/xmpp/status.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -from kaikout.database import Toml +from kaikout.database import DatabaseToml from kaikout.log import Logger from kaikout.xmpp.presence import XmppPresence from kaikout.xmpp.utilities import XmppUtilities @@ -27,8 +27,8 @@ class XmppStatus: if not status_mode and not status_text: if XmppUtilities.is_moderator(self, room, self.alias): if room not in self.settings: - Toml.instantiate(self, room) - # Toml.load_jid_settings(self, room) + DatabaseToml.instantiate(self, room) + # DatabaseToml.load_jid_settings(self, room) if self.settings[room]['enabled']: jid_task = self.actions[room] if room in self.actions else None if jid_task and len(jid_task):