From 4aaa657f40f9b2ef787886e89cf0a7fc10323fab Mon Sep 17 00:00:00 2001 From: Pavel Kirilin <win10@list.ru> Date: Sat, 27 Jun 2020 19:43:57 +0400 Subject: [PATCH] Updated server. Signed-off-by: Pavel Kirilin <win10@list.ru> --- .gitignore | 2 +- .gitlab-ci.yml | 1 - deploy.sh | 8 ++++--- src/actions/fun.py | 2 +- src/config.py | 2 -- src/initializator.py | 23 ++++++++++++++------ src/server_app.py | 43 ++++++++++++++++++++++---------------- src/templates/index.html | 45 +++++++++++++++++++++++++++++++++++++++- 8 files changed, 93 insertions(+), 33 deletions(-) diff --git a/.gitignore b/.gitignore index 3b3dce8..52b9cfe 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,5 @@ # Local app configuration -.env.local +.env # Ide shit .idea/* # Session shit diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 9c4dcb8..4067891 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -16,4 +16,3 @@ deploy: - bots-deployer script: - sh deploy.sh - diff --git a/deploy.sh b/deploy.sh index 6b24245..02d2227 100644 --- a/deploy.sh +++ b/deploy.sh @@ -8,9 +8,11 @@ TELEGRAM_APP_ID="${TELEGRM_APP_ID_MASKED//a/}" } >>.env # Store some info in app.info file -printf "Maintainer: \`win10@list.ru\`\n" >app.info -printf "Repo url: \`%s\`\n" "$CI_PROJECT_URL" >>app.info -printf "Last commit: \`\`\`\n%s \`\`\`\n" "$(git log -1 --pretty=%B)" >>app.info +{ +printf "Maintainer: \`win10@list.ru\`\n" +printf "Repo url: \`%s\`\n" "$CI_PROJECT_URL" +printf "Last commit: \`\`\`\n%s \`\`\`\n" "$(git log -1 --pretty=%B)" +} > ./static_messages/app.info sed -i "s#WorkingDirectory=.*#WorkingDirectory=${APP_DIR:?}#" -i ./systemd/bot_s3rius_san.service diff --git a/src/actions/fun.py b/src/actions/fun.py index df62df9..83a4fe0 100644 --- a/src/actions/fun.py +++ b/src/actions/fun.py @@ -17,7 +17,7 @@ swearing = [ "(П|п)издуй на хуй", "(С|Ñ)ъеби нахуй", "(С|Ñ)ъеби на хуй", - "(С|Ñ)ÑоÑи хуй", + "(С|Ñ)оÑи хуй", "(Ð¥|Ñ…)уй ÑоÑи", "(С|Ñ)оÑать", ] diff --git a/src/config.py b/src/config.py index c4f14d1..3ed8fd8 100644 --- a/src/config.py +++ b/src/config.py @@ -22,8 +22,6 @@ class Config(BaseSettings): flask_port: str = Field(name="flask_port", default="8080", env="FLASK_PORT") - telegram_token: str = None - telegram_client: TelegramClient = None diff --git a/src/initializator.py b/src/initializator.py index 483df67..f0448a2 100644 --- a/src/initializator.py +++ b/src/initializator.py @@ -1,4 +1,6 @@ +import asyncio import logging +from multiprocessing import Process, Manager from telethon import TelegramClient @@ -15,10 +17,15 @@ def setup_logging(): logging.getLogger("telethon").setLevel(logging.WARNING) -async def get_code_from_web(): - create_web_app() - logger.info("Token received!") - return config.telegram_token +def get_code_from_web(token): + async def waiter(): + while token.value is None: + logger.debug("Waiting for token") + await asyncio.sleep(1) + logger.info("Token received!") + return token.value + + return waiter def init(): @@ -27,9 +34,13 @@ def init(): client = TelegramClient( "bot_session", config.telegram_app_id, config.telegram_api_hash ) - client.start(phone=config.telegram_account_phone, code_callback=get_code_from_web) + manager = Manager() + token = manager.Value('s', None) + web_app = Process(target=create_web_app, args=(token,)) + web_app.start() + client.start(phone=config.telegram_account_phone, code_callback=get_code_from_web(token)) config.telegram_client = client from src.actions import finish - finish() + return client diff --git a/src/server_app.py b/src/server_app.py index a3f1925..cb9c262 100644 --- a/src/server_app.py +++ b/src/server_app.py @@ -1,41 +1,48 @@ import logging import random -from flask import Flask, redirect, render_template, request, send_file +from flask import Flask, render_template, request, send_file, current_app from src.config import config -app = Flask(__name__) logger = logging.getLogger(__name__) -def shutdown_server(): - func = request.environ.get("werkzeug.server.shutdown") - if func is None: - raise RuntimeError("Not running with the Werkzeug Server") - func() - - -@app.route("/") def form_template(): - return render_template("index.html") + return render_template("index.html", activated=current_app.activated) -@app.route("/girl.png") def girl_image(): num = random.randint(1, 3) return send_file(f"./templates/static/girl_{num}.png", mimetype="image/png") -@app.route("/code", methods=["POST"]) def get_code(): code = request.form.get("code", None) if code is not None: - logger.debug("Code found. Stopping server!") - config.telegram_token = code - shutdown_server() - return redirect("/", code=302) + logger.debug("Updating token!") + current_app.update_token(code) + return "Ok" + + +class MyServer(Flask): + + def __init__(self, token_value, *args, **kwargs): + super(MyServer, self).__init__(*args, **kwargs) + self.token_value = token_value + self.activated = False + self.init_routes() + + def init_routes(self): + self.add_url_rule("/", None, form_template) + self.add_url_rule("/girl.png", None, girl_image) + self.add_url_rule("/code", None, get_code, methods=["POST"]) + + def update_token(self, new_val): + self.token_value.value = new_val + self.activated = True -def create_web_app(): +def create_web_app(token): + app = MyServer(token, __name__) app.run("0.0.0.0", config.flask_port) diff --git a/src/templates/index.html b/src/templates/index.html index e7c74e6..15963c0 100644 --- a/src/templates/index.html +++ b/src/templates/index.html @@ -56,14 +56,21 @@ .nes-input { cursor: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABFklEQVRYR9WXURLDIAhE6/0PbSdOtUpcd1Gnpv1KGpTHBpCE1/cXq+vrMph7dGvXZTtpfW10DCA5jrH1H0Jhs5E0hnZdCR+vb5S8Nn8mQCeS9BdSalYJqMBjAGzq59xAESN7VFVUgV8AZB/dZBR7QTFDCqGquvUBVVoEtgIwpQRzmANSFHgWQKExHdIrPeuMvQNDarXe6nC/AutgV3JW+6bgqQLeV8FekRtgV+ToDKEKnACYKsfZjjkam7a0ZpYTytwmgainpC3HvwBocgKOxqRjehoR9DFKNFYtOwCGYCszobeCbl26N6yyQ6g8X/Wex/rBPsNEV6qAMaJPMynIHQCoSqS9JSMmwef51LflTgCRszU7DvAGiV6mHWfsaVUAAAAASUVORK5CYII=), auto; } + + .mtr-2 { + margin-top: 2rem; + } </style> <title>Bot code</title> </head> <body> + +{% if not activated %} <div class="h-center"> Welcome back, s3rius! </div> -<form action="/code" method="post" class="center" autocomplete="off"> + +<form id="code_form" action="/code" method="post" class="center" autocomplete="off"> <div class="nes-field is-inline"> <label for="inline_field">Verification code</label> <input type="text" id="inline_field" class="nes-input is-success" name="code" placeholder="Your code"> @@ -72,6 +79,42 @@ <input type="submit" class="nes-input is-success" value="Submit code"> </div> </form> +{%else%} +<div class="center"> + Hi, there! The bot is running. +</div> +<div class="center mtr-2"> + Just write a message to <a href="tg://resolve?domain=s3rius_san">@s3rius_san</a> in telegram. +</div> +{% endif %} <img src="/girl.png" alt="" class="at_bottom"> </body> +<script> + function sendData() { + const XHR = new XMLHttpRequest(); + // Bind the FormData object and the form element + const FD = new FormData(form); + // Define what happens on successful data submission + XHR.addEventListener("load", function (event) { + location.reload() + }); + // Define what happens in case of error + XHR.addEventListener("error", function (event) { + location.reload() + }); + // Set up our request + XHR.open("POST", "/code"); + // The data sent is what the user provided in the form + XHR.send(FD); + } + + const form = document.getElementById("code_form"); + + // ...and take over its submit event. + form.addEventListener("submit", function (event) { + event.preventDefault(); + + sendData(); + }); +</script> </html> -- GitLab