Skip to content

Commit

Permalink
✨ feat: 백과사전 이미지 업로드 추가, 구조 리팩토링
Browse files Browse the repository at this point in the history
  • Loading branch information
kms0219kms committed Apr 2, 2024
1 parent dd23115 commit f7cff29
Show file tree
Hide file tree
Showing 8 changed files with 236 additions and 253 deletions.
299 changes: 47 additions & 252 deletions src/cogs/ZzalUpload.py

Large diffs are not rendered by default.

Empty file added src/cogs/__init__.py
Empty file.
Empty file added src/plugins/__init__.py
Empty file.
40 changes: 40 additions & 0 deletions src/plugins/filestation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from os import getenv
from dotenv import load_dotenv
from synology_api.filestation import FileStation


@staticmethod
def getSynologyHost() -> dict:
host = getenv("SYNOLOGY_HOST")

return {
"ip_address": host.split("@")[1].split(":")[0],
"port": host.split("@")[1].split(":")[1],
"username": host.split("//")[1].split(":")[0],
"password": host.split("//")[1].split(":")[1].split("@")[0],
"secure": getenv("MODE") != "PRODUCTION",
"cert_verify": False,
"dsm_version": 7,
"debug": True,
}


class FileStationPlugin:
def __init__(self) -> None:
load_dotenv()

host = getSynologyHost()

self._filestation = FileStation(
ip_address=host["ip_address"],
port=host["port"],
username=host["username"],
password=host["password"],
secure=host["secure"] or False,
cert_verify=host["cert_verify"] or False,
dsm_version=host["dsm_version"] or 7,
debug=host["debug"] or False,
)

def getFileStation(self) -> FileStation:
return self._filestation
2 changes: 1 addition & 1 deletion src/plugins/google.py → src/plugins/sheet.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from gspread import Client, Worksheet, authorize


class GoogleUtil:
class SheetPlugin:
def __init__(self):
self._credentials = Credentials.from_service_account_info(
json.loads(base64.b64decode(os.getenv("GOOGLE_CREDENTIALS"))),
Expand Down
Empty file added src/repositories/__init__.py
Empty file.
Empty file added src/services/__init__.py
Empty file.
148 changes: 148 additions & 0 deletions src/services/uploadService.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import os
import re
from os.path import join

from enum import Enum
from typing import List

from discord import Attachment
from PIL import Image
from synology_api import filestation

from src.plugins import sheet, filestation


class UploadType(Enum):
ZZAL = 1 # 짤 업로드, 시트 번호 1
TIME = 2 # ~~시 업로드, 시트 번호 2
DICT = 3 # 백과사전 이미지 업로드, 시트 번호 3


class UploadService:
def __init__(self):
self.google_util = sheet.SheetPlugin()
self.nasStation = filestation.FileStationPlugin().getFileStation()

async def upload(self, type: UploadType, message: str, files: List[Attachment]) -> tuple[int, List[str]]:
worksheet = self.google_util.get_worksheet_by_index(
key="1hfW3FTo9cjuMW9Kxvfnrbc6p_HyEnyYeA38mKM7nrOE", index=type
)

worksheet_data = worksheet.get_all_records(empty2zero=True, head=2 if type == UploadType.DICT else 1)
resv_zzal_names = [x.get("이름") for x in worksheet_data]

uploaded = 0
errors = []

for file in files:
filename = file.filename

if not (
filename.endswith(".webp")
or filename.endswith(".gif")
or filename.endswith(".jpg")
or filename.endswith(".jpeg")
or filename.endswith(".png")
):
_error_msg = f"`{filename}` 파일은 지원하지 않는 형식입니다."

if len(files) == 1:
raise Exception(_error_msg)
else:
errors.append(_error_msg)
continue

zzal_name = (
message.content.split("time: ")[1] if type == UploadType.TIME else message.content.split("name: ")[1]
)

member_dict_name = (
(
worksheet_data[row]
.get("인물")
.replace(" ", "_")
.replace(":", "_")
.replace("?", "_")
.replace("!", "_")
.replace(".", "_")
.replace(",", "_")
.replace("'", "_")
.replace('"', "_")
)
if type == UploadType.TIME
else None
)

if not zzal_name in resv_zzal_names:
_error_msg = f"`{zzal_name}` 시트에 등록되지 않은 짤 이름입니다. 등록 후 다시 시도해 주세요."

if len(files) == 1:
raise Exception(_error_msg)
else:
errors.append(_error_msg)
continue

zzal_dict_name = (
zzal_name.replace(" ", "_")
.replace(":", "_")
.replace("?", "_")
.replace("!", "_")
.replace(".", "_")
.replace(",", "_")
.replace("'", "_")
.replace('"', "_")
)

row = resv_zzal_names.index(zzal_name)

await file.save(join("temp/", f"{message.author.id}_{filename}"))

if filename.endswith(".jpg") or filename.endswith(".png"):
converted_image = Image.open(join("temp/", f"{message.author.id}_{filename}"))
converted_image.save(
join("temp/", f"{message.author.id}_{re.sub(r'\.(jpg|png)$', '.webp', filename)}"), "webp"
)
converted_image.close()

upload_dest_path = (
f"/files/zzals/{zzal_dict_name}"
if type == UploadType.ZZAL
else (
f"/files/plagueTimes/{member_dict_name}/{zzal_dict_name}"
if type == UploadType.TIME
else f"/files/dictionary/{zzal_dict_name}"
)
)

uploadRes = self.nasStation.upload_file(
dest_path=upload_dest_path,
file_path=join("temp/", f"{message.author.id}_{re.sub(r'\.(jpg|png)$', '.webp', filename)}"),
overwrite=True,
)

if uploadRes == "Upload Complete":
uploaded += 1
else:
_error_msg = f"업로드 중 문제가 발생했습니다.\n\n{uploadRes}"

if len(files) == 1:
raise Exception(_error_msg)
else:
errors.append(_error_msg)
continue

os.remove(join("temp/", f"{message.author.id}_{filename}"))

if filename.endswith(".jpg") or filename.endswith(".jpeg") or filename.endswith(".png"):
os.remove(join("temp/", f"{message.author.id}_{re.sub(r'\.(jpg|jpeg|png)$', '.webp', filename)}"))

if uploaded > 0:
if uploaded == 1:
return (1, [])

if len(errors) >= 1:
return (uploaded, chr(10).join(errors))
else:
return (uploaded, [])
else:
raise Exception(f"업로드 중 문제가 발생했습니다.")

0 comments on commit f7cff29

Please sign in to comment.