few formating changes and update logo endpoint

This commit is contained in:
odysseusmax 2021-06-14 11:00:52 +05:30
parent 71f0a11789
commit bf9348699a
8 changed files with 45 additions and 37 deletions

View File

@ -5,13 +5,12 @@ import asyncio
from telethon import TelegramClient, utils
from telethon.sessions import StringSession
class Client(TelegramClient):
class Client(TelegramClient):
def __init__(self, session_string, *args, **kwargs):
super().__init__(StringSession(session_string), *args, **kwargs)
self.log = logging.getLogger(__name__)
async def download(self, file, file_size, offset, limit):
part_size_kb = utils.get_appropriated_part_size(file_size)
part_size = int(part_size_kb * 1024)
@ -22,10 +21,12 @@ class Client(TelegramClient):
part_count = math.ceil(file_size / part_size)
part = first_part
try:
async for chunk in self.iter_download(file, offset=first_part * part_size, request_size=part_size):
async for chunk in self.iter_download(
file, offset=first_part * part_size, request_size=part_size
):
if part == first_part:
yield chunk[first_part_cut:]
elif part == last_part-1:
elif part == last_part - 1:
yield chunk[:last_part_cut]
else:
yield chunk

View File

@ -1,7 +1,5 @@
import base64
import hashlib
import random
import string
from ..config import SHORT_URL_LEN
@ -17,7 +15,6 @@ from .logout_view import LogoutView
from .middlewhere import middleware_factory
class Views(
HomeView,
Download,
@ -39,14 +36,18 @@ class Views(
title = chat.title
while True:
orig_id = f"{chat_id}" # the original id
orig_id = f"{chat_id}" # the original id
unique_hash = hashlib.md5(orig_id.encode()).digest()
alias_id = base64.urlsafe_b64encode(unique_hash).decode()[:self.url_len]
alias_id = base64.urlsafe_b64encode(unique_hash).decode()[: self.url_len]
if alias_id in self.chat_ids:
self.url_len += 1 # increment url_len just incase the hash is already used.
self.url_len += (
1 # increment url_len just incase the hash is already used.
)
continue
elif (self.url_len > SHORT_URL_LEN): # reset url_len to initial if hash was unique.
elif (
self.url_len > SHORT_URL_LEN
): # reset url_len to initial if hash was unique.
self.url_len = SHORT_URL_LEN
self.chat_ids[alias_id] = {

View File

@ -33,7 +33,6 @@ class LoginView:
return web.HTTPFound(location=loc)
session = await new_session(req)
print(session)
session["logged_in"] = True
session["logged_in_at"] = time.time()
return web.HTTPFound(location=redirect_to)

View File

@ -1,5 +1,6 @@
import logging
from PIL import Image, ImageDraw
import math
from PIL import Image, ImageDraw, ImageFont
import random
from aiohttp import web
@ -16,11 +17,11 @@ class LogoView:
alias_id = req.match_info["chat"]
chat = self.chat_ids[alias_id]
chat_id = chat["chat_id"]
chat_name = "Image not available"
chat_name = " ".join(map(lambda x: x[0].upper(), chat["title"].split(" ")))
logo_path = logo_folder.joinpath(f"{alias_id}.jpg")
if not logo_path.exists():
try:
photo = await self.client.get_profile_photos(chat_id)
(photo,) = await self.client.get_profile_photos(chat_id, limit=1)
except Exception:
log.debug(
f"Error in getting profile picture in {chat_id}", exc_info=True
@ -28,15 +29,17 @@ class LogoView:
photo = None
if not photo:
W, H = (160, 160)
color = tuple([random.randint(0, 255) for i in range(3)])
W, H = (360, 360)
color = tuple((random.randint(0, 255) for _ in range(3)))
im = Image.new("RGB", (W, H), color)
draw = ImageDraw.Draw(im)
w, h = draw.textsize(chat_name)
draw.text(((W - w) / 2, (H - h) / 2), chat_name, fill="white")
font = ImageFont.truetype("arial.ttf", 50)
w, h = draw.textsize(chat_name, font=font)
draw.text(
((W - w) / 2, (H - h) / 2), chat_name, fill="white", font=font
)
im.save(logo_path)
else:
photo = photo[0]
pos = -1 if req.query.get("big", None) else int(len(photo.sizes) / 2)
size = self.client._get_thumb(photo.sizes, pos)
if isinstance(size, (types.PhotoCachedSize, types.PhotoStrippedSize)):

View File

@ -51,7 +51,7 @@ class ThumbnailView:
except Exception as e:
logging.debug(e)
thumbnail = None
if not thumbnail or isinstance(thumbnail, types.PhotoSizeEmpty):
return web.Response(
status=410,

View File

@ -4,3 +4,4 @@ telethon>=1.16.4
cryptg
pillow
aiohttp_session[secure]
dotenv

View File

@ -8,22 +8,26 @@ load_dotenv() # take environment variables from .env.
# os.system("alias python3=python")
def runSetup():
def alert(missing="API_ID , API_HASH"):
print(f"\nCopy your {missing} and save it into Secrets(Environment variables) Sidebar!\n")
def alert(missing="API_ID , API_HASH"):
print(
f"\nCopy your {missing} and save it into Secrets(Environment variables) Sidebar!\n"
)
api_id = os.getenv("API_ID")
if api_id == None:
alert()
return
api_id = os.getenv("API_ID")
if api_id is None:
alert()
return
session_string = os.getenv("SESSION_STRING")
if session_string == None:
os.system("python app/generate_session_string.py")
alert(missing = "SESSION_STRING")
return
session_string = os.getenv("SESSION_STRING")
if session_string is None:
os.system("python app/generate_session_string.py")
alert(missing="SESSION_STRING")
return
os.system("python -m app")
os.system("python -m app")
if __name__ == '__main__':
runSetup()
if __name__ == "__main__":
runSetup()

View File

@ -1 +0,0 @@
python-3.8.5