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

View File

@ -1,7 +1,5 @@
import base64 import base64
import hashlib import hashlib
import random
import string
from ..config import SHORT_URL_LEN from ..config import SHORT_URL_LEN
@ -17,7 +15,6 @@ from .logout_view import LogoutView
from .middlewhere import middleware_factory from .middlewhere import middleware_factory
class Views( class Views(
HomeView, HomeView,
Download, Download,
@ -39,14 +36,18 @@ class Views(
title = chat.title title = chat.title
while True: 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() 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: 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 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.url_len = SHORT_URL_LEN
self.chat_ids[alias_id] = { self.chat_ids[alias_id] = {

View File

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

View File

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

View File

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

View File

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

View File

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