a
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
# 相册查看器
|
||||
|
||||
手机端友好的相册浏览 Web 应用。
|
||||
|
||||
## 功能特性
|
||||
|
||||
- 📱 手机浏览器优化,响应式布局
|
||||
- 🖼️ 三列网格展示,留白均匀
|
||||
- 📂 支持多级相册嵌套
|
||||
- 🔄 懒加载优化,流畅浏览
|
||||
- 🔍 点击查看原图
|
||||
- ⚡ 缩略图加速加载
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
album-viewer/
|
||||
├── backend/
|
||||
│ └── app.py # Flask 后端服务
|
||||
├── frontend/
|
||||
│ └── index.html # 前端页面
|
||||
├── tools/
|
||||
│ └── generate_thumbnails.py # 缩略图生成工具
|
||||
└── start.sh # 启动脚本
|
||||
```
|
||||
|
||||
## 安装依赖
|
||||
|
||||
```bash
|
||||
# 安装 Python 依赖
|
||||
pip3 install flask flask-cors
|
||||
|
||||
# 确保已安装 ImageMagick(用于生成缩略图)
|
||||
which convert
|
||||
```
|
||||
|
||||
## 使用方法
|
||||
|
||||
### 1. 生成缩略图(首次使用必需)
|
||||
|
||||
```bash
|
||||
cd ~/nanocode/album-viewer
|
||||
python3 tools/generate_thumbnails.py
|
||||
```
|
||||
|
||||
**工具特性:**
|
||||
- ✅ **递归处理**:自动扫描所有子目录
|
||||
- ✅ **重复安全**:已存在的缩略图自动跳过
|
||||
- ✅ **智能更新**:原图修改后自动重新生成
|
||||
- ✅ **自动清理**:删除原图后自动清理对应缩略图
|
||||
|
||||
缩略图会生成在每个相册的 `thumbnails/` 子目录下。
|
||||
|
||||
### 2. 启动服务
|
||||
|
||||
```bash
|
||||
./start.sh
|
||||
```
|
||||
|
||||
或手动启动:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python3 app.py
|
||||
```
|
||||
|
||||
### 3. 访问
|
||||
|
||||
- PC: http://localhost:8892
|
||||
- 手机: http://<服务器IP>:8892
|
||||
|
||||
## 相册目录结构
|
||||
|
||||
```
|
||||
/home/ubuntu/albums/
|
||||
├── 相册1/
|
||||
│ ├── image1.jpg
|
||||
│ ├── image2.jpg
|
||||
│ └── thumbnails/ # 自动生成的缩略图
|
||||
│ ├── image1.jpg
|
||||
│ └── image2.jpg
|
||||
├── 相册2/
|
||||
│ └── ...
|
||||
└── 子相册/
|
||||
└── ...
|
||||
```
|
||||
|
||||
## 技术规格
|
||||
|
||||
| 项目 | 规格 |
|
||||
|------|------|
|
||||
| 缩略图宽度 | 320px(等比缩放)|
|
||||
| 网格布局 | 3列,间距 12px |
|
||||
| 缩略图比例 | 2:3(高度=宽度×1.5)|
|
||||
| 图片质量 | 85% |
|
||||
| 服务端口 | 8892 |
|
||||
|
||||
## 更新相册
|
||||
|
||||
添加新图片后,重新生成缩略图:
|
||||
|
||||
```bash
|
||||
python3 tools/generate_thumbnails.py
|
||||
```
|
||||
|
||||
工具会自动跳过已存在的缩略图。
|
||||
@@ -0,0 +1,231 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
相册查看器后端(带登录保护)—— 双模式认证(本地 Session + SSO Cookie)
|
||||
"""
|
||||
from flask import Flask, jsonify, send_from_directory, request, make_response
|
||||
from flask_cors import CORS
|
||||
from flask_login import LoginManager, login_required, current_user
|
||||
from pathlib import Path
|
||||
from datetime import timedelta
|
||||
import os
|
||||
import sys
|
||||
|
||||
# 添加当前目录到路径
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from models import db, User, init_default_users
|
||||
from auth import auth_bp, api_login_required
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config['SECRET_KEY'] = 'album-viewer-secret-key-change-in-production'
|
||||
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///album_auth.db'
|
||||
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
||||
|
||||
# Session cookie 配置(支持跨域)
|
||||
app.config['SESSION_COOKIE_HTTPONLY'] = True
|
||||
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax' # HTTP环境用Lax
|
||||
app.config['SESSION_COOKIE_SECURE'] = False # HTTP环境
|
||||
app.config['SESSION_COOKIE_DOMAIN'] = None
|
||||
|
||||
# 初始化扩展
|
||||
db.init_app(app)
|
||||
# CORS 精确白名单(不能用 *,因为需要 credentials)
|
||||
CORS(app, supports_credentials=True, origins=[
|
||||
"http://129.211.173.87:8892",
|
||||
"http://129.211.173.87:9000",
|
||||
"http://localhost:8892",
|
||||
])
|
||||
|
||||
# Flask-Login
|
||||
login_manager = LoginManager()
|
||||
login_manager.init_app(app)
|
||||
|
||||
@login_manager.user_loader
|
||||
def load_user(user_id):
|
||||
return User.query.get(int(user_id))
|
||||
|
||||
# 注册蓝图
|
||||
app.register_blueprint(auth_bp)
|
||||
|
||||
# 配置
|
||||
ALBUMS_ROOT = Path('/home/ubuntu/albums')
|
||||
THUMB_WIDTH = 320
|
||||
IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'}
|
||||
|
||||
# SSO Cookie 配置(与 SSO 中心一致,用于清除 Cookie)
|
||||
SSO_COOKIE_DOMAIN = "129.211.173.87"
|
||||
|
||||
|
||||
def is_image(filename):
|
||||
"""检查是否为图片文件"""
|
||||
return Path(filename).suffix.lower() in IMAGE_EXTENSIONS
|
||||
|
||||
|
||||
def get_directory_contents(path):
|
||||
"""获取目录内容(相册和图片)"""
|
||||
items = {'albums': [], 'images': []}
|
||||
|
||||
if not path.exists():
|
||||
return items
|
||||
|
||||
for item in sorted(path.iterdir(), key=lambda x: x.name.lower()):
|
||||
if item.is_dir() and item.name != 'thumbnails':
|
||||
has_content = False
|
||||
for child in item.iterdir():
|
||||
if child.is_file() and is_image(child.name):
|
||||
has_content = True
|
||||
break
|
||||
if child.is_dir() and child.name != 'thumbnails':
|
||||
has_content = True
|
||||
break
|
||||
|
||||
cover = None
|
||||
thumb_dir = item / 'thumbnails'
|
||||
if thumb_dir.exists():
|
||||
for thumb in sorted(thumb_dir.iterdir()):
|
||||
if is_image(thumb.name):
|
||||
cover = f"/thumbs/{item.relative_to(ALBUMS_ROOT)}/thumbnails/{thumb.name}"
|
||||
break
|
||||
|
||||
items['albums'].append({
|
||||
'name': item.name,
|
||||
'path': str(item.relative_to(ALBUMS_ROOT)),
|
||||
'cover': cover,
|
||||
'type': 'album'
|
||||
})
|
||||
|
||||
elif item.is_file() and is_image(item.name):
|
||||
rel_path = item.relative_to(ALBUMS_ROOT)
|
||||
thumb_path = item.parent / 'thumbnails' / item.name
|
||||
has_thumbnail = thumb_path.exists()
|
||||
|
||||
items['images'].append({
|
||||
'name': item.name,
|
||||
'path': str(rel_path),
|
||||
'thumbnail': f"/thumbs/{rel_path.parent}/thumbnails/{item.name}" if has_thumbnail else None,
|
||||
'size': item.stat().st_size,
|
||||
'type': 'image'
|
||||
})
|
||||
|
||||
return items
|
||||
|
||||
|
||||
# ========== 受保护路由(需要登录)==========
|
||||
|
||||
@app.route('/api/albums', strict_slashes=False)
|
||||
@api_login_required
|
||||
def list_albums():
|
||||
"""列出相册 - 需要登录"""
|
||||
contents = get_directory_contents(ALBUMS_ROOT)
|
||||
return jsonify({
|
||||
'path': '',
|
||||
'name': '相册首页',
|
||||
'albums': contents['albums'],
|
||||
'images': contents['images']
|
||||
})
|
||||
|
||||
|
||||
@app.route('/api/albums/<path:album_path>', strict_slashes=False)
|
||||
@api_login_required
|
||||
def get_album(album_path):
|
||||
"""获取相册内容 - 需要登录"""
|
||||
album_full_path = ALBUMS_ROOT / album_path
|
||||
|
||||
try:
|
||||
album_full_path.relative_to(ALBUMS_ROOT)
|
||||
except ValueError:
|
||||
return jsonify({'error': 'Invalid path'}), 403
|
||||
|
||||
if not album_full_path.exists():
|
||||
return jsonify({'error': 'Album not found'}), 404
|
||||
|
||||
contents = get_directory_contents(album_full_path)
|
||||
|
||||
return jsonify({
|
||||
'path': album_path,
|
||||
'name': album_full_path.name,
|
||||
'albums': contents['albums'],
|
||||
'images': contents['images']
|
||||
})
|
||||
|
||||
|
||||
@app.route('/api/image/<path:image_path>')
|
||||
@api_login_required
|
||||
def get_image(image_path):
|
||||
"""获取原图 - 需要登录 ⭐ 关键保护 """
|
||||
full_path = ALBUMS_ROOT / image_path
|
||||
|
||||
try:
|
||||
full_path.relative_to(ALBUMS_ROOT)
|
||||
except ValueError:
|
||||
return jsonify({'error': 'Invalid path'}), 403
|
||||
|
||||
if not full_path.exists() or not is_image(full_path.name):
|
||||
return jsonify({'error': 'Image not found'}), 404
|
||||
|
||||
return send_from_directory(full_path.parent, full_path.name)
|
||||
|
||||
|
||||
@app.route('/thumbs/<path:thumb_path>')
|
||||
@api_login_required
|
||||
def serve_thumbnail(thumb_path):
|
||||
"""服务缩略图 - 需要登录 ⭐ 关键保护 """
|
||||
full_path = ALBUMS_ROOT / thumb_path
|
||||
|
||||
try:
|
||||
full_path.relative_to(ALBUMS_ROOT)
|
||||
except ValueError:
|
||||
return jsonify({'error': 'Invalid path'}), 403
|
||||
|
||||
if not full_path.exists():
|
||||
return jsonify({'error': 'Thumbnail not found'}), 404
|
||||
|
||||
return send_from_directory(full_path.parent, full_path.name)
|
||||
|
||||
|
||||
# ========== SSO 退出路由 ==========
|
||||
|
||||
@app.route('/api/auth/sso-logout', methods=['POST'])
|
||||
def sso_logout():
|
||||
"""退出登录 —— 同时清除本地 Session 和 SSO Cookie"""
|
||||
from flask_login import logout_user
|
||||
if current_user.is_authenticated:
|
||||
logout_user()
|
||||
# 清除 SSO Cookie
|
||||
resp = make_response(jsonify({'success': True, 'message': '已登出'}))
|
||||
resp.delete_cookie('access_token', domain=SSO_COOKIE_DOMAIN, path='/')
|
||||
return resp
|
||||
|
||||
|
||||
# ========== 前端路由 ==========
|
||||
|
||||
@app.route('/')
|
||||
def index():
|
||||
"""首页 - 公开,但前端会检查登录状态"""
|
||||
return send_from_directory('../frontend', 'index.html')
|
||||
|
||||
|
||||
@app.route('/<path:path>')
|
||||
def static_files(path):
|
||||
"""静态文件 - 公开(CSS/JS/HTML)"""
|
||||
# 排除 API 路径
|
||||
if path.startswith('api/'):
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
return send_from_directory('../frontend', path)
|
||||
|
||||
|
||||
# ========== 初始化 ==========
|
||||
|
||||
with app.app_context():
|
||||
db.create_all()
|
||||
init_default_users()
|
||||
print("✅ 数据库初始化完成")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("🖼️ 相册查看器(带登录保护)启动...")
|
||||
print(f" 相册根目录: {ALBUMS_ROOT}")
|
||||
print(f" 默认账号: admin / abcd1234")
|
||||
print(f" 访问: http://localhost:8892")
|
||||
|
||||
app.run(host='0.0.0.0', port=8892, debug=False)
|
||||
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
认证相关路由和装饰器 —— 双模式认证(本地 Session + SSO Cookie)
|
||||
"""
|
||||
from functools import wraps
|
||||
from datetime import timedelta
|
||||
from flask import Blueprint, request, jsonify, session
|
||||
from flask_login import login_user, logout_user, login_required, current_user
|
||||
from models import User, db
|
||||
from sso_client import get_user_from_sso_cookie
|
||||
|
||||
auth_bp = Blueprint('auth', __name__)
|
||||
|
||||
|
||||
def api_login_required(f):
|
||||
"""API 登录检查装饰器 - 双模式认证
|
||||
1. 优先检查本地 Flask-Login Session
|
||||
2. 无 Session 则检查 SSO Cookie,本地验签后查本地 User 表
|
||||
"""
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
# 模式一:本地 Session
|
||||
if current_user.is_authenticated:
|
||||
return f(*args, **kwargs)
|
||||
|
||||
# 模式二:SSO Cookie
|
||||
sso_user = get_user_from_sso_cookie(request)
|
||||
if sso_user:
|
||||
username = sso_user.get("username")
|
||||
user = User.query.filter_by(username=username).first()
|
||||
if user:
|
||||
# 自动登录到本地 Session,后续请求走模式一
|
||||
login_user(user, remember=True, duration=timedelta(days=30))
|
||||
return f(*args, **kwargs)
|
||||
|
||||
return jsonify({
|
||||
'error': 'Unauthorized',
|
||||
'message': '请先登录',
|
||||
'code': 401
|
||||
}), 401
|
||||
return decorated_function
|
||||
|
||||
|
||||
@auth_bp.route('/api/auth/login', methods=['POST'])
|
||||
def login():
|
||||
"""用户登录 API"""
|
||||
data = request.get_json()
|
||||
|
||||
if not data:
|
||||
return jsonify({'error': '请求数据为空'}), 400
|
||||
|
||||
username = data.get('username', '').strip()
|
||||
password = data.get('password', '').strip()
|
||||
|
||||
if not username or not password:
|
||||
return jsonify({'error': '用户名和密码不能为空'}), 400
|
||||
|
||||
user = User.query.filter_by(username=username).first()
|
||||
|
||||
if not user or not user.check_password(password):
|
||||
return jsonify({'error': '用户名或密码错误'}), 401
|
||||
|
||||
# 登录用户(记住我 30 天)
|
||||
login_user(user, remember=True, duration=timedelta(days=30))
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'message': '登录成功',
|
||||
'user': user.to_dict()
|
||||
})
|
||||
|
||||
|
||||
@auth_bp.route('/api/auth/logout', methods=['POST'])
|
||||
def logout():
|
||||
"""用户登出 API —— 不要求登录态,确保未登录也能退出"""
|
||||
if current_user.is_authenticated:
|
||||
logout_user()
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'message': '已登出'
|
||||
})
|
||||
|
||||
|
||||
@auth_bp.route('/api/auth/status')
|
||||
def auth_status():
|
||||
"""检查登录状态 API —— 双模式"""
|
||||
# 模式一:本地 Session
|
||||
if current_user.is_authenticated:
|
||||
return jsonify({
|
||||
'authenticated': True,
|
||||
'user': current_user.to_dict()
|
||||
})
|
||||
|
||||
# 模式二:SSO Cookie
|
||||
sso_user = get_user_from_sso_cookie(request)
|
||||
if sso_user:
|
||||
username = sso_user.get("username")
|
||||
user = User.query.filter_by(username=username).first()
|
||||
if user:
|
||||
return jsonify({
|
||||
'authenticated': True,
|
||||
'user': user.to_dict()
|
||||
})
|
||||
|
||||
return jsonify({
|
||||
'authenticated': False,
|
||||
'user': None
|
||||
})
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
数据库模型 - 用户管理
|
||||
"""
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
from flask_login import UserMixin
|
||||
|
||||
db = SQLAlchemy()
|
||||
|
||||
class User(UserMixin, db.Model):
|
||||
"""用户模型"""
|
||||
__tablename__ = 'users'
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
username = db.Column(db.String(80), unique=True, nullable=False)
|
||||
password_hash = db.Column(db.String(200), nullable=False)
|
||||
created_at = db.Column(db.DateTime, default=db.func.current_timestamp())
|
||||
|
||||
def set_password(self, password):
|
||||
self.password_hash = generate_password_hash(password)
|
||||
|
||||
def check_password(self, password):
|
||||
return check_password_hash(self.password_hash, password)
|
||||
|
||||
def to_dict(self):
|
||||
return {
|
||||
'id': self.id,
|
||||
'username': self.username,
|
||||
'created_at': self.created_at.isoformat() if self.created_at else None
|
||||
}
|
||||
|
||||
|
||||
def init_default_users():
|
||||
"""初始化默认用户(如果不存在)"""
|
||||
default_users = [
|
||||
{'username': 'admin', 'password': 'abcd1234'},
|
||||
{'username': 'caixianming', 'password': 'cxm123456'}
|
||||
]
|
||||
|
||||
for user_data in default_users:
|
||||
# 检查用户是否已存在
|
||||
existing = User.query.filter_by(username=user_data['username']).first()
|
||||
if not existing:
|
||||
user = User(username=user_data['username'])
|
||||
user.set_password(user_data['password'])
|
||||
db.session.add(user)
|
||||
print(f"✅ 创建默认用户: {user_data['username']}")
|
||||
|
||||
db.session.commit()
|
||||
@@ -0,0 +1,5 @@
|
||||
Flask>=2.0.0
|
||||
Flask-SQLAlchemy>=3.0.0
|
||||
Flask-Login>=0.6.0
|
||||
Flask-CORS>=4.0.0
|
||||
Werkzeug>=2.0.0
|
||||
@@ -0,0 +1,21 @@
|
||||
"""SSO Cookie 本地验签 —— 与 SSO 中心共享 SECRET_KEY(Flask 版)"""
|
||||
from jose import jwt, JWTError
|
||||
|
||||
# 必须与 SSO 中心 sso_config.py 完全一致
|
||||
SECRET_KEY = "your-secret-key-change-in-production"
|
||||
ALGORITHM = "HS256"
|
||||
|
||||
|
||||
def get_user_from_sso_cookie(request):
|
||||
"""从请求 Cookie 中读取 access_token,本地验签后返回用户信息"""
|
||||
token = request.cookies.get("access_token")
|
||||
if not token:
|
||||
return None
|
||||
try:
|
||||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||
username = payload.get("sub")
|
||||
if not username:
|
||||
return None
|
||||
return {"username": username}
|
||||
except JWTError:
|
||||
return None
|
||||
@@ -0,0 +1,797 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
||||
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
|
||||
<meta http-equiv="Pragma" content="no-cache">
|
||||
<meta http-equiv="Expires" content="0">
|
||||
<title>相册查看器</title>
|
||||
<style>
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
background: #f5f5f5;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
/* ========== 登录弹窗 ========== */
|
||||
.login-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0,0,0,0.8);
|
||||
z-index: 10000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
backdrop-filter: blur(5px);
|
||||
}
|
||||
|
||||
.login-overlay.hidden {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.login-box {
|
||||
background: white;
|
||||
padding: 30px;
|
||||
border-radius: 16px;
|
||||
width: 90%;
|
||||
max-width: 360px;
|
||||
box-shadow: 0 20px 60px rgba(0,0,0,0.3);
|
||||
}
|
||||
|
||||
.login-title {
|
||||
text-align: center;
|
||||
font-size: 22px;
|
||||
font-weight: 600;
|
||||
margin-bottom: 8px;
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.login-subtitle {
|
||||
text-align: center;
|
||||
font-size: 14px;
|
||||
color: #999;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.login-input {
|
||||
width: 100%;
|
||||
padding: 14px 16px;
|
||||
margin-bottom: 12px;
|
||||
border: 1px solid #e0e0e0;
|
||||
border-radius: 10px;
|
||||
font-size: 16px;
|
||||
transition: border-color 0.2s;
|
||||
-webkit-appearance: none;
|
||||
}
|
||||
|
||||
.login-input:focus {
|
||||
outline: none;
|
||||
border-color: #007aff;
|
||||
}
|
||||
|
||||
.login-btn {
|
||||
width: 100%;
|
||||
padding: 14px;
|
||||
background: #007aff;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.login-btn:hover {
|
||||
background: #0056cc;
|
||||
}
|
||||
|
||||
.login-btn:disabled {
|
||||
background: #ccc;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.sso-login-btn {
|
||||
width: 100%;
|
||||
padding: 12px;
|
||||
margin-top: 12px;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
font-size: 15px;
|
||||
cursor: pointer;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.sso-login-btn:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.login-divider {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin: 12px 0;
|
||||
color: #aaa;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.login-divider::before,
|
||||
.login-divider::after {
|
||||
content: '';
|
||||
flex: 1;
|
||||
border-bottom: 1px solid #ddd;
|
||||
}
|
||||
|
||||
.login-divider::before { margin-right: 8px; }
|
||||
.login-divider::after { margin-left: 8px; }
|
||||
|
||||
.login-error {
|
||||
color: #ff3b30;
|
||||
font-size: 14px;
|
||||
margin-top: 12px;
|
||||
text-align: center;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.login-error.show {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* ========== 顶部导航 ========== */
|
||||
.header {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
height: 50px;
|
||||
background: #fff;
|
||||
border-bottom: 1px solid #e0e0e0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0 16px;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
.back-btn {
|
||||
display: none;
|
||||
padding: 8px 12px;
|
||||
background: #007aff;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.back-btn.visible {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.title {
|
||||
flex: 1;
|
||||
text-align: center;
|
||||
font-size: 17px;
|
||||
font-weight: 600;
|
||||
color: #333;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
padding: 0 10px;
|
||||
}
|
||||
|
||||
.user-info {
|
||||
display: none;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 13px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.user-info.visible {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.logout-btn {
|
||||
padding: 4px 10px;
|
||||
background: #ff3b30;
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* ========== 主内容区 ========== */
|
||||
.content {
|
||||
padding: 66px 12px 20px;
|
||||
}
|
||||
|
||||
/* 网格布局:每行3个 */
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
/* 缩略图项 */
|
||||
.item {
|
||||
position: relative;
|
||||
aspect-ratio: 2/3;
|
||||
background: #e0e0e0;
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
cursor: pointer;
|
||||
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
.item img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
transition: opacity 0.3s;
|
||||
}
|
||||
|
||||
.item img.lazy {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.item img.loaded {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* 文件名标签 */
|
||||
.item-filename {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
padding: 6px 8px;
|
||||
background: linear-gradient(to bottom, rgba(0,0,0,0.6), transparent);
|
||||
color: white;
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
z-index: 2;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* 相册图标 */
|
||||
.album-icon {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
}
|
||||
|
||||
.album-icon svg {
|
||||
width: 50%;
|
||||
height: 50%;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
/* 相册封面 */
|
||||
.album-cover {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
/* 相册名称 */
|
||||
.item-name {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
padding: 20px 8px 8px;
|
||||
background: linear-gradient(transparent, rgba(0,0,0,0.7));
|
||||
color: white;
|
||||
font-size: 12px;
|
||||
text-align: center;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* ========== 图片查看器 ========== */
|
||||
.lightbox {
|
||||
display: none;
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(0,0,0,0.95);
|
||||
z-index: 1000;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.lightbox.active {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.lightbox img {
|
||||
max-width: 100%;
|
||||
max-height: 100%;
|
||||
object-fit: contain;
|
||||
transition: transform 0.2s ease, opacity 0.2s ease;
|
||||
user-select: none;
|
||||
-webkit-user-drag: none;
|
||||
}
|
||||
|
||||
.lightbox-close {
|
||||
position: absolute;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
background: rgba(255,255,255,0.2);
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
color: white;
|
||||
font-size: 24px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
/* ========== 加载/空状态 ========== */
|
||||
.loading {
|
||||
text-align: center;
|
||||
padding: 40px;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.empty {
|
||||
text-align: center;
|
||||
padding: 60px 20px;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.empty-icon {
|
||||
font-size: 64px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.login-required {
|
||||
text-align: center;
|
||||
padding: 60px 20px;
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.login-required-icon {
|
||||
font-size: 64px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<!-- 登录弹窗 -->
|
||||
<div class="login-overlay" id="loginOverlay">
|
||||
<div class="login-box">
|
||||
<div class="login-title">🔒 相册查看器</div>
|
||||
<div class="login-subtitle">请先登录后继续</div>
|
||||
<input type="text" class="login-input" id="username" placeholder="用户名" autocomplete="username">
|
||||
<input type="password" class="login-input" id="password" placeholder="密码" autocomplete="current-password">
|
||||
<button class="login-btn" id="loginBtn" onclick="doLogin()">登录</button>
|
||||
<div class="login-divider">或</div>
|
||||
<button class="sso-login-btn" onclick="doSSOLogin()">🔐 SSO 统一登录</button>
|
||||
<div class="login-error" id="loginError"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 顶部导航 -->
|
||||
<div class="header">
|
||||
<button class="back-btn" onclick="goBack()">← 返回</button>
|
||||
<div class="title">相册首页</div>
|
||||
<div class="user-info" id="userInfo">
|
||||
<span id="usernameDisplay"></span>
|
||||
<button class="logout-btn" onclick="doLogout()">退出</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 内容区 -->
|
||||
<div class="content">
|
||||
<div class="grid" id="grid">
|
||||
<div class="loading">加载中...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 图片查看器 -->
|
||||
<div class="lightbox" id="lightbox" onclick="closeLightbox()">
|
||||
<button class="lightbox-close" onclick="event.stopPropagation(); closeLightbox()">×</button>
|
||||
<img id="lightbox-img" src="" alt="" onclick="event.stopPropagation()">
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// ========== 状态 ==========
|
||||
let isAuthenticated = false;
|
||||
let pathStack = [''];
|
||||
let currentImages = [];
|
||||
let currentImageIndex = -1;
|
||||
let touchStartX = 0;
|
||||
let touchStartY = 0;
|
||||
let touchEndX = 0;
|
||||
let isSwiping = false;
|
||||
|
||||
// ========== 初始化 ==========
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
// 检查登录状态
|
||||
await checkAuth();
|
||||
|
||||
if (isAuthenticated) {
|
||||
loadAlbum('');
|
||||
setupSwipeNavigation();
|
||||
}
|
||||
|
||||
// 回车键登录
|
||||
document.getElementById('password').addEventListener('keypress', (e) => {
|
||||
if (e.key === 'Enter') doLogin();
|
||||
});
|
||||
});
|
||||
|
||||
// ========== 认证相关 ==========
|
||||
async function checkAuth() {
|
||||
try {
|
||||
const response = await fetch('/api/auth/status', {
|
||||
credentials: 'include', // 携带 cookie
|
||||
cache: 'no-cache' // 禁用缓存
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
isAuthenticated = data.authenticated;
|
||||
|
||||
if (isAuthenticated) {
|
||||
showMainUI(data.user);
|
||||
} else {
|
||||
showLoginUI();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('检查登录状态失败:', error);
|
||||
showLoginUI();
|
||||
}
|
||||
}
|
||||
|
||||
async function doLogin() {
|
||||
const username = document.getElementById('username').value.trim();
|
||||
const password = document.getElementById('password').value.trim();
|
||||
const btn = document.getElementById('loginBtn');
|
||||
const errorDiv = document.getElementById('loginError');
|
||||
|
||||
if (!username || !password) {
|
||||
errorDiv.textContent = '请输入用户名和密码';
|
||||
errorDiv.classList.add('show');
|
||||
return;
|
||||
}
|
||||
|
||||
btn.disabled = true;
|
||||
btn.textContent = '登录中...';
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ username, password })
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
isAuthenticated = true;
|
||||
showMainUI(data.user);
|
||||
loadAlbum('');
|
||||
setupSwipeNavigation();
|
||||
} else {
|
||||
errorDiv.textContent = data.error || '登录失败';
|
||||
errorDiv.classList.add('show');
|
||||
}
|
||||
} catch (error) {
|
||||
errorDiv.textContent = '网络错误: ' + error.message;
|
||||
errorDiv.classList.add('show');
|
||||
console.error('登录错误:', error);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.textContent = '登录';
|
||||
}
|
||||
}
|
||||
|
||||
async function doLogout() {
|
||||
try {
|
||||
// 调后端同时清除本地 Session 和 SSO Cookie
|
||||
await fetch('/api/auth/sso-logout', {
|
||||
method: 'POST',
|
||||
credentials: 'include'
|
||||
});
|
||||
} catch (e) {}
|
||||
|
||||
isAuthenticated = false;
|
||||
location.reload();
|
||||
}
|
||||
|
||||
function doSSOLogin() {
|
||||
// 跳转到 SSO 中心,携带 redirect 参数
|
||||
const redirect = window.location.origin;
|
||||
window.location.href = 'http://129.211.173.87:9000/?redirect=' + encodeURIComponent(redirect + '/');
|
||||
}
|
||||
|
||||
function showLoginUI() {
|
||||
document.getElementById('loginOverlay').classList.remove('hidden');
|
||||
document.getElementById('userInfo').classList.remove('visible');
|
||||
document.getElementById('grid').innerHTML = `
|
||||
<div class="login-required" style="grid-column: span 3;">
|
||||
<div class="login-required-icon">🔒</div>
|
||||
<div>请先登录查看相册</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function showMainUI(user) {
|
||||
document.getElementById('loginOverlay').classList.add('hidden');
|
||||
document.getElementById('userInfo').classList.add('visible');
|
||||
document.getElementById('usernameDisplay').textContent = user.username;
|
||||
// 清空输入
|
||||
document.getElementById('username').value = '';
|
||||
document.getElementById('password').value = '';
|
||||
document.getElementById('loginError').classList.remove('show');
|
||||
}
|
||||
|
||||
// ========== API 请求封装(自动处理认证)==========
|
||||
async function authFetch(url, options = {}) {
|
||||
options.credentials = 'include'; // 携带 cookie
|
||||
|
||||
const response = await fetch(url, options);
|
||||
|
||||
// 401 未授权,显示登录
|
||||
if (response.status === 401) {
|
||||
isAuthenticated = false;
|
||||
showLoginUI();
|
||||
throw new Error('未登录');
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
// ========== 相册功能(保持原有逻辑)==========
|
||||
async function loadAlbum(path) {
|
||||
if (!isAuthenticated) return;
|
||||
|
||||
const grid = document.getElementById('grid');
|
||||
grid.innerHTML = '<div class="loading">加载中...</div>';
|
||||
|
||||
try {
|
||||
const response = await authFetch(`/api/albums/${path}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (data.error) {
|
||||
grid.innerHTML = `<div class="empty">加载失败: ${data.error}</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
document.querySelector('.title').textContent = data.name || '相册';
|
||||
|
||||
const backBtn = document.querySelector('.back-btn');
|
||||
if (pathStack.length > 1) {
|
||||
backBtn.classList.add('visible');
|
||||
} else {
|
||||
backBtn.classList.remove('visible');
|
||||
}
|
||||
|
||||
renderGrid(data);
|
||||
|
||||
} catch (error) {
|
||||
if (error.message !== '未登录') {
|
||||
grid.innerHTML = `<div class="empty">加载失败,请刷新重试</div>`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function renderGrid(data) {
|
||||
const grid = document.getElementById('grid');
|
||||
grid.innerHTML = '';
|
||||
|
||||
const items = [...data.albums, ...data.images];
|
||||
currentImages = data.images || [];
|
||||
|
||||
if (items.length === 0) {
|
||||
grid.innerHTML = `
|
||||
<div class="empty" style="grid-column: span 3;">
|
||||
<div class="empty-icon">🖼️</div>
|
||||
<div>暂无内容</div>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
items.forEach(item => {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'item';
|
||||
|
||||
if (item.type === 'album') {
|
||||
const coverHtml = item.cover
|
||||
? `<img class="album-cover lazy" data-src="${item.cover}" alt="${item.name}">`
|
||||
: `<div class="album-icon">
|
||||
<svg viewBox="0 0 24 24" fill="white">
|
||||
<path d="M20 6h-8l-2-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V8h16v10z"/>
|
||||
<circle cx="12" cy="13" r="3"/>
|
||||
</svg>
|
||||
</div>`;
|
||||
|
||||
div.innerHTML = `
|
||||
${coverHtml}
|
||||
<div class="item-name">${item.name}</div>
|
||||
`;
|
||||
div.onclick = () => openAlbum(item.path);
|
||||
|
||||
} else {
|
||||
const thumbUrl = item.thumbnail || `/api/image/${item.path}`;
|
||||
const imageIndex = data.images.indexOf(item);
|
||||
div.innerHTML = `
|
||||
<div class="item-filename">${item.name}</div>
|
||||
<img class="lazy" data-src="${thumbUrl}" alt="${item.name}" onclick="showImage(${imageIndex})">
|
||||
`;
|
||||
}
|
||||
|
||||
grid.appendChild(div);
|
||||
});
|
||||
|
||||
setupLazyLoad();
|
||||
}
|
||||
|
||||
function openAlbum(path) {
|
||||
pathStack.push(path);
|
||||
loadAlbum(path);
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
if (pathStack.length > 1) {
|
||||
pathStack.pop();
|
||||
loadAlbum(pathStack[pathStack.length - 1]);
|
||||
}
|
||||
}
|
||||
|
||||
function showImage(index) {
|
||||
event.stopPropagation();
|
||||
if (index < 0 || index >= currentImages.length) return;
|
||||
|
||||
currentImageIndex = index;
|
||||
const image = currentImages[index];
|
||||
|
||||
const lightbox = document.getElementById('lightbox');
|
||||
const img = document.getElementById('lightbox-img');
|
||||
img.src = `/api/image/${image.path}`;
|
||||
lightbox.classList.add('active');
|
||||
document.body.style.overflow = 'hidden';
|
||||
}
|
||||
|
||||
function navigateImage(direction) {
|
||||
const newIndex = currentImageIndex + direction;
|
||||
|
||||
if (newIndex < 0 || newIndex >= currentImages.length) {
|
||||
const img = document.getElementById('lightbox-img');
|
||||
img.style.transform = direction > 0 ? 'translateX(-20px)' : 'translateX(20px)';
|
||||
setTimeout(() => {
|
||||
img.style.transform = 'translateX(0)';
|
||||
}, 150);
|
||||
return;
|
||||
}
|
||||
|
||||
currentImageIndex = newIndex;
|
||||
const image = currentImages[currentImageIndex];
|
||||
const img = document.getElementById('lightbox-img');
|
||||
|
||||
img.style.opacity = '0.5';
|
||||
img.style.transform = direction > 0 ? 'translateX(-50px)' : 'translateX(50px)';
|
||||
|
||||
setTimeout(() => {
|
||||
img.src = `/api/image/${image.path}`;
|
||||
img.style.transition = 'none';
|
||||
img.style.transform = direction > 0 ? 'translateX(50px)' : 'translateX(-50px)';
|
||||
|
||||
setTimeout(() => {
|
||||
img.style.transition = 'all 0.2s ease';
|
||||
img.style.opacity = '1';
|
||||
img.style.transform = 'translateX(0)';
|
||||
}, 50);
|
||||
}, 150);
|
||||
}
|
||||
|
||||
function closeLightbox() {
|
||||
const lightbox = document.getElementById('lightbox');
|
||||
lightbox.classList.remove('active');
|
||||
document.body.style.overflow = '';
|
||||
}
|
||||
|
||||
function setupSwipeNavigation() {
|
||||
const lightbox = document.getElementById('lightbox');
|
||||
|
||||
lightbox.addEventListener('touchstart', (e) => {
|
||||
touchStartX = e.touches[0].clientX;
|
||||
touchStartY = e.touches[0].clientY;
|
||||
isSwiping = false;
|
||||
}, { passive: true });
|
||||
|
||||
lightbox.addEventListener('touchmove', (e) => {
|
||||
if (!lightbox.classList.contains('active')) return;
|
||||
|
||||
touchEndX = e.touches[0].clientX;
|
||||
const diffX = touchStartX - touchEndX;
|
||||
const diffY = Math.abs(e.touches[0].clientY - touchStartY);
|
||||
|
||||
if (Math.abs(diffX) > diffY && Math.abs(diffX) > 10) {
|
||||
isSwiping = true;
|
||||
}
|
||||
}, { passive: true });
|
||||
|
||||
lightbox.addEventListener('touchend', (e) => {
|
||||
if (!lightbox.classList.contains('active') || !isSwiping) return;
|
||||
|
||||
const diffX = touchStartX - touchEndX;
|
||||
const threshold = 50;
|
||||
|
||||
if (Math.abs(diffX) > threshold) {
|
||||
if (diffX > 0) {
|
||||
navigateImage(1);
|
||||
} else {
|
||||
navigateImage(-1);
|
||||
}
|
||||
}
|
||||
|
||||
isSwiping = false;
|
||||
}, { passive: true });
|
||||
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (!lightbox.classList.contains('active')) return;
|
||||
|
||||
if (e.key === 'ArrowLeft') navigateImage(-1);
|
||||
else if (e.key === 'ArrowRight') navigateImage(1);
|
||||
else if (e.key === 'Escape') closeLightbox();
|
||||
});
|
||||
}
|
||||
|
||||
function setupLazyLoad() {
|
||||
const images = document.querySelectorAll('img.lazy');
|
||||
|
||||
const imageObserver = new IntersectionObserver((entries, observer) => {
|
||||
entries.forEach(entry => {
|
||||
if (entry.isIntersecting) {
|
||||
const img = entry.target;
|
||||
img.src = img.dataset.src;
|
||||
img.onload = () => img.classList.add('loaded');
|
||||
img.classList.remove('lazy');
|
||||
observer.unobserve(img);
|
||||
}
|
||||
});
|
||||
}, {
|
||||
rootMargin: '50px 0px',
|
||||
threshold: 0.01
|
||||
});
|
||||
|
||||
images.forEach(img => imageObserver.observe(img));
|
||||
}
|
||||
|
||||
window.onpopstate = function(event) {
|
||||
if (pathStack.length > 1) {
|
||||
pathStack.pop();
|
||||
loadAlbum(pathStack[pathStack.length - 1]);
|
||||
}
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/bin/bash
|
||||
# 相册查看器启动脚本
|
||||
|
||||
echo "🖼️ 相册查看器"
|
||||
echo "=================="
|
||||
|
||||
# 检查相册目录
|
||||
if [ ! -d "/home/ubuntu/albums" ]; then
|
||||
echo "❌ 相册目录不存在: /home/ubuntu/albums"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "📁 相册根目录: /home/ubuntu/albums"
|
||||
|
||||
# 检查缩略图
|
||||
echo ""
|
||||
echo "🔍 检查缩略图..."
|
||||
ALBUM_COUNT=$(find /home/ubuntu/albums -type d -not -path "*/thumbnails" | wc -l)
|
||||
THUMB_COUNT=$(find /home/ubuntu/albums -type d -name "thumbnails" | wc -l)
|
||||
|
||||
echo " 相册数量: $ALBUM_COUNT"
|
||||
echo " 有缩略图的相册: $THUMB_COUNT"
|
||||
|
||||
if [ "$THUMB_COUNT" -lt "$ALBUM_COUNT" ]; then
|
||||
echo ""
|
||||
echo "⚠️ 部分相册缺少缩略图"
|
||||
echo " 建议先运行: python3 tools/generate_thumbnails.py"
|
||||
echo ""
|
||||
read -p "是否先生成缩略图? [y/N]: " choice
|
||||
if [ "$choice" = "y" ] || [ "$choice" = "Y" ]; then
|
||||
python3 tools/generate_thumbnails.py
|
||||
fi
|
||||
fi
|
||||
|
||||
# 启动服务
|
||||
echo ""
|
||||
echo "🚀 启动服务..."
|
||||
cd backend
|
||||
python3 app.py
|
||||
@@ -0,0 +1,175 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
相册缩略图生成工具
|
||||
为当前目录及所有子目录下的图片生成缩略图
|
||||
缩略图存放在每个相册的 thumbnails/ 子目录下
|
||||
|
||||
特性:
|
||||
- 可在任意目录执行(不限定 /home/ubuntu/albums)
|
||||
- 递归处理当前目录下所有子目录(不限子目录名称)
|
||||
- 已存在的缩略图自动跳过
|
||||
- 只处理 jpg/jpeg/png 图片,跳过视频等其他文件
|
||||
|
||||
使用方法:
|
||||
cd 任意目录
|
||||
python3 generate_thumbnails.py
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import time
|
||||
|
||||
# 配置
|
||||
THUMB_WIDTH = 320
|
||||
THUMB_QUALITY = 85
|
||||
|
||||
# 支持的图片格式(只处理图片,跳过视频等其他文件)
|
||||
IMAGE_EXTENSIONS = {'.jpg', '.jpeg', '.png'}
|
||||
|
||||
# 统计信息
|
||||
stats = {
|
||||
'albums': 0,
|
||||
'images_found': 0,
|
||||
'generated': 0,
|
||||
'skipped': 0,
|
||||
'failed': 0
|
||||
}
|
||||
|
||||
|
||||
def is_image(filename):
|
||||
"""检查是否为图片文件"""
|
||||
return Path(filename).suffix.lower() in IMAGE_EXTENSIONS
|
||||
|
||||
|
||||
def generate_thumbnail(img_path, thumb_path):
|
||||
"""生成单个缩略图"""
|
||||
try:
|
||||
# 确保缩略图目录存在
|
||||
thumb_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
cmd = [
|
||||
'convert', str(img_path),
|
||||
'-resize', f'{THUMB_WIDTH}x>',
|
||||
'-quality', str(THUMB_QUALITY),
|
||||
str(thumb_path)
|
||||
]
|
||||
subprocess.run(cmd, check=True, capture_output=True, timeout=30)
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f" ❌ 失败: {img_path.name}")
|
||||
return False
|
||||
|
||||
|
||||
def process_directory(dir_path, depth=0):
|
||||
"""
|
||||
递归处理目录
|
||||
为当前目录下的每张图片生成缩略图(如果尚未存在)
|
||||
"""
|
||||
global stats
|
||||
|
||||
if not dir_path.is_dir():
|
||||
return False
|
||||
|
||||
# 跳过 thumbnails 目录
|
||||
if dir_path.name == 'thumbnails':
|
||||
return False
|
||||
|
||||
indent = " " * depth
|
||||
|
||||
# 收集当前目录的图片
|
||||
images = []
|
||||
subdirs = []
|
||||
|
||||
for item in dir_path.iterdir():
|
||||
if item.is_dir() and item.name != 'thumbnails':
|
||||
subdirs.append(item)
|
||||
elif item.is_file() and is_image(item.name):
|
||||
images.append(item)
|
||||
|
||||
# 处理当前目录的图片
|
||||
if images:
|
||||
stats['albums'] += 1
|
||||
print(f"\n{indent}📁 {dir_path.name}")
|
||||
print(f"{indent} 发现 {len(images)} 张图片")
|
||||
|
||||
# 确保 thumbnails 目录存在
|
||||
thumb_dir = dir_path / 'thumbnails'
|
||||
thumb_dir.mkdir(exist_ok=True)
|
||||
|
||||
for img in images:
|
||||
stats['images_found'] += 1
|
||||
|
||||
# 检查缩略图是否已存在
|
||||
thumb_path = thumb_dir / img.name
|
||||
|
||||
if thumb_path.exists():
|
||||
# 缩略图已存在,跳过
|
||||
stats['skipped'] += 1
|
||||
continue
|
||||
|
||||
# 生成缩略图
|
||||
if generate_thumbnail(img, thumb_path):
|
||||
stats['generated'] += 1
|
||||
print(f"{indent} ✓ {img.name}")
|
||||
else:
|
||||
stats['failed'] += 1
|
||||
|
||||
# 递归处理子目录(所有子目录,不限名称)
|
||||
for subdir in subdirs:
|
||||
process_directory(subdir, depth + 1)
|
||||
|
||||
return len(images) > 0 or len(subdirs) > 0
|
||||
|
||||
|
||||
def print_stats(start_time):
|
||||
"""打印统计信息"""
|
||||
elapsed = time.time() - start_time
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("✅ 缩略图生成完成!")
|
||||
print("=" * 60)
|
||||
print(f" 处理相册: {stats['albums']} 个")
|
||||
print(f" 图片总数: {stats['images_found']} 张")
|
||||
print(f" 新生成: {stats['generated']} 张")
|
||||
print(f" 跳过(已存在): {stats['skipped']} 张")
|
||||
print(f" 失败: {stats['failed']} 张")
|
||||
print(f" 耗时: {elapsed:.1f}秒")
|
||||
print("=" * 60)
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
# 获取当前目录(执行时所在的目录,不是工具所在目录)
|
||||
current_dir = Path.cwd()
|
||||
|
||||
print("=" * 60)
|
||||
print("🖼️ 相册缩略图生成工具")
|
||||
print(f" 目标目录: {current_dir}")
|
||||
print(f" 缩略图宽度: {THUMB_WIDTH}px")
|
||||
print("=" * 60)
|
||||
|
||||
# 检查 ImageMagick
|
||||
try:
|
||||
subprocess.run(['convert', '--version'], capture_output=True, check=True)
|
||||
except:
|
||||
print("❌ 未安装 ImageMagick,请先安装: sudo apt install imagemagick")
|
||||
return
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
# 递归处理
|
||||
print("\n🔍 扫描相册...")
|
||||
process_directory(current_dir)
|
||||
|
||||
# 打印统计
|
||||
print_stats(start_time)
|
||||
|
||||
# 提示
|
||||
print("\n💡 提示:")
|
||||
print(" - 可在任意目录执行此工具")
|
||||
print(" - 已存在的缩略图会自动跳过")
|
||||
print(" - 新增的图片会被自动处理")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user