-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #10 from teleportx/delta
Delta version pre pr
- Loading branch information
Showing
104 changed files
with
6,122 additions
and
415 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -163,4 +163,5 @@ data.json | |
.setupdb.py | ||
test.py | ||
|
||
logs | ||
logs/ | ||
.pio/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,36 @@ | ||
# URA Project | ||
Бот для того чтобы держать вкурсе, когда ты идешь... | ||
# [YPA Project](https://t.me/uragv_bot) | ||
Бот для того чтобы держать вкурсе, когда ты идешь ... | ||
|
||
### Команда | ||
- [Степан Хожемпо](https://github.com/teleportx) - Backend developer & Bot developer | ||
- [Максим Кузнецов](https://github.com/uuuuuno-devops) - Frontend developer & DevOps engineer | ||
- [Алексей Шаблыкин](https://t.me/AllShabCH) - Project manager | ||
- [Матвей Рябчиков](https://github.com/ronanru) - Frontend develover | ||
|
||
### История | ||
> C давних времён, с самого зарождения цивилизаций, информация всегда | ||
> была самым ценным ресурсом. Какой смысл в добыче металлов, если ты не | ||
> знаешь, как изготовить из этого металла инструмент? Передача же | ||
> информации была чем-то сакральным, она передавалась от отца к сыну, от | ||
> кузнеца к подмастерью и всегда была на вес золота. Войны выигрывались | ||
> из-за получения ключевой информации о противнике одной из сторон. | ||
> | ||
> Сейчас идёт век глобализации, информация стала более доступной для | ||
> обычного человека, но по настоящему важная информация остаётся скрытой | ||
> в архивах государств, за дверьми домов самых богатых людей мира и в | ||
> памяти учёных, которые не хотят делиться своими знаниями. | ||
> | ||
> И вот, группа энтузиастов, которые хотят явить народу истинные знания, | ||
> представляют вашему вниманию проект УРА! Уведомления Ректальной | ||
> Активности откроет вам глаза на важный аспект нашей жизни, на личную | ||
> жизнь жопы каждого, кто присоединился к нашему проекту. | ||
> | ||
> Всё началось с идеи, что каждый наш друг должен знать, что мы в | ||
> безопасности, что наша жопа открыта для каждого толчка на Земле. Позже | ||
> наша небольшая команда поняла, что в этом нуждается каждый житель | ||
> планеты и мы начали масштабироваться. Мы сделали всё, чтобы каждый | ||
> смог прикоснуться к Big Data, к которой ранее имели доступ только | ||
> самые богатые корпорации и люди планеты. Сегодня наш проект является | ||
> лучшим олицетворением свободы передачи информации всемирного масштаба. | ||
> Мы не остановимся ни перед чем, чтобы каждый мог посрать не в | ||
> одиночестве! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
from fastapi import FastAPI | ||
|
||
from .auth import AuthMiddleware | ||
|
||
|
||
def setup(app: FastAPI, raise_unauthorized: bool = False): | ||
app.add_middleware(AuthMiddleware, raise_unauthorized=raise_unauthorized) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
from fastapi import Request | ||
from starlette.middleware.base import BaseHTTPMiddleware | ||
from starlette.responses import JSONResponse | ||
|
||
from db.ApiAuth import ApiToken | ||
|
||
|
||
class AuthMiddleware(BaseHTTPMiddleware): | ||
def __init__(self, app, raise_unauthorized: bool = False): | ||
super().__init__(app) | ||
self.raise_unauthorized = raise_unauthorized | ||
|
||
async def dispatch(self, request: Request, call_next): | ||
token = await ApiToken.get_or_none(token=ApiToken.hash_token(request.headers.get('Authorization', ''))) | ||
if token is None: | ||
request.state.user = None | ||
if self.raise_unauthorized: | ||
return JSONResponse({"detail": "Failed auth by token"}, status_code=401) | ||
|
||
else: | ||
request.state.user = await token.owner | ||
|
||
response = await call_next(request) | ||
return response |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
FROM python:3.10-slim-buster | ||
|
||
WORKDIR /app | ||
|
||
COPY ../requirements.txt requirements.txt | ||
RUN pip3 install -r requirements.txt | ||
|
||
|
||
COPY .. . | ||
|
||
WORKDIR /app/api_services/srat_service | ||
CMD ["fastapi", "run", "main.py", "--port", "80"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
import sys | ||
|
||
sys.path.append('..') | ||
sys.path.append('../..') | ||
|
||
from typing import Optional | ||
|
||
from aiogram import Bot | ||
from fastapi import FastAPI, Request | ||
from pydantic import BaseModel | ||
from starlette.responses import JSONResponse | ||
|
||
import brocker | ||
import config | ||
import db | ||
import api_middlewares | ||
import setup_logger | ||
from db.ToiletSessions import SretSession, SretType | ||
from db.User import User | ||
from utils import send_srat_notification | ||
|
||
setup_logger.__init__("API srat") | ||
|
||
app = FastAPI(docs_url=None, redoc_url=None) | ||
api_middlewares.setup(app, True) | ||
|
||
|
||
class SratModel(BaseModel): | ||
status: Optional[SretType] | ||
|
||
|
||
@app.on_event("startup") | ||
async def startup_event(): | ||
await db.init() | ||
await brocker.init() | ||
|
||
bot = Bot( | ||
token=config.Telegram.token, | ||
parse_mode='html', | ||
) | ||
config.bot = bot | ||
|
||
|
||
@app.get('/api/srat/', status_code=200, response_model=SratModel) | ||
async def get_srat(request: Request): | ||
user: User = request.state.user | ||
|
||
last_open_session = await SretSession.filter(user=user, end=None).get_or_none() | ||
if last_open_session is None: | ||
srat_status = None | ||
|
||
else: | ||
srat_status = last_open_session.sret_type | ||
|
||
return SratModel(status=srat_status) | ||
|
||
|
||
@app.post('/api/srat/', status_code=204) | ||
async def set_srat(request: Request, srat: SratModel): | ||
if srat.status is None: | ||
srat.status = 0 | ||
|
||
user: User = request.state.user | ||
|
||
if not await send_srat_notification.verify_action(user, srat.status): | ||
return JSONResponse({"detail": "You cannot make this action"}, status_code=400) | ||
|
||
await send_srat_notification.send(user, srat.status) | ||
return |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
from .command_mention import CommandMention | ||
from .user import UserAuthFilter |
File renamed without changes.
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.