KaikOut/kaikout/database.py
Schimon Jehudah, Adv. a2e5f652da Improve reference to bot;
Add more handlers instead of repeatedly processing for data.
2024-11-21 13:40:43 +02:00

93 lines
2.8 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from asyncio import Lock
from kaikout.log import Logger
import os
import sys
import time
import tomli_w
import tomllib
# from eliot import start_action, to_file
# # with start_action(action_type="list_feeds()", db=db_file):
# # with start_action(action_type="last_entries()", num=num):
# # with start_action(action_type="get_feeds()"):
# # with start_action(action_type="remove_entry()", source=source):
# # with start_action(action_type="search_entries()", query=query):
# # with start_action(action_type="check_entry()", link=link):
logger = Logger(__name__)
class DatabaseToml:
def instantiate(self, room):
"""
Callback function to instantiate action on database.
Parameters
----------
jid_file : str
Filename.
callback : ?
Function name.
message : str, optional
Optional kwarg when a message is a part or
required argument. The default is None.
Returns
-------
object
Coroutine object.
"""
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')
if not os.path.isdir(data_dir_toml):
os.mkdir(data_dir_toml)
filename = os.path.join(data_dir_toml, f'{room}.toml')
if not os.path.exists(filename):
DatabaseToml.create_settings_file(self, filename)
DatabaseToml.load_jid_settings(self, room, filename)
return filename
def get_default_data_directory():
if os.environ.get('HOME'):
data_home = os.path.join(os.environ.get('HOME'), '.local', 'share')
return os.path.join(data_home, 'kaikout')
elif sys.platform == 'win32':
data_home = os.environ.get('APPDATA')
if data_home is None:
return 'kaikout_data'
else:
return 'kaikout_data'
def get_data_file(data_dir, room):
toml_file = os.path.join(data_dir, 'toml', f'{room}.toml')
return toml_file
def create_settings_file(self, filename):
data = self.defaults
content = tomli_w.dumps(data)
with open(filename, 'w') as f: f.write(content)
def load_jid_settings(self, room, filename):
# 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)
def update_jid_settings(self, room, filename, key, value):
with open(filename, 'rb') as f: data = tomllib.load(f)
self.settings[room][key] = value
data = self.settings[room]
content = tomli_w.dumps(data)
with open(filename, 'w') as f: f.write(content)