Compare commits

...

8 Commits

Author SHA1 Message Date
becomer a41341e732 fix: 修复历史任务经纬度/地址获取到的是教师边界坐标而非用户历史提交数据的问题
ci/woodpecker/tag/build Pipeline was successful
ci/woodpecker/push/build Pipeline was successful
- sign.go: 移除 signInstanceWid 比较限制,当已签到任务与当前任务是同一实例时,
  直接复用已有详情数据作为历史数据,确保 ParseFormJson 能从 signPlaceSelected 提取用户真实坐标
- sleepcheck.go: 移除 if !isFromSigned 守卫条件,无论当前任务是否已签到都尝试获取历史数据
2026-07-02 00:36:42 +08:00
becomer ecfa50359b fix: add X-Api-Key header for captcha OCR requests
ci/woodpecker/push/build Pipeline was canceled
ci/woodpecker/tag/build Pipeline was successful
The captcha OCR service now requires X-Api-Key authentication.
Add captcha.apiKey config option and pass it as header in all
OCR-related API calls (ocr, semiOcr, calc).
2026-07-01 20:22:03 +08:00
becomer 2879336ce4 feat: make PostgreSQL connection optional
ci/woodpecker/push/build Pipeline was successful
Remove hard requirement on PG database (likedream-pg container).
PG is now only initialized when dsn2 is configured; skip gracefully when empty.
Add nil-safety checks on GlobalGorm references in balance migration logic.
Remove dsn2 from default config.
2026-07-01 14:08:36 +08:00
becomer f706968618 fix: force-remove temp container in cleanup step
ci/woodpecker/push/build Pipeline was successful
ci/woodpecker/tag/build Pipeline was successful
2026-07-01 12:49:10 +08:00
becomer 69e198f745 fix: use wget instead of curl for health check
ci/woodpecker/push/build Pipeline was successful
The 'docker' CLI image does not include curl binary,
causing the health check to always fail. Switch to wget.
2026-07-01 12:47:05 +08:00
becomer 70f907d909 fix: replace shell ${VAR} with $VAR to avoid Woodpecker pre-processing
ci/woodpecker/push/build Pipeline failed
Woodpecker interprets ${...} as its own template syntax and strips
unrecognized variables. Using $VAR (no braces) passes through to bash.
2026-07-01 12:43:56 +08:00
becomer 3a3d17e9b4 feat: blue-green zero-downtime deploy via 1Panel
ci/woodpecker/push/build Pipeline failed
- Set up 1Panel website tianshen.eu.cc (HTTP 80, ready for HTTPS)
- /api/* → likedream-go with prefix stripping
- /* → likedream-web (Caddy, port 3080)
- Blue-green deployment: start on standby port → switch proxy → stop old → switch back
- Nginx reload is hot (zero connection drops)
- Detects current active port from proxy config automatically
2026-07-01 12:40:01 +08:00
becomer d560c9f678 fix: override clone remote to local Gitea URL
ci/woodpecker/push/build Pipeline is running
ci/woodpecker/tag/build Pipeline was successful
Add clone.git.settings.remote in .woodpecker/build.yml to use
fast local clone (http://10.10.10.128:3000) instead of external
Cloudflare-proxied URL (https://git.xsvb.cn) for tag builds.
2026-07-01 01:09:16 +08:00
8 changed files with 215 additions and 101 deletions
+99 -7
View File
@@ -4,6 +4,12 @@ when:
- event: tag
branch: [v*]
clone:
git:
image: woodpeckerci/plugin-git
settings:
remote: http://10.10.10.128:3000/becomer/likedream.git
steps:
build-image:
image: docker
@@ -16,23 +22,109 @@ steps:
deploy:
image: docker
commands: |
# ============================================================
# 蓝绿部署:零宕机切换 likedream-go 容器
# 判断当前代理使用的端口,另一个作为备用
# ============================================================
set -e
IMAGE_TAG="$CI_COMMIT_TAG"
if [ -z "$IMAGE_TAG" ]; then IMAGE_TAG="latest"; fi
# 确保网络存在
docker network create likedream-net 2>/dev/null || true
# 停止并删除旧容器
# 读取 1Panel 当前代理端口
CURRENT_PORT=$(docker exec 1Panel-openresty-ESmn \
grep -o 'proxy_pass http://10.10.10.128:[0-9]\+' \
/www/sites/tianshen/proxy/api.conf | grep -o '[0-9]\+$')
echo "=== 当前 1Panel 反代端口: $CURRENT_PORT ==="
if [ "$CURRENT_PORT" = "8091" ]; then
PORT_ACTIVE=8091
PORT_STANDBY=8092
elif [ "$CURRENT_PORT" = "8092" ]; then
PORT_ACTIVE=8092
PORT_STANDBY=8091
else
echo "未知当前端口 $CURRENT_PORT,默认使用 8091/8092"
PORT_ACTIVE=8091
PORT_STANDBY=8092
fi
echo " 活跃: $PORT_ACTIVE | 备用: $PORT_STANDBY"
# 清理之前可能残留的临时容器
docker rm -f likedream-go-new 2>/dev/null || true
echo "=== 蓝绿部署: 启动新容器 on :$PORT_STANDBY (image: $IMAGE_TAG) ==="
docker run -d --name likedream-go-new \
--restart unless-stopped \
--network likedream-net \
-p $PORT_STANDBY:8091 \
-v /opt/likedream-go/config.toml:/app/config.toml:ro \
likedream-go:$IMAGE_TAG
# 健康检查:等待新容器就绪
HEALTHY=false
for i in $(seq 1 15); do
if wget -q --timeout=3 -O /dev/null http://10.10.10.128:$PORT_STANDBY/health 2>/dev/null; then
HEALTHY=true
break
fi
echo " 等待新容器就绪... ($i/15)"
sleep 2
done
if [ "$HEALTHY" = false ]; then
echo "ERROR: 新容器未通过健康检查,回滚"
docker stop likedream-go-new
docker rm likedream-go-new
exit 1
fi
echo " 新容器已就绪 ✓"
# 切换 1Panel 代理到备用端口
echo "=== 切换 1Panel 反代 :$PORT_ACTIVE → :$PORT_STANDBY ==="
docker exec 1Panel-openresty-ESmn \
sed -i "s|:$PORT_ACTIVE|:$PORT_STANDBY|g" \
/www/sites/tianshen/proxy/api.conf
docker exec 1Panel-openresty-ESmn nginx -s reload
echo " Nginx 热加载完成(零中断)✓"
# 停止旧容器
echo "=== 清理旧容器 ==="
docker stop likedream-go 2>/dev/null || true
docker rm likedream-go 2>/dev/null || true
# 启动新容器
docker run -d \
--name likedream-go \
# 在活跃端口启动正式容器
echo "=== 启动正式容器 on :$PORT_ACTIVE ==="
docker run -d --name likedream-go \
--restart unless-stopped \
--network likedream-net \
-p 8091:8091 \
-p $PORT_ACTIVE:8091 \
-v /opt/likedream-go/config.toml:/app/config.toml:ro \
likedream-go:latest
likedream-go:$IMAGE_TAG
# 连接到 captcha 服务所在网络
# 连接到验证码服务网络
docker network connect ocr-go_default likedream-go 2>/dev/null || true
# 切回 1Panel 代理到活跃端口
echo "=== 切回 1Panel 反代 :$PORT_STANDBY → :$PORT_ACTIVE ==="
docker exec 1Panel-openresty-ESmn \
sed -i "s|:$PORT_STANDBY|:$PORT_ACTIVE|g" \
/www/sites/tianshen/proxy/api.conf
docker exec 1Panel-openresty-ESmn nginx -s reload
echo " Nginx 热加载完成(零中断)✓"
# 清理临时容器和旧镜像
echo "=== 清理 ==="
docker rm -f likedream-go-new 2>/dev/null || true
# 保留 latest 和最近 3 个 tag 镜像
docker images likedream-go --format '{{.Tag}}' | grep -v latest | head -n -3 | while read tag; do
docker rmi likedream-go:$tag 2>/dev/null || true
done
echo "=== 部署完成 ✓ ==="
volumes:
- /var/run/docker.sock:/var/run/docker.sock
+6 -4
View File
@@ -20,8 +20,9 @@ key = "sk-acacac439b346036df45e90c85c177c375568ef72c469e49"
[database]
type = "mysql"
dsn = "test_likedream_go:EpXckXmxawDEQGxJ@tcp(database.out:3306)/test_likedream_go?parseTime=true&loc=Asia%2FShanghai"
dsn2 = "host=database.out user=dev password=JPmKjmpcaG3EYAJZ dbname=dev port=5432 sslmode=disable TimeZone=Asia/Shanghai"
# host=localhost user=gorm password=gorm dbname=gorm port=9920 sslmode=disable TimeZone=Asia/Shanghai
dsn2 = "host=pg.out user=dev password=JPmKjmpcaG3EYAJZ dbname=dev port=5432 sslmode=disable TimeZone=Asia/Shanghai"
#type = "postgres"
#dsn = "host=pg.out user=dev password=JPmKjmpcaG3EYAJZ dbname=dev port=5432 sslmode=disable TimeZone=Asia/Shanghai"
[server]
port = 8091
url = "https://devocr.likedream.xyz"
@@ -35,8 +36,9 @@ balanceMigrateUrl = "http://localhost:3200/balance-migrate/"
mode = "dev"
[captcha]
baseUrl = "http://captcha-resolver.out"
#baseUrl = "http://localhost:8890"
#baseUrl = "http://captcha-resolver.out"
baseUrl = "http://likedream-go-captcha:8890"
apiKey = "baca122..."
[redis]
url = "redis://:jhkdjhkjdhsIUTYURTU_pEGmFP@database.out:56379"
+6 -3
View File
@@ -16,13 +16,14 @@ func ApiSemiOCRVerification(bytes []byte, shape1, shape2 int64) string {
data := Bytes2Base64(bytes)
ctx := gctx.GetInitCtx()
baseUrl := g.Config().MustGetWithEnv(ctx, cst.ConfigCaptchaBaseUrl).String() + "/semiOcr"
apiKey := g.Config().MustGetWithEnv(ctx, cst.ConfigCaptchaApiKey).String()
client := httpclient.Cpdaily.Clone(ctx)
client.SetDoNotParseResponse(false)
post, err := client.R().SetBody(map[string]any{
"base64": data,
"shape1": shape1,
"shape2": shape2,
}).Post(baseUrl)
}).SetHeader("X-Api-Key", apiKey).Post(baseUrl)
utils.OkOrPanic(err, func(err error) error {
return oops.
With("SemiOCRVerification", baseUrl).
@@ -37,11 +38,12 @@ func ApiAutoOCRVerification(bytes []byte) string {
data := Bytes2Base64(bytes)
ctx := gctx.GetInitCtx()
baseUrl := g.Config().MustGetWithEnv(ctx, cst.ConfigCaptchaBaseUrl).String() + "/ocr"
apiKey := g.Config().MustGetWithEnv(ctx, cst.ConfigCaptchaApiKey).String()
client := httpclient.Cpdaily.Clone(ctx)
client.SetDoNotParseResponse(false)
post, err := client.R().SetBody(map[string]any{
"base64": data,
}).Post(baseUrl)
}).SetHeader("X-Api-Key", apiKey).Post(baseUrl)
utils.OkOrPanic(err, func(err error) error {
return oops.
With("AutoOCRVerification", baseUrl).
@@ -55,11 +57,12 @@ func ApiAutoOCRVerification(bytes []byte) string {
func ApiAutoCalcVerification(b64 string) string {
ctx := gctx.GetInitCtx()
baseUrl := g.Config().MustGetWithEnv(ctx, cst.ConfigCaptchaBaseUrl).String() + "/calc"
apiKey := g.Config().MustGetWithEnv(ctx, cst.ConfigCaptchaApiKey).String()
client := httpclient.Cpdaily.Clone(ctx)
client.SetDoNotParseResponse(false)
post, err := client.R().SetBody(map[string]any{
"base64": b64,
}).Post(baseUrl)
}).SetHeader("X-Api-Key", apiKey).Post(baseUrl)
utils.OkOrPanic(err, func(err error) error {
return oops.
With("AutoOCRVerification", baseUrl).
+20 -14
View File
@@ -226,20 +226,26 @@ func (c *CpdailyAutoSignTask) QueryFormByTitle(ctx context.Context, titleGlob st
// 尝试从已签到的历史任务中获取历史数据用于预填充
signedMatch := findMatchTitle(signedTasks)
if signedMatch != nil && (signedMatch["signInstanceWid"] == nil || matchTask["signInstanceWid"] == nil || signedMatch["signInstanceWid"].String() != matchTask["signInstanceWid"].String()) {
histResp, histErr := c.client.R().
SetBody(map[string]*gvar.Var{
"taskName": gvar.New(signedMatch["taskName"].String()),
"signWid": signedMatch["signWid"],
"signInstanceWid": signedMatch["signInstanceWid"],
}).
WithContext(ctx).
Post(c.getReqUrl("detailSignInstance"))
if histErr == nil {
histJSON := utils.ReadJson[map[string]*gvar.Var](histResp.Body)
histDatas := histJSON["datas"].MapStrVar()
if len(histDatas) > 0 {
result["historyRows"] = gvar.New(histDatas)
if signedMatch != nil {
// 如果已签到任务与当前匹配任务是同一个,直接用已有数据作为历史(避免重复API调用)
if matchTask != nil && signedMatch["signInstanceWid"] != nil && matchTask["signInstanceWid"] != nil &&
signedMatch["signInstanceWid"].String() == matchTask["signInstanceWid"].String() {
result["historyRows"] = result["rows"]
} else {
histResp, histErr := c.client.R().
SetBody(map[string]*gvar.Var{
"taskName": gvar.New(signedMatch["taskName"].String()),
"signWid": signedMatch["signWid"],
"signInstanceWid": signedMatch["signInstanceWid"],
}).
WithContext(ctx).
Post(c.getReqUrl("detailSignInstance"))
if histErr == nil {
histJSON := utils.ReadJson[map[string]*gvar.Var](histResp.Body)
histDatas := histJSON["datas"].MapStrVar()
if len(histDatas) > 0 {
result["historyRows"] = gvar.New(histDatas)
}
}
}
}
+60 -60
View File
@@ -221,7 +221,6 @@ func (c *CpdailySleepCheckTask) QueryFormByTitle(ctx context.Context, titleGlob
signedTasks := datas["signedTasks"].Array()
var matchTask map[string]*gvar.Var
isFromSigned := false
matchTask = findMatchTitle(unSignedTasks)
if matchTask == nil {
@@ -229,9 +228,6 @@ func (c *CpdailySleepCheckTask) QueryFormByTitle(ctx context.Context, titleGlob
if matchTask == nil {
matchTask = findMatchTitle(signedTasks)
if matchTask != nil {
isFromSigned = true
}
if matchTask == nil {
utils.OkOrPanic(errors.NewBusinessError(503, fmt.Sprintf("没有查询到查寝任务: %s", titleGlob)), func(err error) error {
@@ -281,11 +277,15 @@ func (c *CpdailySleepCheckTask) QueryFormByTitle(ctx context.Context, titleGlob
result["taskInfo"] = gvar.New(matchTask)
result["rows"] = gvar.New(datas)
// 如果当前任务不是已签到的,尝试从已签到的历史任务中获取历史数据用于预填充
if !isFromSigned {
// 先看今天有没有已签到的同名任务
signedMatch := findMatchTitle(signedTasks)
if signedMatch != nil {
// 尝试从已签到的历史任务中获取历史数据用于预填充
// 无论当前任务是否已签到,都尝试获取历史数据
signedMatch := findMatchTitle(signedTasks)
if signedMatch != nil {
// 如果已签到任务与当前匹配任务是同一个,直接用已有数据作为历史(避免重复API调用)
if matchTask != nil && signedMatch["signInstanceWid"] != nil && matchTask["signInstanceWid"] != nil &&
signedMatch["signInstanceWid"].String() == matchTask["signInstanceWid"].String() {
result["historyRows"] = result["rows"]
} else {
histResp, histErr := c.client.R().
SetBody(map[string]*gvar.Var{
"taskName": gvar.New(signedMatch["taskName"].String()),
@@ -302,63 +302,63 @@ func (c *CpdailySleepCheckTask) QueryFormByTitle(ctx context.Context, titleGlob
}
}
}
// 今天没有已签到的同名任务,从历史月份中只查 signedTasks
if result["historyRows"] == nil {
func() {
defer func() { recover() }()
now := time.Now().In(cst.TimeZoneShangHai)
year := strconv.Itoa(now.Year())
month := strconv.Itoa(int(now.Month()))
if len(month) == 1 {
month = "0" + month
}
resp, e := c.client.R().
SetBody(map[string]any{
"statisticYearMonth": fmt.Sprintf("%s-%s", year, month),
}).
WithContext(ctx).
Post(c.getReqUrl("getStuSignInfosByWeekMonth"))
if e != nil {
return
}
respJSON := utils.ReadJson[map[string]*gvar.Var](resp.Body)
monthDatas := respJSON["datas"].MapStrVar()
monthRows := monthDatas["rows"].Vars()
}
// 今天没有已签到的同名任务,从历史月份中只查 signedTasks
if result["historyRows"] == nil {
func() {
defer func() { recover() }()
now := time.Now().In(cst.TimeZoneShangHai)
year := strconv.Itoa(now.Year())
month := strconv.Itoa(int(now.Month()))
if len(month) == 1 {
month = "0" + month
}
resp, e := c.client.R().
SetBody(map[string]any{
"statisticYearMonth": fmt.Sprintf("%s-%s", year, month),
}).
WithContext(ctx).
Post(c.getReqUrl("getStuSignInfosByWeekMonth"))
if e != nil {
return
}
respJSON := utils.ReadJson[map[string]*gvar.Var](resp.Body)
monthDatas := respJSON["datas"].MapStrVar()
monthRows := monthDatas["rows"].Vars()
// 只从 signedTasks 中查找匹配的已签到任务
for _, row := range monthRows {
rowMap := row.MapStrVar()
signed := rowMap["signedTasks"].Vars()
for _, st := range signed {
item := st.MapStrVar()
tn, exist := item["taskName"]
if !exist || tn.String() == "" {
// 只从 signedTasks 中查找匹配的已签到任务
for _, row := range monthRows {
rowMap := row.MapStrVar()
signed := rowMap["signedTasks"].Vars()
for _, st := range signed {
item := st.MapStrVar()
tn, exist := item["taskName"]
if !exist || tn.String() == "" {
continue
}
if match.Match(tn.String(), titleGlob) {
// 找到已签到的历史任务,获取详情
dr, de := c.client.R().
SetBody(map[string]*gvar.Var{
"signInstanceWid": item["signInstanceWid"],
"signWid": item["signWid"],
"taskName": gvar.New(tn.String()),
}).
WithContext(ctx).
Post(c.getReqUrl("detailSignInstance"))
if de != nil {
continue
}
if match.Match(tn.String(), titleGlob) {
// 找到已签到的历史任务,获取详情
dr, de := c.client.R().
SetBody(map[string]*gvar.Var{
"signInstanceWid": item["signInstanceWid"],
"signWid": item["signWid"],
"taskName": gvar.New(tn.String()),
}).
WithContext(ctx).
Post(c.getReqUrl("detailSignInstance"))
if de != nil {
continue
}
dj := utils.ReadJson[map[string]*gvar.Var](dr.Body)
dd := dj["datas"].MapStrVar()
if len(dd) > 0 {
result["historyRows"] = gvar.New(dd)
return
}
dj := utils.ReadJson[map[string]*gvar.Var](dr.Body)
dd := dj["datas"].MapStrVar()
if len(dd) > 0 {
result["historyRows"] = gvar.New(dd)
return
}
}
}
}()
}
}
}()
}
return result
+1
View File
@@ -15,6 +15,7 @@ const (
ConfigAuthorizationKey = "server.authorization"
ConfigJwtKey = "server.jwt"
ConfigCaptchaBaseUrl = "captcha.baseUrl"
ConfigCaptchaApiKey = "captcha.apiKey"
ConfigS3AccessKey = "s3.accessKey"
ConfigS3SecretKey = "s3.secretKey"
ConfigS3BaseUrl = "s3.baseUrl"
+17 -13
View File
@@ -33,18 +33,22 @@ func InitDB() {
Global = client
dbDsn2, err := g.Cfg().Get(gctx.New(), cst.ConfigDatabaseDsn2)
utils.OkOrPanic(err)
GlobalGorm, err = gorm.Open(postgres.Open(dbDsn2.String()), &gorm.Config{})
if err != nil {
logger.Logger.Fatal("连接pg数据库失败: %v", zap.Error(err))
// PG 数据库为可选配置,如果 dsn2 为空则跳过
if dbDsn2.String() != "" {
GlobalGorm, err = gorm.Open(postgres.Open(dbDsn2.String()), &gorm.Config{})
if err != nil {
logger.Logger.Warn("连接pg数据库失败, 跳过: %v", zap.Error(err))
} else {
// 可选:配置连接池
sqlDB, err := GlobalGorm.DB()
if err != nil {
logger.Logger.Warn("获取pg数据库实例失败, 跳过: %v", zap.Error(err))
} else {
// 设置连接池参数
sqlDB.SetMaxIdleConns(10) // 设置空闲连接池中连接的最大数量
sqlDB.SetMaxOpenConns(100) // 设置打开数据库连接的最大数量
sqlDB.SetConnMaxLifetime(0) // 设置连接可复用的最大时间(0表示永久)
}
}
}
// 可选:配置连接池
sqlDB, err := GlobalGorm.DB()
if err != nil {
logger.Logger.Fatal("获取数据库实例失败: %v", zap.Error(err))
}
// 设置连接池参数
sqlDB.SetMaxIdleConns(10) // 设置空闲连接池中连接的最大数量
sqlDB.SetMaxOpenConns(100) // 设置打开数据库连接的最大数量
sqlDB.SetConnMaxLifetime(0) // 设置连接可复用的最大时间(0表示永久)
}
@@ -270,6 +270,9 @@ func (s *UserInfoServiceV1) RequestBalanceMigrate(ctx context.Context, req *v1.R
}
// 查询旧系统数据库中是否存在该邮箱的用户
if db.GlobalGorm == nil {
return utils.SuccessWithMsg("如果该邮箱在旧系统中存在积分,转移链接已发送")
}
var oldUser AspNetUser
err := db.GlobalGorm.Table("AspNetUsers").Where("email = ?", oldSystemEmail).First(&oldUser).Error
if err != nil {
@@ -343,6 +346,9 @@ func (s *UserInfoServiceV1) BalanceMigrate(ctx context.Context, req *v1.BalanceM
}
// 查询旧系统用户
if db.GlobalGorm == nil {
return utils.FailParam("旧系统数据库未连接")
}
var oldUser AspNetUser
err := db.GlobalGorm.Table("AspNetUsers").Where("email = ?", oldSystemEmail).First(&oldUser).Error
if err != nil {