aboutsummaryrefslogblamecommitdiff
blob: 37feface80239b49b631e1575115e3bdd12af782 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13



                
                               







                                                                                           
          
            
 









                                                                                                           

















                                                   
                                                 





















                                                                                     
                                                                                
















                                                 
                                     


                                                                                 
                                                                 
                                                                        
















































                                                                                                          
                                              






                                                                                                                 


                           
                            





                                                          
                                                                                   
 
                             
                                                                  











                                                                                                 
                                                 
                                        
                                                    
                                                                                              





                                                           




                                                                                                                    
                     














                                                                                                      
import io
import os
import logging
import traceback
from PIL import Image, ExifTags
import boto3
from telegram import Update
from telegram.constants import ParseMode
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
from peewee import *
from uuid import uuid4
from datetime import datetime
import json
import sys
import httpx


if os.getenv("DB_DRIVER") == "psql":
    db = PostgresqlDatabase(os.getenv("DB_NAME"), user=os.getenv("DB_USER"), password=os.getenv("DB_PASS"),
                            host=os.getenv("DB_HOST"), port=os.getenv("DB_PORT"))
elif os.getenv("DB_DRIVER") == "sqlite3":
    db = SqliteDatabase("database/photos.db")
else:
    print("No DB_DRIVER specified")
    sys.exit(1)

db.connect(reuse_if_open=True)


class BaseModel(Model):
    class Meta:
        database = db


class Photo(BaseModel):
    guid = CharField(unique=True, primary_key=True)
    fileId = CharField(max_length=256)
    width = IntegerField()
    height = IntegerField()
    ratio = FloatField()
    orientation = CharField(max_length=128)
    path = CharField(max_length=256)
    caption = CharField(max_length=256)
    alt = CharField(max_length=256)
    model = CharField(max_length=256, default="")
    createdAt = DateTimeField()
    uploadedAt = DateTimeField()


with db.connection_context():
    db.create_tables([Photo])

logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)

logger = logging.getLogger(__name__)


async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text("This is a bot to output image in square shape")


bucket_name = "pixel-jinwei-me"
cf_account_id = os.getenv("CF_ACCOUNT_ID")
aws_access_key_id = os.getenv("CF_R2_KEY_ID")
aws_secret_access_key = os.getenv("CF_R2_ACCESS_KEY_SECRET")
cloudflare_pages_deploy_hook_url = os.getenv("CLOUDFLARE_PAGES_DEPLOY_HOOK_URL")


def write_json() -> bool:
    with db.connection_context():
        photos = Photo.select()
        results = []
        for photo in photos:
            results.append({
                "guid": photo.guid,
                "fileId": photo.fileId,
                "width": photo.width,
                "height": photo.height,
                "ratio": photo.ratio,
                "orientation": photo.orientation,
                "path": photo.path,
                "caption": photo.caption,
                "alt": photo.alt,
                "model": photo.model,
                "createdAt": photo.createdAt.strftime("%Y-%m-%dT%H:%M:%S.000Z"),
                "uploadedAt": photo.uploadedAt.strftime("%Y-%m-%dT%H:%M:%S.000Z")
            })
        results.sort(key=lambda x: x["uploadedAt"], reverse=True)
        upload_to_s3("photos.json", json.dumps(results).encode("utf-8"))
    return True


def upload_to_s3(key_name: str, file: bytes):
    endpoint_ca_central = "https://{}.r2.cloudflarestorage.com".format(cf_account_id)

    client = boto3.client("s3",
                          region_name="auto",
                          endpoint_url=endpoint_ca_central,
                          aws_access_key_id=aws_access_key_id,
                          aws_secret_access_key=aws_secret_access_key)

    response = client.list_buckets()
    buckets = [b["Name"] for b in response['Buckets']]

    if bucket_name not in buckets:
        print("{} doesn't exist".format(bucket_name))
        print('Existing buckets:')
        for bucket in response['Buckets']:
            print(f' {bucket["Name"]}')
        return False

    response = client.put_object(Body=file, Bucket=bucket_name, Key=key_name, ContentType="image/webp")
    status = response["ResponseMetadata"]["HTTPStatusCode"]
    if status == 200:
        print("upload {} to {} succeed".format(key_name, bucket_name))
        return True
    else:
        print("upload {} to {} failed, status: {}".format(key_name, bucket_name, status))
        return False


async def process(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    chat_id = update.message.chat_id

    if update.message.document is not None:
        names = update.message.document.file_name.split(".")
        file_ext = names[1]
        filename = names[0]

        if str.upper(file_ext) not in ("JPG", "JPEG", "PNG"):
            await context.bot.send_message(chat_id, "Image extension `{}` not supported".format(file_ext),
                                           parse_mode=ParseMode.MARKDOWN_V2)
            return

        file = await update.message.effective_attachment.get_file()
    else:
        return

    caption = update.effective_message.caption
    await context.bot.send_message(chat_id, "Processing `{}`".format(filename), parse_mode=ParseMode.MARKDOWN_V2)

    img = io.BytesIO()
    await file.download_to_memory(img)

    try:
        im = Image.open(img)
        exif = im.getexif()

        camera_model = ""
        shot_datetime = None
        if exif:
            for key, val in exif.items():
                if key in ExifTags.TAGS:
                    if ExifTags.TAGS[key] == "Model":
                        camera_model = val
                    elif ExifTags.TAGS[key] == "DateTime":
                        shot_datetime = datetime.strptime(val, "%Y:%m:%d %H:%M:%S")

        output = io.BytesIO()
        im.save(output, format="webp", lossless=False, quality=80)

        now = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
        key_name = "{}-{}.webp".format(now, filename)

        with db.connection_context():
            photo = Photo.create(guid=str.upper(str(uuid4())),
                                 fileId=key_name,
                                 width=im.width,
                                 height=im.height,
                                 ratio=im.width / im.height,
                                 orientation="landscape" if im.width > im.height else "portrait",
                                 path="https://pixelstatic.jinwei.me/{}".format(key_name),
                                 caption=caption,
                                 alt="",
                                 model=camera_model,
                                 createdAt=shot_datetime if shot_datetime else datetime.now(),
                                 uploadedAt=datetime.now())

            output.seek(0)
            upload_to_s3(photo.fileId, output.read())

        write_json()
        response = httpx.post(cloudflare_pages_deploy_hook_url)
        if response.status_code == 200:
            await update.message.reply_markdown_v2(text="trigger deploy succeed")
        else:
            await update.message.reply_markdown_v2("trigger deploy failed, status: {}".format(response.status_code))
    except Exception:
        await update.message.reply_markdown_v2(text="Error:\n```{}```".format(traceback.format_exc()))


def main() -> None:
    tg_token = os.getenv("TG_TOKEN")
    application = Application.builder().token(tg_token).build()

    application.add_handler(CommandHandler("start", start))
    application.add_handler(MessageHandler(filters.ATTACHMENT & ~filters.COMMAND, process))

    application.run_polling()


if __name__ == "__main__":
    main()
Powered by cgit v1.2.3 (git 2.41.0)