Merge branch 'main' into security
Some checks failed
continuous-integration/drone/push Build is failing

This commit is contained in:
2025-09-07 14:22:04 +09:00
16 changed files with 1051 additions and 133 deletions

View File

@@ -1,8 +1,12 @@
# handlers/add_channel.py
from telegram import Update
from telegram.ext import ContextTypes, ConversationHandler, CommandHandler, MessageHandler, filters
from telegram.ext import (
ContextTypes, ConversationHandler, CommandHandler, MessageHandler, filters
)
from sqlalchemy import select
from db import AsyncSessionLocal
from models import Channel
from models import Channel, Admin
INPUT_NAME, INPUT_LINK = range(2)
@@ -14,35 +18,46 @@ async def add_channel_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
return INPUT_NAME
async def input_channel_name(update: Update, context: ContextTypes.DEFAULT_TYPE):
if context.user_data is None:
context.user_data = {}
text = update.message.text.strip() if update.message and update.message.text else ''
context.user_data['channel_name'] = text
if update.message:
await update.message.reply_text('Теперь отправьте ссылку на канал (должна начинаться с @):')
if not update.message:
return ConversationHandler.END
name = (update.message.text or "").strip()
if not name:
await update.message.reply_text("Имя не может быть пустым. Введите имя канала:")
return INPUT_NAME
context.user_data["channel_name"] = name
await update.message.reply_text('Отправьте ссылку на канал (формат "@username" или "-100..."):')
return INPUT_LINK
async def input_channel_link(update: Update, context: ContextTypes.DEFAULT_TYPE):
if context.user_data is None:
context.user_data = {}
link = update.message.text.strip() if update.message and update.message.text else ''
if not link.startswith('@'):
if update.message:
await update.message.reply_text('Ошибка: ссылка на канал должна начинаться с @. Попробуйте снова.')
return INPUT_LINK
context.user_data['channel_link'] = link
return await save_channel(update, context)
async def _get_or_create_admin(session, tg_id: int) -> Admin:
res = await session.execute(select(Admin).where(Admin.tg_id == tg_id))
admin = res.scalar_one_or_none()
if not admin:
admin = Admin(tg_id=tg_id)
session.add(admin)
await session.flush()
return admin
async def save_channel(update: Update, context: ContextTypes.DEFAULT_TYPE):
if context.user_data is None:
context.user_data = {}
name = context.user_data.get('channel_name')
link = context.user_data.get('channel_link')
if not name or not link:
if update.message:
await update.message.reply_text('Ошибка: не указано название или ссылка.')
async def input_channel_link(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message:
return ConversationHandler.END
link = (update.message.text or "").strip()
if not (link.startswith("@") or link.startswith("-100")):
await update.message.reply_text('Неверный формат. Укажите "@username" или "-100...".')
return INPUT_LINK
name = (context.user_data or {}).get("channel_name", "").strip()
if not name:
await update.message.reply_text("Не найдено имя. Начните заново: /add_channel")
return ConversationHandler.END
user = update.effective_user
if not user:
await update.message.reply_text("Не удалось определить администратора.")
return ConversationHandler.END
async with AsyncSessionLocal() as session:
<<<<<<< HEAD
channel = Channel(name=name, link=link)
session.add(channel)
await session.commit()
@@ -51,6 +66,23 @@ async def save_channel(update: Update, context: ContextTypes.DEFAULT_TYPE):
await log_action(user_id, "add_channel", f"name={name}, link={link}")
if update.message:
await update.message.reply_text(f'Канал "{name}" добавлен.')
=======
admin = await _get_or_create_admin(session, user.id)
# если канал уже есть — обновим имя и владельца
existing_q = await session.execute(select(Channel).where(Channel.link == link))
existing = existing_q.scalar_one_or_none()
if existing:
existing.name = name
existing.admin_id = admin.id
await session.commit()
await update.message.reply_text(f'Канал "{name}" уже был — обновил владельца и имя.')
else:
channel = Channel(name=name, link=link, admin_id=admin.id)
session.add(channel)
await session.commit()
await update.message.reply_text(f'Канал "{name}" добавлен и привязан к вашему админ-аккаунту.')
>>>>>>> main
return ConversationHandler.END
add_channel_conv = ConversationHandler(

View File

@@ -1,48 +1,139 @@
# from telegram import Update
# from telegram.ext import ContextTypes, ConversationHandler, CommandHandler, MessageHandler, filters
# from db import AsyncSessionLocal
# from models import Group
# INPUT_NAME, INPUT_LINK = range(2)
# async def add_group_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
# if context.user_data is None:
# context.user_data = {}
# if update.message:
# await update.message.reply_text('Введите имя группы:')
# return INPUT_NAME
# async def input_group_name(update: Update, context: ContextTypes.DEFAULT_TYPE):
# if context.user_data is None:
# context.user_data = {}
# text = update.message.text.strip() if update.message and update.message.text else ''
# context.user_data['group_name'] = text
# if update.message:
# await update.message.reply_text('Теперь отправьте chat_id группы (например, -1001234567890):')
# return INPUT_LINK
# async def input_group_link(update: Update, context: ContextTypes.DEFAULT_TYPE):
# if context.user_data is None:
# context.user_data = {}
# link = update.message.text.strip() if update.message and update.message.text else ''
# if not link.startswith('-100'):
# if update.message:
# await update.message.reply_text('Ошибка: chat_id группы должен начинаться с -100. Попробуйте снова.')
# return INPUT_LINK
# context.user_data['group_link'] = link
# return await save_group(update, context)
# async def save_group(update: Update, context: ContextTypes.DEFAULT_TYPE):
# if context.user_data is None:
# context.user_data = {}
# name = context.user_data.get('group_name')
# link = context.user_data.get('group_link')
# if not name or not link:
# if update.message:
# await update.message.reply_text('Ошибка: не указано название или ссылка.')
# return ConversationHandler.END
# async with AsyncSessionLocal() as session:
# group = Group(name=name, link=link)
# session.add(group)
# await session.commit()
# if update.message:
# await update.message.reply_text(f'Группа "{name}" добавлена.')
# return ConversationHandler.END
# add_group_conv = ConversationHandler(
# entry_points=[CommandHandler('add_group', add_group_start)],
# states={
# INPUT_NAME: [MessageHandler(filters.TEXT & ~filters.COMMAND, input_group_name)],
# INPUT_LINK: [MessageHandler(filters.TEXT & ~filters.COMMAND, input_group_link)],
# },
# fallbacks=[]
# )
# handlers/add_group.py
from telegram import Update
from telegram.ext import ContextTypes, ConversationHandler, CommandHandler, MessageHandler, filters
from telegram.ext import (
ContextTypes,
ConversationHandler,
CommandHandler,
MessageHandler,
filters,
)
from sqlalchemy import select
from db import AsyncSessionLocal
from models import Group
from models import Group, Admin
INPUT_NAME, INPUT_LINK = range(2)
async def add_group_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
if context.user_data is None:
context.user_data = {}
if update.message:
await update.message.reply_text('Введите имя группы:')
await update.message.reply_text("Введите имя группы:")
return INPUT_NAME
async def input_group_name(update: Update, context: ContextTypes.DEFAULT_TYPE):
if context.user_data is None:
context.user_data = {}
text = update.message.text.strip() if update.message and update.message.text else ''
context.user_data['group_name'] = text
if update.message:
await update.message.reply_text('Теперь отправьте chat_id группы (например, -1001234567890):')
if not update.message:
return ConversationHandler.END
name = (update.message.text or "").strip()
if not name:
await update.message.reply_text("Имя не может быть пустым. Введите имя группы:")
return INPUT_NAME
context.user_data["group_name"] = name
await update.message.reply_text('Отправьте ссылку на группу (формат "@username" или "-100..."):')
return INPUT_LINK
async def input_group_link(update: Update, context: ContextTypes.DEFAULT_TYPE):
if context.user_data is None:
context.user_data = {}
link = update.message.text.strip() if update.message and update.message.text else ''
if not link.startswith('-100'):
if update.message:
await update.message.reply_text('Ошибка: chat_id группы должен начинаться с -100. Попробуйте снова.')
return INPUT_LINK
context.user_data['group_link'] = link
return await save_group(update, context)
async def save_group(update: Update, context: ContextTypes.DEFAULT_TYPE):
if context.user_data is None:
context.user_data = {}
name = context.user_data.get('group_name')
link = context.user_data.get('group_link')
if not name or not link:
if update.message:
await update.message.reply_text('Ошибка: не указано название или ссылка.')
async def _get_or_create_admin(session: AsyncSessionLocal, tg_id: int) -> Admin:
res = await session.execute(select(Admin).where(Admin.tg_id == tg_id))
admin = res.scalar_one_or_none()
if not admin:
admin = Admin(tg_id=tg_id)
session.add(admin)
# Чтобы получить admin.id до commit
await session.flush()
return admin
async def input_group_link(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not update.message:
return ConversationHandler.END
link = (update.message.text or "").strip()
if not (link.startswith("@") or link.startswith("-100")):
await update.message.reply_text(
'Неверный формат. Укажите "@username" (публичная группа/супергруппа) или "-100..." (ID).'
)
return INPUT_LINK
name = (context.user_data or {}).get("group_name", "").strip()
if not name:
await update.message.reply_text("Не найдено имя группы. Начните заново: /add_group")
return ConversationHandler.END
user = update.effective_user
if not user:
await update.message.reply_text("Не удалось определить администратора. Попробуйте ещё раз.")
return ConversationHandler.END
async with AsyncSessionLocal() as session:
<<<<<<< HEAD
group = Group(name=name, link=link)
session.add(group)
await session.commit()
@@ -51,13 +142,36 @@ async def save_group(update: Update, context: ContextTypes.DEFAULT_TYPE):
log_action(user_id, "add_group", f"name={name}, link={link}")
if update.message:
await update.message.reply_text(f'Группа "{name}" добавлена.')
=======
# гарантируем наличие админа
admin = await _get_or_create_admin(session, user.id)
# проверка на существование группы по ссылке
existing_q = await session.execute(select(Group).where(Group.link == link))
existing = existing_q.scalar_one_or_none()
if existing:
existing.name = name
existing.admin_id = admin.id
await session.commit()
await update.message.reply_text(
f'Группа "{name}" уже была в базе — обновил владельца и имя.'
)
else:
group = Group(name=name, link=link, admin_id=admin.id)
session.add(group)
await session.commit()
await update.message.reply_text(f'Группа "{name}" добавлена и привязана к вашему админ-аккаунту.')
>>>>>>> main
return ConversationHandler.END
add_group_conv = ConversationHandler(
entry_points=[CommandHandler('add_group', add_group_start)],
entry_points=[CommandHandler("add_group", add_group_start)],
states={
INPUT_NAME: [MessageHandler(filters.TEXT & ~filters.COMMAND, input_group_name)],
INPUT_LINK: [MessageHandler(filters.TEXT & ~filters.COMMAND, input_group_link)],
},
fallbacks=[]
fallbacks=[],
)

View File

@@ -1,28 +1,112 @@
from telegram import Update, InputMediaPhoto, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import ContextTypes, ConversationHandler, MessageHandler, CommandHandler, filters, CallbackQueryHandler, ContextTypes
# handlers/new_post.py
from __future__ import annotations
from typing import List, Optional, Tuple
from telegram import (
Update, InlineKeyboardMarkup, InlineKeyboardButton, MessageEntity, Bot
)
from telegram.ext import (
ContextTypes, ConversationHandler, MessageHandler, CommandHandler, CallbackQueryHandler, filters
)
from telegram.constants import MessageEntityType
from telegram.error import BadRequest
from sqlalchemy import select as sa_select
from db import AsyncSessionLocal
<<<<<<< HEAD
from models import Channel, Group, Button, Admin
=======
from models import Channel, Group
from .permissions import get_or_create_admin, list_channels_for_admin, has_scope_on_channel, SCOPE_POST
from models import Channel, Group, Button
>>>>>>> main
SELECT_MEDIA, SELECT_TEXT, SELECT_TARGET = range(3)
# ===== UTF-16 helpers (для custom_emoji) =====
def _utf16_units_len(s: str) -> int:
return len(s.encode("utf-16-le")) // 2
def _utf16_index_map(text: str) -> List[Tuple[int, int, str]]:
out: List[Tuple[int, int, str]] = []
off = 0
for ch in text:
ln = _utf16_units_len(ch)
out.append((off, ln, ch))
off += ln
return out
def _split_custom_emoji_by_utf16(text: str, entities: List[MessageEntity]) -> List[MessageEntity]:
if not text or not entities:
return entities or []
map_utf16 = _utf16_index_map(text)
out: List[MessageEntity] = []
for e in entities:
if (e.type == MessageEntityType.CUSTOM_EMOJI and e.length and e.length > 1 and getattr(e, "custom_emoji_id", None)):
start = e.offset
end = e.offset + e.length
for uoff, ulen, _ in map_utf16:
if start <= uoff < end:
out.append(MessageEntity(
type=MessageEntityType.CUSTOM_EMOJI,
offset=uoff,
length=ulen,
custom_emoji_id=e.custom_emoji_id,
))
else:
out.append(e)
out.sort(key=lambda x: x.offset)
return out
def _strip_broken_entities(entities: Optional[List[MessageEntity]]) -> List[MessageEntity]:
cleaned: List[MessageEntity] = []
for e in entities or []:
if e.offset is None or e.length is None or e.offset < 0 or e.length < 1:
continue
if e.type == MessageEntityType.CUSTOM_EMOJI and not getattr(e, "custom_emoji_id", None):
continue
cleaned.append(e)
cleaned.sort(key=lambda x: x.offset)
return cleaned
def _extract_text_and_entities(msg) -> tuple[str, List[MessageEntity], bool]:
if getattr(msg, "text", None):
return msg.text, (msg.entities or []), False
if getattr(msg, "caption", None):
return msg.caption, (msg.caption_entities or []), True
return "", [], False
# ===== Conversation =====
async def new_post_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.message:
await update.message.reply_text('Отправьте картинку для поста или /skip:')
await update.message.reply_text("Отправьте медиа для поста или пришлите /skip:")
return SELECT_MEDIA
return ConversationHandler.END
async def select_media(update: Update, context: ContextTypes.DEFAULT_TYPE):
if update.message and hasattr(update.message, 'photo') and update.message.photo:
if context.user_data is None:
context.user_data = {}
context.user_data['photo'] = update.message.photo[-1].file_id
if update.message:
await update.message.reply_text('Введите текст поста или пересланное сообщение:')
if context.user_data is None:
context.user_data = {}
if not update.message:
return ConversationHandler.END
msg = update.message
if msg.text and msg.text.strip().lower() == "/skip":
await update.message.reply_text("Введите текст поста или перешлите сообщение (можно с кастом-эмодзи):")
return SELECT_TEXT
return ConversationHandler.END
if msg.photo: context.user_data["photo"] = msg.photo[-1].file_id
elif msg.animation:context.user_data["animation"] = msg.animation.file_id
elif msg.video: context.user_data["video"] = msg.video.file_id
elif msg.document: context.user_data["document"] = msg.document.file_id
elif msg.audio: context.user_data["audio"] = msg.audio.file_id
elif msg.voice: context.user_data["voice"] = msg.voice.file_id
elif msg.sticker: context.user_data["sticker"] = msg.sticker.file_id
await update.message.reply_text("Введите текст поста или перешлите сообщение (можно с кастом-эмодзи):")
return SELECT_TEXT
async def select_text(update: Update, context: ContextTypes.DEFAULT_TYPE):
<<<<<<< HEAD
if update.message:
if context.user_data is None:
context.user_data = {}
@@ -58,41 +142,185 @@ async def select_text(update: Update, context: ContextTypes.DEFAULT_TYPE):
finally:
await session.close()
return ConversationHandler.END
=======
if not update.message:
return ConversationHandler.END
if context.user_data is None:
context.user_data = {}
msg = update.message
text, entities, _ = _extract_text_and_entities(msg)
entities = _strip_broken_entities(entities)
entities = _split_custom_emoji_by_utf16(text, entities)
# сохраним исходник для copyMessage
context.user_data["text"] = text
context.user_data["entities"] = entities
context.user_data["src_chat_id"] = update.effective_chat.id
context.user_data["src_msg_id"] = update.message.message_id
# дать выбор только тех каналов, где у текущего админа есть право постинга
async with AsyncSessionLocal() as session:
me = await get_or_create_admin(session, update.effective_user.id)
channels = await list_channels_for_admin(session, me.id)
# группы оставляем без ACL (как было)
groups = (await session.execute(sa_select(Group))).scalars().all()
# если каналов нет — всё равно покажем группы
keyboard = []
for c in channels:
keyboard.append([InlineKeyboardButton(f'Канал: {c.name}', callback_data=f'channel_{c.id}')])
for g in groups:
keyboard.append([InlineKeyboardButton(f'Группа: {g.name}', callback_data=f'group_{g.id}')])
if not keyboard:
await update.message.reply_text("Нет доступных каналов/групп для отправки.")
return ConversationHandler.END
await update.message.reply_text('Выберите, куда отправить пост:', reply_markup=InlineKeyboardMarkup(keyboard))
return SELECT_TARGET
>>>>>>> main
async def select_target(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
if not query:
return ConversationHandler.END
await query.answer()
data = query.data
session = AsyncSessionLocal()
try:
chat_id = None
markup = None
if data and data.startswith('channel_'):
from sqlalchemy import select
channel_id = int(data.split('_')[1])
channel_result = await session.execute(select(Channel).where(Channel.id == channel_id))
channel = channel_result.scalar_one_or_none()
buttons_result = await session.execute(select(Button).where(Button.channel_id == channel_id))
buttons = buttons_result.scalars().all()
markup = InlineKeyboardMarkup([[InlineKeyboardButton(str(b.name), url=str(b.url))] for b in buttons]) if buttons else None
chat_id = getattr(channel, 'link', None)
elif data and data.startswith('group_'):
from sqlalchemy import select
group_id = int(data.split('_')[1])
group_result = await session.execute(select(Group).where(Group.id == group_id))
group = group_result.scalar_one_or_none()
buttons_result = await session.execute(select(Button).where(Button.group_id == group_id))
buttons = buttons_result.scalars().all()
markup = InlineKeyboardMarkup([[InlineKeyboardButton(str(b.name), url=str(b.url))] for b in buttons]) if buttons else None
chat_id = getattr(group, 'link', None)
if chat_id:
chat_id = chat_id.strip()
if not (chat_id.startswith('@') or chat_id.startswith('-')):
await query.edit_message_text('Ошибка: ссылка должна быть username (@channel) или числовой ID (-100...)')
data = (query.data or "")
async with AsyncSessionLocal() as session:
chat_id: str | None = None
markup: InlineKeyboardMarkup | None = None
selected_title: str | None = None
btns = []
if data.startswith('channel_'):
channel_id = int(data.split('_', 1)[1])
# ACL: право постинга в канал
me = await get_or_create_admin(session, update.effective_user.id)
allowed = await has_scope_on_channel(session, me.id, channel_id, SCOPE_POST)
if not allowed:
await query.edit_message_text("У вас нет права постить в этот канал.")
return ConversationHandler.END
channel = (await session.execute(sa_select(Channel).where(Channel.id == channel_id))).scalar_one_or_none()
if not channel:
await query.edit_message_text("Канал не найден.")
return ConversationHandler.END
chat_id = (channel.link or "").strip()
selected_title = channel.name
# Кнопки канала
btns = (await session.execute(sa_select(Button).where(Button.channel_id == channel_id))).scalars().all()
if btns:
rows = [[InlineKeyboardButton(str(b.name), url=str(b.url))] for b in btns]
markup = InlineKeyboardMarkup(rows)
elif data.startswith('group_'):
group_id = int(data.split('_', 1)[1])
group = (await session.execute(sa_select(Group).where(Group.id == group_id))).scalar_one_or_none()
if not group:
await query.edit_message_text("Группа не найдена.")
return ConversationHandler.END
chat_id = (group.link or "").strip()
selected_title = group.name
# Кнопки группы
btns = (await session.execute(sa_select(Button).where(Button.group_id == group_id))).scalars().all()
if btns:
rows = [[InlineKeyboardButton(str(b.name), url=str(b.url))] for b in btns]
markup = InlineKeyboardMarkup(rows)
if not chat_id or not (chat_id.startswith('@') or chat_id.startswith('-')):
await query.edit_message_text('Ошибка: ссылка должна быть username (@channel) или числовой ID (-100...)')
return ConversationHandler.END
# DEBUG: сколько кнопок нашли и есть ли markup
print(f"[DEBUG] send -> chat_id={chat_id} title={selected_title!r} buttons={len(btns)} has_markup={bool(markup)}")
# Текст и entities (без parse_mode)
ud = context.user_data or {}
text: str = ud.get("text", "") or ""
entities: List[MessageEntity] = ud.get("entities", []) or []
entities = _strip_broken_entities(entities)
entities = _split_custom_emoji_by_utf16(text, entities)
# Всегда ручная отправка (send_*), чтобы гарантированно приклеить inline-клавиатуру
try:
sent_msg = None
if "photo" in ud:
sent_msg = await context.bot.send_photo(
chat_id=chat_id,
photo=ud["photo"],
caption=(text or None),
caption_entities=(entities if text else None),
reply_markup=markup,
)
elif "animation" in ud:
sent_msg = await context.bot.send_animation(
chat_id=chat_id,
animation=ud["animation"],
caption=(text or None),
caption_entities=(entities if text else None),
reply_markup=markup,
)
elif "video" in ud:
sent_msg = await context.bot.send_video(
chat_id=chat_id,
video=ud["video"],
caption=(text or None),
caption_entities=(entities if text else None),
reply_markup=markup,
)
elif "document" in ud:
sent_msg = await context.bot.send_document(
chat_id=chat_id,
document=ud["document"],
caption=(text or None),
caption_entities=(entities if text else None),
reply_markup=markup,
)
elif "audio" in ud:
sent_msg = await context.bot.send_audio(
chat_id=chat_id,
audio=ud["audio"],
caption=(text or None),
caption_entities=(entities if text else None),
reply_markup=markup,
)
elif "voice" in ud:
sent_msg = await context.bot.send_voice(
chat_id=chat_id,
voice=ud["voice"],
caption=(text or None),
caption_entities=(entities if text else None),
reply_markup=markup,
)
elif "sticker" in ud:
sent_msg = await context.bot.send_sticker(
chat_id=chat_id,
sticker=ud["sticker"],
reply_markup=markup,
)
if text:
await context.bot.send_message(chat_id=chat_id, text=text, entities=entities)
else:
sent_msg = await context.bot.send_message(
chat_id=chat_id,
text=text,
entities=entities,
reply_markup=markup,
)
# Страховка: если вдруг Telegram проглотил клаву — доклеим её
if markup and getattr(sent_msg, "message_id", None):
try:
<<<<<<< HEAD
# Пересылка исходного сообщения
await context.bot.forward_message(
chat_id=chat_id,
@@ -107,15 +335,35 @@ async def select_target(update: Update, context: ContextTypes.DEFAULT_TYPE):
await query.edit_message_text(f'Ошибка пересылки поста: {e}')
finally:
await session.close()
=======
await context.bot.edit_message_reply_markup(
chat_id=chat_id,
message_id=sent_msg.message_id,
reply_markup=markup,
)
except Exception:
pass
await query.edit_message_text(f'Пост отправлен{(" в: " + selected_title) if selected_title else "!"}')
except BadRequest as e:
await query.edit_message_text(f'Ошибка отправки поста: {e}')
>>>>>>> main
return ConversationHandler.END
new_post_conv = ConversationHandler(
entry_points=[CommandHandler('new_post', new_post_start)],
entry_points=[CommandHandler("new_post", new_post_start)],
states={
SELECT_MEDIA: [MessageHandler(filters.PHOTO | filters.Document.IMAGE | filters.COMMAND, select_media)],
SELECT_TEXT: [MessageHandler(filters.TEXT | filters.FORWARDED, select_text)],
SELECT_MEDIA: [MessageHandler(
filters.PHOTO | filters.ANIMATION | filters.VIDEO | filters.Document.ALL |
filters.AUDIO | filters.VOICE | filters.Sticker.ALL | filters.COMMAND,
select_media
)],
SELECT_TEXT: [MessageHandler(filters.TEXT | filters.FORWARDED | filters.CAPTION, select_text)],
SELECT_TARGET: [CallbackQueryHandler(select_target)],
},
fallbacks=[],
)
)

68
handlers/permissions.py Normal file
View File

@@ -0,0 +1,68 @@
# permissions.py
import hashlib, secrets
from datetime import datetime, timedelta
from sqlalchemy import select
from models import Admin, Channel, ChannelAccess, SCOPE_POST, SCOPE_SHARE
from sqlalchemy.exc import OperationalError
def make_token(nbytes: int = 9) -> str:
# Короткий URL-safe токен (<= ~12-16 символов укладывается в /start payload)
return secrets.token_urlsafe(nbytes)
def token_hash(token: str) -> str:
return hashlib.sha256(token.encode('utf-8')).hexdigest()
async def get_or_create_admin(session, tg_id: int) -> Admin:
res = await session.execute(select(Admin).where(Admin.tg_id == tg_id))
admin = res.scalar_one_or_none()
if not admin:
admin = Admin(tg_id=tg_id)
session.add(admin)
await session.flush()
return admin
async def has_scope_on_channel(session, admin_id: int, channel_id: int, scope: int) -> bool:
# Владелец канала — всегда полный доступ
res = await session.execute(select(Channel).where(Channel.id == channel_id))
ch = res.scalar_one_or_none()
if ch and ch.admin_id == admin_id:
return True
# Иначе ищем активный доступ с нужной маской
res = await session.execute(
select(ChannelAccess).where(
ChannelAccess.channel_id == channel_id,
ChannelAccess.invited_admin_id == admin_id,
ChannelAccess.status == "active",
)
)
acc = res.scalar_one_or_none()
if not acc:
return False
return (acc.scopes & scope) == scope
async def list_channels_for_admin(session, admin_id: int):
q1 = await session.execute(select(Channel).where(Channel.admin_id == admin_id))
owned = q1.scalars().all()
try:
q2 = await session.execute(
select(ChannelAccess).where(
ChannelAccess.invited_admin_id == admin_id,
ChannelAccess.status == "active",
)
)
rows = q2.scalars().all()
except OperationalError:
return owned # таблицы ещё нет — просто вернём свои каналы
can_post_ids = {r.channel_id for r in rows if (r.scopes & SCOPE_POST)}
if not can_post_ids:
return owned
q3 = await session.execute(select(Channel).where(Channel.id.in_(can_post_ids)))
shared = q3.scalars().all()
d = {c.id: c for c in owned}
for c in shared:
d[c.id] = c
return list(d.values())

140
handlers/share_channel.py Normal file
View File

@@ -0,0 +1,140 @@
# handlers/share_channel.py
from datetime import datetime, timedelta
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
ContextTypes, ConversationHandler, CommandHandler, CallbackQueryHandler
)
from sqlalchemy import select
from db import AsyncSessionLocal
from models import Channel, ChannelAccess, SCOPE_POST
from .permissions import get_or_create_admin, make_token, token_hash
from telegram.error import BadRequest
import os
from telegram import InlineKeyboardMarkup, InlineKeyboardButton
async def _get_bot_username(context: ContextTypes.DEFAULT_TYPE) -> str:
# кэшируем, чтобы не дёргать get_me() каждый раз
uname = context.application.bot.username
if uname:
return uname
me = await context.bot.get_me()
return me.username
SELECT_CHANNEL, CONFIRM_INVITE = range(2)
async def share_channel_start(update: Update, context: ContextTypes.DEFAULT_TYPE):
async with AsyncSessionLocal() as session:
me = await get_or_create_admin(session, update.effective_user.id)
q = await session.execute(select(Channel).where(Channel.admin_id == me.id))
channels = q.scalars().all()
if not channels:
if update.message:
await update.message.reply_text("Нет каналов, которыми вы владеете.")
return ConversationHandler.END
kb = [[InlineKeyboardButton(f"{c.name} ({c.link})", callback_data=f"sch_{c.id}")] for c in channels]
rm = InlineKeyboardMarkup(kb)
if update.message:
await update.message.reply_text("Выберите канал для выдачи доступа:", reply_markup=rm)
return SELECT_CHANNEL
async def select_channel(update: Update, context: ContextTypes.DEFAULT_TYPE):
q = update.callback_query
if not q: return ConversationHandler.END
await q.answer()
if not q.data.startswith("sch_"): return ConversationHandler.END
channel_id = int(q.data.split("_")[1])
context.user_data["share_channel_id"] = channel_id
kb = [
[InlineKeyboardButton("Срок: 7 дней", callback_data="ttl_7"),
InlineKeyboardButton("30 дней", callback_data="ttl_30"),
InlineKeyboardButton("", callback_data="ttl_inf")],
[InlineKeyboardButton("Выдать право постинга", callback_data="scope_post")],
[InlineKeyboardButton("Сгенерировать ссылку", callback_data="go")],
]
await q.edit_message_text("Настройте приглашение:", reply_markup=InlineKeyboardMarkup(kb))
context.user_data["ttl_days"] = 7
context.user_data["scopes"] = SCOPE_POST
return CONFIRM_INVITE
async def confirm_invite(update: Update, context: ContextTypes.DEFAULT_TYPE):
q = update.callback_query
if not q:
return ConversationHandler.END
# Лёгкий ACK, чтобы исчез «часик» на кнопке
await q.answer()
data = q.data
# --- настройки TTL (ничего не меняем в разметке, только сохраняем выбор) ---
if data.startswith("ttl_"):
context.user_data["ttl_days"] = {"ttl_7": 7, "ttl_30": 30, "ttl_inf": None}[data]
# Нечего редактировать — markup не менялся. Просто остаёмся в состоянии.
return CONFIRM_INVITE
# --- права: сейчас фиксировано SCOPE_POST, разметку не меняем ---
if data == "scope_post":
# если позже сделаешь тумблеры прав — тут можно перестраивать клавиатуру
context.user_data["scopes"] = SCOPE_POST
return CONFIRM_INVITE
# --- генерация ссылки приглашения ---
if data != "go":
return CONFIRM_INVITE
channel_id = context.user_data.get("share_channel_id")
ttl_days = context.user_data.get("ttl_days")
scopes = context.user_data.get("scopes", SCOPE_POST)
async with AsyncSessionLocal() as session:
me = await get_or_create_admin(session, update.effective_user.id)
token = make_token(9)
thash = token_hash(token)
expires_at = None
if ttl_days:
from datetime import datetime, timedelta
expires_at = datetime.utcnow() + timedelta(days=ttl_days)
acc = ChannelAccess(
channel_id=channel_id,
invited_by_admin_id=me.id,
token_hash=thash,
scopes=scopes,
status="pending",
created_at=datetime.utcnow(),
expires_at=expires_at,
)
session.add(acc)
await session.commit()
invite_id = acc.id
payload = f"sch_{invite_id}_{token}"
bot_username = await _get_bot_username(context)
deep_link = f"https://t.me/{bot_username}?start={payload}"
# Кнопка для удобства
kb = InlineKeyboardMarkup([[InlineKeyboardButton("Открыть ссылку", url=deep_link)]])
await q.edit_message_text(
"Ссылка для предоставления доступа к каналу:\n"
f"`{deep_link}`\n\n"
"Передайте её коллеге. Срок действия — "
+ ("не ограничен." if ttl_days is None else f"{ttl_days} дней."),
parse_mode="Markdown",
reply_markup=kb,
)
return ConversationHandler.END
share_channel_conv = ConversationHandler(
entry_points=[CommandHandler("share_channel", share_channel_start)],
states={
SELECT_CHANNEL: [CallbackQueryHandler(select_channel, pattern="^sch_")],
CONFIRM_INVITE: [CallbackQueryHandler(confirm_invite)],
},
fallbacks=[],
)