aboutsummaryrefslogtreecommitdiff
path: root/bot.py
blob: 20529c014c50d83f5cd95960c1300f88855bce60 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
import io
import os
import logging
import traceback
from PIL import Image
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

db = SqliteDatabase("database/photos.db")
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)
    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")


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,
                "createdAt": photo.createdAt.strftime("%Y-%m-%dT%H:%M:%S.000Z"),
                "uploadedAt": photo.uploadedAt.strftime("%Y-%m-%dT%H:%M:%S.000Z")
            })
        with open("database/photos.json", "w") as f:
            f.write(json.dumps(results))
    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

    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)
        output = io.BytesIO()
        im.save(output, format="webp", lossless=True, quality=100)

        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="dsadas",
                                 alt="dsada",
                                 createdAt=datetime.now(),
                                 uploadedAt=datetime.now())

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

        write_json()
        await update.message.reply_markdown_v2(text="Sending processed result")

        await context.bot.send_document(chat_id=update.message.chat_id,
                                        filename="{}-result.{}".format(filename, file_ext),
                                        document=output.getvalue())

    except Exception as e:
        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)