diff --git a/app/api/routes/content.py b/app/api/routes/content.py index 206fb3a..c76e9d4 100644 --- a/app/api/routes/content.py +++ b/app/api/routes/content.py @@ -1,5 +1,7 @@ +from datetime import datetime, timedelta from sanic import response from aiogram import Bot, types +from sqlalchemy import and_ from app.core.logger import make_log from app.core.models.node_storage import StoredContent from app.core.models.keys import KnownKey @@ -58,34 +60,44 @@ async def s_api_v1_content_view(request, content_address: str): ) if not have_access: stars_cost = 1 - invoice_id = f"access_{uuid.uuid4().hex}" - request.ctx.db_session.add( - StarsInvoice( - external_id=invoice_id, - type='access', - amount=stars_cost, - content_hash=content['encrypted_content'].hash, + exist_invoice = request.ctx.db_session.query(StarsInvoice).filter( + and_( + StarsInvoice.user_id == request.ctx.user.id, + StarsInvoice.created > datetime.now() - timedelta(minutes=25), ) - ) - request.ctx.db_session.commit() - - try: - opts['invoice'] = { - 'url': ( - await Bot(token=CLIENT_TELEGRAM_API_KEY).create_invoice_link( - 'Lifetime access to content', - 'You will receive NFT with lifetime access to content', - f"access_{invoice_id}", "", "XTR", - [ - types.LabeledPrice(label='Lifetime access', amount=stars_cost), - ], + ).first() + if exist_invoice: + invoice_url = exist_invoice.invoice_url + else: + invoice_id = f"access_{uuid.uuid4().hex}" + try: + invoice_url = await Bot(token=CLIENT_TELEGRAM_API_KEY).create_invoice_link( + 'Lifetime access to content', + 'You will receive NFT with lifetime access to content', + f"access_{invoice_id}", "", "XTR", + [ + types.LabeledPrice(label='Lifetime access', amount=stars_cost), + ], + ) + request.ctx.db_session.add( + StarsInvoice( + external_id=invoice_id, + type='access', + amount=stars_cost, + user_id=request.ctx.user.id, + content_hash=content['encrypted_content'].hash, + invoice_url=invoice_url ) - ), - 'amount': stars_cost, - } - except BaseException as e: - make_log("Content", f"Can't create invoice link: {e}", level='warning') + ) + request.ctx.db_session.commit() + except BaseException as e: + make_log("Content", f"Can't create invoice link: {e}", level='warning') + + opts['invoice'] = { + 'url': invoice_url, + 'amount': stars_cost, + } display_options = { 'content_url': content['decrypted_content'].web_url + ( diff --git a/app/core/models/transaction.py b/app/core/models/transaction.py index 03d8fbe..288f42c 100644 --- a/app/core/models/transaction.py +++ b/app/core/models/transaction.py @@ -47,6 +47,9 @@ class StarsInvoice(AlchemyBase): type = Column(String(256), nullable=False) amount = Column(Integer, nullable=False) + user_id = Column(Integer, ForeignKey('users.id'), nullable=True) content_hash = Column(String(256), nullable=True) + invoice_url = Column(String(256), nullable=True) + created = Column(DateTime, nullable=False, default=datetime.utcnow)