mai2: rework photo uploads, relates to #67

This commit is contained in:
2024-10-06 03:47:10 -04:00
parent ed5e7dc561
commit 0cef797a8a
6 changed files with 272 additions and 42 deletions

View File

@ -2,7 +2,7 @@ from datetime import datetime, timedelta
from typing import Any, Dict, List
import logging
from base64 import b64decode
from os import path, stat, remove
from os import path, stat, remove, mkdir, access, W_OK
from PIL import ImageFile
from random import randint
@ -866,46 +866,33 @@ class Mai2Base:
self.logger.warning(f"Incorrect data size after decoding (Expected 10240, got {len(photo_chunk)})")
return {'returnCode': 0, 'apiName': 'UploadUserPhotoApi'}
out_name = f"{self.game_config.uploads.photos_dir}/{user_id}_{playlog_id}_{track_num}"
photo_data = await self.data.profile.get_user_photo_by_user_playlog_track(user_id, playlog_id, track_num)
if not photo_data:
photo_id = await self.data.profile.put_user_photo(user_id, playlog_id, track_num)
else:
photo_id = photo_data['id']
if not path.exists(f"{out_name}.bin") and div_num != 0:
self.logger.warning(f"Out of order photo upload (div_num {div_num})")
return {'returnCode': 0, 'apiName': 'UploadUserPhotoApi'}
if path.exists(f"{out_name}.bin") and div_num == 0:
self.logger.warning(f"Duplicate file upload")
out_folder = f"{self.game_config.uploads.photos_dir}/{photo_id}"
out_file = f"{out_folder}/{div_num}_{div_len - 1}.bin"
if not path.exists(out_folder):
mkdir(out_folder)
if not access(out_folder, W_OK):
self.logger.error(f"Cannot access {out_folder}")
return {'returnCode': 0, 'apiName': 'UploadUserPhotoApi'}
elif path.exists(f"{out_name}.bin"):
fstats = stat(f"{out_name}.bin")
if fstats.st_size != 10240 * div_num:
self.logger.warning(f"Out of order photo upload (trying to upload div {div_num}, expected div {fstats.st_size / 10240} for file sized {fstats.st_size} bytes)")
if path.exists(out_file):
self.logger.warning(f"Photo chunk {out_file} already exists, skipping")
else:
with open(out_file, "wb") as f:
written = f.write(photo_chunk)
if written != len(photo_chunk):
self.logger.error(f"Writing {out_file} failed! Wrote {written} bytes, expected {photo_chunk} bytes")
return {'returnCode': 0, 'apiName': 'UploadUserPhotoApi'}
try:
with open(f"{out_name}.bin", "ab") as f:
f.write(photo_chunk)
except Exception:
self.logger.error(f"Failed writing to {out_name}.bin")
return {'returnCode': 0, 'apiName': 'UploadUserPhotoApi'}
if div_num + 1 == div_len and path.exists(f"{out_name}.bin"):
try:
p = ImageFile.Parser()
with open(f"{out_name}.bin", "rb") as f:
p.feed(f.read())
im = p.close()
im.save(f"{out_name}.jpeg")
except Exception:
self.logger.error(f"File {out_name}.bin failed image validation")
try:
remove(f"{out_name}.bin")
except Exception:
self.logger.error(f"Failed to delete {out_name}.bin, please remove it manually")
return {'returnCode': ret_code, 'apiName': 'UploadUserPhotoApi'}