feat: 每日积分模式与 Bark 完成提醒

- 按课时类型计分:文档 1 / 视频 3 / 音频 2 / 微课 2,每次 3 分,单日封顶 24 分;满额换类,无内容即停
- 积分计数落 localStorage,跨刷新/重启保留、跨天清零;面板与无头 TUI 都显示今日积分
- 运行器自己收尾时通过 Bark 推送今日积分、完成门数、用时和结束原因;手动停止与 --check 不推送
- 新增 --points-mode / --bark-* 参数及对应 YUN_XUE_TANG_* 环境变量
- 补充 points / notify 离线回归测试与 OpenSpec 配置

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
voidandClaude Sonnet 4.6 committed 2026-11-01 22:19:52 +08:00
1 parent 17217dbeb1
commit 0eb4c40629
31 files changed
+2954 -21

No files matched your search

@@ -0,0 +1,185 @@
---
name: openspec-apply-change
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.7.0"
---
Implement tasks from an OpenSpec change.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
Always announce: "Using change: <name>" and how to override (e.g., `/openspec-apply-change <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- `planningHome`, `changeRoot`, and `actionContext`: planning scope and edit constraints
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- `contextFiles`: artifact ID -> array of concrete file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
- Optional `context`: current required project instruction input from the selected root
- Optional `operationGuidance`: current advisory guidance for apply
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change (if it is not installed, run `openspec status --change "<name>" --json` to see the next artifact and `openspec instructions <artifact-id> --change "<name>" --json` for how to create it)
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
Treat `context` as a required prompt-level input. Read and consider it, and
apply relevant project facts, conventions, and constraints while implementing.
Treat `operationGuidance` as optional additive advice. Read and consider every
entry, and follow entries that are applicable and compatible with the built-in
workflow.
Keep both fields separate from CLI-returned state, missing artifacts, tasks,
progress, `contextFiles`, and the built-in `instruction`. They are not
evidence of task completion, do not replace the built-in instruction, and do
not permit bypassing a blocked state. If context conflicts with the built-in
instruction, an explicit user choice, or a CLI-controlled value, report the
conflict and preserve the controlling value. If guidance is inapplicable or
conflicts with those controlling inputs, do not follow it and explain why.
These are prompt-level behavior contracts, not enforceable checks.
4. **Read context files**
Read every file path listed under `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
Do not copy `context` or `operationGuidance` verbatim into implementation
files or planning artifacts unless the user separately asks for that content.
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! Ready to archive this change.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
- Do not use context or operation guidance as proof that a task is complete
- Apply relevant project context; report conflicts with controlling workflow inputs
- Consider every guidance entry; explain any inapplicable or conflicting advice
- Do not copy runtime context or operation guidance into implementation files or planning artifacts
- Preserve CLI-controlled blocked/ready/all-done behavior and completion criteria
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly
@@ -0,0 +1,180 @@
---
name: openspec-archive-change
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.7.0"
---
Archive a completed change in the experimental workflow.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
When prompting, show only active changes (not already archived).
Include the schema used for each change if available.
Always announce: "Using change: <name>" and how to override (e.g., `/openspec-archive-change <other>`).
**Load current archive inputs before the existing archive checks:**
After resolving the selected change and planning root, run:
```bash
openspec instructions archive --change "<name>" --json
```
Keep the same selected-root flags on this command. This lookup is advisory and
optional: it only supplies extra prompt inputs, so it must never block archiving.
If it exits non-zero or returns invalid JSON — for example on an older CLI that
does not support this command yet — continue the archive workflow with no
context and no operation guidance. Do not report an error and do not stop.
A successful response may omit both optional fields. Treat `context` as a
required prompt-level input: read and consider it, and apply relevant project
facts, conventions, and constraints. Treat `operationGuidance` as optional
additive advice: read and consider every entry, and follow entries that are
applicable and compatible with the built-in archive workflow.
Keep both fields separate from built-in steps, explicit user choices, resolved
paths, CLI checks, and command contracts. If context conflicts with one of those
controlling inputs, report the conflict and preserve the controlling value. If
guidance is inapplicable or conflicts with a controlling input, do not follow it
and explain why. Do not infer replacement paths, skipped prompts, or flags from
either field, and do not copy their text verbatim into specs, change artifacts,
or archive summaries unless the user separately asks for it. These are
prompt-level behavior contracts, not enforceable checks.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context
- `artifacts`: List of artifacts with their status (`done`, `skipped`, or other)
**If any artifacts are neither `done` nor `skipped`** (skipped artifacts satisfy the requirement - the change declares skip_specs):
- Display warning listing incomplete artifacts
- Ask the user to confirm they want to proceed
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Ask the user to confirm they want to proceed
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Use `artifactPaths.specs.existingOutputPaths` from status JSON as the only
delta-spec source. If the `specs` entry is missing or
`existingOutputPaths` is empty, proceed without a sync prompt and do not infer
delta specs from other artifacts.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `<planningHome.root>/openspec/specs/<capability>/spec.md` (use the store-aware `planningHome.root` from step 2, not a hardcoded repo path)
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
Route on the answer:
- "Cancel" — stop, do not archive
- "Archive without syncing" or "Archive now" — proceed to archive
- "Sync now" or "Sync anyway" — sync, then verify (below)
- Anything else — ask again rather than archiving
Before a selected sync writes any main spec, run
`openspec instructions specs --change "<name>" --json` once with the same
selected-root flags. Require a zero exit status and valid artifact-instruction
JSON. If the lookup fails or returns invalid JSON, report the error and stop
before writing any main spec or moving the change. A valid response with omitted
`rules` is the no-rules case. Apply returned `rules` only to the content and
form of main specs produced by this merge; do not use them as archive guidance,
change CLI behavior, or copy the rule text into any output file.
Then run the `openspec-sync-specs` workflow inline (agent-driven intelligent merge) for change '<name>', passing the delta spec analysis and the fetched specs-rule snapshot from above, and wait for it to finish. The inline sync must reuse that snapshot without fetching `specs` instructions again. Do not delegate it to a background task — step 5 would move `changeRoot` out from under a sync that is still reading it, leaving the change archived and the main specs never updated. If your agent can only run it by delegation, delegate synchronously and wait for the result.
Then re-run the comparison from the top of this step against every capability that has a delta spec in `artifactPaths.specs.existingOutputPaths` — not only the ones the sync reports it touched. A successful sync leaves nothing left to apply, so each capability must now read as already synced:
- ADDED requirements present
- MODIFIED requirements carrying the scenario and description changes named in the delta, with their other scenarios intact
- REMOVED requirements gone
- RENAMED requirements present under the new name and absent under the old one
If the sync failed, or any capability does not match, report what differs and stop — do not archive. Nothing has moved and `changeRoot` is intact, so the user can fix the mismatch or re-run the sync and start the archive again.
5. **Perform the archive**
Create an `archive` directory under `planningHome.changesDir` if it doesn't exist:
```bash
mkdir -p "<planningHome.changesDir>/archive"
```
Generate the target name: use the change name as-is when it already starts with a `YYYY-MM-DD-` prefix; otherwise prepend the current date as `YYYY-MM-DD-<change-name>`. Never stack a second date (same rule as `openspec archive`).
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move `changeRoot` to the archive directory
```bash
mv "<changeRoot>" "<planningHome.changesDir>/archive/<target-name>"
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Whether specs were synced (if applicable)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```markdown
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** the archive path derived from `planningHome.changesDir`/<target-name>/
**Specs:** <"✓ Synced to main specs" only if the step 4 verification passed; otherwise "No delta specs" or "Sync skipped">
<"All artifacts complete. All tasks complete." — or, if archived with warnings, list them instead (e.g. "Archived with 2 incomplete tasks")>
```
**Guardrails**
- Announce the selected change; prompt for selection when it is ambiguous
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, run the `openspec-sync-specs` workflow inline (agent-driven)
- Never archive while a spec sync is still in flight — run the sync inline and verify the main specs before moving `changeRoot`
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
- Apply relevant runtime context and report conflicts; operation guidance remains advisory
- Consider every guidance entry and explain any inapplicable or conflicting advice
- Existing CLI checks, resolved paths, prompts, and command contracts are unchanged
- Artifact rules constrain only the specs being written and are never operation guidance
- Never copy runtime context, operation guidance, or artifact-rule text verbatim into output files
+296
View File
@@ -0,0 +1,296 @@
---
name: openspec-explore
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.7.0"
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
Then read the project's own context from the resolved root - `<root.path>/openspec/config.yaml` (or `config.yml`). Use the `root.path` returned above, and skip this if neither file exists:
- `context`: project background - tech stack, conventions, constraints
- `rules`: keyed by artifact id - the entries for an artifact apply only when you write that artifact
Ground your thinking in these. They are constraints for you to follow, not content to reproduce: do NOT copy them into the conversation or into any artifact you create.
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Resolve and read existing artifacts for context**
- Run `openspec status --change "<name>" --json`.
- Use `changeRoot`, `artifactPaths`, and `actionContext` from the status JSON.
- Read existing files from `artifactPaths.<artifact>.existingOutputPaths`.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|----------------------------|--------------------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Handling Different Entry Points
**User brings a vague idea:**
```
User: I'm thinking about adding real-time collaboration
You: Real-time collab is a big space. Let me think about this...
COLLABORATION SPECTRUM
════════════════════════════════════════════
Awareness Coordination Sync
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│Presence│ │Cursors │ │ CRDT │
│ "3 │ │ Multi │ │Conflict│
│online" │ │ select │ │ free │
└────────┘ └────────┘ └────────┘
│ │ │
trivial moderate complex
Where's your head at?
```
**User brings a specific problem:**
```
User: The auth system is a mess
You: [reads codebase]
┌─────────────────────────────────────────────┐
│ CURRENT AUTH FLOW │
└─────────────────────────────────────────────┘
│
┌─────────────┼─────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Google │ │ GitHub │ │ Email │
│ OAuth │ │ OAuth │ │ Magic │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
└─────────────┼─────────────┘
▼
┌───────────┐
│ Session │
└─────┬─────┘
│
▼
┌───────────┐
│ Perms │
└───────────┘
I see three tangles. Which one's burning?
```
**User is stuck mid-implementation:**
```
User: /openspec-explore add-auth-system
The OAuth integration is more complex than expected
You: [reads change artifacts]
You're on task 4: "Implement OAuth flow"
Let me trace what's involved...
[draws diagram, explores options, suggests paths]
Want to update the design to reflect this?
Or add a spike task to investigate?
```
**User wants to compare options:**
```
User: Should we use Postgres or SQLite?
You: Generic answer is boring. What's the context?
User: A CLI tool that tracks local dev environments
You: That changes everything.
┌─────────────────────────────────────────────────┐
│ CLI TOOL DATA STORAGE │
└─────────────────────────────────────────────────┘
Key constraints:
• No daemon running
• Must work offline
• Single user
SQLite Postgres
Deployment embedded ✓ needs server ✗
Offline yes ✓ no ✗
Single file yes ✓ no ✗
SQLite. Not even close.
Unless... is there a sync component?
```
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When it feels like things are crystallizing, you might summarize:
```
## What We Figured Out
**The problem**: [crystallized understanding]
**The approach**: [if one emerged]
**Open questions**: [if any remain]
**Next steps** (if ready):
- Create a change proposal
- Keep exploring: just keep talking
```
But this summary is optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own
+123
View File
@@ -0,0 +1,123 @@
---
name: openspec-propose
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.7.0"
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with the artifacts your schema defines. With the default spec-driven schema that is:
- proposal.md (what & why)
- `specs/<capability>/spec.md` (what the system must do - a delta, not the main spec)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /openspec-apply-change
---
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **If no clear input provided, ask what they want to build**
Ask the user (open-ended, no preset options):
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change in the planning home resolved by the CLI with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts, each with its `status` and its `requires` edges (the artifact IDs it directly depends on)
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
4. **Create every artifact in the required set**
Use a todo list to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `skipped`/`warning`: present when the change declares skip_specs and this artifact must NOT be created - stop and pick another artifact
- `resolvedOutputPath`: Resolved path or pattern to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context - always re-read them from disk, even if you saw them earlier in the conversation (the user may have edited them)
- If the `instruction` field delegates creation to a specific skill or command, invoke it to produce the artifact instead of writing the file yourself, then verify the artifact file exists at `resolvedOutputPath`
- Otherwise create the artifact file using `template` as the structure and write it to `resolvedOutputPath`. If `resolvedOutputPath` is a glob, follow `instruction` to choose the concrete file path
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until every artifact in the required set exists (not just `apply.requires`)**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- The required set is `applyRequires` plus every artifact reachable from those by following the `requires` edges in `status --json` - walk them transitively (spec-driven closes over proposal, specs, design, tasks). Leave artifacts outside that set alone
- `status` is file-existence only, so an `applyRequires` artifact reading `done` does NOT mean its dependencies exist - writing `tasks.md` early marks `tasks` done while `specs` was never written. Use each artifact's `requires` edges, not its `status`, to build the required set: a `done` artifact still lists what it depends on
- An artifact already reading `status: "skipped"` is satisfied: the change declares `skip_specs` in `.openspec.yaml`, so its files must NOT exist. Never try to create one
- Create every artifact in the required set that is missing, then re-check - creating one can unblock others
- Skip one only when `status` already reports it `skipped`, or when its own `instruction` says it is conditional: run `openspec instructions <artifact-id> --change "<name>" --json` and skip only if its `instruction` field marks it optional (e.g. "create only if..."). Spec-driven's `design.md` qualifies; `specs` qualifies only via the `skipped` status above, never by your own judgment. Tell the user, and do not reconsider it
- Dependencies are enablers, not gates: if a required artifact is still `blocked` only because you skipped a conditional dependency, write it anyway
- Stop when every artifact in the required set is `done`, `skipped`, or was deliberately skipped
c. **If an artifact requires user input** (unclear context):
- Ask the user to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions, plus any conditional artifact you skipped and why
- What's ready: "All artifacts needed for implementation are ready."
- Prompt: "Run `/openspec-apply-change` or ask me to implement to start working on the tasks."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type - it is the authoritative guidance, even for familiar artifact names
- If the `instruction` field directs you to use a specific skill or command to create the artifact, invoke it instead of writing the artifact directly
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create every artifact the apply phase transitively depends on, not just the ids listed in `apply.requires`
- Always read dependency artifacts before creating a new one - re-read from disk, not from conversation memory (files may have changed since you last saw them)
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next
+223
View File
@@ -0,0 +1,223 @@
---
name: openspec-sync-specs
description: Sync delta specs from a change to main specs. Use when the user wants to update main specs with changes from a delta spec, without archiving the change.
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.7.0"
---
Sync delta specs from a change to main specs.
This is an **agent-driven** operation - you will read delta specs and directly edit main specs to apply the changes. This allows intelligent merging (e.g., adding a scenario without copying the entire requirement).
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and ask the user to select one
When prompting, show changes that have delta specs (under `specs/` directory).
Always announce: "Using change: <name>" and how to override (e.g., `/openspec-sync-specs <other>`).
2. **Resolve change context**
Run:
```bash
openspec status --change "<name>" --json
```
The JSON includes `planningHome.root`. Main specs live under `<planningHome.root>/openspec/specs/` — use that (store-aware) root for every main-spec path below, not a hardcoded repo path. When a store is selected it points at the store, not the current repository.
3. **Find delta specs**
Use `artifactPaths.specs.existingOutputPaths` from the status JSON as the
only source of delta spec paths. If the `specs` entry is missing or
`existingOutputPaths` is empty, report that there are no delta specs to sync,
do not infer them from other artifacts, and stop without requesting artifact
instructions or writing a main spec.
Sync every path in `existingOutputPaths` unless the caller narrowed the set.
A caller narrows it by naming an explicit list of delta spec paths to sync —
archive does this inline, and a user can too ("only sync the billing delta").
Then sync only the named paths and leave the remaining delta specs untouched:
bulk archive excludes a delta whose implementation it could not find, and
syncing it anyway would write a main spec the caller deliberately withheld.
Carry that narrowed selection through step 4; never widen it back to the full
list. If a named path is not in `existingOutputPaths`, do not sync it —
report it and stop, rather than dropping it silently. If the named list is
empty, report that there is nothing to sync and stop without writing a main
spec.
Each delta spec file contains sections like:
- `## ADDED Requirements` - New requirements to add
- `## MODIFIED Requirements` - Changes to existing requirements
- `## REMOVED Requirements` - Requirements to remove
- `## RENAMED Requirements` - Requirements to rename (FROM:/TO: format)
If no delta specs found, inform user and stop.
4. **For each delta spec, apply changes to main specs**
Before the first main-spec write, obtain one current specs-rule snapshot:
- If archive invoked this workflow inline and supplied a valid snapshot from
`openspec instructions specs --change "<name>" --json`, reuse it and do not
fetch the same instructions again.
- Otherwise run that command once now with the same selected-root flags.
- If the direct lookup exits non-zero or returns invalid artifact-instruction
JSON, report the error and stop before writing any main spec. Do not treat the
failure as an absent rule set.
- A valid response with omitted `rules` means no artifact rules are configured
and the existing semantic merge continues.
Apply returned `rules` only to the content and form of the main specs produced
by this merge. Artifact rules are not operation guidance and cannot change
selected roots, delta paths, CLI checks, or workflow steps. Use their text as
constraints without copying it verbatim into a main spec or summary.
For each capability delta spec path selected in step 3 — the full `existingOutputPaths` list, or the narrowed subset when a caller supplied one (these may belong to a selected store, not the repo):
a. **Read the delta spec** to understand the intended changes
b. **Read the main spec** at `<planningHome.root>/openspec/specs/<capability>/spec.md` (may not exist yet)
c. **Apply changes intelligently**:
**ADDED Requirements:**
- If requirement doesn't exist in main spec → add it
- If requirement already exists → update it to match (treat as implicit MODIFIED)
**MODIFIED Requirements:**
- Find the requirement in main spec
- Apply the changes - this can be:
- Adding new scenarios (don't need to copy existing ones)
- Modifying existing scenarios
- Changing the requirement description
- Preserve scenarios/content not mentioned in the delta
**REMOVED Requirements:**
- Remove the entire requirement block from main spec
**RENAMED Requirements:**
- Find the FROM requirement, rename to TO
**`## Purpose` in the delta:**
- The main spec already has one and it is authoritative - leave it alone
(this is what `openspec archive` does; it warns and moves on)
d. **Create new main spec** if capability doesn't exist yet:
- Create `<planningHome.root>/openspec/specs/<capability>/spec.md`
- Add Purpose section: copy the delta's `## Purpose` body verbatim when it has one
(this is what `openspec archive` does); only write a brief TBD placeholder when it does not
- Add Requirements section with the ADDED requirements
- Follow the **Main Spec Format Reference** below
5. **Show summary**
After applying all changes, summarize:
- Which capabilities were updated
- What changes were made (requirements added/modified/removed/renamed)
- Any new main spec left with a TBD Purpose placeholder, so it gets written
now rather than lingering
**Delta Spec Format Reference**
```markdown
## Purpose
Only on a delta that introduces a brand-new capability. Seeds the new main spec.
## ADDED Requirements
### Requirement: New Feature
The system SHALL do something new.
#### Scenario: Basic case
- **WHEN** user does X
- **THEN** system does Y
## MODIFIED Requirements
### Requirement: Existing Feature
#### Scenario: New scenario to add
- **WHEN** user does A
- **THEN** system does B
## REMOVED Requirements
### Requirement: Deprecated Feature
## RENAMED Requirements
- FROM: `### Requirement: Old Name`
- TO: `### Requirement: New Name`
```
**Main Spec Format Reference**
Main specs are what the delta merges INTO. They must never contain delta operation headers (`## ADDED/MODIFIED/REMOVED/RENAMED Requirements`) - after syncing, every requirement lives under a single `## Requirements` section:
```markdown
# <capability> Specification
## Purpose
Short description of what this capability does and why it exists.
## Requirements
### Requirement: New Feature
The system SHALL do something new.
#### Scenario: Basic case
- **WHEN** user does X
- **THEN** system does Y
```
**Key Principle: Intelligent Merging**
Unlike programmatic merging, you can apply **partial updates**:
- To add a scenario, just include that scenario under MODIFIED - don't copy existing scenarios
- The delta represents *intent*, not a wholesale replacement
- Use your judgment to merge changes sensibly
**Output On Success**
```markdown
## Specs Synced: <change-name>
Updated main specs:
**<capability-1>**:
- Added requirement: "New Feature"
- Modified requirement: "Existing Feature" (added 1 scenario)
**<capability-2>**:
- Created new spec file
- Added requirement: "Another Feature"
Main specs are now updated. The change remains active - archive when implementation is complete.
```
**Guardrails**
- Read both delta and main specs before making changes
- Preserve existing content not mentioned in delta
- Never copy a delta file into a main spec as-is - merge its content so the main spec keeps the Main Spec Format Reference structure, with no delta operation headers
- If something is unclear, ask for clarification
- Show what you're changing as you go
- The operation should be idempotent - running twice should give same result
- Use only `artifactPaths.specs.existingOutputPaths`; never infer delta specs from unrelated artifacts
- Honor a caller-supplied subset of `existingOutputPaths`; never widen it back to the full list
- Fetch specs instructions once for direct sync, or reuse the archive-supplied snapshot inline
- Stop before every main-spec write on a non-zero or invalid JSON specs-instruction response
- Artifact rules constrain only the specs being written and are never copied into output files
@@ -0,0 +1,90 @@
---
name: openspec-update-change
description: Update an OpenSpec change by revising its existing planning artifacts and keeping them coherent with one another. Use when the user wants to revise a change's plan, fold new decisions into it, or reconcile its artifacts after an edit. Never edits code.
allowed-tools: Bash(openspec:*)
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.7.0"
---
Revise a change's existing planning artifacts and keep them coherent. Never edit code.
**Store selection:** If the user names a store (a store is a standalone OpenSpec repo registered on this machine) or the work lives in one, run `openspec store list --json` to discover registered store ids, then pass `--store <id>` on the commands that read or write specs and changes (`new change`, `status`, `instructions`, `list`, `show`, `validate`, `archive`, `doctor`, `context`, `view`). Other commands do not take the flag. Hints printed by commands already carry the flag; keep it on follow-ups. Without a store, commands act on the nearest local `openspec/` root.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes sorted by most recently modified, and ask the user to select one
When prompting, present the top 3-4 most recently modified changes as options, showing:
- Change name
- Schema (from `schema` field if present, otherwise "spec-driven")
- Status (e.g., "0/5 tasks", "complete", "no tasks")
- How recently it was modified (from `lastModified` field)
Mark the most recently modified change as "(Recommended)" since it's likely what the user wants to update.
Always announce: "Using change: <name>" and how to override (e.g., `/openspec-update-change <other>`).
2. **Get the change's artifacts**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand current state. The response includes:
- `schemaName`: The workflow schema being used (e.g., "spec-driven")
- `artifacts`: Array of artifacts with their status ("done", "skipped", "ready", "blocked")
- `isComplete`: Boolean indicating if all artifacts are complete
- `planningHome`, `changeRoot`, `artifactPaths`, and `actionContext`: path and scope context. Use these instead of assuming repo-local paths.
The artifact ids and paths come from the active schema - do NOT assume them, and do NOT branch on hardcoded artifact names. Custom schemas must work unchanged.
The files to edit are `artifactPaths.<id>.existingOutputPaths` - the concrete files that exist on disk, already glob-expanded for glob artifacts (e.g. `specs/**/*.md`). Do NOT write to `resolvedOutputPath`: for a glob artifact it is still the glob pattern, not a real file.
3. **Understand the request**
- If the user asked for a specific revision ("the design now uses X"), that is the starting edit.
- If they only said "update" / "make this coherent", treat it as a coherence review: read the existing artifacts and check them against each other for contradictions, gaps, and duplication.
4. **Read and reconcile**
- Read the artifact(s) the request touches and the change's other existing artifacts.
- Apply the requested edit. Then check every other existing artifact against it - in ANY direction: an edit to a later artifact may require revising an earlier one, not only the other way around. Build order is a useful reading order, not a constraint on which artifacts may be revised.
- Note everything that is now inconsistent, missing, or contradictory.
- Revise only files that already exist (`existingOutputPaths`). Do NOT create artifacts that don't exist yet, and do NOT invent new files under a glob artifact - note them and point the user to `/openspec-continue-change` to create them.
- If the change is already coherent, say so and make no edits.
5. **Confirm and apply, one artifact at a time**
- Show each proposed revision and why. Write only after the user confirms.
- If the user rejects a revision, do not write it - leave that artifact unchanged.
- When a substantial rewrite is needed, get that artifact's rules and template first:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
6. **Point to the next step (guidance only - NEVER act on it)**
- Artifacts still missing -> suggest `/openspec-continue-change` to create them.
- Change already implemented (tasks checked off / already applied) -> the code may no longer match the revised plan; suggest `/openspec-apply-change` to carry the delta into code.
- Everything done and implemented -> suggest `/openspec-archive-change`.
**Output**
After each invocation, show:
- Which artifacts were revised (and which proposed revisions were rejected)
- Anything deferred to `/openspec-continue-change` (not-yet-created artifacts or files)
- Where the change stands and the recommended next command
**Guardrails**
- Planning artifacts only - NEVER edit implementation code. If the revised plan implies code changes, stop and point to `/openspec-apply-change`.
- Use the artifact ids and paths reported by `openspec status`; never branch on hardcoded artifact names.
- Edit only the concrete files in `existingOutputPaths`; never write to a glob `resolvedOutputPath`.
- Do not advance the build frontier: no new artifacts, no new files under glob artifacts - that is `/openspec-continue-change`'s job.
- Confirm every edit with the user before writing.
- If the request changes the change's *intent* rather than refining it, recommend starting fresh with `/openspec-new-change` (the "Update vs. Start Fresh" heuristic).
- `/openspec-continue-change` and `/openspec-new-change` may not be installed (core profile). When suggesting one that is unavailable, point to the CLI instead: `openspec status --change "<name>" --json` shows the next artifact and `openspec instructions <artifact-id> --change "<name>" --json` explains how to create it.
+8
View File
@@ -6,6 +6,14 @@ YUN_XUE_TANG_PWD=
# 本次最多完成几门课(docker compose 用;0 / 留空 = 不限)
YUN_XUE_TANG_MAX_COURSES=100
# 任务结束时推送 Bark 手机通知(正常刷完 / 卡死 / 登录失败)。
# 填 Bark App 里的推送地址(含设备 key),留空 = 不推送。优先级高于 config/runner.config.mjs
YUN_XUE_TANG_BARK_URL=
# 通知分组,留空 = Bark 默认
YUN_XUE_TANG_BARK_GROUP=云学堂助手
# 通知在 Bark 服务端保留多少秒,0 = Bark 默认
YUN_XUE_TANG_BARK_TTL=600
# 时区,影响日志时间戳
TZ=Asia/Shanghai
+55
View File
@@ -20,6 +20,7 @@ Tampermonkey 用户脚本。支持多课时课程与单视频/音频课程;含
| 防挂机验证 | 识别「已触发防挂机验证」弹窗并点「继续学习」;滑块/拼图类验证不绕过,提示人工处理 |
| 课程列表自动刷课 | 在列表页逐门进入未学完的课程;每完成一门都重新调列表接口拿平台实时状态再选下一门,本次门数上限见下方配置表 |
| 短课程优先 | 列表刷课默认按课程总时长**从短到长**选课(跨页),先完成 1 分钟的课再学 1 小时的课;面板可关闭 |
| 每日积分模式 | 按**课时类型**计分:文档 1 次、视频 3 次、音频 2 次、微课 2 次,每次 3 分,单日封顶 24 分。先补文档/音频/微课单条内容,视频额度靠课程里的视频课时;某类满额自动切下一类,四类都满(或剩余类型没内容)就停止刷课。计数存 localStorage、跨刷新/重启不丢、跨天清零;面板可随时关闭 |
| 考试自动空卷 | 含考试章节的课程不再跳过:自动点进考试节 → 开始/继续考试 → 一题不做直接「提交考试」→ 点「确定」交卷,交卷后课程进度被平台记账,课程即可完成。只有本页真的点过「提交考试/确定交卷」,看到的结果页才算一次交卷;平台恢复的旧结果页会先回「考试说明页」重新进入,不会在结果页和课程页之间空转。同一门课最多交卷 `maxExamTries` 次,超过仍不记账就跳过该课继续下一门(写明原因) |
| 不跳过普通课程 | 没有任何「跳过本课」入口,也不会把普通课程加入黑名单;没学完就退避重试(30 秒起翻倍,最长 5 分钟),同一门课最多重试 `maxCourseRetries` 次,超过才停下整轮刷课并提示原因,等人工处理。**唯一例外**:考试空卷交卷达到 `maxExamTries` 仍未计入进度,或考试页始终没有可点的「开始考试/提交考试」——继续重试只会反复进同一门课,因此本轮跳过它、继续刷其它课 |
| 进度可续 | 学习进度存在 `sessionStorage`(`yun-xue-tang-run-state-v3`),整页跳转/刷新后继续上次的队列和页码;**运行开关不跨会话** —— 浏览器重启、运行器新建标签页后一律回到待机,必须显式开跑(避免未登录就报「运行中」) |
@@ -52,6 +53,7 @@ Tampermonkey 用户脚本。支持多课时课程与单视频/音频课程;含
| `courseRetryDelayMs` | `30000` | 首次重试前的等待;每次翻倍,最长 5 分钟 |
| `alignToFirstIncomplete` | `true` | 进入课程先从第一个未学完的课时学起;`false` = 沿用平台上次位置 |
| `preferShortCourses` | `true` | 列表刷课时优先总时长更短的课程(正序);面板勾选框「优先短课程(时长正序)」可随时切换 |
| `pointsEnabled`(`localStorage`) | `true` | 每日积分模式:文档 1 / 视频 3 / 音频 2 / 微课 2(每次 3 分,封顶 24 分);面板勾选框「每日积分模式」可随时切换 |
| `maxExamTries` | `2` | 同一门课「空卷交卷」的最大次数;超过仍没计入进度就本轮跳过该课、继续下一门(记录在会话里,重启后会重新尝试) |
| `examClickCooldownMs` | `1500` | 考试页内两次点击的间隔(毫秒) |
@@ -63,6 +65,11 @@ Tampermonkey 用户脚本。支持多课时课程与单视频/音频课程;含
逐个进入。接口不可用(未登录、跨域、平台改版)时自动降级为「当前页按时长正序」,
再不行就回到原来的列表顺序,不会让刷课任务卡住。
每日积分模式按**课时**计数:多课时课程里每学完一节视频/文档/音频/微课各算一次,
单视频/音频/课件播放页学完也算一次。某类满额后自动换下一类;四类都满额,
或剩余额度的类型在当前目录里确认没有内容时,停止刷课并在面板/日志里汇报今日积分。
识别不出类型的课时(例如考试节)不计分;同一课时当天重复上报只算一次。
## 无头运行(Linux / Windows 服务器)
用 `runner/headless.mjs` 把整套逻辑跑在一个无头 Chromium 里:自己起浏览器、用 CDP 把构建产物
@@ -236,6 +243,7 @@ Windows 上要注意:`Ctrl+C` 会让运行器优雅收尾(暂停视频、停
| `--restart-minutes N`(旧名 `--restart`) | `YUN_XUE_TANG_RESTART_MINUTES` | `restartMinutes` | `0` | 脚本自己停下后等待多少分钟再开新一轮;`0` = 直接退出 |
| `--idle-restart-minutes N`(旧名 `--idle`) | `YUN_XUE_TANG_IDLE_RESTART_MINUTES` | `idleRestartMinutes` | `30` | 连续多少分钟无进展判定卡死 |
| `--prefer-short 0\|1` | `YUN_XUE_TANG_PREFER_SHORT` | `preferShort` | `1` | 是否优先短课程(时长正序) |
| `--points-mode 0\|1` | `YUN_XUE_TANG_POINTS_MODE` | `pointsMode` | `1` | 每日积分模式:文档1/视频3/音频2/微课2,封顶即停 |
| `--headless 0\|1`(旧名 `--visible`) | `YUN_XUE_TANG_HEADLESS` | `headless` | `1` | `1` = 无头;`0` = 开有界面浏览器(仅本机调试;无图形会话时被忽略并强制无头) |
| `--origin URL` | `YUN_XUE_TANG_ORIGIN` | `origin` | `https://kfmic.yunxuetang.cn` | 站点根地址(换分公司环境时改这个) |
| `--url URL` | `YUN_XUE_TANG_URL` | `url` | `<origin>/login.html` | 起始页面 |
@@ -245,6 +253,9 @@ Windows 上要注意:`Ctrl+C` 会让运行器优雅收尾(暂停视频、停
| `--extra-args "…"` | `YUN_XUE_TANG_EXTRA_ARGS` | `extraArgs` | 空 | 追加给浏览器的命令行参数(空格分隔) |
| `--log-file PATH`(旧名 `--log`) | `YUN_XUE_TANG_LOG_FILE` | `logFile` | `./run-logs/headless.log` | 日志文件路径 |
| `--log-max-bytes N`(旧名 `--log-max`) | `YUN_XUE_TANG_LOG_MAX_BYTES` | `logMaxBytes` | `5242880` | 单文件上限,超出轮转 |
| `--bark-url URL` | `YUN_XUE_TANG_BARK_URL` | `barkUrl` | 空 | Bark 推送地址(含设备 key),运行器自己收尾时推手机通知;空 = 不推送 |
| `--bark-group NAME` | `YUN_XUE_TANG_BARK_GROUP` | `barkGroup` | 空 | Bark 通知分组(App 里按组折叠) |
| `--bark-ttl N` | `YUN_XUE_TANG_BARK_TTL` | `barkTtl` | `0` | 通知在 Bark 服务端保留多少秒;`0` = 默认 |
| `--no-tui` | `YUN_XUE_TANG_TUI` | `tui` | 开 | `1`/`0`,是否在终端显示实时面板;stdout 不是 TTY 时自动关闭 |
| `--no-color` | `YUN_XUE_TANG_COLOR` | `color` | 开 | `1`/`0`,面板是否带 ANSI 颜色(也认 `NO_COLOR`) |
| `--config PATH` | `YUN_XUE_TANG_CONFIG` | — | `./config/runner.config.mjs` | 指定另一个配置文件 |
@@ -280,6 +291,41 @@ export default {
- 个人机器的差异建议放 `runner.local.mjs`(已在 `.gitignore` 里)并用 `--config ./runner.local.mjs`
- 配置文件里写 `username` / `password` 会被**忽略并告警**(凭据只认环境变量);写未知字段也会告警
### 完成提醒(Bark)
运行器**自己结束**时(正常刷完 / 达到上限 / 长时间无进展 / 连续登录失败)会推一条
[Bark](https://github.com/Finb/Bark) 手机通知,正文是今日积分、完成门数、用时和结束原因:
```json
{
"title": "云学堂助手:任务完成",
"body": "今日积分 15/24 · 文档1/1 视频3/3 音频1/2 微课0/2\n完成 4 门 · 用时 18 分 6 秒\n脚本已停止:今日积分:可用内容已学完"
}
```
配置(三选一,优先级从低到高):
```js
// config/runner.config.mjs
barkUrl: 'https://api.day.app/<你的设备 key>', // 也接受带 {title}/{body} 的完整模板
barkGroup: '云学堂助手', // 通知分组
barkTtl: 600, // 服务端保留秒数
```
```sh
YUN_XUE_TANG_BARK_URL=https://api.day.app/<key> YUN_XUE_TANG_BARK_GROUP=云学堂助手 node runner/headless.mjs
```
```sh
# 环境变量优先级最高;Docker 里写进 .env 即可(.env 不入库)
YUN_XUE_TANG_BARK_URL=https://api.day.app/<key>
```
- 手动 `Ctrl+C` 主动停止**不推送**(人在终端前,不需要再提醒);`--check` 自检也不推送。
- 推送失败只在日志里告警(网络不通 / key 错),不影响运行器退出码。
- 配了 `restartMinutes` 时,重复的同一结论(例如「今日积分已学完」)只推一次,不会每轮刷屏。
- `--help` 与启动日志里的 key 会打码成 `/***`,避免日志泄露推送权限。
退出码:`0` 正常收尾(达到 `maxCourses` / `budgetMinutes` / 无更多可学课程)、`1` 无进展卡死、
`2` 环境或参数问题(缺构建产物、缺凭据、找不到浏览器、端口被占、参数写错)、`3` 连续 5 次登录失败(见 runner/)
(多半是密码错误或站点要求验证码)。
@@ -438,6 +484,7 @@ runner/ 无头运行器(Linux / Windows,无图形
page.mjs 页面求值封装与注入后调用的表达式
session.mjs 单次会话:起浏览器 / 注入 / 自动重登 / 崩溃自愈
selfcheck.mjs --check 只读环境自检
notify.mjs 任务结束时的 Bark 手机通知
tui.mjs 终端面板(框线 + 进度条,q 退出,非 TTY 自动关闭)
study.mjs 学习统计(本次播放时长 / 获得学分)
supervisor.mjs 崩溃重启循环与退出码
@@ -471,6 +518,8 @@ docs/
| `yun-xue-tang-login-v1` | 勾选「记住密码」时的账号密码(base64 混淆,**不是加密**) |
| `yun-xue-tang-auto-play-enabled` | 「当前课程自动连播」开关 |
| `yun-xue-tang-prefer-short` | 「优先短课程(时长正序)」开关(`1` / `0`) |
| `yun-xue-tang-daily-points-mode` | 「每日积分模式」开关(`1` / `0`) |
| `yun-xue-tang-daily-points-v1` | 今日积分计数(按本地日期自动清零,含当天已计分的课时去重表) |
| `yun-xue-tang-target-catalog-url` | 目标目录 URL:决定刷哪个学院/目录的课(短课程队列的缓存键也来自它) |
| `yun-xue-tang-auto-start-after-login` | 登录后自动开始刷课的一次性标记(5 分钟内有效) |
@@ -478,6 +527,7 @@ docs/
| --- | --- |
| `yun-xue-tang-run-state-v3` | 本轮是否在跑、页码、当前课程、本轮已完成 / 待重试 / 已跳过(考试交不了)记录 |
| `yun-xue-tang-short-catalog-v1` | 短课程时长队列缓存(TTL 5 分钟) |
| `yun-xue-tang-points-inventory-v1` | 文档/音频/微课单条内容库存缓存(TTL 5 分钟) |
旧版本(v2.8.0 之前)把所有状态整块存在 `localStorage` 的 `yun-xue-tang-batch-v2` 里,
包括「是否在跑」。现在这个键只在启动时做一次性迁移:只迁进度(已完成书目、
@@ -518,6 +568,11 @@ v2.6.0 新增「优先短课程(时长正序)」:真实站点读取 5148
v2.8.0 状态分层重构:刷课开关不再进 localStorage(修「还没登录就开始刷课」)、字段名语义化、
短课程模式下页码导航所有权归一到 `chooseShortCourse`(省掉每次多跳一页+白等 3.5 秒)。
每日积分模式:按课时类型(文档/视频/音频/微课)分别计数,文档 1、视频 3、音频 2、微课 2,
每次 3 分封顶 24 分;先补文档/音频/微课单条内容,视频靠课程课时;某类满额自动换下一类,
四类都满或无内容即停。计数落 localStorage 并跨天清零,面板与无头 TUI 都显示今日积分。
离线回归见 `node dev/tests/points-test.mjs`(`npm run test:points`)。
v2.7.0 修复「进入课程有概率不自动播放」和「学完后不转下一门」:新增单视频/音频/课件播放页识别,
完成判定同时支持 `已完成 x/y`、`已完成 N%`、`已完成学习`;真机复现、修复前后对比与回归结果见
[`docs/evidence/completion-next-evidence.txt`](docs/evidence/completion-next-evidence.txt)。
+16
View File
@@ -20,6 +20,8 @@ export default {
budgetMinutes: 0,
/** 优先总时长最短的课程(正序);false = 按列表原顺序 */
preferShort: true,
/** 每日积分模式:按课时类型计分(文档1/视频3/音频2/微课2,每次3分),四类封顶即停;false = 普通刷课 */
pointsMode: true,
/** 脚本自己停下后等多少分钟再开新一轮;0 = 直接退出。配合 --max 可以实现分段刷完 */
restartMinutes: 0,
/** 连续多少分钟没有任何进展就判定卡死并退出(0 = 用内置的 30 分钟) */
@@ -47,6 +49,20 @@ export default {
/** 单个日志文件上限(字节),超出后轮转成 .1 */
logMaxBytes: 5 * 1024 * 1024,
// ---------- 完成提醒(Bark) ----------
/**
* 运行器自己收尾时推一条手机通知:正常刷完 / 长时间无进展 / 登录失败。
* 填 Bark App 里的推送地址(含设备 key),留空 = 不推送。
* 也可以只写带占位符的完整模板:https://api.day.app/<key>/{title}/{body}
* 注意:这个 key 等于「谁能往你手机推通知」,不要写进仓库;
* 实际使用请设环境变量 YUN_XUE_TANG_BARK_URL(.env 不入库)。
*/
barkUrl: '',
/** 通知分组(Bark App 里把同一组折叠在一起),留空 = Bark 默认 */
barkGroup: '云学堂助手',
/** 通知在 Bark 服务端保留多少秒;0 = Bark 默认(效仿 curl 示例里的 600) */
barkTtl: 600,
// ---------- 终端面板 ----------
/** 终端里显示实时面板(框线 + 进度条);false = 回到逐行日志。非 TTY(重定向/计划任务)时自动关闭 */
tui: true,
+1
View File
@@ -59,6 +59,7 @@ node dev/tests/real-test.mjs --keep # 跑完不关浏览器,便于人工复
```bash
npm run test:tui # 面板渲染 / 列宽 / 尺寸自适应
npm run test:study # 学习时长与学分累计口径
npm run test:points # 每日积分:类型识别 / 封顶 / 去重 / 跨天清零 / 选类顺序
```
它用假 stdout 渲染真实帧,逐行量列宽,重点盯五件容易错的事:
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env node
/**
* Bark 完成提醒(runner/notify.mjs)自测:只验证地址拼接与文案,不发真实请求。
*
* 这两块错了都不会让运行器报错——只会在手机上收到一条打不开的链接或看不懂的文案,
* 而且往往要等到真正刷完那一刻才发现。用纯函数把格式钉死。
*
* 用法:
* node dev/tests/notify-test.mjs
* npm run test:notify
*/
import { buildBarkUrl, buildFinishMessage } from '../../runner/notify.mjs';
let failed = 0;
function ok(cond, name, extra) {
if (cond) console.log(' ✔ ' + name);
else { failed++; console.log(' ✘ ' + name + (extra ? ' → ' + extra : '')); }
}
function eq(actual, expect, name) {
ok(actual === expect, name, '期望 ' + JSON.stringify(expect) + ',实际 ' + JSON.stringify(actual));
}
console.log('地址拼接');
{
eq(buildBarkUrl('', 't', 'b'), '', '空地址 = 不推送');
eq(
buildBarkUrl('https://api.day.app/KEY', '任务完成', '积分 15/24'),
'https://api.day.app/KEY/' + encodeURIComponent('任务完成') + '/' + encodeURIComponent('积分 15/24'),
'根地址 + 中文标题/正文按路径段编码'
);
eq(
buildBarkUrl('https://api.day.app/KEY/', 't', 'b', { group: '云学堂', ttl: 600 }),
'https://api.day.app/KEY/t/b?group=' + encodeURIComponent('云学堂') + '&ttl=600',
'结尾斜杠不会拼出双斜杠,group/ttl 追加为查询参数'
);
eq(
buildBarkUrl('https://api.day.app/KEY/{title}/{body}', 't', 'b'),
'https://api.day.app/KEY/t/b',
'带 {title}/{body} 占位符的完整模板'
);
eq(
buildBarkUrl('https://api.day.app/KEY/{title}/{body}?group=example&ttl=600', 't', 'b', { group: 'x', ttl: 1 }),
'https://api.day.app/KEY/t/b?group=example&ttl=600',
'模板里已经有 group/ttl 时不再重复追加'
);
ok(
buildBarkUrl('https://api.day.app/KEY', 'a&b', 'c?d').indexOf('a%26b') > 0,
'特殊字符不会破坏路径'
);
}
console.log('收尾文案');
{
const done = buildFinishMessage({
kind: 'done',
finishReason: '已完成 10 门(达到上限 maxCourses=10)',
completed: 10,
elapsed: 125,
points: { enabled: true, text: '今日积分 15/24 · 文档1/1 视频3/3 音频1/2 微课0/2' },
});
eq(done.title, '云学堂助手:任务完成', '正常完成标题');
ok(done.body.indexOf('今日积分 15/24') === 0, '正文以今日积分开头');
ok(done.body.indexOf('完成 10 门 · 用时 2 分 5 秒') > 0, '完成门数与用时');
ok(done.body.indexOf('达到上限') > 0, '带上结束原因');
eq(buildFinishMessage({ kind: 'stalled' }).title, '云学堂助手:长时间无进展', '卡死标题');
eq(buildFinishMessage({ kind: 'login' }).title, '云学堂助手:登录失败', '登录失败标题');
ok(buildFinishMessage({ kind: 'done', elapsed: 45 }).body.indexOf('用时 45 秒') > 0, '不足一分钟只显示秒');
const noPoints = buildFinishMessage({ kind: 'done', completed: 3, elapsed: 0 });
ok(noPoints.body.indexOf('今日积分') < 0, '积分模式关闭时不硬塞今日积分');
const off = buildFinishMessage({
kind: 'done', completed: 3, elapsed: 0,
points: { enabled: false, text: '今日积分 0/24 · 文档0/1 视频0/3 音频0/2 微课0/2' },
});
ok(off.body.indexOf('今日积分 0/24') < 0 && off.body.indexOf('每日积分模式:关') >= 0,
'enabled=false 时只说明模式已关闭,不贴 0/24');
}
console.log('');
if (failed) {
console.log('✘ ' + failed + ' 项失败');
process.exit(1);
}
console.log('✔ 全部通过');
+239
View File
@@ -0,0 +1,239 @@
#!/usr/bin/env node
/**
* 每日积分(src/points.js)自测:纯数据逻辑,假时钟 + 假存储,不需要浏览器。
*
* 口径一旦错,日志和面板上的「今日积分 12/24」就是假的,而这种错在运行日志里
* 完全看不出来。用假时钟把「每日封顶」「同节不重复计」「跨日清零」「缺内容的类型不阻塞」
* 这些边界钉死。
*
* 用法:
* node dev/tests/points-test.mjs
* npm run test:points
*/
import {
POINT_RULES, POINTS_PER_TASK, MAX_DAILY_POINTS,
detectLessonType, apiTypeKey, createPointsTracker, nextTarget,
} from '../../src/points.js';
let failed = 0;
function ok(cond, name, extra) {
if (cond) console.log(' ✔ ' + name);
else { failed++; console.log(' ✘ ' + name + (extra ? ' → ' + extra : '')); }
}
function eq(actual, expect, name) {
ok(actual === expect, name, '期望 ' + JSON.stringify(expect) + ',实际 ' + JSON.stringify(actual));
}
/** 假存储:只实现 getItem / setItem,跨 tracker 实例复用即验证持久化 */
function fakeStorage() {
const mem = new Map();
return {
getItem: (k) => (mem.has(k) ? mem.get(k) : null),
setItem: (k, v) => { mem.set(k, String(v)); },
removeItem: (k) => { mem.delete(k); },
dump: () => Object.fromEntries(mem),
};
}
/** 假时钟:手动推进 */
function clock(start = new Date(2026, 10, 1, 9, 0, 0).getTime()) {
let t = start;
return {
now: () => t,
tick: (sec) => { t += sec * 1000; },
set: (d) => { t = d.getTime(); },
};
}
function newTracker(c, storage) {
return createPointsTracker({ now: c.now, storage: storage || fakeStorage() });
}
// ---------------------------------------------------------------------------
// 1. 规则与类型识别
// ---------------------------------------------------------------------------
console.log('规则与类型识别');
{
eq(POINTS_PER_TASK, 3, '每条任务 3 分');
eq(MAX_DAILY_POINTS, 24, '每日上限 1+3+2+2 = 8 条 × 3 = 24 分');
eq(POINT_RULES.map((r) => r.key).join(','), 'doc,video,audio,micro', '四类顺序:文档/视频/音频/微课');
eq(detectLessonType({ tag: '视频' }), 'video', '课时标签「视频」');
eq(detectLessonType({ tag: '文档' }), 'doc', '课时标签「文档」');
eq(detectLessonType({ tag: '课件' }), 'doc', '课时标签「课件」按文档算');
eq(detectLessonType({ tag: '音频' }), 'audio', '课时标签「音频」');
eq(detectLessonType({ tag: '微课' }), 'micro', '课时标签「微课」');
eq(detectLessonType({ hash: '#/video/play?kngId=x' }), 'video', '单视频路由');
eq(detectLessonType({ hash: '#/audio/play?kngId=x' }), 'audio', '单音频路由');
eq(detectLessonType({ hash: '#/ppt/play?kngId=x' }), 'doc', '单课件路由按文档算');
eq(detectLessonType({ hash: '#/document/play?kngId=x' }), 'doc', '文档路由');
eq(detectLessonType({ hash: '#/micro/play?kngId=x' }), 'micro', '微课路由');
eq(detectLessonType({ fileType: 'video' }), 'video', '接口 fileType=video');
eq(detectLessonType({ fileType: 'ppt' }), 'doc', '接口 fileType=ppt');
eq(detectLessonType({ tag: '视频', hash: '#/document/play' }), 'doc', '多来源冲突时以路由/精确类型为准(文档优先)');
eq(detectLessonType({ hash: '#/course/play?kngId=x' }), '', '多课时课程容器本身不算类型');
eq(detectLessonType({ tag: '考试' }), '', '考试节点不计积分');
eq(detectLessonType({}), '', '没有信息时返回空(不瞎猜)');
eq(apiTypeKey(1), 'doc', '列表接口 type=1 → 文档');
eq(apiTypeKey(2), 'video', '列表接口 type=2 → 视频');
eq(apiTypeKey(3), 'audio', '列表接口 type=3 → 音频');
eq(apiTypeKey(0), '', 'type=0 是课程容器,不计');
eq(apiTypeKey(99), '', '未知 type 不计');
}
// ---------------------------------------------------------------------------
// 2. 每日封顶:四类各自上限
// ---------------------------------------------------------------------------
console.log('每日封顶');
{
const c = clock();
const p = newTracker(c);
let n = 0;
for (let i = 0; i < 5; i++) if (p.record('doc', 'course-a|doc-' + i)) n++;
eq(n, 1, '文档每天只计 1 次');
eq(p.count('doc'), 1, '文档计数封顶 1');
eq(p.isFull('doc'), true, '文档封顶后 isFull');
eq(p.remaining('doc'), 0, '文档剩余额度 0');
n = 0;
for (let i = 0; i < 6; i++) if (p.record('video', 'course-a|v-' + i)) n++;
eq(n, 3, '视频每天只计 3 次');
n = 0;
for (let i = 0; i < 5; i++) if (p.record('audio', 'a-' + i)) n++;
eq(n, 2, '音频每天只计 2 次');
n = 0;
for (let i = 0; i < 5; i++) if (p.record('micro', 'm-' + i)) n++;
eq(n, 2, '微课每天只计 2 次');
eq(p.totalPoints(), 24, '四类满额 = 24 分');
eq(p.maxPoints(), 24, '每日满分 24');
eq(p.allFull(), true, '四类都满');
}
// ---------------------------------------------------------------------------
// 3. 去重:同一课时重复上报不重复计
// ---------------------------------------------------------------------------
console.log('去重');
{
const c = clock();
const p = newTracker(c);
eq(p.record('video', 'course-a|lesson-1'), true, '第一次记录成功');
eq(p.record('video', 'course-a|lesson-1'), false, '同一课时再次上报不计');
eq(p.count('video'), 1, '计数仍为 1');
eq(p.record('video', 'course-a|lesson-2'), true, '下一节正常计');
eq(p.count('video'), 2, '计数 2');
eq(p.record('video', ''), true, '没有课时 id 时不做去重(按事件计一次)');
eq(p.record('video', ''), false, '无 id 事件也受每日封顶限制');
eq(p.count('video'), 3, '视频封顶 3');
}
// ---------------------------------------------------------------------------
// 4. 跨日清零 + 持久化
// ---------------------------------------------------------------------------
console.log('跨日与持久化');
{
const c = clock();
const storage = fakeStorage();
const p = newTracker(c, storage);
p.record('doc', 'd1');
p.record('video', 'v1');
eq(p.totalPoints(), 6, '当天 2 条 = 6 分');
// 同一份存储、新的 tracker 实例(模拟刷新 / 运行器重启)
const p2 = newTracker(c, storage);
eq(p2.count('doc'), 1, '刷新后计数保留');
eq(p2.record('video', 'v1'), false, '刷新后同节仍不重复计');
// 跨日
c.set(new Date(2026, 10, 2, 0, 0, 5));
const p3 = newTracker(c, storage);
eq(p3.count('doc'), 0, '新的一天文档清零');
eq(p3.totalPoints(), 0, '新的一天积分清零');
eq(p3.record('video', 'v1'), true, '新的一天同一课时可以重新计');
}
// ---------------------------------------------------------------------------
// 5. 可用性:没内容的类型不阻塞「今天已完成」
// ---------------------------------------------------------------------------
console.log('可用性与完成判断');
{
const c = clock();
const p = newTracker(c);
p.record('doc', 'd1');
p.record('audio', 'a1');
p.record('video', 'v1');
p.record('video', 'v2');
p.record('video', 'v3');
// 音频每天 2 次,但全站只有 1 条音频;微课 0 条
const available = { doc: false, video: true, audio: false, micro: false };
eq(p.isFull('audio'), false, '音频只学了 1 次,还没到上限');
eq(p.done(available), true, '剩余额度的类型都没内容 → 今日任务已完成');
eq(p.done({ doc: true, video: true, audio: true, micro: true }), false, '还有可用内容时不算完成');
eq(p.done(), false, '不传可用性时按「都还有内容」处理,不误判完成');
}
// ---------------------------------------------------------------------------
// 6. 选类顺序:文档 → 视频 → 音频 → 微课;跳过已满/无内容
// ---------------------------------------------------------------------------
console.log('选类顺序');
{
const full = {};
const avail = { doc: true, video: true, audio: true, micro: true };
const isFull = (k) => !!full[k];
eq(nextTarget({ isFull, available: avail }).type, 'doc', '第一步先补文档');
full.doc = true;
eq(nextTarget({ isFull, available: avail }).type, 'video', '文档满后学视频');
full.video = true;
eq(nextTarget({ isFull, available: avail }).type, 'audio', '视频满后换音频');
full.audio = true;
eq(nextTarget({ isFull, available: avail }).type, 'micro', '音频满后换微课');
full.micro = true;
eq(nextTarget({ isFull, available: avail }), null, '全满 → 没有可做任务');
// 文档没内容:直接跳过(不能卡在缺内容的类型上)
const f2 = {};
eq(nextTarget({ isFull: (k) => !!f2[k], available: { doc: false, video: true, audio: true, micro: true } }).type, 'video', '文档无内容时跳过');
// 视频靠课程里的课时,不用单独库存;课程也没有时跳过
eq(nextTarget({ isFull: () => false, available: { doc: false, video: false, audio: true, micro: true } }).type, 'audio', '没有可学课程时跳过视频');
}
// ---------------------------------------------------------------------------
// 7. 关闭开关:完全不计数
// ---------------------------------------------------------------------------
console.log('开关');
{
const c = clock();
const p = createPointsTracker({ now: c.now, storage: fakeStorage(), enabled: false });
eq(p.isEnabled(), false, '初始关闭');
eq(p.record('video', 'v1'), false, '关闭时不计分');
eq(p.totalPoints(), 0, '关闭时积分 0');
p.setEnabled(true);
eq(p.record('video', 'v1'), true, '重新开启后可以计分');
eq(p.totalPoints(), 3, '开启后计 3 分');
}
// ---------------------------------------------------------------------------
// 8. 摘要文本
// ---------------------------------------------------------------------------
console.log('摘要');
{
const c = clock();
const p = newTracker(c);
p.record('doc', 'd1');
p.record('video', 'v1');
eq(p.summary(), '今日积分 6/24 · 文档1/1 视频1/3 音频0/2 微课0/2', '摘要含总分与各类进度');
eq(p.snapshot().total, 6, 'snapshot 给运行器用:总分');
eq(p.snapshot().max, 24, 'snapshot 给运行器用:满分');
eq(p.snapshot().progress.length, 4, 'snapshot 给运行器用:四类进度');
}
console.log('');
if (failed) {
console.log('每日积分自测:' + failed + ' 项失败');
process.exit(1);
}
console.log('每日积分自测:全部通过');
+4
View File
@@ -38,6 +38,10 @@ services:
YUN_XUE_TANG_TUI: "0"
# 本次最多完成几门课;0 = 不限
YUN_XUE_TANG_MAX_COURSES: "${YUN_XUE_TANG_MAX_COURSES:-100}"
# 任务结束时推 Bark 手机通知;不填则沿用 config/runner.config.mjs 里的 barkUrl
YUN_XUE_TANG_BARK_URL: "${YUN_XUE_TANG_BARK_URL:-}"
YUN_XUE_TANG_BARK_GROUP: "${YUN_XUE_TANG_BARK_GROUP:-}"
YUN_XUE_TANG_BARK_TTL: "${YUN_XUE_TANG_BARK_TTL:-}"
volumes:
# 持久化登录态(cookie / localStorage):删掉该目录等于重置登录与进度缓存
# 注意:与裸机运行共用同一个目录,容器内以 root 写入,宿主机上会是 root 所有
+32
View File
@@ -0,0 +1,32 @@
schema: spec-driven
# Project context (optional)
# This is shown to AI when creating artifacts.
# Add your tech stack, conventions, style guides, domain knowledge, etc.
# Example:
# context: |
# Tech stack: TypeScript, React, Node.js
# We use conventional commits
# Domain: e-commerce platform
# Per-artifact rules (optional)
# Add custom rules for specific artifacts.
# Example:
# rules:
# proposal:
# - Keep proposals under 500 words
# - Always include a "Non-goals" section
# tasks:
# - Break tasks into chunks of max 2 hours
# Per-operation guidance (optional)
# Add advisory guidance for how apply and archive work should be conducted.
# This is separate from artifact rules above.
# Example:
# operations:
# apply:
# guidance:
# - Keep test summaries concise
# archive:
# guidance:
# - Summarize the archive outcome before finishing
+2
View File
@@ -14,6 +14,8 @@
"test:e2e:play": "node dev/tests/real-e2e.mjs --play",
"test:tui": "node dev/tests/tui-test.mjs",
"test:study": "node dev/tests/study-test.mjs",
"test:points": "node dev/tests/points-test.mjs",
"test:notify": "node dev/tests/notify-test.mjs",
"test:exam": "node dev/tests/exam-test.mjs",
"docker:build": "node scripts/build-docker.mjs",
"docker:check": "node scripts/build-docker.mjs --check",
+35 -3
View File
@@ -26,6 +26,7 @@ const DEFAULTS = {
maxCourses: 0, // 0 = 不限(一直刷到没有未学完的课)
budgetMinutes: 0, // 0 = 不限
preferShort: true,
pointsMode: true, // 每日积分模式:按课时类型计分,四类封顶后停止(文档1/视频3/音频2/微课2)
restartMinutes: 0, // 0 = 停下就退出
idleRestartMinutes: 30,
origin: 'https://kfmic.yunxuetang.cn',
@@ -39,6 +40,12 @@ const DEFAULTS = {
logMaxBytes: 5 * 1024 * 1024,
tui: true, // true = 交互式终端里启用面板;非 TTY 自动退化为逐行日志
color: true, // false = 面板不用 ANSI 颜色(也认 NO_COLOR 环境变量)
// Bark 推送:运行器自己收尾时发一条手机通知(正常刷完 / 卡死 / 登录失败)。
// barkUrl 是含设备 key 的地址(https://api.day.app/<key>),留空 = 不推送。
// key 等价于「谁能往你手机推通知」,别提交到公开仓库;可用环境变量覆盖。
barkUrl: '',
barkGroup: '', // 通知分组(Bark App 里按组折叠),留空 = Bark 默认
barkTtl: 0, // 通知在 Bark 服务端保留多少秒;0 = Bark 默认
};
const argv = process.argv.slice(2);
@@ -102,9 +109,9 @@ if (CONFIG_FILE) {
// ---------------------------------------------------------------------------
// 命令行解析:--key value / --key=value / --flag
// ---------------------------------------------------------------------------
const BOOL_KEYS = ['preferShort', 'headless', 'check', 'tui', 'color'];
const NUM_KEYS = ['maxCourses', 'budgetMinutes', 'restartMinutes', 'idleRestartMinutes', 'port', 'logMaxBytes'];
const STR_KEYS = ['origin', 'url', 'profile', 'logFile', 'chrome', 'extraArgs', 'config'];
const BOOL_KEYS = ['preferShort', 'pointsMode', 'headless', 'check', 'tui', 'color'];
const NUM_KEYS = ['maxCourses', 'budgetMinutes', 'restartMinutes', 'idleRestartMinutes', 'port', 'logMaxBytes', 'barkTtl'];
const STR_KEYS = ['origin', 'url', 'profile', 'logFile', 'chrome', 'extraArgs', 'config', 'barkUrl', 'barkGroup'];
/** kebab-case → camelCase:--max-courses → maxCourses */
function toCamel(flag) {
@@ -207,6 +214,7 @@ merged.idleRestartMinutes = envNum('YUN_XUE_TANG_IDLE_RESTART_MINUTES', merged.i
merged.port = envNum('YUN_XUE_TANG_CDP_PORT', merged.port);
merged.logMaxBytes = envNum('YUN_XUE_TANG_LOG_MAX_BYTES', merged.logMaxBytes);
merged.preferShort = envBool('YUN_XUE_TANG_PREFER_SHORT', merged.preferShort);
merged.pointsMode = envBool('YUN_XUE_TANG_POINTS_MODE', merged.pointsMode);
merged.headless = envBool('YUN_XUE_TANG_HEADLESS', merged.headless);
merged.origin = envStr('YUN_XUE_TANG_ORIGIN', merged.origin);
merged.url = envStr('YUN_XUE_TANG_URL', merged.url);
@@ -216,6 +224,9 @@ merged.chrome = envStr('YUN_XUE_TANG_CHROME_BIN', merged.chrome);
merged.extraArgs = envStr('YUN_XUE_TANG_EXTRA_ARGS', merged.extraArgs);
merged.tui = envBool('YUN_XUE_TANG_TUI', merged.tui);
merged.color = envBool('YUN_XUE_TANG_COLOR', merged.color);
merged.barkTtl = envNum('YUN_XUE_TANG_BARK_TTL', merged.barkTtl);
merged.barkUrl = envStr('YUN_XUE_TANG_BARK_URL', merged.barkUrl);
merged.barkGroup = envStr('YUN_XUE_TANG_BARK_GROUP', merged.barkGroup);
// 命令行最后覆盖
const numBad = [];
@@ -243,6 +254,7 @@ if (numBad.length === 0) {
if (!(merged.restartMinutes >= 0)) problems.push('restartMinutes 不能为负,收到 ' + merged.restartMinutes);
if (!(merged.idleRestartMinutes >= 0)) problems.push('idleRestartMinutes 不能为负,收到 ' + merged.idleRestartMinutes);
if (!(merged.logMaxBytes >= 0)) problems.push('logMaxBytes 不能为负,收到 ' + merged.logMaxBytes);
if (!(merged.barkTtl >= 0)) problems.push('barkTtl 不能为负,收到 ' + merged.barkTtl);
}
if (unknownFlags.length) {
const uniq = [...new Set(unknownFlags)];
@@ -285,6 +297,7 @@ export const WANT_VISIBLE = !merged.headless;
export const VISIBLE = WANT_VISIBLE && hasDisplay();
export const PREFER_SHORT = merged.preferShort;
export const POINTS_MODE = merged.pointsMode;
/** 脚本自己停下后等待多少分钟再开新一轮(0 = 直接退出) */
export const RESTART_MINUTES = merged.restartMinutes;
/** 连续多少分钟没有任何进展判定卡死 */
@@ -296,8 +309,21 @@ export const LOG_MAX_BYTES = merged.logMaxBytes;
export const EXTRA_ARGS = String(merged.extraArgs || '').split(/\s+/).filter(Boolean);
/** 配置文件里指定的浏览器路径(空 = 自动探测;优先级低于 YUN_XUE_TANG_CHROME_BIN,见 browser.mjs) */
export const CHROME_BIN = merged.chrome || '';
/** Bark 推送地址(含设备 key);空 = 不推送 */
export const BARK_URL = String(merged.barkUrl || '').trim();
export const BARK_GROUP = String(merged.barkGroup || '').trim();
export const BARK_TTL = merged.barkTtl;
export const WARNINGS = configWarnings;
/** 打印/展示 Bark 地址时把路径里的第一段(设备 key)打码,避免日志泄露推送权限 */
export function maskBarkUrl(url) {
const s = String(url || '');
if (!s) return '(未配置)';
const m = s.match(/^(https?:\/\/[^/]+)(\/.*)?$/i);
if (!m) return '(已配置)';
return m[1] + (m[2] || '').replace(/^\/([^/?]*)/, '/***');
}
/** 面板是否带颜色:配置 / 环境变量 / 行业惯例的 NO_COLOR 都生效 */
export const COLOR = merged.color && !process.env.NO_COLOR;
@@ -329,12 +355,14 @@ export function describeRun() {
maxCourses: MAX_COURSES > 0 ? MAX_COURSES : '不限',
budgetMinutes: BUDGET_MINUTES > 0 ? BUDGET_MINUTES : '不限',
preferShort: PREFER_SHORT,
pointsMode: POINTS_MODE,
restartMinutes: RESTART_MINUTES,
idleRestartMinutes: IDLE_RESTART_MINUTES,
profileDir: PROFILE_DIR,
logFile: LOG_FILE,
tui: TUI,
color: COLOR,
bark: BARK_URL ? (maskBarkUrl(BARK_URL) + (BARK_GROUP ? '(分组 ' + BARK_GROUP + ')' : '')) : '(未配置)',
};
}
@@ -345,6 +373,7 @@ export function helpText() {
['maxCourses', '--max-courses', 'YUN_XUE_TANG_MAX_COURSES', MAX_COURSES, '本次最多完成几门课;0 = 不限'],
['budgetMinutes', '--budget-minutes', 'YUN_XUE_TANG_BUDGET_MINUTES', BUDGET_MINUTES, '跑多少分钟后收尾;0 = 不限'],
['preferShort', '--prefer-short', 'YUN_XUE_TANG_PREFER_SHORT', PREFER_SHORT, '优先总时长最短的课程'],
['pointsMode', '--points-mode', 'YUN_XUE_TANG_POINTS_MODE', POINTS_MODE, '每日积分模式:文档1/视频3/音频2/微课2,封顶即停'],
['restartMinutes', '--restart-minutes', 'YUN_XUE_TANG_RESTART_MINUTES', RESTART_MINUTES, '脚本停下后等几分钟开新一轮;0 = 退出'],
['idleRestartMinutes', '--idle-restart-minutes', 'YUN_XUE_TANG_IDLE_RESTART_MINUTES', IDLE_RESTART_MINUTES, '多少分钟无进展判卡死'],
['origin', '--origin', 'YUN_XUE_TANG_ORIGIN', ORIGIN, '站点根地址'],
@@ -358,6 +387,9 @@ export function helpText() {
['color', '--no-color', 'YUN_XUE_TANG_COLOR', COLOR ? '开' : '关', '面板是否用 ANSI 颜色(也认 NO_COLOR)'],
['logFile', '--log-file', 'YUN_XUE_TANG_LOG_FILE', LOG_FILE, '日志文件'],
['logMaxBytes', '--log-max-bytes', 'YUN_XUE_TANG_LOG_MAX_BYTES', LOG_MAX_BYTES, '单文件上限,超出轮转'],
['barkUrl', '--bark-url', 'YUN_XUE_TANG_BARK_URL', maskBarkUrl(BARK_URL), 'Bark 推送地址(含设备 key);留空 = 不推送'],
['barkGroup', '--bark-group', 'YUN_XUE_TANG_BARK_GROUP', BARK_GROUP || '(Bark 默认)', 'Bark 通知分组'],
['barkTtl', '--bark-ttl', 'YUN_XUE_TANG_BARK_TTL', BARK_TTL, 'Bark 通知在服务端保留秒数;0 = 默认'],
['(字段 check)', '--check', '', CHECK_ONLY, '只做环境自检,不动进度'],
['(无字段)', '--config', 'YUN_XUE_TANG_CONFIG', CONFIG_FILE || '(内置默认)', '指定配置文件路径'],
];
+5
View File
@@ -17,6 +17,7 @@
* page.mjs 注入后要调用的页面 JS 表达式 + page 求值封装
* session.mjs 单次会话:起浏览器 → 注入 → 自动登录 → 刷课 → 监控 → 收尾
* selfcheck.mjs --check 的只读环境自检
* notify.mjs 任务结束时的 Bark 手机通知
* supervisor.mjs 崩溃重启循环与退出码
* tui.mjs 交互式终端面板(框线 + 进度条,q 退出;非 TTY 自动关闭)
*
@@ -42,6 +43,7 @@
* YUN_XUE_TANG_CHROME_BIN Chrome/Chromium 可执行文件路径(默认自动探测)
* YUN_XUE_TANG_EXTRA_ARGS 追加给浏览器的命令行参数(空格分隔)
* YUN_XUE_TANG_PREFER_SHORT 1/0,是否优先短课程(默认 1)
* YUN_XUE_TANG_POINTS_MODE 1/0,每日积分模式(默认 1;文档1/视频3/音频2/微课2,封顶即停)
* YUN_XUE_TANG_RESTART_MINUTES 脚本停止/无进展后等待多久重新开始(0 = 直接退出,默认 0)
* YUN_XUE_TANG_IDLE_RESTART_MINUTES 连续无进展多少分钟后判定卡死(默认 30)
* YUN_XUE_TANG_LOG_FILE 日志文件路径(默认 ./run-logs/headless.log)
@@ -49,6 +51,9 @@
* YUN_XUE_TANG_HAS_DISPLAY 0/1,强制认定「有没有图形显示会话」(自动判断不准时用)
* YUN_XUE_TANG_TUI 0/1,是否启用终端面板(默认 1,非 TTY 时无效)
* YUN_XUE_TANG_COLOR 0/1,面板是否带颜色(也认 NO_COLOR)
* YUN_XUE_TANG_BARK_URL Bark 推送地址(含设备 key);留空 = 不推送
* YUN_XUE_TANG_BARK_GROUP Bark 通知分组(默认 Bark 自己的分组)
* YUN_XUE_TANG_BARK_TTL Bark 通知在服务端保留多少秒(0 = 默认)
*
* 退出码:0 正常收尾 / 1 无进展卡死 / 2 环境或参数问题 / 3 连续登录失败
*/
+114
View File
@@ -0,0 +1,114 @@
// Bark 推送:运行器自己收尾时把结果发到手机。
//
// 只覆盖「运行器自己结束」的场景(正常刷完 / 长时间无进展 / 登录失败),
// 手动 Ctrl+C 主动停止不发:人就在键盘前,不需要再提醒一次。
// 通知是附加信息:发送失败只记告警,绝不影响退出码,也不阻塞下一次会话。
//
// Bark 接口:GET https://api.day.app/<key>/<title>/<body>?group=<分组>&ttl=<秒>
/** 单次请求超时:Bark 正常在 1 秒内返回,卡住就当失败,别拖慢收尾 */
export const BARK_TIMEOUT_MS = 8000;
function withParam(url, key, val) {
if (val === '' || val == null) return url;
// 地址里已经写了同名参数(例如配置里直接粘了完整 curl 地址)就不再追加
if (new RegExp('[?&]' + key + '=').test(url)) return url;
return url + (url.includes('?') ? '&' : '?') + key + '=' + encodeURIComponent(val);
}
/**
* 拼 Bark 请求地址。
* base 可以是:
* · 含设备 key 的根地址:https://api.day.app/KEY
* · 带 {title}/{body} 占位符的完整模板:https://api.day.app/KEY/{title}/{body}?group=x
*/
export function buildBarkUrl(base, title, body, opts = {}) {
let url = String(base || '').trim();
if (!url) return '';
const t = encodeURIComponent(title || '');
const b = encodeURIComponent(body || '');
if (/\{title\}|\{body\}/.test(url)) {
url = url.replace(/\{title\}/g, t).replace(/\{body\}/g, b);
} else {
url = url.replace(/\/+$/, '') + '/' + t + '/' + b;
}
url = withParam(url, 'group', opts.group);
url = withParam(url, 'ttl', opts.ttl ? String(opts.ttl) : '');
return url;
}
/** 收尾通知的标题与正文:把本次刷课的结论压缩成手机上能一眼看懂的两三行 */
export function buildFinishMessage(result) {
const r = result || {};
const kind = r.kind || 'done';
const title = kind === 'login'
? '云学堂助手:登录失败'
: kind === 'stalled' ? '云学堂助手:长时间无进展'
: '云学堂助手:任务完成';
const lines = [];
// 积分模式关闭时 snapshot 里仍是 0/24,直接贴出来会让人以为今天一条都没刷到
if (r.points && r.points.enabled === false) lines.push('每日积分模式:关');
else if (r.points && r.points.text) lines.push(String(r.points.text));
// 登录失败时还没开始刷,「完成 0 门 · 用时 0 秒」只会让人以为跑过一轮
if (kind !== 'login') {
const secs = Number(r.elapsed) || 0;
const used = secs >= 60
? Math.floor(secs / 60) + ' 分 ' + (secs % 60) + ' 秒'
: secs + ' 秒';
lines.push('完成 ' + (Number(r.completed) || 0) + ' 门 · 用时 ' + used);
}
if (r.finishReason) lines.push(String(r.finishReason));
return { title, body: lines.join('\n') };
}
/**
* 发送 Bark 通知。永远不抛异常。
* @returns {Promise<{ok?:boolean, skipped?:boolean, status?:number}>}
*/
export async function sendBark(opts) {
const o = opts || {};
const log = o.log || (() => {});
const warn = o.warn || (() => {});
const url = buildBarkUrl(o.url, o.title, o.body, { group: o.group, ttl: o.ttl });
if (!url) return { skipped: true };
if (typeof fetch !== 'function') {
warn('当前 Node 没有全局 fetch(需要 Node 18+),跳过 Bark 通知');
return { skipped: true };
}
try {
const res = await fetch(url, {
method: 'GET',
signal: AbortSignal.timeout(o.timeoutMs || BARK_TIMEOUT_MS),
});
let data = null;
try { data = await res.json(); } catch (e) { /* 非 JSON 响应按状态码判断 */ }
const code = data && data.code != null ? Number(data.code) : 200;
if (!res.ok || code !== 200) {
warn('Bark 通知发送失败:HTTP ' + res.status +
(data && data.message ? '(' + data.message + ')' : ''));
return { ok: false, status: res.status };
}
log('已发送 Bark 通知:' + o.title);
return { ok: true, status: res.status };
} catch (e) {
warn('Bark 通知发送失败:' + (e && e.message ? e.message : e));
return { ok: false };
}
}
/** 按运行器配置发送收尾通知;没配 barkUrl 时是空操作 */
export function notifyRunFinished(cfg, result, io) {
if (!cfg || !cfg.BARK_URL) return Promise.resolve({ skipped: true });
const msg = buildFinishMessage(result);
return sendBark({
url: cfg.BARK_URL,
group: cfg.BARK_GROUP,
ttl: cfg.BARK_TTL,
title: msg.title,
body: msg.body,
log: io && io.log,
warn: io && io.warn,
});
}
+9 -2
View File
@@ -104,6 +104,8 @@ export const EXPR_SNAPSHOT = `JSON.stringify((function () {
return m ? Number(m[1]) : null;
})(),
status: (document.getElementById('yun-xue-tang-status') || {}).textContent || '',
// 每日积分:{ enabled, total, max, progress:[{label,count,cap}], text }
points: (a.points && a.points.snapshot ? a.points.snapshot() : null),
doneCount: Object.keys(a.S.completedTitles || {}).length,
retryCount: Object.keys(a.S.courseRetries || {}).length,
retryWait: (a.retryWaitSeconds ? a.retryWaitSeconds() : 0),
@@ -123,6 +125,8 @@ export const EXPR_FINAL_STATS = `JSON.stringify((function () {
completed: a.S.completedThisRun,
doneCount: Object.keys(a.S.completedTitles || {}).length,
retryCount: Object.keys(a.S.courseRetries || {}).length,
// 每日积分:收尾通知里要带上「今日积分 X/24 · 各类次数」
points: (a.points && a.points.snapshot ? a.points.snapshot() : null),
};
})())`;
@@ -137,11 +141,14 @@ export const EXPR_PAUSE_AND_SAVE = `(function () {
export const exprSetMaxCourses = (max) =>
`(function(){ var a = window.__yunXueTangAuto; if (a && a.CFG) a.CFG.maxCourses = ${Number(max)}; return true; })()`;
/** 启动 / 接续批量刷课,同时同步「优先短课程」偏好 */
export const exprStartBatch = (preferShort) => `(function () {
/** 启动 / 接续批量刷课,同时同步「优先短课程」「每日积分」偏好 */
export const exprStartBatch = (preferShort, pointsMode) => `(function () {
var a = window.__yunXueTangAuto;
try { localStorage.setItem('yun-xue-tang-prefer-short', '${preferShort ? '1' : '0'}'); } catch (e) {}
try { localStorage.setItem('yun-xue-tang-daily-points-mode', '${pointsMode ? '1' : '0'}'); } catch (e) {}
a.state.preferShortCourses = ${preferShort ? 'true' : 'false'};
a.state.pointsEnabled = ${pointsMode ? 'true' : 'false'};
try { a.points.setEnabled(${pointsMode ? 'true' : 'false'}); } catch (e) {}
a.startBatch();
return true;
})()`;
+8 -3
View File
@@ -212,10 +212,11 @@ export async function runSession(o) {
return;
}
if (!st.batchRunning && st.route !== 'other') {
const ok = await page.tryEval(exprStartBatch(cfg.PREFER_SHORT));
const ok = await page.tryEval(exprStartBatch(cfg.PREFER_SHORT, cfg.POINTS_MODE));
if (ok) {
tui.set({ phase: '刷课中', tone: 'ok' });
log('已启动列表刷课' + (cfg.PREFER_SHORT ? '(优先短课程)' : ''));
log('已启动列表刷课' + (cfg.PREFER_SHORT ? '(优先短课程)' : '') +
(cfg.POINTS_MODE ? '(每日积分模式)' : ''));
}
}
};
@@ -239,6 +240,7 @@ export async function runSession(o) {
' 上限 ' + (cfg.MAX_COURSES > 0 ? cfg.MAX_COURSES + ' 门' : '不限') +
' 预算 ' + (cfg.BUDGET_MINUTES > 0 ? cfg.BUDGET_MINUTES + ' 分钟' : '不限') +
' 短课程优先 ' + (cfg.PREFER_SHORT ? '开' : '关') +
' 每日积分 ' + (cfg.POINTS_MODE ? '开' : '关') +
' 无进展 ' + cfg.IDLE_RESTART_MINUTES + ' 分钟');
watchdog = setInterval(() => {
@@ -363,5 +365,8 @@ export async function runSession(o) {
unregister();
activeCleanup = null;
return { finishReason, limitReached, completed: final.completed || 0, elapsed, injected, ok: true };
return {
finishReason, limitReached, completed: final.completed || 0, elapsed, injected, ok: true,
points: final.points || null,
};
}
+35
View File
@@ -8,6 +8,7 @@ import { runSession, disposeActiveSession } from './session.mjs';
import { openLog } from './log.mjs';
import { noDisplayReason, platformName } from './platform.mjs';
import { createTui } from './tui.mjs';
import { notifyRunFinished } from './notify.mjs';
const RETRY_BASE_MS = 15000;
const RETRY_MAX_MS = 120000;
@@ -58,6 +59,30 @@ export async function runSupervisor(o) {
let attempt = 0;
let last = null;
let lastNotified = '';
/**
* 收尾 Bark 通知。通知识别键相同的只发一次:配了 restartMinutes 时,
* 「今日积分已学完」这类结论会在每一轮重启后原样重复,没必要每小时推一次。
* 用户按 Ctrl+C 主动停的不发;自检模式不发。
*/
const notify = async (result) => {
if (stop.stopping || cfg.CHECK_ONLY) return;
const key = [result.kind, result.finishReason, result.completed,
result.points && result.points.text].join('|');
if (key === lastNotified) return;
lastNotified = key;
await notifyRunFinished(cfg, result, { log, warn });
};
/** 一次会话的结果 → 通知入参:卡死和无进展在退出码里是两种结论,标题也不同 */
const finishResult = (s) => ({
kind: /没有任何进展/.test((s && s.finishReason) || '') ? 'stalled' : 'done',
finishReason: (s && s.finishReason) || '',
completed: (s && s.completed) || 0,
elapsed: (s && s.elapsed) || 0,
points: s && s.points,
});
/** 收尾时先把面板收掉,退出日志和退出码提示才会逐行打印出来 */
const finishTui = (phase, tone) => {
@@ -73,6 +98,10 @@ export async function runSupervisor(o) {
last = await runSession({ ...o, cfg, tui });
if (stop.stopping) break;
if (cfg.CHECK_ONLY) break;
// 每轮会话自己结束就先推一次:配了 restartMinutes 时进程不会退出,
// 只在最终收尾推就等于永远不推。重复结论由 notify() 的识别键挡掉。
tui.set({ phase: '发送 Bark 通知', tone: 'info' });
await notify(finishResult(last));
// 正常结束:只有「脚本自己停了 / 无进展」且配了重启间隔才再来一轮
const restartable = !last.limitReached && cfg.RESTART_MINUTES > 0;
if (!restartable) break;
@@ -90,6 +119,8 @@ export async function runSupervisor(o) {
tui.set({ phase: '会话异常,准备重试', tone: 'error' });
// 连登 5 次失败基本都是密码错 / 要验证码,重试没意义,直接用专门的退出码结束
if (e && e.message && /连续 \d+ 次登录失败/.test(e.message)) {
tui.set({ phase: '发送 Bark 通知', tone: 'info' });
await notify({ kind: 'login', finishReason: e.message, completed: 0, elapsed: 0 });
finishTui('登录失败,检查账号密码 / 验证码', 'error');
return { exitCode: 3, last };
}
@@ -107,6 +138,10 @@ export async function runSupervisor(o) {
const phase = cfg.CHECK_ONLY
? (exitCode === 0 ? '自检通过' : '自检失败')
: stalled ? '退出:长时间无进展' : '正常收尾';
if (last) {
tui.set({ phase: '发送 Bark 通知', tone: 'info' });
await notify(finishResult(last));
}
finishTui(phase, exitCode === 0 ? 'ok' : (stalled ? 'warn' : 'error'));
log('=== 运行器退出 ===');
+6
View File
@@ -181,6 +181,7 @@ export function createTui(opts = {}) {
studySeconds: 0, // 学习时长:只累加视频真正在播的时间
creditEarned: 0, // 获得学分:只算本次运行里完成(刷完)的课程
credit: null, // 当前课程可得多少学分(平台只在播放期间写在倒计时文案里)
points: null, // 每日积分:{ enabled, total, max, progress, text }
injected: 0,
logFile: opts.logFile || '',
startedAt: Date.now(),
@@ -296,6 +297,10 @@ export function createTui(opts = {}) {
const parts = [C.cyan('已学 ' + formatDuration(state.studySeconds))];
parts.push(C.green('学分 ' + study.creditText(state.creditEarned)));
const used = () => textWidth(parts.join(' · '));
if (state.points && state.points.enabled) {
const p = '积分 ' + state.points.total + '/' + state.points.max;
if (used() + 3 + textWidth(p) <= width) parts.push(C.cyan(p));
}
if (state.credit != null) {
const now = '本门 ' + study.creditText(state.credit);
if (used() + 3 + textWidth(now) <= width) parts.push(now);
@@ -529,6 +534,7 @@ export function createTui(opts = {}) {
state.studySeconds = st.studySeconds;
state.creditEarned = st.creditEarned;
state.credit = st.credit;
state.points = s.points || null;
state.course = pick(s.course, '');
state.lesson = pick(s.lesson, '');
+2
View File
@@ -29,7 +29,9 @@ export const LS_PENDING = 'yun-xue-tang-auto-start-after-login';
// ---- sessionStorage:本次进度 + 本次运行状态(换标签页/重启即作废) ----
export const SS_RUN_STATE = 'yun-xue-tang-run-state-v3';
export const SS_SHORT_CATALOG = 'yun-xue-tang-short-catalog-v1';
export const SS_POINTS_INVENTORY = 'yun-xue-tang-points-inventory-v1';
export const SHORT_CATALOG_TTL = 5 * 60 * 1000;
export const POINTS_INVENTORY_TTL = 5 * 60 * 1000;
// 旧版本把「进度 + 运行意图」整块塞进 localStorage,只用于一次性迁移(迁移后即删除)
export const LEGACY_LS_BATCH = 'yun-xue-tang-batch-v2';
+51 -2
View File
@@ -1,6 +1,8 @@
// ======== 课程页 ========
import { CFG, TAG } from './config.js';
import { R, S, saveRunState, PHASE_LEARNING } from './state.js';
import { R, S, state, points, saveRunState, PHASE_LEARNING } from './state.js';
import { detectLessonType, pointLabel } from './points.js';
import { pointsAfterLesson } from './list.js';
import { goToList, mediaPage } from './route.js';
import { courseIdFromUrl, norm, textOf, truncate, findVisibleClickable } from './utils.js';
import { later } from './lifecycle.js';
@@ -15,6 +17,40 @@ import {
import { examTick, examPhase } from './exam.js';
import { completeCurrent, failCurrent } from './complete.js';
// ---- 每日积分:把「课时完成」折算成一次任务 ----
// 类型在播放期间就按 lessonId 缓存下来:平台记账或自动切节后页面可能已经
// 跳到下一节,事后再读目录就不知道刚完成的是哪一类了。
function pointLessonId(key) {
const courseId = (S.activeCourse && S.activeCourse.id) || courseIdFromUrl() || '';
return courseId + '|' + (key || 'media');
}
function rememberLessonType(key) {
if (!state.pointsEnabled) return;
const li = lessonActiveLi();
const tagEl = li ? li.querySelector('.tag-type') : null;
const type = detectLessonType({
tag: tagEl ? textOf(tagEl) : '',
hash: location.hash,
});
if (!type) return;
R.lessonType = type;
R.lessonTypes[pointLessonId(key)] = type;
}
// 记一次课时完成;返回计入的类型(没计入/识别不出来返回 '')
function recordLessonPoint(key) {
if (!state.pointsEnabled) return '';
const id = pointLessonId(key);
const type = R.lessonTypes[id] || R.lessonType || detectLessonType({ hash: location.hash });
if (!type) return '';
if (!points.record(type, id)) return '';
const text = points.snapshot().text;
console.log(TAG, '积分 +3:' + pointLabel(type) + '(' + text + ')');
setStatus('积分 +3:' + pointLabel(type) + '(' + text + ')');
return type;
}
export function courseTick() {
R.listWithCurrentSince = 0;
if (!S.activeCourse) {
@@ -86,6 +122,8 @@ export function courseTick() {
if (!examPhase() && !isSummaryComplete() && enterPendingExamLesson()) return;
// 6) 整门课程是否已完成 / 平台是否刚记录了一节
// 先把当前课时的类型记下来,后面平台记账/课程完成时才知道该给哪一类计分。
rememberLessonType(readActiveLessonKey());
const summary = readSummary();
const prevSummaryX = R.lastSummary ? R.lastSummary.x : -1;
if (summary) {
@@ -95,6 +133,7 @@ export function courseTick() {
const confirmed = !!(R.lastSummary && R.lastSummary.complete);
R.lastSummary = summary;
if (confirmed) {
recordLessonPoint(R.waitLessonKey || R.lastLessonKey);
completeCurrent();
return;
}
@@ -108,6 +147,11 @@ export function courseTick() {
const curKey = readActiveLessonKey();
R.lastSummary = summary;
// 平台刚记录了一节 → 按这一节的类型计一次积分
const pointType = (!isMedia && summary.kind !== 'percent')
? recordLessonPoint(prevKey) : '';
if (pointType && pointsAfterLesson(pointType)) return;
// 单视频/音频页的百分比是播放进度,不是「一节学完」,不能据此切节
if (!isMedia && summary.kind !== 'percent' && (!prevKey || curKey === prevKey)) {
// 平台已记账但没有自动切节 → 脚本主动切下一节
@@ -209,6 +253,7 @@ export function courseTick() {
}
R.waitStart = 0;
R.lastProgressAt = Date.now();
recordLessonPoint(R.waitLessonKey || R.lastLessonKey);
completeCurrent();
return;
}
@@ -219,6 +264,8 @@ export function courseTick() {
R.lastLessonKey = newKey;
R.doneLatchKey = '';
R.lastProgressAt = Date.now();
const pointType = recordLessonPoint(R.waitLessonKey);
if (pointType && pointsAfterLesson(pointType)) return;
setStatus('已自动进入下一节');
return;
}
@@ -227,9 +274,10 @@ export function courseTick() {
if (!isMedia && s2 && s2.x > R.waitSummaryX) {
R.waitStart = 0;
R.lastProgressAt = Date.now();
const pointType = recordLessonPoint(R.waitLessonKey || R.lastLessonKey);
if (s2.complete) {
completeCurrent();
} else {
} else if (!pointType || !pointsAfterLesson(pointType)) {
advanceLesson();
}
return;
@@ -304,6 +352,7 @@ export function advanceLesson() {
const s = readSummary();
if (s && s.complete) {
recordLessonPoint(R.waitLessonKey || R.lastLessonKey);
completeCurrent();
} else {
setStatus('没有找到下一节,等待课程完成…');
+5 -2
View File
@@ -1,7 +1,7 @@
// ======== 主循环 ========
'use strict';
import { CFG, VERSION, TAG } from './config.js';
import { R, S, state, saveRunState, flushRunState, invalidateShortCatalog } from './state.js';
import { R, S, state, points, saveRunState, flushRunState, invalidateShortCatalog } from './state.js';
import { every, later, onWindow } from './lifecycle.js';
import { courseIdFromUrl } from './utils.js';
import { route, mediaPage } from './route.js';
@@ -12,6 +12,7 @@ import {
chooseShortCourse, sortCardsByDuration, formatDuration,
pendingShortItems, scanCards, currentPage, maxPageNumber,
startCourse, jumpToPage, nextPage,
ensurePointsInventory, pointsAvailability, pointsDone, pointsTarget, pointsAfterLesson, startStandalone,
} from './list.js';
import { courseTick, manualCourseTick } from './course.js';
import {
@@ -76,7 +77,7 @@ if (window.top !== window.self) {
try {
Object.defineProperty(window, '__yunXueTangAuto', {
value: {
S, R, state, tick, save: saveRunState, flush: flushRunState, route,
S, R, state, points, tick, save: saveRunState, flush: flushRunState, route,
// CFG 暴露给无头运行器:可用 --max / YUN_XUE_TANG_MAX_COURSES 覆盖本次运行的门数上限
CFG,
mediaPage, courseIdFromUrl,
@@ -98,6 +99,8 @@ try {
completeCurrent, failCurrent, skipCurrent, courseSkipped,
// 以下供开发/真机测试驱动内部路径使用:
scanCards, currentPage, maxPageNumber, startCourse, jumpToPage, nextPage,
ensurePointsInventory, pointsAvailability, pointsDone, pointsTarget,
pointsAfterLesson, startStandalone,
listTick, courseTick, manualCourseTick,
loginFields, findLoginVm, checkLoginAgreement, setNativeValue,
saveCreds, loadCreds, clearSavedCreds,
+275 -3
View File
@@ -1,9 +1,13 @@
// ======== 列表页 ========
import { SHORT_CATALOG_TTL, SS_SHORT_CATALOG, TAG } from './config.js';
import {
R, S, state, saveRunState, setTargetCatalogUrl, resetCourseRuntime, invalidateShortCatalog,
PHASE_ENTERING, PHASE_LEARNING, PHASE_IDLE,
SHORT_CATALOG_TTL, SS_SHORT_CATALOG, SS_POINTS_INVENTORY, POINTS_INVENTORY_TTL, TAG,
} from './config.js';
import {
R, S, state, points, saveRunState, setTargetCatalogUrl, resetCourseRuntime,
invalidateShortCatalog, PHASE_ENTERING, PHASE_LEARNING, PHASE_IDLE,
} from './state.js';
import { apiTypeKey, detectLessonType, nextTarget, pointLabel, POINT_RULES } from './points.js';
import { goToList } from './route.js';
import { norm, textOf, truncate } from './utils.js';
import { clickNode } from './player.js';
import { setStatus, updatePanel } from './panel.js';
@@ -352,6 +356,247 @@ export function shortFallback(reason) {
}
}
// ======== 每日积分:文档/音频/微课库存 ========
// 列表默认只显示课程容器(fileType=course),文档/音频/微课是单条知识,
// 要用列表接口的 type 过滤(1=文档 2=视频 3=音频,更高编号留给微课)单独找。
// 只读未学完的条目;视频额度不靠这里(靠课程里的视频课时)。
function emptyPointsInventory() {
return { at: Date.now(), doc: [], audio: [], micro: [] };
}
function pointsInventoryCacheKey(vm) {
return String((vm && vm.collegeId) || localStorage.getItem('orgId') || '');
}
function readPointsInventory(key) {
try {
const raw = sessionStorage.getItem(SS_POINTS_INVENTORY);
if (!raw) return null;
const obj = JSON.parse(raw);
if (!obj || obj.key !== key || !obj.doc || !obj.audio || !obj.micro) return null;
if (Date.now() - (obj.at || 0) > POINTS_INVENTORY_TTL) return null;
return obj;
} catch (e) {
return null;
}
}
function writePointsInventory(inv, key) {
if (!inv) return;
try {
sessionStorage.setItem(SS_POINTS_INVENTORY, JSON.stringify({
key: key, at: inv.at, doc: inv.doc, audio: inv.audio, micro: inv.micro,
}));
} catch (e) { /* 容量不足时只用内存库存 */ }
}
function routeForFileType(fileType) {
const s = String(fileType || '').toLowerCase();
if (s === 'audio') return 'audio/play';
if (s === 'video') return 'video/play';
if (s === 'document' || s === 'doc') return 'document/play';
if (s === 'article') return 'article/play';
if (/micro/.test(s)) return 'micro/play';
return 'ppt/play';
}
// 一次读齐文档/音频/微课库存。单类失败不影响其它类;全失败才算读取失败。
async function fetchPointsInventory(vm) {
const req = shortCatalogRequest(vm);
const baseBody = JSON.parse(req.body);
const api = shortApiBase();
const inv = emptyPointsInventory();
const seen = new Set();
const types = [1, 3, 4, 5, 6, 7, 8];
let failed = 0;
for (const type of types) {
let list = null;
try {
const body = JSON.stringify(Object.assign({}, baseBody, { type: String(type) }));
const res = await fetch(api + '?limit=50&offset=0&orderType=desc&orderBy=createTime', {
method: 'POST', headers: req.headers, body: body,
});
if (!res.ok) throw new Error('HTTP ' + res.status);
const json = await res.json();
list = Array.isArray(json && json.datas) ? json.datas : [];
} catch (e) {
failed++;
continue;
}
for (const item of list) {
if (!item || !item.title) continue;
if (Number(item.status) === 2 || item.studyComplete === 1 || item.studyComplete === true) continue;
const key = apiTypeKey(item.type) || detectLessonType({ fileType: item.fileType });
if (!key || key === 'video') continue; // 视频靠课程里的课时
const id = item.id ? String(item.id) : '';
if (!id || seen.has(id)) continue;
seen.add(id);
inv[key].push({
id: id,
title: norm(item.title),
fileType: item.fileType || '',
route: routeForFileType(item.fileType),
hours: Number(item.studyHours) || 0,
});
}
}
if (failed >= types.length) throw new Error('积分库存接口全部失败');
return inv;
}
// 返回 'off' | 'loading' | 'ready' | 'failed'
export function ensurePointsInventory() {
if (!state.pointsEnabled) return 'off';
if (R.pointsInventory) return 'ready';
const vm = listVm();
if (!vm) {
if (!R.pointsNoVmSince) R.pointsNoVmSince = Date.now();
if (Date.now() - R.pointsNoVmSince > 5000) {
R.pointsInventory = emptyPointsInventory();
R.pointsInventoryFailedAt = Date.now();
if (Date.now() - (R.pointsWarnedAt || 0) > 10000) {
R.pointsWarnedAt = Date.now();
console.warn(TAG, '未找到课程列表组件,积分库存按「只有视频课时」处理');
}
return 'failed';
}
return 'loading';
}
R.pointsNoVmSince = 0;
if (R.pointsInventoryLoading) {
if (Date.now() - R.pointsFetchStartedAt > 20000) {
R.pointsInventoryLoading = false;
R.pointsInventory = emptyPointsInventory();
R.pointsInventoryFailedAt = Date.now();
return 'failed';
}
return 'loading';
}
if (R.pointsInventoryFailedAt && Date.now() - R.pointsInventoryFailedAt < 30000) return 'failed';
const key = pointsInventoryCacheKey(vm);
const cached = readPointsInventory(key);
if (cached) {
R.pointsInventory = cached;
return 'ready';
}
R.pointsInventoryLoading = true;
R.pointsFetchStartedAt = Date.now();
setStatus('正在读取文档/音频/微课库存…');
fetchPointsInventory(vm).then(function (inv) {
R.pointsInventoryLoading = false;
R.pointsInventory = inv;
writePointsInventory(inv, key);
const parts = POINT_RULES
.filter(function (r) { return r.key !== 'video'; })
.map(function (r) { return r.label + ' ' + ((inv[r.key] && inv[r.key].length) || 0) + ' 条'; });
console.log(TAG, '积分库存已就绪:' + parts.join(','));
updatePanel();
}).catch(function (e) {
R.pointsInventoryLoading = false;
R.pointsInventory = emptyPointsInventory();
R.pointsInventoryFailedAt = Date.now();
if (Date.now() - (R.pointsWarnedAt || 0) > 10000) {
R.pointsWarnedAt = Date.now();
console.warn(TAG, '读取积分库存失败,按「只有视频课时」处理:', e && e.message ? e.message : e);
}
});
return 'loading';
}
// 某类还有没有可学的单条内容(排除本轮已完成 / 已跳过)
function nextPointsItem(type) {
const inv = R.pointsInventory;
const arr = (inv && inv[type]) || [];
return arr.find(function (item) {
if (!item || !item.title) return false;
if (S.completedTitles[item.title] || courseSkipped(item.title)) return false;
return true;
}) || null;
}
export function pointsAvailability(videoAvailable) {
return {
doc: !!nextPointsItem('doc'),
video: videoAvailable !== false,
audio: !!nextPointsItem('audio'),
micro: !!nextPointsItem('micro'),
};
}
export function pointsDone() {
if (!state.pointsEnabled) return false;
return points.done(pointsAvailability());
}
export function pointsTarget() {
return nextTarget({
isFull: function (key) { return points.isFull(key); },
available: pointsAvailability(),
});
}
// 从当前课程页回列表,交给 listTick 停止或换下一类。
function leaveForPoints(reason) {
if (S.activeCourse) {
S.activeCourse = null;
S.coursePhase = PHASE_IDLE;
}
S.awaitingListReturn = true;
saveRunState();
setStatus(reason);
console.log(TAG, reason);
goToList(true);
}
// 本类刚满额 / 今日任务已无内容时离开课程页。
// 返回 true = 已经发起跳转,调用方不要再切下一节。
export function pointsAfterLesson(type) {
if (!state.pointsEnabled) return false;
if (!R.pointsInventory) { ensurePointsInventory(); return false; }
if (pointsDone()) {
leaveForPoints('今日积分:可用内容已学完(' + points.summary() + ')');
return true;
}
if (type && points.isFull(type)) {
const target = pointsTarget();
if (target && target.type !== type) {
leaveForPoints('“' + pointLabel(type) + '”已满额,切换学习“' + pointLabel(target.type) + '”');
return true;
}
}
return false;
}
// 进入单条文档/音频/微课:直接按 kngId 打开对应播放页
export function startStandalone(item, type) {
if (!item) return false;
R.lastCardClickAt = Date.now();
R.shortJumpAt = 0;
S.activeCourse = {
title: item.title,
id: item.id,
startedAt: Date.now(),
standalone: true,
pointType: type,
};
S.coursePhase = PHASE_ENTERING;
S.awaitingListReturn = false;
resetCourseRuntime();
saveRunState();
const label = pointLabel(type);
setStatus('进入' + label + ':' + truncate(item.title, 26));
console.log(TAG, '进入' + label, item.title, '(积分模式)');
location.href = location.origin + '/kng/#/' + item.route + '?kngId=' + encodeURIComponent(item.id);
return true;
}
export function pendingShortItems() {
const cat = R.shortCatalog;
if (!cat) return [];
@@ -605,6 +850,33 @@ export function listTick() {
}
R.retryStatusSec = -1;
// 每日积分模式:先补文档/音频/微课的单条内容;视频额度靠课程里的视频课时。
// 四类都满额(或剩余类型确认没内容)就收尾,不再无意义地刷课。
if (state.pointsEnabled) {
const invStatus = ensurePointsInventory();
if (invStatus === 'loading') return;
if (pointsDone()) {
const text = points.summary();
console.log(TAG, '今日积分:可用内容已学完', text);
stopBatch('今日积分:可用内容已学完(' + text + ')');
return;
}
const target = pointsTarget();
if (!target) {
stopBatch('今日积分任务:剩余类型都没有可学内容');
return;
}
if (target.kind === 'item') {
const item = nextPointsItem(target.type);
if (item) {
if (Date.now() - R.lastCardClickAt < 3000) return;
startStandalone(item, target.type);
return;
}
}
// target.kind === 'course':继续走下面的短课程 / 原顺序选课
}
const pending = cards.filter((c) => {
if (!c.title) return false;
if (/已学完|已完成|已学习/.test(c.status)) return false;
+39 -1
View File
@@ -1,6 +1,7 @@
// ======== 面板 ========
import { CFG, VERSION, LS_ENABLED, LS_PREFER_SHORT, SS_SHORT_CATALOG, PANEL_ID, TAG } from './config.js';
import { R, S, state, saveRunState } from './state.js';
import { R, S, state, points, saveRunState } from './state.js';
import { LS_POINTS_MODE } from './points.js';
import { route } from './route.js';
import { isLoginPage, startBatch, doLoginAndStart, clearSavedCreds } from './login.js';
@@ -14,6 +15,9 @@ let labelAuto = null;
let labelBatch = null;
let labelShort = null;
let cbPreferShort = null;
let labelPoints = null;
let cbPoints = null;
let pointsEl = null;
let cbAuto = null;
let loginBox = null;
export let loginUserEl = null;
@@ -58,13 +62,20 @@ export function updatePanel() {
}
if (cbAuto) cbAuto.checked = state.autoPlayEnabled;
if (cbPreferShort) cbPreferShort.checked = state.preferShortCourses;
if (cbPoints) cbPoints.checked = state.pointsEnabled;
if (pointsEl) {
pointsEl.style.display = state.pointsEnabled ? 'block' : 'none';
pointsEl.textContent = state.pointsEnabled ? points.summary() : '';
}
const onLogin = isLoginPage();
if (loginBox) loginBox.style.display = onLogin ? 'block' : 'none';
if (labelAuto) labelAuto.style.display = onLogin ? 'none' : 'flex';
if (labelBatch) labelBatch.style.display = onLogin ? 'none' : 'flex';
if (labelShort) labelShort.style.display = onLogin ? 'none' : 'flex';
if (labelPoints) labelPoints.style.display = onLogin ? 'none' : 'flex';
if (statsEl) statsEl.style.display = onLogin ? 'none' : 'block';
if (pointsEl) pointsEl.style.display = onLogin ? 'none' : (state.pointsEnabled ? 'block' : 'none');
if (btnOne) {
// 「停止刷课」只在播放页出现;列表页等位置始终显示「一键刷课」
const onCourse = route() === 'course' && !!S.activeCourse;
@@ -255,6 +266,27 @@ export function buildPanel() {
labelShort.appendChild(cbPreferShort);
labelShort.appendChild(document.createTextNode('优先短课程(时长正序)'));
labelPoints = document.createElement('label');
labelPoints.style.cssText = LABEL_CSS;
cbPoints = document.createElement('input');
cbPoints.type = 'checkbox';
cbPoints.id = 'yun-xue-tang-points-enabled';
cbPoints.checked = state.pointsEnabled;
cbPoints.title = '按课时类型计分:文档1 / 视频3 / 音频2 / 微课2,每天最多 24 分';
cbPoints.addEventListener('change', function () {
state.pointsEnabled = cbPoints.checked;
points.setEnabled(state.pointsEnabled);
try { localStorage.setItem(LS_POINTS_MODE, state.pointsEnabled ? '1' : '0'); } catch (e) {}
R.pointsInventory = null;
R.pointsInventoryFailedAt = 0;
setStatus(state.pointsEnabled
? '已开启每日积分模式:' + points.summary()
: '已关闭每日积分模式,恢复普通刷课');
updatePanel();
});
labelPoints.appendChild(cbPoints);
labelPoints.appendChild(document.createTextNode('每日积分模式(凑满 24 分就停)'));
statusEl = document.createElement('div');
statusEl.id = 'yun-xue-tang-status';
statusEl.textContent = '待机';
@@ -264,6 +296,10 @@ export function buildPanel() {
statsEl.id = 'yun-xue-tang-stats';
statsEl.style.cssText = 'margin-top:2px;color:#aaa;';
pointsEl = document.createElement('div');
pointsEl.id = 'yun-xue-tang-points';
pointsEl.style.cssText = 'margin-top:2px;color:#8ee6c0;';
const hint = document.createElement('div');
hint.textContent = '真实播放计时 · 保持窗口可见';
hint.style.cssText = 'margin-top:6px;color:#777;font-size:11px;';
@@ -280,8 +316,10 @@ export function buildPanel() {
box.appendChild(labelAuto);
box.appendChild(labelBatch);
box.appendChild(labelShort);
box.appendChild(labelPoints);
box.appendChild(statusEl);
box.appendChild(statsEl);
box.appendChild(pointsEl);
box.appendChild(hint);
box.appendChild(footer);
document.documentElement.appendChild(box);
+267
View File
@@ -0,0 +1,267 @@
// ======== 每日积分模式 ========
// 平台按「学习完成」发积分,四类任务各有每日上限:
// 文档 1 次 + 视频 3 次 + 音频 2 次 + 微课 2 次,每次 3 分,单日最多 24 分。
//
// 这里的口径是「完成一个课时算一次」,不是「完成一整门课」:
// · 多课时课程里每学完一节视频/文档/音频/微课,各计一次;
// · 单视频/音频/课件播放页学完即计一次;
// · 类型识别不出来的课时不猜、不计分;
// · 同一天同一课时重复上报(刷新、重进、平台重发)只计一次。
//
// 计数落 localStorage 并带日期,跨刷新/运行器重启不丢,跨天自动清零。
// 纯数据逻辑,不碰 DOM,方便脱离浏览器直接测。
export const POINT_RULES = [
{ key: 'doc', label: '文档', cap: 1 },
{ key: 'video', label: '视频', cap: 3 },
{ key: 'audio', label: '音频', cap: 2 },
{ key: 'micro', label: '微课', cap: 2 },
];
export const POINTS_PER_TASK = 3;
export const MAX_DAILY_POINTS = POINT_RULES.reduce((n, r) => n + r.cap, 0) * POINTS_PER_TASK;
export const LS_POINTS_MODE = 'yun-xue-tang-daily-points-mode';
export const LS_POINTS_STATE = 'yun-xue-tang-daily-points-v1';
// 顺序有讲究:微课/文档/音频在前,视频最后。某一类同时命中多个关键词时,
// 按更具体的类型算(例如「微课视频」按微课,而不是按视频)。
const TYPE_MATCHERS = [
['micro', /微课|micro/i],
['doc', /文档|课件|ppt|document|article/i],
['audio', /音频|audio/i],
['video', /视频|video/i],
];
/**
* 识别一个课时的积分类型。
* 优先级:播放页路由 > 接口 fileType > 目录里的 tag-type 文本。
* 多课时课程的路由(#/course/play)不带类型,会落到 tag-type 上。
* 识别不出来返回 '',调用方不应计分。
*/
export function detectLessonType(input) {
input = input || {};
const sources = [input.hash, input.fileType, input.tag];
for (const src of sources) {
if (!src) continue;
const s = String(src);
for (const pair of TYPE_MATCHERS) {
if (pair[1].test(s)) return pair[0];
}
}
return '';
}
/** 列表接口的 type 字段:1=文档/课件 2=视频 3=音频;0 是课程容器,不计。 */
export function apiTypeKey(type) {
const n = Number(type);
if (n === 1) return 'doc';
if (n === 2) return 'video';
if (n === 3) return 'audio';
return '';
}
/** 类型的中文名(日志/面板用);未知类型原样返回 */
export function pointLabel(key) {
const rule = POINT_RULES.find((r) => r.key === key);
return rule ? rule.label : (key || '未知');
}
/**
* 选择本轮该补哪一类:按 文档 → 视频 → 音频 → 微课 的顺序,
* 跳过已满额和确认没有内容的类型。
*
* @param {object} opts
* @param {Function} opts.isFull (key) => boolean
* @param {object} [opts.available] { doc, video, audio, micro };false = 没内容。
* video 的可用性由调用方根据「还有没有可学的课程」判断。
* @returns {{type:string, kind:'item'|'course'}|null} null = 今日任务已无可做项
*/
export function nextTarget(opts) {
opts = opts || {};
const isFull = typeof opts.isFull === 'function' ? opts.isFull : () => false;
const available = opts.available || {};
for (const rule of POINT_RULES) {
if (isFull(rule.key)) continue;
if (rule.key === 'video') {
// 视频额度靠课程里的视频课时完成,不依赖单条库存
if (available.video !== false) return { type: 'video', kind: 'course' };
continue;
}
if (available[rule.key]) return { type: rule.key, kind: 'item' };
}
return null;
}
function pad2(n) {
return n < 10 ? '0' + n : '' + n;
}
function dayKey(ms) {
const d = new Date(ms);
return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate());
}
function blankState(date) {
const counts = {};
for (const rule of POINT_RULES) counts[rule.key] = 0;
return { date: date, counts: counts, seen: {} };
}
function normalizeState(obj) {
const state = blankState(obj && obj.date ? String(obj.date) : '');
for (const rule of POINT_RULES) {
const n = Number(obj && obj.counts && obj.counts[rule.key]);
state.counts[rule.key] = Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
}
if (obj && obj.seen && typeof obj.seen === 'object') state.seen = obj.seen;
return state;
}
/**
* @param {object} [opts]
* @param {Function} [opts.now] 取当前时间(毫秒),测试用假时钟
* @param {object} [opts.storage] getItem/setItem,默认 localStorage
* @param {boolean} [opts.enabled] 是否启用积分模式,默认 true
* @param {string} [opts.storageKey]
*/
export function createPointsTracker(opts = {}) {
const now = opts.now || (() => Date.now());
const storage = opts.storage !== undefined
? opts.storage
: (typeof localStorage !== 'undefined' ? localStorage : null);
const storageKey = opts.storageKey || LS_POINTS_STATE;
let enabled = opts.enabled !== undefined ? !!opts.enabled : true;
let state = load();
rollover(); // 打开页面时如果已经跨天,先清零再用
function load() {
try {
const raw = storage && storage.getItem(storageKey);
if (!raw) return blankState(dayKey(now()));
return normalizeState(JSON.parse(raw));
} catch (e) {
return blankState(dayKey(now()));
}
}
function save() {
try {
if (storage) storage.setItem(storageKey, JSON.stringify(state));
} catch (e) { /* 容量不足 / 隐私模式:内存里照常计数 */ }
}
/** 跨天自动清零;返回是否发生了重置 */
function rollover() {
const today = dayKey(now());
if (state.date === today) return false;
state = blankState(today);
save();
return true;
}
function ruleOf(key) {
return POINT_RULES.find((r) => r.key === key) || null;
}
function count(key) {
return state.counts[key] || 0;
}
function cap(key) {
const rule = ruleOf(key);
return rule ? rule.cap : 0;
}
function isFull(key) {
return count(key) >= cap(key);
}
function remaining(key) {
return Math.max(0, cap(key) - count(key));
}
/**
* 记一次课时完成。
* @param {string} key detectLessonType 的返回值
* @param {string} [lessonId] 当天去重键(建议 courseId|lessonKey);空串表示不去重
* @returns {boolean} 是否真的计入了
*/
function record(key, lessonId) {
rollover();
if (!enabled) return false;
if (!ruleOf(key) || isFull(key)) return false;
if (lessonId) {
if (state.seen[lessonId]) return false;
state.seen[lessonId] = 1;
}
state.counts[key] = count(key) + 1;
save();
return true;
}
function totalPoints() {
let total = 0;
for (const rule of POINT_RULES) {
total += Math.min(count(rule.key), rule.cap) * POINTS_PER_TASK;
}
return total;
}
function maxPoints() {
return MAX_DAILY_POINTS;
}
function allFull() {
return POINT_RULES.every((rule) => isFull(rule.key));
}
/**
* 今日任务是否已完成:四类都满额,或剩余额度的类型都确认没有内容。
* available 缺省时不把「没内容」当成完成依据(避免误停)。
*/
function done(available) {
return POINT_RULES.every((rule) =>
isFull(rule.key) || (!!available && available[rule.key] === false));
}
function progress() {
return POINT_RULES.map((rule) => ({
key: rule.key,
label: rule.label,
count: Math.min(count(rule.key), rule.cap),
cap: rule.cap,
}));
}
function summary() {
const parts = progress().map((p) => p.label + p.count + '/' + p.cap);
return '今日积分 ' + totalPoints() + '/' + maxPoints() + ' · ' + parts.join(' ');
}
function snapshot() {
return {
enabled: enabled,
date: state.date,
total: totalPoints(),
max: maxPoints(),
progress: progress(),
text: summary(),
};
}
function setEnabled(on) {
enabled = !!on;
if (enabled) rollover();
}
function isEnabled() {
return enabled;
}
return {
record, count, cap, isFull, remaining, totalPoints, maxPoints,
allFull, done, progress, summary, snapshot, setEnabled, isEnabled, rollover,
};
}
+1 -1
View File
@@ -17,7 +17,7 @@ export function route() {
// 单媒体播放页(没有多课时目录):完成判定看进度百分比/「已完成学习」,
// 不需要找下一节。
export function mediaPage() {
return /^#\/(?:video|audio|ppt|document|article)\/play(?:[?/]|$)/i.test(location.hash || '');
return /^#\/(?:video|audio|ppt|document|article|micro|microcourse)\/play(?:[?/]|$)/i.test(location.hash || '');
}
// 回列表页。
+18
View File
@@ -13,11 +13,13 @@ import {
CFG, LS_ENABLED, LS_PREFER_SHORT, LS_TARGET_CATALOG_URL,
SS_RUN_STATE, SS_SHORT_CATALOG, LEGACY_LS_BATCH,
} from './config.js';
import { createPointsTracker, LS_POINTS_MODE } from './points.js';
// ======== 用户偏好(localStorage) ========
export const state = {
autoPlayEnabled: true, // 当前课程自动连播(自己点开的课)
preferShortCourses: CFG.preferShortCourses, // 列表刷课时优先后时长更短的课程(正序)
pointsEnabled: true, // 每日积分模式:按课时类型计分并封顶
};
try {
state.autoPlayEnabled = localStorage.getItem(LS_ENABLED) !== '0';
@@ -26,6 +28,12 @@ try {
const v = localStorage.getItem(LS_PREFER_SHORT);
if (v === '0' || v === '1') state.preferShortCourses = v === '1';
} catch (e) { /* ignore */ }
try {
state.pointsEnabled = localStorage.getItem(LS_POINTS_MODE) !== '0';
} catch (e) { /* ignore */ }
// 每日积分计数落 localStorage(带日期,跨刷新/重启不丢,跨天自动清零)
export const points = createPointsTracker({ enabled: state.pointsEnabled });
// ======== 本次运行状态(sessionStorage) ========
export const PHASE_ENTERING = 'entering';
@@ -248,6 +256,15 @@ export const R = {
shortNoVmSince: 0,
shortWarnedAt: 0,
retryStatusSec: -1, // 「等待重试」提示上次写出的剩余秒数(只在变化时刷状态)
// 每日积分模式:当前课时的类型缓存(课时 id → doc/video/audio/micro),
// 以及文档/音频/微课的单条库存(视频靠课程里的课时,不单独存)
lessonTypes: {},
pointsInventory: null,
pointsInventoryLoading: false,
pointsInventoryFailedAt: 0,
pointsFetchStartedAt: 0,
pointsNoVmSince: 0,
pointsWarnedAt: 0,
};
// 丢掉时长队列缓存:下一次选课会重新调列表接口,拿平台实时的
@@ -264,6 +281,7 @@ export function invalidateShortCatalog() {
export function resetCourseRuntime() {
R.lastLessonKey = '';
R.doneLatchKey = '';
R.lessonTypes = {};
R.lastSummary = null;
R.lastCountdown = null;
R.lastProgressAt = Date.now();
+544 -4
View File
@@ -106,17 +106,217 @@
var LS_PENDING = "yun-xue-tang-auto-start-after-login";
var SS_RUN_STATE = "yun-xue-tang-run-state-v3";
var SS_SHORT_CATALOG = "yun-xue-tang-short-catalog-v1";
var SS_POINTS_INVENTORY = "yun-xue-tang-points-inventory-v1";
var SHORT_CATALOG_TTL = 5 * 60 * 1e3;
var POINTS_INVENTORY_TTL = 5 * 60 * 1e3;
var LEGACY_LS_BATCH = "yun-xue-tang-batch-v2";
var PANEL_ID = "yun-xue-tang-panel";
var TAG = "[云学堂助手]";
// src/points.js
var POINT_RULES = [
{ key: "doc", label: "文档", cap: 1 },
{ key: "video", label: "视频", cap: 3 },
{ key: "audio", label: "音频", cap: 2 },
{ key: "micro", label: "微课", cap: 2 }
];
var POINTS_PER_TASK = 3;
var MAX_DAILY_POINTS = POINT_RULES.reduce((n, r) => n + r.cap, 0) * POINTS_PER_TASK;
var LS_POINTS_MODE = "yun-xue-tang-daily-points-mode";
var LS_POINTS_STATE = "yun-xue-tang-daily-points-v1";
var TYPE_MATCHERS = [
["micro", /微课|micro/i],
["doc", /文档|课件|ppt|document|article/i],
["audio", /音频|audio/i],
["video", /视频|video/i]
];
function detectLessonType(input) {
input = input || {};
const sources = [input.hash, input.fileType, input.tag];
for (const src of sources) {
if (!src) continue;
const s = String(src);
for (const pair of TYPE_MATCHERS) {
if (pair[1].test(s)) return pair[0];
}
}
return "";
}
function apiTypeKey(type) {
const n = Number(type);
if (n === 1) return "doc";
if (n === 2) return "video";
if (n === 3) return "audio";
return "";
}
function pointLabel(key) {
const rule = POINT_RULES.find((r) => r.key === key);
return rule ? rule.label : key || "未知";
}
function nextTarget(opts) {
opts = opts || {};
const isFull = typeof opts.isFull === "function" ? opts.isFull : () => false;
const available = opts.available || {};
for (const rule of POINT_RULES) {
if (isFull(rule.key)) continue;
if (rule.key === "video") {
if (available.video !== false) return { type: "video", kind: "course" };
continue;
}
if (available[rule.key]) return { type: rule.key, kind: "item" };
}
return null;
}
function pad2(n) {
return n < 10 ? "0" + n : "" + n;
}
function dayKey(ms) {
const d = new Date(ms);
return d.getFullYear() + "-" + pad2(d.getMonth() + 1) + "-" + pad2(d.getDate());
}
function blankState(date) {
const counts = {};
for (const rule of POINT_RULES) counts[rule.key] = 0;
return { date, counts, seen: {} };
}
function normalizeState(obj) {
const state2 = blankState(obj && obj.date ? String(obj.date) : "");
for (const rule of POINT_RULES) {
const n = Number(obj && obj.counts && obj.counts[rule.key]);
state2.counts[rule.key] = Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
}
if (obj && obj.seen && typeof obj.seen === "object") state2.seen = obj.seen;
return state2;
}
function createPointsTracker(opts = {}) {
const now = opts.now || (() => Date.now());
const storage = opts.storage !== void 0 ? opts.storage : typeof localStorage !== "undefined" ? localStorage : null;
const storageKey = opts.storageKey || LS_POINTS_STATE;
let enabled = opts.enabled !== void 0 ? !!opts.enabled : true;
let state2 = load();
rollover();
function load() {
try {
const raw = storage && storage.getItem(storageKey);
if (!raw) return blankState(dayKey(now()));
return normalizeState(JSON.parse(raw));
} catch (e) {
return blankState(dayKey(now()));
}
}
function save() {
try {
if (storage) storage.setItem(storageKey, JSON.stringify(state2));
} catch (e) {
}
}
function rollover() {
const today = dayKey(now());
if (state2.date === today) return false;
state2 = blankState(today);
save();
return true;
}
function ruleOf(key) {
return POINT_RULES.find((r) => r.key === key) || null;
}
function count(key) {
return state2.counts[key] || 0;
}
function cap(key) {
const rule = ruleOf(key);
return rule ? rule.cap : 0;
}
function isFull(key) {
return count(key) >= cap(key);
}
function remaining(key) {
return Math.max(0, cap(key) - count(key));
}
function record(key, lessonId) {
rollover();
if (!enabled) return false;
if (!ruleOf(key) || isFull(key)) return false;
if (lessonId) {
if (state2.seen[lessonId]) return false;
state2.seen[lessonId] = 1;
}
state2.counts[key] = count(key) + 1;
save();
return true;
}
function totalPoints() {
let total = 0;
for (const rule of POINT_RULES) {
total += Math.min(count(rule.key), rule.cap) * POINTS_PER_TASK;
}
return total;
}
function maxPoints() {
return MAX_DAILY_POINTS;
}
function allFull() {
return POINT_RULES.every((rule) => isFull(rule.key));
}
function done(available) {
return POINT_RULES.every((rule) => isFull(rule.key) || !!available && available[rule.key] === false);
}
function progress() {
return POINT_RULES.map((rule) => ({
key: rule.key,
label: rule.label,
count: Math.min(count(rule.key), rule.cap),
cap: rule.cap
}));
}
function summary() {
const parts = progress().map((p) => p.label + p.count + "/" + p.cap);
return "今日积分 " + totalPoints() + "/" + maxPoints() + " · " + parts.join(" ");
}
function snapshot() {
return {
enabled,
date: state2.date,
total: totalPoints(),
max: maxPoints(),
progress: progress(),
text: summary()
};
}
function setEnabled(on) {
enabled = !!on;
if (enabled) rollover();
}
function isEnabled() {
return enabled;
}
return {
record,
count,
cap,
isFull,
remaining,
totalPoints,
maxPoints,
allFull,
done,
progress,
summary,
snapshot,
setEnabled,
isEnabled,
rollover
};
}
// src/state.js
var state = {
autoPlayEnabled: true,
// 当前课程自动连播(自己点开的课)
preferShortCourses: CFG.preferShortCourses
preferShortCourses: CFG.preferShortCourses,
// 列表刷课时优先后时长更短的课程(正序)
pointsEnabled: true
// 每日积分模式:按课时类型计分并封顶
};
try {
state.autoPlayEnabled = localStorage.getItem(LS_ENABLED) !== "0";
@@ -127,6 +327,11 @@
if (v === "0" || v === "1") state.preferShortCourses = v === "1";
} catch (e) {
}
try {
state.pointsEnabled = localStorage.getItem(LS_POINTS_MODE) !== "0";
} catch (e) {
}
var points = createPointsTracker({ enabled: state.pointsEnabled });
var PHASE_ENTERING = "entering";
var PHASE_LEARNING = "learning";
var PHASE_IDLE = "idle";
@@ -352,8 +557,17 @@
shortJumpAt: 0,
shortNoVmSince: 0,
shortWarnedAt: 0,
retryStatusSec: -1
retryStatusSec: -1,
// 「等待重试」提示上次写出的剩余秒数(只在变化时刷状态)
// 每日积分模式:当前课时的类型缓存(课时 id → doc/video/audio/micro),
// 以及文档/音频/微课的单条库存(视频靠课程里的课时,不单独存)
lessonTypes: {},
pointsInventory: null,
pointsInventoryLoading: false,
pointsInventoryFailedAt: 0,
pointsFetchStartedAt: 0,
pointsNoVmSince: 0,
pointsWarnedAt: 0
};
function invalidateShortCatalog() {
R.shortCatalog = null;
@@ -368,6 +582,7 @@
function resetCourseRuntime() {
R.lastLessonKey = "";
R.doneLatchKey = "";
R.lessonTypes = {};
R.lastSummary = null;
R.lastCountdown = null;
R.lastProgressAt = Date.now();
@@ -548,7 +763,7 @@
return "other";
}
function mediaPage() {
return /^#\/(?:video|audio|ppt|document|article)\/play(?:[?/]|$)/i.test(location.hash || "");
return /^#\/(?:video|audio|ppt|document|article|micro|microcourse)\/play(?:[?/]|$)/i.test(location.hash || "");
}
function goToList(force) {
if (!force && Date.now() - R.lastGoListAt < 5e3) return;
@@ -880,6 +1095,9 @@
var labelBatch = null;
var labelShort = null;
var cbPreferShort = null;
var labelPoints = null;
var cbPoints = null;
var pointsEl = null;
var cbAuto = null;
var loginBox = null;
var loginUserEl = null;
@@ -921,12 +1139,19 @@
}
if (cbAuto) cbAuto.checked = state.autoPlayEnabled;
if (cbPreferShort) cbPreferShort.checked = state.preferShortCourses;
if (cbPoints) cbPoints.checked = state.pointsEnabled;
if (pointsEl) {
pointsEl.style.display = state.pointsEnabled ? "block" : "none";
pointsEl.textContent = state.pointsEnabled ? points.summary() : "";
}
const onLogin = isLoginPage();
if (loginBox) loginBox.style.display = onLogin ? "block" : "none";
if (labelAuto) labelAuto.style.display = onLogin ? "none" : "flex";
if (labelBatch) labelBatch.style.display = onLogin ? "none" : "flex";
if (labelShort) labelShort.style.display = onLogin ? "none" : "flex";
if (labelPoints) labelPoints.style.display = onLogin ? "none" : "flex";
if (statsEl) statsEl.style.display = onLogin ? "none" : "block";
if (pointsEl) pointsEl.style.display = onLogin ? "none" : state.pointsEnabled ? "block" : "none";
if (btnOne) {
const onCourse = route() === "course" && !!S.activeCourse;
btnOne.textContent = onLogin ? "一键登录并刷课" : onCourse && S.batchRunning ? "停止刷课" : "一键刷课";
@@ -1131,6 +1356,27 @@
});
labelShort.appendChild(cbPreferShort);
labelShort.appendChild(document.createTextNode("优先短课程(时长正序)"));
labelPoints = document.createElement("label");
labelPoints.style.cssText = LABEL_CSS;
cbPoints = document.createElement("input");
cbPoints.type = "checkbox";
cbPoints.id = "yun-xue-tang-points-enabled";
cbPoints.checked = state.pointsEnabled;
cbPoints.title = "按课时类型计分:文档1 / 视频3 / 音频2 / 微课2,每天最多 24 分";
cbPoints.addEventListener("change", function() {
state.pointsEnabled = cbPoints.checked;
points.setEnabled(state.pointsEnabled);
try {
localStorage.setItem(LS_POINTS_MODE, state.pointsEnabled ? "1" : "0");
} catch (e) {
}
R.pointsInventory = null;
R.pointsInventoryFailedAt = 0;
setStatus(state.pointsEnabled ? "已开启每日积分模式:" + points.summary() : "已关闭每日积分模式,恢复普通刷课");
updatePanel();
});
labelPoints.appendChild(cbPoints);
labelPoints.appendChild(document.createTextNode("每日积分模式(凑满 24 分就停)"));
statusEl = document.createElement("div");
statusEl.id = "yun-xue-tang-status";
statusEl.textContent = "待机";
@@ -1138,6 +1384,9 @@
statsEl = document.createElement("div");
statsEl.id = "yun-xue-tang-stats";
statsEl.style.cssText = "margin-top:2px;color:#aaa;";
pointsEl = document.createElement("div");
pointsEl.id = "yun-xue-tang-points";
pointsEl.style.cssText = "margin-top:2px;color:#8ee6c0;";
const hint = document.createElement("div");
hint.textContent = "真实播放计时 · 保持窗口可见";
hint.style.cssText = "margin-top:6px;color:#777;font-size:11px;";
@@ -1152,8 +1401,10 @@
box.appendChild(labelAuto);
box.appendChild(labelBatch);
box.appendChild(labelShort);
box.appendChild(labelPoints);
box.appendChild(statusEl);
box.appendChild(statsEl);
box.appendChild(pointsEl);
box.appendChild(hint);
box.appendChild(footer);
document.documentElement.appendChild(box);
@@ -2116,6 +2367,229 @@
setStatus("短课程优先暂不可用,先按当前页时长排序");
}
}
function emptyPointsInventory() {
return { at: Date.now(), doc: [], audio: [], micro: [] };
}
function pointsInventoryCacheKey(vm) {
return String(vm && vm.collegeId || localStorage.getItem("orgId") || "");
}
function readPointsInventory(key) {
try {
const raw = sessionStorage.getItem(SS_POINTS_INVENTORY);
if (!raw) return null;
const obj = JSON.parse(raw);
if (!obj || obj.key !== key || !obj.doc || !obj.audio || !obj.micro) return null;
if (Date.now() - (obj.at || 0) > POINTS_INVENTORY_TTL) return null;
return obj;
} catch (e) {
return null;
}
}
function writePointsInventory(inv, key) {
if (!inv) return;
try {
sessionStorage.setItem(SS_POINTS_INVENTORY, JSON.stringify({
key,
at: inv.at,
doc: inv.doc,
audio: inv.audio,
micro: inv.micro
}));
} catch (e) {
}
}
function routeForFileType(fileType) {
const s = String(fileType || "").toLowerCase();
if (s === "audio") return "audio/play";
if (s === "video") return "video/play";
if (s === "document" || s === "doc") return "document/play";
if (s === "article") return "article/play";
if (/micro/.test(s)) return "micro/play";
return "ppt/play";
}
async function fetchPointsInventory(vm) {
const req = shortCatalogRequest(vm);
const baseBody = JSON.parse(req.body);
const api = shortApiBase();
const inv = emptyPointsInventory();
const seen = /* @__PURE__ */ new Set();
const types = [1, 3, 4, 5, 6, 7, 8];
let failed = 0;
for (const type of types) {
let list = null;
try {
const body = JSON.stringify(Object.assign({}, baseBody, { type: String(type) }));
const res = await fetch(api + "?limit=50&offset=0&orderType=desc&orderBy=createTime", {
method: "POST",
headers: req.headers,
body
});
if (!res.ok) throw new Error("HTTP " + res.status);
const json = await res.json();
list = Array.isArray(json && json.datas) ? json.datas : [];
} catch (e) {
failed++;
continue;
}
for (const item of list) {
if (!item || !item.title) continue;
if (Number(item.status) === 2 || item.studyComplete === 1 || item.studyComplete === true) continue;
const key = apiTypeKey(item.type) || detectLessonType({ fileType: item.fileType });
if (!key || key === "video") continue;
const id = item.id ? String(item.id) : "";
if (!id || seen.has(id)) continue;
seen.add(id);
inv[key].push({
id,
title: norm(item.title),
fileType: item.fileType || "",
route: routeForFileType(item.fileType),
hours: Number(item.studyHours) || 0
});
}
}
if (failed >= types.length) throw new Error("积分库存接口全部失败");
return inv;
}
function ensurePointsInventory() {
if (!state.pointsEnabled) return "off";
if (R.pointsInventory) return "ready";
const vm = listVm();
if (!vm) {
if (!R.pointsNoVmSince) R.pointsNoVmSince = Date.now();
if (Date.now() - R.pointsNoVmSince > 5e3) {
R.pointsInventory = emptyPointsInventory();
R.pointsInventoryFailedAt = Date.now();
if (Date.now() - (R.pointsWarnedAt || 0) > 1e4) {
R.pointsWarnedAt = Date.now();
console.warn(TAG, "未找到课程列表组件,积分库存按「只有视频课时」处理");
}
return "failed";
}
return "loading";
}
R.pointsNoVmSince = 0;
if (R.pointsInventoryLoading) {
if (Date.now() - R.pointsFetchStartedAt > 2e4) {
R.pointsInventoryLoading = false;
R.pointsInventory = emptyPointsInventory();
R.pointsInventoryFailedAt = Date.now();
return "failed";
}
return "loading";
}
if (R.pointsInventoryFailedAt && Date.now() - R.pointsInventoryFailedAt < 3e4) return "failed";
const key = pointsInventoryCacheKey(vm);
const cached = readPointsInventory(key);
if (cached) {
R.pointsInventory = cached;
return "ready";
}
R.pointsInventoryLoading = true;
R.pointsFetchStartedAt = Date.now();
setStatus("正在读取文档/音频/微课库存…");
fetchPointsInventory(vm).then(function(inv) {
R.pointsInventoryLoading = false;
R.pointsInventory = inv;
writePointsInventory(inv, key);
const parts = POINT_RULES.filter(function(r) {
return r.key !== "video";
}).map(function(r) {
return r.label + " " + (inv[r.key] && inv[r.key].length || 0) + " 条";
});
console.log(TAG, "积分库存已就绪:" + parts.join(","));
updatePanel();
}).catch(function(e) {
R.pointsInventoryLoading = false;
R.pointsInventory = emptyPointsInventory();
R.pointsInventoryFailedAt = Date.now();
if (Date.now() - (R.pointsWarnedAt || 0) > 1e4) {
R.pointsWarnedAt = Date.now();
console.warn(TAG, "读取积分库存失败,按「只有视频课时」处理:", e && e.message ? e.message : e);
}
});
return "loading";
}
function nextPointsItem(type) {
const inv = R.pointsInventory;
const arr = inv && inv[type] || [];
return arr.find(function(item) {
if (!item || !item.title) return false;
if (S.completedTitles[item.title] || courseSkipped(item.title)) return false;
return true;
}) || null;
}
function pointsAvailability(videoAvailable) {
return {
doc: !!nextPointsItem("doc"),
video: videoAvailable !== false,
audio: !!nextPointsItem("audio"),
micro: !!nextPointsItem("micro")
};
}
function pointsDone() {
if (!state.pointsEnabled) return false;
return points.done(pointsAvailability());
}
function pointsTarget() {
return nextTarget({
isFull: function(key) {
return points.isFull(key);
},
available: pointsAvailability()
});
}
function leaveForPoints(reason) {
if (S.activeCourse) {
S.activeCourse = null;
S.coursePhase = PHASE_IDLE;
}
S.awaitingListReturn = true;
saveRunState();
setStatus(reason);
console.log(TAG, reason);
goToList(true);
}
function pointsAfterLesson(type) {
if (!state.pointsEnabled) return false;
if (!R.pointsInventory) {
ensurePointsInventory();
return false;
}
if (pointsDone()) {
leaveForPoints("今日积分:可用内容已学完(" + points.summary() + ")");
return true;
}
if (type && points.isFull(type)) {
const target = pointsTarget();
if (target && target.type !== type) {
leaveForPoints("“" + pointLabel(type) + "”已满额,切换学习“" + pointLabel(target.type) + "”");
return true;
}
}
return false;
}
function startStandalone(item, type) {
if (!item) return false;
R.lastCardClickAt = Date.now();
R.shortJumpAt = 0;
S.activeCourse = {
title: item.title,
id: item.id,
startedAt: Date.now(),
standalone: true,
pointType: type
};
S.coursePhase = PHASE_ENTERING;
S.awaitingListReturn = false;
resetCourseRuntime();
saveRunState();
const label = pointLabel(type);
setStatus("进入" + label + ":" + truncate(item.title, 26));
console.log(TAG, "进入" + label, item.title, "(积分模式)");
location.href = location.origin + "/kng/#/" + item.route + "?kngId=" + encodeURIComponent(item.id);
return true;
}
function pendingShortItems() {
const cat = R.shortCatalog;
if (!cat) return [];
@@ -2328,6 +2802,29 @@
return;
}
R.retryStatusSec = -1;
if (state.pointsEnabled) {
const invStatus = ensurePointsInventory();
if (invStatus === "loading") return;
if (pointsDone()) {
const text = points.summary();
console.log(TAG, "今日积分:可用内容已学完", text);
stopBatch("今日积分:可用内容已学完(" + text + ")");
return;
}
const target = pointsTarget();
if (!target) {
stopBatch("今日积分任务:剩余类型都没有可学内容");
return;
}
if (target.kind === "item") {
const item = nextPointsItem(target.type);
if (item) {
if (Date.now() - R.lastCardClickAt < 3e3) return;
startStandalone(item, target.type);
return;
}
}
}
const pending = cards.filter((c) => {
if (!c.title) return false;
if (/已学完|已完成|已学习/.test(c.status)) return false;
@@ -2687,6 +3184,33 @@
}
// src/course.js
function pointLessonId(key) {
const courseId = S.activeCourse && S.activeCourse.id || courseIdFromUrl() || "";
return courseId + "|" + (key || "media");
}
function rememberLessonType(key) {
if (!state.pointsEnabled) return;
const li = lessonActiveLi();
const tagEl = li ? li.querySelector(".tag-type") : null;
const type = detectLessonType({
tag: tagEl ? textOf(tagEl) : "",
hash: location.hash
});
if (!type) return;
R.lessonType = type;
R.lessonTypes[pointLessonId(key)] = type;
}
function recordLessonPoint(key) {
if (!state.pointsEnabled) return "";
const id = pointLessonId(key);
const type = R.lessonTypes[id] || R.lessonType || detectLessonType({ hash: location.hash });
if (!type) return "";
if (!points.record(type, id)) return "";
const text = points.snapshot().text;
console.log(TAG, "积分 +3:" + pointLabel(type) + "(" + text + ")");
setStatus("积分 +3:" + pointLabel(type) + "(" + text + ")");
return type;
}
function courseTick() {
R.listWithCurrentSince = 0;
if (!S.activeCourse) {
@@ -2741,6 +3265,7 @@
}
}
if (!examPhase() && !isSummaryComplete() && enterPendingExamLesson()) return;
rememberLessonType(readActiveLessonKey());
const summary = readSummary();
const prevSummaryX = R.lastSummary ? R.lastSummary.x : -1;
if (summary) {
@@ -2748,6 +3273,7 @@
const confirmed = !!(R.lastSummary && R.lastSummary.complete);
R.lastSummary = summary;
if (confirmed) {
recordLessonPoint(R.waitLessonKey || R.lastLessonKey);
completeCurrent();
return;
}
@@ -2759,6 +3285,8 @@
const prevKey = R.lastLessonKey;
const curKey = readActiveLessonKey();
R.lastSummary = summary;
const pointType = !isMedia && summary.kind !== "percent" ? recordLessonPoint(prevKey) : "";
if (pointType && pointsAfterLesson(pointType)) return;
if (!isMedia && summary.kind !== "percent" && (!prevKey || curKey === prevKey)) {
setStatus("本节已记录,切换下一节…");
advanceLesson();
@@ -2836,6 +3364,7 @@
}
R.waitStart = 0;
R.lastProgressAt = Date.now();
recordLessonPoint(R.waitLessonKey || R.lastLessonKey);
completeCurrent();
return;
}
@@ -2844,15 +3373,18 @@
R.lastLessonKey = newKey;
R.doneLatchKey = "";
R.lastProgressAt = Date.now();
const pointType = recordLessonPoint(R.waitLessonKey);
if (pointType && pointsAfterLesson(pointType)) return;
setStatus("已自动进入下一节");
return;
}
if (!isMedia && s2 && s2.x > R.waitSummaryX) {
R.waitStart = 0;
R.lastProgressAt = Date.now();
const pointType = recordLessonPoint(R.waitLessonKey || R.lastLessonKey);
if (s2.complete) {
completeCurrent();
} else {
} else if (!pointType || !pointsAfterLesson(pointType)) {
advanceLesson();
}
return;
@@ -2924,6 +3456,7 @@
}
const s = readSummary();
if (s && s.complete) {
recordLessonPoint(R.waitLessonKey || R.lastLessonKey);
completeCurrent();
} else {
setStatus("没有找到下一节,等待课程完成…");
@@ -3066,6 +3599,7 @@
S,
R,
state,
points,
tick: tick2,
save: saveRunState,
flush: flushRunState,
@@ -3112,6 +3646,12 @@
startCourse,
jumpToPage,
nextPage,
ensurePointsInventory,
pointsAvailability,
pointsDone,
pointsTarget,
pointsAfterLesson,
startStandalone,
listTick,
courseTick,
manualCourseTick,