81 lines
2.3 KiB
Python
81 lines
2.3 KiB
Python
from flask import Blueprint, Response, jsonify, request
|
|
|
|
from app.extensions import db
|
|
from app.models.session import Session
|
|
from app.models.task import Task
|
|
from paper.errors import NeedPasswordException
|
|
from paper.parser import PaperParser
|
|
|
|
sessions = Blueprint("sessions", __name__, url_prefix="/sessions")
|
|
|
|
@sessions.route("/", methods=["POST"])
|
|
async def create_session(**kwargs):
|
|
data = kwargs or request.json or request.form
|
|
data["name"] = data["name"].replace("/", "").replace("\\", "")
|
|
|
|
session = Session.query.filter_by(name=data.get("name")).first()
|
|
|
|
if not session:
|
|
session = Session(
|
|
name=data.get("name"),
|
|
authorized=False
|
|
)
|
|
|
|
db.session.add(session)
|
|
|
|
response = {"status": "ok"}
|
|
|
|
async with PaperParser(data.get("name")) as parser:
|
|
try:
|
|
result = await parser.sign_in(**data)
|
|
|
|
if hasattr(result, "phone_code_hash"):
|
|
response = {
|
|
"status": "error",
|
|
"message": "Need secret code from telegram",
|
|
"action": "code",
|
|
"phone_hash": result.phone_code_hash,
|
|
}
|
|
else:
|
|
session.authorized = True
|
|
|
|
except NeedPasswordException:
|
|
response = {
|
|
"status": "error",
|
|
"message": "Need 2FA Password",
|
|
"action": "password",
|
|
}
|
|
|
|
except Exception as e:
|
|
response = {
|
|
"status": "exception",
|
|
"message": str(e),
|
|
}
|
|
|
|
finally:
|
|
db.session.commit()
|
|
|
|
return jsonify(response)
|
|
|
|
@sessions.route("/", methods=["GET"])
|
|
def get_sessions(**kwargs):
|
|
return Session.query.filter_by(authorized=True).all()
|
|
|
|
@sessions.route("/<int:id>", methods=["DELETE"])
|
|
async def remove_session(id: int):
|
|
session: Session = Session.query.get_or_404(id)
|
|
|
|
if session.has_depending_tasks():
|
|
return 'Есть зависимые задачи', 409
|
|
|
|
async with PaperParser(session.name) as parser:
|
|
try:
|
|
await parser.client.log_out()
|
|
|
|
except Exception as e:
|
|
return Response(e, 500)
|
|
|
|
db.session.delete(session)
|
|
db.session.commit()
|
|
|
|
return Response('ok', status=200) |