#!/usr/bin/env python3
import os, tempfile, re
from flask import Flask, request, jsonify
import boto3
from botocore.client import Config
import pillow_heif
from PIL import Image
pillow_heif.register_heif_opener()
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024
S3_CONFIG = dict(
endpoint_url='https://s3.regru.cloud',
aws_access_key_id='TXBN3MRO1YCC2Y593URD',
aws_secret_access_key='GIMA9lJetvXgMtl8GCO4dNSpJDGHvKgGBVfiA9zV',
region_name='ru-1',
config=Config(signature_version='s3v4')
)
BUCKET = 'sleeptrip-dev'
MIME = {
'jpg':'image/jpeg','jpeg':'image/jpeg','png':'image/png',
'gif':'image/gif','webp':'image/webp','mp4':'video/mp4','mov':'video/quicktime',
'heic':'image/jpeg','heif':'image/jpeg'
}
ALLOWED = set(MIME.keys())
PAGE = r"""
PTP Post Wizard
PTP Post Wizard
Загрузка фото → готовый пост для Sveltia CMS
2. Фотографии
Фото автоматически называются slug-YYYYMMDD-N.jpg и загружаются в S3. Первое фото = обложка.
3. Готовый контент — копируй в Sveltia
Поля формы
Markdown контент
Все URL фото
"""
@app.route('/upload/')
def index():
return PAGE
@app.route('/upload/api', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return jsonify({'error': 'Нет файла'}), 400
f = request.files['file']
custom_filename = request.form.get('filename', '').strip()
if not f.filename:
return jsonify({'error': 'Пустое имя файла'}), 400
ext = f.filename.rsplit('.', 1)[-1].lower() if '.' in f.filename else ''
if ext not in ALLOWED:
return jsonify({'error': 'Формат .{} не поддерживается'.format(ext)}), 400
# Use custom filename from wizard if provided
if custom_filename:
out_name = custom_filename
out_ext = out_name.rsplit('.', 1)[-1].lower()
else:
original = os.path.splitext(f.filename)[0]
out_ext = 'jpg' if ext in ('heic', 'heif') else ext
out_name = '{}.{}'.format(original, out_ext)
s3_key = 'images/{}'.format(out_name)
tmp_path = None
try:
with tempfile.NamedTemporaryFile(delete=False, suffix='.{}'.format(ext)) as tmp:
f.save(tmp.name)
tmp_path = tmp.name
# HEIC → JPG conversion
if ext in ('heic', 'heif'):
img = Image.open(tmp_path)
converted = tmp_path.rsplit('.', 1)[0] + '.jpg'
img.convert('RGB').save(converted, 'JPEG', quality=92)
os.unlink(tmp_path)
tmp_path = converted
import urllib3
urllib3.disable_warnings()
s3 = boto3.client('s3', verify=False, **S3_CONFIG)
s3.upload_file(
tmp_path, BUCKET, s3_key,
ExtraArgs={
'ContentType': MIME.get(out_ext, 'application/octet-stream'),
'CacheControl': 'max-age=31536000'
}
)
url = 'https://s3.regru.cloud/{}/{}'.format(BUCKET, s3_key)
return jsonify({'url': url, 'filename': out_name})
except Exception as e:
return jsonify({'error': str(e)}), 500
finally:
if tmp_path and os.path.exists(tmp_path):
os.unlink(tmp_path)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=9001, debug=False)