初版:上传接口(从线上实例导出,适配容器端口)
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""utils package"""
|
||||
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
过期时间计算
|
||||
"""
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
def get_expiry_info(created_at_str, expires_at_str=None):
|
||||
"""获取过期信息"""
|
||||
if not created_at_str:
|
||||
return None
|
||||
|
||||
try:
|
||||
created_at = datetime.fromisoformat(
|
||||
created_at_str.replace('Z', '+00:00'))
|
||||
|
||||
# 没有设置过期时间 -> 永不过期
|
||||
if not expires_at_str:
|
||||
return {
|
||||
'created_at': created_at.isoformat(),
|
||||
'expires_at': None,
|
||||
'remaining_days': None,
|
||||
'remaining_hours': None,
|
||||
'remaining_minutes': None,
|
||||
'is_expired': False,
|
||||
'never_expires': True
|
||||
}
|
||||
|
||||
expires_at = datetime.fromisoformat(
|
||||
expires_at_str.replace('Z', '+00:00'))
|
||||
remaining = expires_at - datetime.now()
|
||||
|
||||
days = remaining.days
|
||||
hours, remainder = divmod(remaining.seconds, 3600)
|
||||
minutes, _ = divmod(remainder, 60)
|
||||
|
||||
return {
|
||||
'created_at': created_at.isoformat(),
|
||||
'expires_at': expires_at.isoformat(),
|
||||
'remaining_days': days,
|
||||
'remaining_hours': hours,
|
||||
'remaining_minutes': minutes,
|
||||
'is_expired': remaining.total_seconds() <= 0,
|
||||
'never_expires': False
|
||||
}
|
||||
except:
|
||||
return None
|
||||
@@ -0,0 +1,73 @@
|
||||
"""
|
||||
工具函数:密码哈希、ID 生成、智能列名识别
|
||||
"""
|
||||
import hashlib
|
||||
import uuid
|
||||
import random
|
||||
import string
|
||||
from difflib import SequenceMatcher
|
||||
from config import FIELD_KEYWORDS
|
||||
|
||||
|
||||
def get_client_ip():
|
||||
"""获取真实客户端 IP。
|
||||
nginx 反代场景下 request.remote_addr 是代理地址(如 127.0.0.1),
|
||||
优先取代理注入的 X-Real-IP,其次 X-Forwarded-For 的首个地址,最后回退 remote_addr。"""
|
||||
from flask import request
|
||||
real_ip = (request.headers.get('X-Real-IP') or '').strip()
|
||||
if real_ip:
|
||||
return real_ip
|
||||
forwarded = (request.headers.get('X-Forwarded-For') or '').strip()
|
||||
if forwarded:
|
||||
# 多级代理时为逗号分隔链,首个为客户端原始 IP
|
||||
return forwarded.split(',')[0].strip()
|
||||
return request.remote_addr or ''
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
"""密码哈希"""
|
||||
return hashlib.sha256(password.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def generate_session_id():
|
||||
"""生成会话ID"""
|
||||
return uuid.uuid4().hex
|
||||
|
||||
|
||||
def generate_form_id():
|
||||
"""生成随机表单ID"""
|
||||
return ''.join(random.choices(string.ascii_letters + string.digits, k=8))
|
||||
|
||||
|
||||
def generate_preset_id():
|
||||
"""生成预设ID"""
|
||||
return 'preset_' + ''.join(random.choices(string.ascii_lowercase + string.digits, k=8))
|
||||
|
||||
|
||||
def smart_field_detection(columns):
|
||||
"""智能识别列名对应关系"""
|
||||
result = {}
|
||||
columns_lower = [str(col).lower().strip() for col in columns]
|
||||
|
||||
for field_type, keywords in FIELD_KEYWORDS.items():
|
||||
best_match = None
|
||||
best_ratio = 0
|
||||
|
||||
for i, col in enumerate(columns_lower):
|
||||
for keyword in keywords:
|
||||
if keyword.lower() == col:
|
||||
best_match = columns[i]
|
||||
best_ratio = 1.0
|
||||
break
|
||||
if keyword.lower() in col or col in keyword.lower():
|
||||
ratio = SequenceMatcher(None, keyword.lower(), col).ratio()
|
||||
if ratio > best_ratio and ratio > 0.6:
|
||||
best_ratio = ratio
|
||||
best_match = columns[i]
|
||||
if best_ratio == 1.0:
|
||||
break
|
||||
|
||||
if best_match:
|
||||
result[field_type] = best_match
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,90 @@
|
||||
"""
|
||||
图标自动生成
|
||||
"""
|
||||
import os
|
||||
from config import BASE_DIR, IMG_DIR, PIL_AVAILABLE
|
||||
|
||||
|
||||
def generate_favicons():
|
||||
"""根据 favicon.png 自动生成各种尺寸的图标文件"""
|
||||
if not PIL_AVAILABLE:
|
||||
print("⚠️ PIL未安装,跳过图标生成")
|
||||
return
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
source_path = os.path.join(IMG_DIR, 'favicon.png')
|
||||
|
||||
if not os.path.exists(source_path):
|
||||
print("⚠️ 未找到 favicon.png,跳过图标生成")
|
||||
print(" 如需自定义图标,请放置 favicon.png 到 static/img/ 目录")
|
||||
return
|
||||
|
||||
try:
|
||||
img = Image.open(source_path)
|
||||
if img.mode != 'RGBA':
|
||||
img = img.convert('RGBA')
|
||||
|
||||
icon_specs = [
|
||||
('favicon-16x16.png', 16, 16),
|
||||
('favicon-32x32.png', 32, 32),
|
||||
('apple-touch-icon.png', 180, 180),
|
||||
('android-chrome-192x192.png', 192, 192),
|
||||
('android-chrome-512x512.png', 512, 512),
|
||||
]
|
||||
|
||||
generated = []
|
||||
|
||||
for filename, width, height in icon_specs:
|
||||
output_path = os.path.join(IMG_DIR, filename)
|
||||
if os.path.exists(output_path):
|
||||
continue
|
||||
|
||||
resized = img.resize((width, height), Image.Resampling.LANCZOS)
|
||||
|
||||
if 'apple-touch-icon' in filename:
|
||||
mask = Image.new('L', (width, height), 0)
|
||||
draw = ImageDraw.Draw(mask)
|
||||
radius = width // 5
|
||||
draw.rounded_rectangle([0, 0, width, height], radius=radius, fill=255)
|
||||
|
||||
output = Image.new('RGBA', (width, height), (255, 255, 255, 0))
|
||||
output.paste(resized, (0, 0))
|
||||
output.putalpha(mask)
|
||||
resized = output
|
||||
|
||||
resized.save(output_path, 'PNG', optimize=True)
|
||||
generated.append(filename)
|
||||
|
||||
ico_path = os.path.join(IMG_DIR, 'favicon.ico')
|
||||
if not os.path.exists(ico_path):
|
||||
sizes = [(16, 16), (32, 32), (48, 48), (64, 64)]
|
||||
ico_images = []
|
||||
|
||||
for size in sizes:
|
||||
resized = img.resize(size, Image.Resampling.LANCZOS)
|
||||
if resized.mode == 'RGBA':
|
||||
background = Image.new('RGB', size, (255, 255, 255))
|
||||
background.paste(resized, mask=resized.split()[3])
|
||||
resized = background
|
||||
elif resized.mode != 'RGB':
|
||||
resized = resized.convert('RGB')
|
||||
ico_images.append(resized)
|
||||
|
||||
ico_images[0].save(
|
||||
ico_path,
|
||||
format='ICO',
|
||||
sizes=sizes,
|
||||
append_images=ico_images[1:]
|
||||
)
|
||||
generated.append('favicon.ico')
|
||||
|
||||
if generated:
|
||||
print(f"✅ 已生成图标文件: {', '.join(generated)}")
|
||||
else:
|
||||
print("✅ 所有图标文件已存在,跳过生成")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 图标生成失败: {str(e)}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Per-form switch for the existing hardcoded submission notification."""
|
||||
import requests
|
||||
|
||||
|
||||
def normalize_webhook(value=None):
|
||||
if value is None:
|
||||
return {'enabled': False}
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError('Webhook 配置必须是对象')
|
||||
enabled = value.get('enabled', False)
|
||||
if not isinstance(enabled, bool):
|
||||
raise ValueError('Webhook enabled 必须为布尔值')
|
||||
return {'enabled': enabled}
|
||||
|
||||
|
||||
def send_form_webhook(form, who, *, is_overwrite=False, uploaded_files=None):
|
||||
from config import NOTIFY_WEBHOOK
|
||||
if not NOTIFY_WEBHOOK:
|
||||
return False
|
||||
try:
|
||||
webhook = normalize_webhook(form.get('webhook'))
|
||||
except ValueError:
|
||||
return False
|
||||
if not webhook['enabled']:
|
||||
return False
|
||||
action = '覆盖' if is_overwrite else '提交'
|
||||
message = (f"{who}{action}成功,表单标题:{form.get('title', '未命名表单')},"
|
||||
f"表单id:{form.get('id', '')}")
|
||||
try:
|
||||
# Preserve the original built-in URL, GET request and per-file notifications.
|
||||
for filename in uploaded_files or [None]:
|
||||
content = f'{message},文件:{filename}' if filename is not None else message
|
||||
response = requests.get(f"https://api.chuckfang.com/c415ce0b/ 表单提交通知/{content}", timeout=3)
|
||||
response.raise_for_status()
|
||||
return True
|
||||
except requests.RequestException:
|
||||
# Keep failures separate from the already-saved submission.
|
||||
print(f"Webhook 通知失败,表单 {form.get('id', '')} 的提交已保存")
|
||||
return False
|
||||
Reference in New Issue
Block a user