Skip to content

Commit fcde08e

Browse files
committed
feat(checkin): configurable daily auto-checkin times
Auto-checkin was hard-wired to 10:00. Add settings.auto_checkin_times (HH:MM list, e.g. ["09:15","17:00"]); empty keeps the old 10:00 default. Each slot fires once per day when its time has passed; a slot is marked done when nothing is retryable, or two hours after its slot as a backstop. Console gains a times input next to the auto-checkin toggle.
1 parent f273667 commit fcde08e

5 files changed

Lines changed: 180 additions & 67 deletions

File tree

‎account/model.go‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,15 @@ type Status struct {
3333
type Settings struct {
3434
Port int `json:"port"`
3535
AutoStart bool `json:"auto_start"`
36-
LogLevel string `json:"log_level"` // "info" | "debug" | "error"
37-
QuotaRefreshInterval int `json:"quota_refresh_interval"` // 秒,0=不自动刷新
38-
BridgeToken string `json:"bridge_token,omitempty"` // 自定义鉴权 token,空则使用默认值 "qccg"
39-
ConsolePassword string `json:"console_password,omitempty"` // Web 控制台登录密码(类似 CPA management key)
40-
ModelMapping map[string]string `json:"model_mapping,omitempty"` // [DEPRECATED] 旧扁平映射(向后兼容,MapModel 中作为兜底回退使用)
41-
ModelMappings map[string]map[string]string `json:"model_mappings,omitempty"` // agent (claude/codex/gemini) → 客户端模型名 → Qoder model.key
42-
AutoCheckin bool `json:"auto_checkin"` // 每日 10:00 自动签到(默认关闭)
43-
MachineSalt string `json:"machine_salt,omitempty"` // 本机设备指纹盐(首次启动自动生成;勿修改,变更即指纹漂移)
36+
LogLevel string `json:"log_level"` // "info" | "debug" | "error"
37+
QuotaRefreshInterval int `json:"quota_refresh_interval"` // 秒,0=不自动刷新
38+
BridgeToken string `json:"bridge_token,omitempty"` // 自定义鉴权 token,空则使用默认值 "qccg"
39+
ConsolePassword string `json:"console_password,omitempty"` // Web 控制台登录密码(类似 CPA management key)
40+
ModelMapping map[string]string `json:"model_mapping,omitempty"` // [DEPRECATED] 旧扁平映射(向后兼容,MapModel 中作为兜底回退使用)
41+
ModelMappings map[string]map[string]string `json:"model_mappings,omitempty"` // agent (claude/codex/gemini) → 客户端模型名 → Qoder model.key
42+
AutoCheckin bool `json:"auto_checkin"` // 自动签到开关(默认关闭)
43+
AutoCheckinTimes []string `json:"auto_checkin_times,omitempty"` // 自动签到时间点,HH:MM 列表,如 ["09:15","17:00"];空=10:00
44+
MachineSalt string `json:"machine_salt,omitempty"` // 本机设备指纹盐(首次启动自动生成;勿修改,变更即指纹漂移)
4445
}
4546

4647
type QuotaInfo struct {

‎checkin.go‎

Lines changed: 81 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ import (
99
"net/http"
1010
"os"
1111
"path/filepath"
12+
"strconv"
13+
"strings"
1214
"sync"
1315
"time"
1416

@@ -600,15 +602,40 @@ func handleCheckin(w http.ResponseWriter, r *http.Request) {
600602
})
601603
}
602604

603-
// ---------- 每日 10:00 自动签到调度 ----------
605+
// ---------- 每日自动签到调度 ----------
604606

605607
var (
606-
checkinMu sync.Mutex
607-
lastCheckinDay string // 最近一次自动签到的日期 (YYYY-MM-DD),防止同日重复
608+
checkinMu sync.Mutex
609+
checkinDone = map[string]bool{} // key: "YYYY-MM-DD HH:MM",当日该时段已执行
608610
)
609611

610-
// StartCheckinScheduler 启动后台调度器(非阻塞)
611-
// 每分钟检查一次:若开关开启且当前时间 >= 当日 10:00 且当日未执行,则自动签到
612+
// defaultCheckinTimes 未配置时的默认签到时间(保持原行为)。
613+
var defaultCheckinTimes = []string{"10:00"}
614+
615+
// CheckinTimes 返回生效的自动签到时间列表(HH:MM)。
616+
func CheckinTimes(settings *account.Settings) []string {
617+
if settings != nil && len(settings.AutoCheckinTimes) > 0 {
618+
return settings.AutoCheckinTimes
619+
}
620+
return defaultCheckinTimes
621+
}
622+
623+
// parseHHMM 解析 "09:15" → (9, 15, true)
624+
func parseHHMM(s string) (int, int, bool) {
625+
parts := strings.Split(strings.TrimSpace(s), ":")
626+
if len(parts) != 2 {
627+
return 0, 0, false
628+
}
629+
h, err1 := strconv.Atoi(strings.TrimSpace(parts[0]))
630+
m, err2 := strconv.Atoi(strings.TrimSpace(parts[1]))
631+
if err1 != nil || err2 != nil || h < 0 || h > 23 || m < 0 || m > 59 {
632+
return 0, 0, false
633+
}
634+
return h, m, true
635+
}
636+
637+
// StartCheckinScheduler 启动后台调度器(非阻塞)。每分钟检查一次:对每个配置的
638+
// 时间点,若开关开启、当前已过该点、且当日该点尚未执行,则自动签到。
612639
func StartCheckinScheduler() {
613640
go func() {
614641
ticker := time.NewTicker(time.Minute)
@@ -617,60 +644,63 @@ func StartCheckinScheduler() {
617644
runScheduledCheckin()
618645
}
619646
}()
620-
logger.Info("auto checkin scheduler started (daily 10:00, default off)")
647+
logger.Info("auto checkin scheduler started (times=%s, default off)", strings.Join(CheckinTimes(nil), ","))
621648
}
622649

623-
// runScheduledCheckin 执行一次调度检查(可手动调用测试)
650+
// runScheduledCheckin 执行一次调度检查(可手动调用测试)。
624651
func runScheduledCheckin() bool {
625-
// 读取开关(默认关闭)
626652
settings, err := account.LoadSettings()
627-
if err != nil || settings == nil {
653+
if err != nil || settings == nil || !settings.AutoCheckin {
628654
return false
629655
}
630-
if !settings.AutoCheckin {
631-
return false
632-
}
633-
634656
now := time.Now()
635-
today := now.Format("2006-01-02")
636-
637-
// 必须已过 10:00
638-
if now.Hour() < 10 {
639-
return false
640-
}
641-
642-
checkinMu.Lock()
643-
defer checkinMu.Unlock()
644-
645-
// 当日已执行过
646-
if lastCheckinDay == today {
647-
return false
648-
}
649-
650-
logger.Info("[Checkin] auto checkin triggered at %s", now.Format("15:04:05"))
651-
results := CheckinAll()
652-
653-
claimed, already, retryable := 0, 0, 0
654-
for _, r := range results {
655-
switch r.Status {
656-
case checkinStatusClaimed:
657-
claimed++
658-
case checkinStatusAlreadyClaimed:
659-
already++
660-
case checkinStatusError, checkinStatusNoCampaign, checkinStatusNoToken:
661-
// 可能活动尚未创建(10:00 整点服务器有延迟)→ 允许重试
662-
retryable++
657+
date := now.Format("2006-01-02")
658+
nowMin := now.Hour()*60 + now.Minute()
659+
660+
ran := false
661+
for _, t := range CheckinTimes(settings) {
662+
h, m, ok := parseHHMM(t)
663+
if !ok {
664+
logger.Error("[Checkin] invalid auto checkin time %q, skipped", t)
665+
continue
666+
}
667+
slotMin := h*60 + m
668+
if nowMin < slotMin {
669+
continue // 还没到点
670+
}
671+
key := date + " " + t
672+
checkinMu.Lock()
673+
done := checkinDone[key]
674+
checkinMu.Unlock()
675+
if done {
676+
continue
663677
}
664-
}
665678

666-
// 标记当日完成的条件:无可重试状态;或已过 12:00(兜底不再重试,避免无限轮询)
667-
if retryable == 0 || now.Hour() >= 12 {
668-
lastCheckinDay = today
669-
logger.Info("[Checkin] auto checkin finished: %d claimed, %d already, %d retryable, total %d",
670-
claimed, already, retryable, len(results))
671-
} else {
672-
logger.Info("[Checkin] auto checkin partial: %d claimed, %d already, %d retryable -> will retry next tick",
673-
claimed, already, retryable)
679+
logger.Info("[Checkin] auto checkin triggered at %s (slot %s)", now.Format("15:04:05"), t)
680+
results := CheckinAll()
681+
claimed, already, retryable := 0, 0, 0
682+
for _, r := range results {
683+
switch r.Status {
684+
case checkinStatusClaimed:
685+
claimed++
686+
case checkinStatusAlreadyClaimed:
687+
already++
688+
case checkinStatusError, checkinStatusNoCampaign, checkinStatusNoToken:
689+
retryable++
690+
}
691+
}
692+
checkinMu.Lock()
693+
if retryable == 0 || nowMin >= slotMin+120 {
694+
// 无可重试状态,或已过该时段 2 小时(兜底,避免无限轮询)
695+
checkinDone[key] = true
696+
logger.Info("[Checkin] slot %s finished: %d claimed, %d already, %d retryable, total %d",
697+
t, claimed, already, retryable, len(results))
698+
} else {
699+
logger.Info("[Checkin] slot %s partial: %d claimed, %d already, %d retryable -> retry next tick",
700+
t, claimed, already, retryable)
701+
}
702+
checkinMu.Unlock()
703+
ran = true
674704
}
675-
return true
705+
return ran
676706
}

‎checkin_test.go‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package main
2+
3+
import (
4+
"testing"
5+
6+
"qoder2api/account"
7+
)
8+
9+
func TestParseHHMM(t *testing.T) {
10+
cases := []struct {
11+
in string
12+
h, m int
13+
ok bool
14+
}{
15+
{"09:15", 9, 15, true},
16+
{"17:00", 17, 0, true},
17+
{"0:00", 0, 0, true},
18+
{"23:59", 23, 59, true},
19+
{"25:00", 0, 0, false},
20+
{"09:60", 0, 0, false},
21+
{"abc", 0, 0, false},
22+
{"", 0, 0, false},
23+
}
24+
for _, c := range cases {
25+
h, m, ok := parseHHMM(c.in)
26+
if ok != c.ok || (ok && (h != c.h || m != c.m)) {
27+
t.Errorf("parseHHMM(%q) = (%d,%d,%v), want (%d,%d,%v)", c.in, h, m, ok, c.h, c.m, c.ok)
28+
}
29+
}
30+
}
31+
32+
func TestCheckinTimesDefaultAndConfigured(t *testing.T) {
33+
if got := CheckinTimes(nil); len(got) != 1 || got[0] != "10:00" {
34+
t.Errorf("default = %v, want [10:00]", got)
35+
}
36+
s := &account.Settings{AutoCheckinTimes: []string{"09:15", "17:00"}}
37+
got := CheckinTimes(s)
38+
if len(got) != 2 || got[0] != "09:15" || got[1] != "17:00" {
39+
t.Errorf("configured = %v, want [09:15 17:00]", got)
40+
}
41+
}

‎main.go‎

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -445,12 +445,13 @@ func handleSaveSettings(w http.ResponseWriter, r *http.Request) {
445445
return
446446
}
447447
var req struct {
448-
Port *int `json:"port"`
449-
BridgeToken *string `json:"bridge_token"`
450-
LogLevel *string `json:"log_level"`
451-
AutoStart *bool `json:"auto_start"`
452-
AutoCheckin *bool `json:"auto_checkin"`
453-
ConsolePassword *string `json:"console_password"`
448+
Port *int `json:"port"`
449+
BridgeToken *string `json:"bridge_token"`
450+
LogLevel *string `json:"log_level"`
451+
AutoStart *bool `json:"auto_start"`
452+
AutoCheckin *bool `json:"auto_checkin"`
453+
AutoCheckinTimes []string `json:"auto_checkin_times"`
454+
ConsolePassword *string `json:"console_password"`
454455
// 新格式:包含旧密码和新密码
455456
ConsolePasswordNew *struct {
456457
OldPassword string `json:"old_password"`
@@ -490,6 +491,22 @@ func handleSaveSettings(w http.ResponseWriter, r *http.Request) {
490491
cur.AutoCheckin = *req.AutoCheckin
491492
logger.Info("auto checkin set to %v", cur.AutoCheckin)
492493
}
494+
if req.AutoCheckinTimes != nil {
495+
var times []string
496+
for _, t := range req.AutoCheckinTimes {
497+
t = strings.TrimSpace(t)
498+
if t == "" {
499+
continue
500+
}
501+
if _, _, ok := parseHHMM(t); !ok {
502+
writeError(w, http.StatusBadRequest, fmt.Errorf("invalid auto_checkin_times entry: %q (want HH:MM)", t))
503+
return
504+
}
505+
times = append(times, t)
506+
}
507+
cur.AutoCheckinTimes = times
508+
logger.Info("auto checkin times set to %v", times)
509+
}
493510

494511
// 处理新格式的密码修改
495512
if req.ConsolePasswordNew != nil {

‎webconsole/index.html‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -224,8 +224,10 @@ <h3>账号列表 / 额度</h3>
224224
<button id="checkinBtn">🎁 每日签到领 100 Credits</button>
225225
<label class="pill" style="cursor:pointer; margin-bottom:0">
226226
<input type="checkbox" id="autoCheckinToggle" style="width:auto; margin-right:6px">
227-
每日 10:00 自动签到
227+
自动签到
228228
</label>
229+
<input id="autoCheckinTimes" placeholder="09:15,17:00" style="width:150px" title="每天自动签到的时间,逗号分隔,HH:MM;留空=10:00">
230+
<button class="secondary" id="autoCheckinTimesSave">保存时间</button>
229231
<span class="msg" id="checkinMsg"></span>
230232
</div>
231233
<div id="checkinResult" style="margin-bottom:12px; display:none">
@@ -378,6 +380,9 @@ <h3>NewAPI / 中转站接入</h3>
378380
if (document.activeElement !== $('autoCheckinToggle')) {
379381
$('autoCheckinToggle').checked = !!st.auto_checkin;
380382
}
383+
if (document.activeElement !== $('autoCheckinTimes')) {
384+
$('autoCheckinTimes').value = (st.auto_checkin_times || []).join(',');
385+
}
381386
} catch (e) {
382387
fillConnection({}, {});
383388
$('connMsg').className = 'msg err';
@@ -396,14 +401,33 @@ <h3>NewAPI / 中转站接入</h3>
396401
body: JSON.stringify({ auto_checkin: enabled }),
397402
});
398403
$('checkinMsg').className = 'msg ok';
399-
$('checkinMsg').textContent = enabled ? '✅ 自动签到已开启(每日 10:00)' : '自动签到已关闭';
404+
$('checkinMsg').textContent = enabled ? '✅ 自动签到已开启' : '自动签到已关闭';
400405
} catch (e) {
401406
ev.target.checked = !enabled;
402407
$('checkinMsg').className = 'msg err';
403408
$('checkinMsg').textContent = e.message;
404409
}
405410
};
406411

412+
// 自动签到时间保存
413+
$('autoCheckinTimesSave').onclick = async () => {
414+
const raw = ($('autoCheckinTimes').value || '').trim();
415+
const times = raw ? raw.split(',').map(s => s.trim()).filter(s => s) : [];
416+
$('checkinMsg').className = 'msg';
417+
$('checkinMsg').textContent = '保存中...';
418+
try {
419+
await api('/api/settings/save', {
420+
method: 'POST',
421+
body: JSON.stringify({ auto_checkin_times: times }),
422+
});
423+
$('checkinMsg').className = 'msg ok';
424+
$('checkinMsg').textContent = times.length ? ('✅ 签到时间已设为 ' + times.join(' / ')) : '✅ 已恢复默认(10:00)';
425+
} catch (e) {
426+
$('checkinMsg').className = 'msg err';
427+
$('checkinMsg').textContent = e.message;
428+
}
429+
};
430+
407431
function renderModelsTable(models) {
408432
if (!models || !models.length) {
409433
return '<div class="muted">暂无模型</div>';

0 commit comments

Comments
 (0)