Compare commits

...

6 Commits

Author SHA1 Message Date
Profitroll
741a01cff6 Fixed literal 2022-12-17 23:26:07 +01:00
Profitroll
6b00f181f6 Avatars caching implemented 2022-12-17 23:25:53 +01:00
Profitroll
41eb6e46ee Added one more type check for HoloUser init 2022-12-17 23:14:12 +01:00
Profitroll
1d5ebd02fe Changed max number of results 2022-12-17 23:12:15 +01:00
Profitroll
43ce2d73b6 Fixed application removal 2022-12-17 23:10:56 +01:00
Profitroll
797d9de7e4 Also handling HEAD requests now 2022-12-17 22:31:30 +01:00
6 changed files with 38 additions and 7 deletions

View File

@ -1,6 +1,6 @@
from os import makedirs, path, sep from os import makedirs, path, sep
from fastapi import FastAPI, HTTPException from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse, JSONResponse from fastapi.responses import FileResponse, JSONResponse, Response
from starlette.status import HTTP_404_NOT_FOUND from starlette.status import HTTP_404_NOT_FOUND
from modules.utils import configGet from modules.utils import configGet
@ -9,12 +9,20 @@ makedirs(f'{configGet("cache", "locations")}{sep}avatars', exist_ok=True)
app = FastAPI(title="HoloUA Avatars API", docs_url=None, redoc_url=None, version="1.0") app = FastAPI(title="HoloUA Avatars API", docs_url=None, redoc_url=None, version="1.0")
@app.get("/check", response_class=JSONResponse, include_in_schema=False) @app.get("/check", response_class=JSONResponse, include_in_schema=False)
@app.head("/check", response_class=JSONResponse, include_in_schema=False)
async def check(): async def check():
return JSONResponse({"detail": "I'm alright, thank you"}) return JSONResponse({"detail": "I'm alright, thank you"})
@app.get("/", response_class=FileResponse, include_in_schema=False) @app.get("/", response_class=FileResponse, include_in_schema=False)
async def favicon(avatar_id: str): async def avatar_get(avatar_id: str):
if path.exists(f'{configGet("cache", "locations")}{sep}avatars{sep}{avatar_id}'): if path.exists(f'{configGet("cache", "locations")}{sep}avatars{sep}{avatar_id}'):
return FileResponse(f'{configGet("cache", "locations")}{sep}avatars{sep}{avatar_id}', media_type="image/jpg") return FileResponse(f'{configGet("cache", "locations")}{sep}avatars{sep}{avatar_id}', media_type="image/jpg")
else:
raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="File not found")
@app.head("/", response_class=Response, include_in_schema=False)
async def avatar_head(avatar_id: str):
if path.exists(f'{configGet("cache", "locations")}{sep}avatars{sep}{avatar_id}'):
return Response(headers={"Content-Length": path.getsize(f'{configGet("cache", "locations")}{sep}avatars{sep}{avatar_id}')})
else: else:
raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="File not found") raise HTTPException(status_code=HTTP_404_NOT_FOUND, detail="File not found")

View File

@ -100,10 +100,10 @@ class HoloUser():
self.locale = holo_user["tg_locale"] self.locale = holo_user["tg_locale"]
self.username = holo_user["tg_username"] self.username = holo_user["tg_username"]
if isinstance(user, User) and ((self.name != user.first_name) and (user.first_name is None)): if isinstance(user, User) and ((self.name != user.first_name) and (user.first_name is not None)):
self.set("tg_name", user.first_name) self.set("tg_name", user.first_name)
if isinstance(user, User) and (self.phone != user.phone_number): if isinstance(user, User) and ((self.phone != user.phone_number) and (user.phone_number is not None)):
self.set("tg_phone", user.phone_number) self.set("tg_phone", user.phone_number)
if isinstance(user, User) and ((self.locale != user.language_code) and (user.language_code is not None)): if isinstance(user, User) and ((self.locale != user.language_code) and (user.language_code is not None)):

View File

@ -37,6 +37,10 @@
"sponsorships": { "sponsorships": {
"time": 9, "time": 9,
"enabled": true "enabled": true
},
"cache_avatars": {
"interval": 6,
"enabled": true
} }
}, },
"locations": { "locations": {

View File

@ -20,7 +20,7 @@ async def callback_reapply_query_accept(app, clb):
await app.send_message(holo_user.id, locale("approved_joined", "message", locale=holo_user)) await app.send_message(holo_user.id, locale("approved_joined", "message", locale=holo_user))
col_applications.delete_one({"user": {"$eq": holo_user.id}}) col_applications.delete_one({"user": holo_user.id})
col_applications.insert_one({"user": holo_user.id, "date": datetime.now(), "admin": clb.from_user.id, "application": col_tmp.find_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}})["application"]}) col_applications.insert_one({"user": holo_user.id, "date": datetime.now(), "admin": clb.from_user.id, "application": col_tmp.find_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}})["application"]})
col_tmp.update_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}}, {"$set": {"state": "approved", "sent": False}}) col_tmp.update_one({"user": {"$eq": holo_user.id}, "type": {"$eq": "application"}}, {"$set": {"state": "approved", "sent": False}})

View File

@ -44,8 +44,10 @@ async def inline_answer(client, inline_query):
if holo_user.application_approved() or (await isAnAdmin(holo_user.id) is True): if holo_user.application_approved() or (await isAnAdmin(holo_user.id) is True):
max_results = configGet("inline_preview_count") if inline_query.query != "" else 200
list_of_users = [] list_of_users = []
async for m in app.get_chat_members(configGet("destination_group"), limit=configGet("inline_preview_count"), filter=ChatMembersFilter.SEARCH, query=inline_query.query): async for m in app.get_chat_members(configGet("destination_group"), limit=max_results, filter=ChatMembersFilter.SEARCH, query=inline_query.query):
list_of_users.append(m) list_of_users.append(m)
results = [] results = []

View File

@ -1,6 +1,8 @@
from os import path, sep
from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.schedulers.asyncio import AsyncIOScheduler
from datetime import datetime from datetime import datetime, timedelta
from app import app from app import app
from pyrogram.enums.chat_members_filter import ChatMembersFilter
from modules.utils import configGet, locale, logWrite from modules.utils import configGet, locale, logWrite
from dateutil.relativedelta import relativedelta from dateutil.relativedelta import relativedelta
from modules.database import col_applications from modules.database import col_applications
@ -19,6 +21,21 @@ scheduler = AsyncIOScheduler()
# except AttributeError: # except AttributeError:
# continue # continue
if configGet("enabled", "scheduler", "cache_avatars"):
@scheduler.scheduled_job(trigger="date", run_date=datetime.now()+timedelta(seconds=10))
@scheduler.scheduled_job(trigger="interval", hours=configGet("interval", "scheduler", "cache_avatars"))
async def cache_avatars():
list_of_users = []
async for member in app.get_chat_members(configGet("destination_group"), filter=ChatMembersFilter.SEARCH, query=""):
list_of_users.append(member.user)
for user in list_of_users:
if user.photo != None:
if not path.exists(f'{configGet("cache", "locations")}{sep}avatars{sep}{user.photo.big_file_id}'):
print(f'Pre-cached avatar {user.photo.big_file_id} of {user.id}', flush=True)
await app.download_media(user.photo.big_file_id, file_name=f'{configGet("cache", "locations")}{sep}avatars{sep}{user.photo.big_file_id}')
logWrite("Avatars caching performed")
if configGet("enabled", "scheduler", "birthdays"): if configGet("enabled", "scheduler", "birthdays"):
@scheduler.scheduled_job(trigger="cron", hour=configGet("time", "scheduler", "birthdays")) @scheduler.scheduled_job(trigger="cron", hour=configGet("time", "scheduler", "birthdays"))
async def check_birthdays(): async def check_birthdays():