aboutsummaryrefslogtreecommitdiff
blob: 307f18f7f7d202153a20558ba8595438348e3b58 (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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
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="application/json")
    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)