cfjyd1list / sync_data.sh
cfjy888's picture
Update sync_data.sh
7443979 verified
#!/bin/bash
set -eo pipefail
# 检查环境变量
required_vars=("WEBDAV_URL" "WEBDAV_USERNAME" "WEBDAV_PASSWORD")
for var in "${required_vars[@]}"; do
if [ -z "${!var}" ]; then
echo "警告: 缺少必要环境变量 $var,将禁用备份功能"
exec ./alist server --data /app/config
exit 0
fi
done
# 设置完整WebDAV路径
FULL_WEBDAV_URL="${WEBDAV_URL}${WEBDAV_BACKUP_PATH:+/$WEBDAV_BACKUP_PATH}"
# 恢复备份函数
restore_backup() {
echo "尝试从WebDAV恢复最新备份..."
python3 <<EOF
import os
import sys
import tarfile
import requests
from webdav3.client import Client
from tenacity import retry, stop_after_attempt, wait_fixed
# 配置WebDAV客户端
options = {
'webdav_hostname': '$FULL_WEBDAV_URL',
'webdav_login': '$WEBDAV_USERNAME',
'webdav_password': '$WEBDAV_PASSWORD'
}
@retry(stop=stop_after_attempt(3), wait=wait_fixed(5))
def download_latest_backup():
client = Client(options)
try:
backups = [f for f in client.list() if f.endswith('.tar.gz') and f.startswith('alist_backup_')]
if not backups:
print("未找到备份文件")
return False
latest = sorted(backups)[-1]
print(f"找到最新备份: {latest}")
# 下载备份
temp_file = f"/tmp/{latest}"
client.download_sync(remote_path=latest, local_path=temp_file)
# 解压备份
if os.path.exists("$DATA_DIR"):
import shutil
shutil.rmtree("$DATA_DIR")
os.makedirs("$DATA_DIR", exist_ok=True)
with tarfile.open(temp_file, "r:gz") as tar:
tar.extractall("$DATA_DIR")
os.remove(temp_file)
print("备份恢复成功")
return True
except Exception as e:
print(f"备份恢复失败: {str(e)}")
raise
download_latest_backup()
EOF
}
# 首次启动恢复备份
restore_backup || echo "使用空数据目录启动"
# 启动AList和Aria2
./alist server --data /app/config &
aria2c --enable-rpc --rpc-listen-all --rpc-allow-origin-all --rpc-listen-port=6800 --daemon
# 同步函数
sync_data() {
while true; do
echo "$(date) 开始同步数据..."
# 创建备份
backup_file="/tmp/alist_backup_$(date +%Y%m%d_%H%M%S).tar.gz"
tar -czf "$backup_file" -C "$DATA_DIR" .
# 上传备份
python3 <<EOF
import os
from webdav3.client import Client
from tenacity import retry, stop_after_attempt, wait_fixed
options = {
'webdav_hostname': '$FULL_WEBDAV_URL',
'webdav_login': '$WEBDAV_USERNAME',
'webdav_password': '$WEBDAV_PASSWORD'
}
@retry(stop=stop_after_attempt(3), wait=wait_fixed(10))
def upload_and_clean():
client = Client(options)
try:
# 上传新备份
client.upload_sync(local_path='$backup_file', remote_path='${backup_file##*/}')
print("备份上传成功")
# 清理旧备份(保留最近5个)
backups = [f for f in client.list() if f.endswith('.tar.gz') and f.startswith('alist_backup_')]
if len(backups) > 5:
for old_backup in sorted(backups)[:-5]:
client.clean(old_backup)
print(f"已删除旧备份: {old_backup}")
except Exception as e:
print(f"备份操作失败: {str(e)}")
raise
upload_and_clean()
EOF
rm -f "$backup_file"
echo "下次同步将在 $SYNC_INTERVAL 秒后..."
sleep "$SYNC_INTERVAL"
done
}
# 启动同步进程
sync_data