notification manager

This commit is contained in:
Egor Matveev 2022-03-20 16:11:06 +03:00
parent 9b3635723e
commit 0d7f2b9496
6 changed files with 65 additions and 27 deletions

View File

@ -1,7 +1,7 @@
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.db.models import Q from django.db.models import Q
from daemons.management.commands.bot import bot from SprintLib.queue import notify
from Main.models import Friendship from Main.models import Friendship
from SprintLib.BaseView import BaseView from SprintLib.BaseView import BaseView
from SprintLib.language import languages from SprintLib.language import languages
@ -46,22 +46,17 @@ class AccountView(BaseView):
).first() ).first()
if friendship is None: if friendship is None:
Friendship.objects.create(from_user=self.request.user, to_user=self.context["account"]) Friendship.objects.create(from_user=self.request.user, to_user=self.context["account"])
if self.context["account"].userinfo.notification_friends: notify(self.context['account'], 'friends', f"Пользователь {self.request.user.username} хочет добавить тебя в друзья")
bot.send_message(self.context["account"].userinfo.telegram_chat_id, f"Пользователь {self.request.user.username} хочет добавить тебя в друзья")
elif friendship.verified or friendship.from_user == self.request.user: elif friendship.verified or friendship.from_user == self.request.user:
friendship.delete() friendship.delete()
else: else:
if self.request.POST["to_do"] == "yes": if self.request.POST["to_do"] == "yes":
friendship.verified = True friendship.verified = True
friendship.save() friendship.save()
if self.context["account"].userinfo.notification_friends: notify(self.context['account'], 'friends', f"Пользователь {self.request.user.username} добавил тебя в друзья")
bot.send_message(self.context["account"].userinfo.telegram_chat_id,
f"Пользователь {self.request.user.username} добавил тебя в друзья")
else: else:
friendship.delete() friendship.delete()
if self.context["account"].userinfo.notification_friends: notify(self.context['account'], 'friends', f"Пользователь {self.request.user.username} отклонил твою заявку")
bot.send_message(self.context["account"].userinfo.telegram_chat_id,
f"Пользователь {self.request.user.username} отклонил твою заявку")
return "/account?username=" + self.request.GET["username"] return "/account?username=" + self.request.GET["username"]
def post_upload_photo(self): def post_upload_photo(self):

View File

@ -1,10 +1,11 @@
from django.contrib.auth import login
from daemons.management.commands.bot import bot
from SprintLib.BaseView import BaseView
from django.contrib.auth.models import User
from random import randrange from random import randrange
from django.contrib.auth import login
from django.contrib.auth.models import User
from SprintLib.BaseView import BaseView
from SprintLib.queue import notify
class SendCodeView(BaseView): class SendCodeView(BaseView):
endpoint = "send_code" endpoint = "send_code"
@ -20,9 +21,7 @@ class SendCodeView(BaseView):
code = randrange(10000, 100000) code = randrange(10000, 100000)
user.userinfo.code = code user.userinfo.code = code
user.userinfo.save() user.userinfo.save()
bot.send_message( notify(user, "any", "Код для входа в сервис: " + str(code))
user.userinfo.telegram_chat_id, "Код для входа в сервис: " + str(code)
)
return {"success": True, "message": "Код отправлен"} return {"success": True, "message": "Код отправлен"}
def post_check(self): def post_check(self):

View File

@ -1,6 +1,7 @@
import json import json
import pika import pika
from django.contrib.auth.models import User
from django.core.management import BaseCommand from django.core.management import BaseCommand
from pika.adapters.utils.connection_workflow import AMQPConnectorException from pika.adapters.utils.connection_workflow import AMQPConnectorException
@ -44,3 +45,11 @@ class MessagingSupport(BaseCommand):
channel.start_consuming() channel.start_consuming()
except AMQPConnectorException: except AMQPConnectorException:
print("connection to rabbit failed: reconnecting") print("connection to rabbit failed: reconnecting")
def notify(user: User, notification_type: str, text: str):
send_to_queue("notifications", {
'user_id': user,
'notification_type': notification_type,
'text': text,
})

View File

@ -2,7 +2,7 @@ from os import listdir, mkdir
from os.path import join, exists from os.path import join, exists
from subprocess import call, TimeoutExpired from subprocess import call, TimeoutExpired
from daemons.management.commands.bot import bot from SprintLib.queue import notify
from Main.models import ExtraFile, SolutionFile from Main.models import ExtraFile, SolutionFile
from Main.models.progress import Progress from Main.models.progress import Progress
from Sprint.settings import CONSTS from Sprint.settings import CONSTS
@ -153,12 +153,10 @@ class BaseTester:
call(f"docker rm --force solution_{self.solution.id}", shell=True) call(f"docker rm --force solution_{self.solution.id}", shell=True)
call(f"docker rm --force solution_{self.solution.id}_checker", shell=True) call(f"docker rm --force solution_{self.solution.id}_checker", shell=True)
self.solution.user.userinfo.refresh_from_db() self.solution.user.userinfo.refresh_from_db()
if self.solution.user.userinfo.notification_solution_result: notify(
bot.send_message( self.solution.user,
self.solution.user.userinfo.telegram_chat_id, "solution_result",
f"Задача: {self.solution.task.name}\n" f"Задача: {self.solution.task.name}\n"
f"Результат: {self.solution.result}\n" f"Результат: {self.solution.result}\n"
f"Очки решения: {Progress.by_solution(self.solution).score}\n" f"Очки решения: {Progress.by_solution(self.solution).score}\n"
f"Текущий рейтинг: {self.solution.user.userinfo.rating}", f"Текущий рейтинг: {self.solution.user.userinfo.rating}")
parse_mode="html",
)

View File

@ -0,0 +1,20 @@
from django.contrib.auth.models import User
from SprintLib.queue import MessagingSupport
from daemons.management.commands.bot import bot
class Command(MessagingSupport):
help = "starts file notification manager"
queue_name = "notifications"
def process(self, payload: dict):
user = User.objects.get(id=payload['user_id'])
notification_type = payload['type']
text = payload['text']
if notification_type == "any" or getattr(user.userinfo, "notification_" + notification_type):
bot.send_message(
user.userinfo.telegram_chat_id,
text,
parse_mode="html",
)

View File

@ -172,6 +172,23 @@ services:
restart_policy: restart_policy:
condition: on-failure condition: on-failure
notification_manager:
image: mathwave/sprint-repo:sprint
command: ./manage.py notification_manager
environment:
SOLUTIONS_ROOT_EXTERNAL: "/sprint-data/data/solutions"
DB_HOST: $DB_HOST
DB_PASSWORD: $DB_PASSWORD
RABBIT_HOST: $RABBIT_HOST
FS_HOST: $FS_HOST
DEBUG: $DEBUG
TELEGRAM_TOKEN: $TELEGRAM_TOKEN
deploy:
mode: replicated
replicas: 1
restart_policy:
condition: on-failure
apply-languages: apply-languages:
image: mathwave/sprint-repo:sprint image: mathwave/sprint-repo:sprint
command: ./manage.py apply_languages command: ./manage.py apply_languages