mariadb -> postgres

This commit is contained in:
user committed 2025-08-22 14:04:21 +03:00
1 parent 21964fa986
commit e51bb86dc0
36 files changed
+650 -464

No files matched your search

+11 -10
View File
@@ -1,6 +1,7 @@
from app.core.logger import make_log, logger
from app.core.models._telegram import Wrapped_CBotChat
from app.core.models.user import User
from sqlalchemy import select
from app.core.storage import db_session
from aiogram import BaseMiddleware, types
from app.core.models.messages import KnownTelegramMessage
@@ -21,9 +22,9 @@ class UserDataMiddleware(BaseMiddleware):
# TODO: maybe make users cache
with db_session(auto_commit=False) as session:
async with db_session(auto_commit=False) as session:
try:
user = session.query(User).filter_by(telegram_id=user_id).first()
user = (await session.execute(select(User).where(User.telegram_id == user_id))).scalars().first()
except BaseException as e:
logger.error(f"Error when middleware getting user: {e}")
user = None
@@ -42,7 +43,7 @@ class UserDataMiddleware(BaseMiddleware):
created=datetime.now()
)
session.add(user)
session.commit()
await session.commit()
else:
if user.username != update_body.from_user.username:
user.username = update_body.from_user.username
@@ -60,7 +61,7 @@ class UserDataMiddleware(BaseMiddleware):
}
user.last_use = datetime.now()
session.commit()
await session.commit()
data['user'] = user
data['db_session'] = session
@@ -72,11 +73,11 @@ class UserDataMiddleware(BaseMiddleware):
if update_body.text.startswith('/start'):
message_type = 'start_command'
if session.query(KnownTelegramMessage).filter_by(
chat_id=update_body.chat.id,
message_id=update_body.message_id,
from_user=True
).first():
if (await session.execute(select(KnownTelegramMessage).where(
(KnownTelegramMessage.chat_id == update_body.chat.id) &
(KnownTelegramMessage.message_id == update_body.message_id) &
(KnownTelegramMessage.from_user == True)
))).scalars().first():
make_log("UserDataMiddleware", f"Message {update_body.message_id} already processed", level='debug')
return
@@ -91,7 +92,7 @@ class UserDataMiddleware(BaseMiddleware):
meta={}
)
session.add(new_message)
session.commit()
await session.commit()
result = await handler(event, data)
return result
+9 -8
View File
@@ -6,6 +6,7 @@ from app.core._keyboards import get_inline_keyboard
from app.core._utils.tg_process_template import tg_process_template
from app.core.logger import make_log
from app.core.models.node_storage import StoredContent
from sqlalchemy import select, and_
import json
router = Router()
@@ -20,12 +21,13 @@ def chunks(lst, n):
async def t_callback_owned_content(query: types.CallbackQuery, memory=None, user=None, db_session=None, chat_wrap=None, **extra):
message_text = user.translated("ownedContent_menu")
content_list = []
for content in db_session.query(StoredContent).filter_by(
owner_address=user.wallet_address(db_session),
type='onchain/content'
).all():
user_addr = await user.wallet_address_async(db_session)
result = await db_session.execute(select(StoredContent).where(
and_(StoredContent.owner_address == user_addr, StoredContent.type == 'onchain/content')
))
for content in result.scalars().all():
try:
metadata_content = StoredContent.from_cid(db_session, content.json_format()['metadata_cid'])
metadata_content = await StoredContent.from_cid_async(db_session, content.json_format()['metadata_cid'])
with open(metadata_content.filepath, 'r') as f:
metadata_content_json = json.loads(f.read())
except BaseException as e:
@@ -59,10 +61,9 @@ async def t_callback_owned_content(query: types.CallbackQuery, memory=None, user
async def t_callback_node_content(query: types.CallbackQuery, memory=None, user=None, db_session=None, chat_wrap=None, **extra):
content_oid = int(query.data.split('_')[1])
row = (await db_session.execute(select(StoredContent).where(StoredContent.id == content_oid))).scalars().first()
return await chat_wrap.send_content(
db_session, db_session.query(StoredContent).filter_by(
id=content_oid
).first(),
db_session, row,
extra_buttons=[
[{
'text': user.translated('back_button'),
+12 -6
View File
@@ -3,6 +3,7 @@ from aiogram.filters import Command
from tonsdk.utils import Address
from app.core._blockchain.ton.connect import TonConnect
from sqlalchemy import select, and_
from app.core._keyboards import get_inline_keyboard
from app.core._utils.tg_process_template import tg_process_template
from app.core.models.wallet_connection import WalletConnection
@@ -32,8 +33,14 @@ async def send_home_menu(chat_wrap, user, wallet_connection, **kwargs):
async def send_connect_wallets_list(db_session, chat_wrap, user, **kwargs):
ton_connect, ton_connection = TonConnect.by_user(db_session, user, callback_fn=())
await ton_connect.restore_connection()
# Try to restore existing connection via DB
result = await db_session.execute(select(WalletConnection).where(
and_(WalletConnection.user_id == user.id, WalletConnection.invalidated == False, WalletConnection.network == 'ton')
).order_by(WalletConnection.created.desc()))
ton_connection = result.scalars().first()
ton_connect = TonConnect.by_key(ton_connection.keys["connection_key"]) if ton_connection else TonConnect()
if ton_connection:
await ton_connect.restore_connection()
wallets = ton_connect._sdk_client.get_wallets()
message_text = user.translated("connectWalletsList_menu")
return await tg_process_template(
@@ -66,10 +73,9 @@ async def t_home_menu(__msg, **extra):
else:
message_id = None
wallet_connection = db_session.query(WalletConnection).filter(
WalletConnection.user_id == user.id,
WalletConnection.invalidated == False
).first()
wallet_connection = (await db_session.execute(select(WalletConnection).where(
and_(WalletConnection.user_id == user.id, WalletConnection.invalidated == False)
))).scalars().first()
# if not wallet_connection:
# return await send_connect_wallets_list(db_session, chat_wrap, user, message_id=message_id)
+24 -14
View File
@@ -7,6 +7,7 @@ from aiogram.filters import Command
from app.bot.routers.home import send_connect_wallets_list, send_home_menu
from app.core._blockchain.ton.connect import TonConnect, unpack_wallet_info
from sqlalchemy import select, and_
from app.core._keyboards import get_inline_keyboard
from app.core._utils.tg_process_template import tg_process_template
from app.core.logger import make_log
@@ -33,15 +34,21 @@ async def t_tonconnect_dev_menu(message: types.Message, memory=None, user=None,
keyboard = []
ton_connect, ton_connection = TonConnect.by_user(db_session, user, callback_fn=())
# Restore recent connection
result = await db_session.execute(select(WalletConnection).where(
and_(WalletConnection.user_id == user.id, WalletConnection.invalidated == False, WalletConnection.network == 'ton')
).order_by(WalletConnection.created.desc()))
ton_connection = result.scalars().first()
ton_connect = TonConnect.by_key(ton_connection.keys["connection_key"]) if ton_connection else TonConnect()
make_log("TonConnect_DevMenu", f"Available wallets: {ton_connect._sdk_client.get_wallets()}", level='debug')
await ton_connect.restore_connection()
if ton_connection:
await ton_connect.restore_connection()
make_log("TonConnect_DevMenu", f"SDK connected?: {ton_connect.connected}", level='info')
if not ton_connect.connected:
if ton_connection:
make_log("TonConnect_DevMenu", f"Invalidating old connection", level='debug')
ton_connection.invalidated = True
db_session.commit()
await db_session.commit()
message_text = f"""<b>Wallet is not connected</b>
@@ -71,8 +78,13 @@ Use /dev_tonconnect <code>{wallet_app_name}</code> for connect to wallet."""
async def t_callback_init_tonconnect(query: types.CallbackQuery, memory=None, user=None, db_session=None, chat_wrap=None, **extra):
wallet_app_name = query.data.split("_")[1]
ton_connect, ton_connection = TonConnect.by_user(db_session, user)
await ton_connect.restore_connection()
result = await db_session.execute(select(WalletConnection).where(
and_(WalletConnection.user_id == user.id, WalletConnection.invalidated == False, WalletConnection.network == 'ton')
).order_by(WalletConnection.created.desc()))
ton_connection = result.scalars().first()
ton_connect = TonConnect.by_key(ton_connection.keys["connection_key"]) if ton_connection else TonConnect()
if ton_connection:
await ton_connect.restore_connection()
connection_link = await ton_connect.new_connection(wallet_app_name)
ton_connect.connected
memory.add_task(pause_ton_connection, ton_connect, delay_s=60 * 3)
@@ -98,10 +110,9 @@ async def t_callback_init_tonconnect(query: types.CallbackQuery, memory=None, us
start_ts = datetime.now()
while datetime.now() - start_ts < timedelta(seconds=180):
new_connection = db_session.query(WalletConnection).filter(
WalletConnection.user_id == user.id,
WalletConnection.invalidated == False
).first()
new_connection = (await db_session.execute(select(WalletConnection).where(
and_(WalletConnection.user_id == user.id, WalletConnection.invalidated == False)
))).scalars().first()
if new_connection:
await tg_process_template(
chat_wrap, user.translated('p_successConnectWallet')
@@ -115,14 +126,13 @@ async def t_callback_init_tonconnect(query: types.CallbackQuery, memory=None, us
async def t_callback_disconnect_wallet(query: types.CallbackQuery, memory=None, user=None, db_session=None, chat_wrap=None, **extra):
wallet_connections = db_session.query(WalletConnection).filter(
WalletConnection.user_id == user.id,
WalletConnection.invalidated == False
).all()
wallet_connections = (await db_session.execute(select(WalletConnection).where(
and_(WalletConnection.user_id == user.id, WalletConnection.invalidated == False)
))).scalars().all()
for wallet_connection in wallet_connections:
wallet_connection.invalidated = True
db_session.commit()
await db_session.commit()
return await send_home_menu(chat_wrap, user, None, message_id=query.message.message_id)