Compare commits
8
Commits
b588b1042f
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c7914d67c7 | ||
|
|
9511237649 | ||
|
|
fff55d1463 | ||
|
|
6b508a0b1a | ||
|
|
18c5e5a3be | ||
|
|
f41fc72fe2 | ||
|
|
0eb4c40629 | ||
|
|
17217dbeb1 |
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
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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.
|
||||||
@@ -2,3 +2,26 @@
|
|||||||
# 凭据只认这两个变量,不能写进 config/runner.config.mjs
|
# 凭据只认这两个变量,不能写进 config/runner.config.mjs
|
||||||
YUN_XUE_TANG_USR=
|
YUN_XUE_TANG_USR=
|
||||||
YUN_XUE_TANG_PWD=
|
YUN_XUE_TANG_PWD=
|
||||||
|
|
||||||
|
# 本次最多刷多少分钟(0 / 留空 = 不限;Docker 里常用)
|
||||||
|
YUN_XUE_TANG_BUDGET_MINUTES=0
|
||||||
|
|
||||||
|
# 开始运行 / 每门课获得学分 / 收尾时推送 Bark 手机通知。
|
||||||
|
# 填 Bark App 里的推送地址(含设备 key),留空 = 不推送。优先级高于 config/runner.config.mjs
|
||||||
|
YUN_XUE_TANG_BARK_URL=
|
||||||
|
# 通知分组,留空 = Bark 默认
|
||||||
|
YUN_XUE_TANG_BARK_GROUP=云学堂助手
|
||||||
|
# 通知在 Bark 服务端保留多少秒,0 = 永久保留(不传 ttl)
|
||||||
|
YUN_XUE_TANG_BARK_TTL=0
|
||||||
|
|
||||||
|
# 时区,影响日志时间戳
|
||||||
|
TZ=Asia/Shanghai
|
||||||
|
|
||||||
|
# ---- 以下三个只在构建镜像时用(docker compose build / npm run docker:build)----
|
||||||
|
# Debian 源地址:国内建议 mirrors.tuna.tsinghua.edu.cn,留空 = 保持 deb.debian.org
|
||||||
|
APT_MIRROR=
|
||||||
|
# npm 源地址:国内建议 https://registry.npmmirror.com,留空 = 官方源
|
||||||
|
NPM_REGISTRY=
|
||||||
|
# Chrome deb 直链:国内常常下不动 dl.google.com,填自己的内网镜像地址;
|
||||||
|
# 留空 = 按架构自动取官网地址
|
||||||
|
CHROME_DEB_URL=
|
||||||
+15
-1
@@ -21,6 +21,12 @@ FROM node:22-bookworm-slim
|
|||||||
# docker build --build-arg CHROME_DEB_URL=https://your-mirror/google-chrome-stable_current_amd64.deb .
|
# docker build --build-arg CHROME_DEB_URL=https://your-mirror/google-chrome-stable_current_amd64.deb .
|
||||||
# 留空则按架构自动取官网地址。
|
# 留空则按架构自动取官网地址。
|
||||||
ARG CHROME_DEB_URL=
|
ARG CHROME_DEB_URL=
|
||||||
|
# Debian 官方源在国内经常慢到几百字节每秒,可用内网/国内镜像替换:
|
||||||
|
# docker build --build-arg APT_MIRROR=mirrors.tuna.tsinghua.edu.cn .
|
||||||
|
# 留空 = 保持基础镜像自带的 deb.debian.org
|
||||||
|
ARG APT_MIRROR=
|
||||||
|
# npm 同理(https://registry.npmmirror.com 之类),留空 = 官方源
|
||||||
|
ARG NPM_REGISTRY=
|
||||||
# tzdata 让日志时间戳跟随 TZ(默认给上海时区);fonts-noto-cjk 只影响截图观感,
|
# tzdata 让日志时间戳跟随 TZ(默认给上海时区);fonts-noto-cjk 只影响截图观感,
|
||||||
# 但缺了它中文在页面里是方块,排查问题时不方便
|
# 但缺了它中文在页面里是方块,排查问题时不方便
|
||||||
ENV TZ=Asia/Shanghai \
|
ENV TZ=Asia/Shanghai \
|
||||||
@@ -30,6 +36,10 @@ ENV TZ=Asia/Shanghai \
|
|||||||
# 步骤:装基础包 → 按架构下官方 Chrome deb → 用 apt 一次装齐依赖 → 清缓存 → 验证能起来。
|
# 步骤:装基础包 → 按架构下官方 Chrome deb → 用 apt 一次装齐依赖 → 清缓存 → 验证能起来。
|
||||||
# procps 提供 ps:运行器启动时靠它找「占着本 profile 的残留浏览器」并收掉(缺了也可跑,自愈会退化)。
|
# procps 提供 ps:运行器启动时靠它找「占着本 profile 的残留浏览器」并收掉(缺了也可跑,自愈会退化)。
|
||||||
RUN set -eux; \
|
RUN set -eux; \
|
||||||
|
if [ -n "$APT_MIRROR" ]; then \
|
||||||
|
sed -ri "s|deb.debian.org|${APT_MIRROR}|g" /etc/apt/sources.list.d/debian.sources /etc/apt/sources.list 2>/dev/null || true; \
|
||||||
|
echo "已切换 apt 源:$APT_MIRROR"; \
|
||||||
|
fi; \
|
||||||
apt-get update; \
|
apt-get update; \
|
||||||
apt-get install -y --no-install-recommends \
|
apt-get install -y --no-install-recommends \
|
||||||
ca-certificates \
|
ca-certificates \
|
||||||
@@ -62,7 +72,11 @@ WORKDIR /app
|
|||||||
# devDependencies 里的 esbuild 是构建注入脚本必需的,所以不能用 --omit=dev;
|
# devDependencies 里的 esbuild 是构建注入脚本必需的,所以不能用 --omit=dev;
|
||||||
# 留着它也能让使用者在容器里直接 `npm run build`
|
# 留着它也能让使用者在容器里直接 `npm run build`
|
||||||
COPY package.json package-lock.json ./
|
COPY package.json package-lock.json ./
|
||||||
RUN npm ci --no-audit --no-fund
|
RUN set -eux; \
|
||||||
|
if [ -n "$NPM_REGISTRY" ]; then \
|
||||||
|
npm config set registry "$NPM_REGISTRY"; \
|
||||||
|
fi; \
|
||||||
|
npm ci --no-audit --no-fund
|
||||||
|
|
||||||
# 业务源码 + 构建脚本 + 无头运行器(node_modules / .run-profile / run-logs / .env 由 .dockerignore 排除)
|
# 业务源码 + 构建脚本 + 无头运行器(node_modules / .run-profile / run-logs / .env 由 .dockerignore 排除)
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|||||||
@@ -20,8 +20,9 @@ Tampermonkey 用户脚本。支持多课时课程与单视频/音频课程;含
|
|||||||
| 防挂机验证 | 识别「已触发防挂机验证」弹窗并点「继续学习」;滑块/拼图类验证不绕过,提示人工处理 |
|
| 防挂机验证 | 识别「已触发防挂机验证」弹窗并点「继续学习」;滑块/拼图类验证不绕过,提示人工处理 |
|
||||||
| 课程列表自动刷课 | 在列表页逐门进入未学完的课程;每完成一门都重新调列表接口拿平台实时状态再选下一门,本次门数上限见下方配置表 |
|
| 课程列表自动刷课 | 在列表页逐门进入未学完的课程;每完成一门都重新调列表接口拿平台实时状态再选下一门,本次门数上限见下方配置表 |
|
||||||
| 短课程优先 | 列表刷课默认按课程总时长**从短到长**选课(跨页),先完成 1 分钟的课再学 1 小时的课;面板可关闭 |
|
| 短课程优先 | 列表刷课默认按课程总时长**从短到长**选课(跨页),先完成 1 分钟的课再学 1 小时的课;面板可关闭 |
|
||||||
| 考试自动空卷 | 含考试章节的课程不再跳过:自动点进考试节 → 开始/继续考试 → 一题不做直接「提交考试」→ 点「确定」交卷,交卷后课程进度被平台记账,课程即可完成;同一门课最多交卷 `maxExamTries` 次,防平台不记账时死循环 |
|
| 每日积分模式 | **以平台积分台账为准**:整门课完成计 1 次,文档 1 次、视频 3 次、音频 2 次、微课 2 次,每次 3 分,单日封顶 24 分。多课时课程要所有课时(含考试)都完成才计分,按今天实际学过的课时类型归类;平台真的入账了才计数。先补文档/音频/微课单条内容,视频额度靠课程;某类满额自动切下一类,四类都满(或剩余类型没内容)就停止刷课。计数存 localStorage、跨刷新/重启不丢、跨天清零;面板可随时关闭 |
|
||||||
| 不跳过课程 | 没有任何「跳过本课」入口,也不会把某门课加入黑名单;没学完就退避重试(30 秒起翻倍,最长 5 分钟),同一门课最多重试 `maxCourseRetries` 次,超过才停下整轮刷课并提示原因,等人工处理 |
|
| 考试自动空卷 | 含考试章节的课程不再跳过:自动点进考试节 → 开始/继续考试 → 一题不做直接「提交考试」→ 点「确定」交卷,交卷后课程进度被平台记账,课程即可完成。只有本页真的点过「提交考试/确定交卷」,看到的结果页才算一次交卷;平台恢复的旧结果页会先回「考试说明页」重新进入,不会在结果页和课程页之间空转。同一门课最多交卷 `maxExamTries` 次,超过仍不记账就跳过该课继续下一门(写明原因) |
|
||||||
|
| 不跳过普通课程 | 没有任何「跳过本课」入口,也不会把普通课程加入黑名单;没学完就退避重试(30 秒起翻倍,最长 5 分钟),同一门课最多重试 `maxCourseRetries` 次,超过才停下整轮刷课并提示原因,等人工处理。**唯一例外**:考试空卷交卷达到 `maxExamTries` 仍未计入进度,或考试页始终没有可点的「开始考试/提交考试」——继续重试只会反复进同一门课,因此本轮跳过它、继续刷其它课 |
|
||||||
| 进度可续 | 学习进度存在 `sessionStorage`(`yun-xue-tang-run-state-v3`),整页跳转/刷新后继续上次的队列和页码;**运行开关不跨会话** —— 浏览器重启、运行器新建标签页后一律回到待机,必须显式开跑(避免未登录就报「运行中」) |
|
| 进度可续 | 学习进度存在 `sessionStorage`(`yun-xue-tang-run-state-v3`),整页跳转/刷新后继续上次的队列和页码;**运行开关不跨会话** —— 浏览器重启、运行器新建标签页后一律回到待机,必须显式开跑(避免未登录就报「运行中」) |
|
||||||
| 无头运行 | 在有/无图形界面的机器上都能跑;`runner/` 可自己起无头 Chromium 并注入脚本,适合 Linux 服务器 / Windows 无人值守常驻(见下方「无头运行」) |
|
| 无头运行 | 在有/无图形界面的机器上都能跑;`runner/` 可自己起无头 Chromium 并注入脚本,适合 Linux 服务器 / Windows 无人值守常驻(见下方「无头运行」) |
|
||||||
|
|
||||||
@@ -47,12 +48,12 @@ Tampermonkey 用户脚本。支持多课时课程与单视频/音频课程;含
|
|||||||
| `startClickCooldownMs` | `3000` | 「开始学习」重复点击冷却:3 秒内没起播就补点 |
|
| `startClickCooldownMs` | `3000` | 「开始学习」重复点击冷却:3 秒内没起播就补点 |
|
||||||
| `entryGraceMs` | `30000` | 进课后标题/课程 id 尚未就绪的宽限,避免慢加载被误判为「课程不一致」 |
|
| `entryGraceMs` | `30000` | 进课后标题/课程 id 尚未就绪的宽限,避免慢加载被误判为「课程不一致」 |
|
||||||
| `stuckMs` | `5 分钟` | 连续多久没有计时进展就放弃当前课程 |
|
| `stuckMs` | `5 分钟` | 连续多久没有计时进展就放弃当前课程 |
|
||||||
| `maxCourses` | `10` | 本次最多完成多少门;`0` = 不限 |
|
|
||||||
| `maxCourseRetries` | `5` | 同一门课最多重试多少次;超过则停止整轮刷课并提示(不会跳过该课) |
|
| `maxCourseRetries` | `5` | 同一门课最多重试多少次;超过则停止整轮刷课并提示(不会跳过该课) |
|
||||||
| `courseRetryDelayMs` | `30000` | 首次重试前的等待;每次翻倍,最长 5 分钟 |
|
| `courseRetryDelayMs` | `30000` | 首次重试前的等待;每次翻倍,最长 5 分钟 |
|
||||||
| `alignToFirstIncomplete` | `true` | 进入课程先从第一个未学完的课时学起;`false` = 沿用平台上次位置 |
|
| `alignToFirstIncomplete` | `true` | 进入课程先从第一个未学完的课时学起;`false` = 沿用平台上次位置 |
|
||||||
| `preferShortCourses` | `true` | 列表刷课时优先总时长更短的课程(正序);面板勾选框「优先短课程(时长正序)」可随时切换 |
|
| `preferShortCourses` | `true` | 列表刷课时优先总时长更短的课程(正序);面板勾选框「优先短课程(时长正序)」可随时切换 |
|
||||||
| `maxExamTries` | `2` | 同一门课「空卷交卷」的最大次数;超过仍没计入进度就按普通未完成重试(防死循环) |
|
| `pointsEnabled`(`localStorage`) | `true` | 每日积分模式:整门课完成计 1 次,文档 1 / 视频 3 / 音频 2 / 微课 2(每次 3 分,封顶 24 分);面板勾选框「每日积分模式」可随时切换 |
|
||||||
|
| `maxExamTries` | `2` | 同一门课「空卷交卷」的最大次数;超过仍没计入进度就本轮跳过该课、继续下一门(记录在会话里,重启后会重新尝试) |
|
||||||
| `examClickCooldownMs` | `1500` | 考试页内两次点击的间隔(毫秒) |
|
| `examClickCooldownMs` | `1500` | 考试页内两次点击的间隔(毫秒) |
|
||||||
|
|
||||||
对齐起点对「一键刷课」和自己点开的课程(需勾选「当前课程自动连播」)都生效,
|
对齐起点对「一键刷课」和自己点开的课程(需勾选「当前课程自动连播」)都生效,
|
||||||
@@ -63,6 +64,17 @@ Tampermonkey 用户脚本。支持多课时课程与单视频/音频课程;含
|
|||||||
逐个进入。接口不可用(未登录、跨域、平台改版)时自动降级为「当前页按时长正序」,
|
逐个进入。接口不可用(未登录、跨域、平台改版)时自动降级为「当前页按时长正序」,
|
||||||
再不行就回到原来的列表顺序,不会让刷课任务卡住。
|
再不行就回到原来的列表顺序,不会让刷课任务卡住。
|
||||||
|
|
||||||
|
每日积分模式按**整门课**计数:多课时课程要所有课时(含考试)都完成才算一次,
|
||||||
|
按今天实际学过的课时类型(视频/文档/音频/微课)归类;单视频/音频/课件播放页学完也算一次。
|
||||||
|
某类满额后自动换下一类;四类都满额,或剩余额度的类型在当前目录里确认没有内容时,
|
||||||
|
停止刷课并在面板/日志里汇报今日积分。只剩考试、今天没学内容的老课不计分;
|
||||||
|
同一门课当天重复上报只算一次。
|
||||||
|
|
||||||
|
积分是否真的拿到,以平台「我的积分」台账为准:`/ssp/#/my/point` 背后的
|
||||||
|
`api-phx-tc.yunxuetang.cn/ssp/point/history/self` 和 `ssp/rule/org`。脚本完成一门课后
|
||||||
|
等平台入账,只有台账新增学习记录才计数;今日学习积分达到规则上限即收尾。
|
||||||
|
接口不可用(未登录 / 跨域 / 网络)时自动退回本地计数。
|
||||||
|
|
||||||
## 无头运行(Linux / Windows 服务器)
|
## 无头运行(Linux / Windows 服务器)
|
||||||
|
|
||||||
用 `runner/headless.mjs` 把整套逻辑跑在一个无头 Chromium 里:自己起浏览器、用 CDP 把构建产物
|
用 `runner/headless.mjs` 把整套逻辑跑在一个无头 Chromium 里:自己起浏览器、用 CDP 把构建产物
|
||||||
@@ -87,8 +99,8 @@ Tampermonkey 用户脚本。支持多课时课程与单视频/音频课程;含
|
|||||||
sudo apt install -y chromium # 或安装官方包:google-chrome-stable
|
sudo apt install -y chromium # 或安装官方包:google-chrome-stable
|
||||||
# 2. 构建产物
|
# 2. 构建产物
|
||||||
npm install && npm run build
|
npm install && npm run build
|
||||||
# 3. 调参:改 config/runner.config.mjs(maxCourses、budgetMinutes、preferShort…)
|
# 3. 调参:改 config/runner.config.mjs(budgetMinutes、preferShort…)
|
||||||
# 只想临时覆盖就用命令行,例如 npm run headless -- --max-courses 3
|
# 只想临时覆盖就用命令行,例如 npm run headless -- --budget-minutes 15
|
||||||
# 4. 凭据走环境变量(不要写进配置文件)
|
# 4. 凭据走环境变量(不要写进配置文件)
|
||||||
export YUN_XUE_TANG_USR='你的账号'
|
export YUN_XUE_TANG_USR='你的账号'
|
||||||
export YUN_XUE_TANG_PWD='你的密码'
|
export YUN_XUE_TANG_PWD='你的密码'
|
||||||
@@ -231,11 +243,11 @@ Windows 上要注意:`Ctrl+C` 会让运行器优雅收尾(暂停视频、停
|
|||||||
| 参数 | 环境变量 | 配置文件字段 | 默认 | 作用 |
|
| 参数 | 环境变量 | 配置文件字段 | 默认 | 作用 |
|
||||||
| --- | --- | --- | --- | --- |
|
| --- | --- | --- | --- | --- |
|
||||||
| `--check` | — | (不支持) | 关 | 只做环境自检:浏览器能启动、页面能打开、脚本能注入、视频编解码可用;不登录、不动进度,通过则退出码 0 |
|
| `--check` | — | (不支持) | 关 | 只做环境自检:浏览器能启动、页面能打开、脚本能注入、视频编解码可用;不登录、不动进度,通过则退出码 0 |
|
||||||
| `--max-courses N`(旧名 `--max`) | `YUN_XUE_TANG_MAX_COURSES` | `maxCourses` | `10` | 本次最多完成 N 门课,`0` = 不限 |
|
|
||||||
| `--budget-minutes N`(旧名 `--budget`) | `YUN_XUE_TANG_BUDGET_MINUTES` | `budgetMinutes` | `0` | 运行 N 分钟后收尾退出(适合放进 cron 定长跑) |
|
| `--budget-minutes N`(旧名 `--budget`) | `YUN_XUE_TANG_BUDGET_MINUTES` | `budgetMinutes` | `0` | 运行 N 分钟后收尾退出(适合放进 cron 定长跑) |
|
||||||
| `--restart-minutes N`(旧名 `--restart`) | `YUN_XUE_TANG_RESTART_MINUTES` | `restartMinutes` | `0` | 脚本自己停下后等待多少分钟再开新一轮;`0` = 直接退出 |
|
| `--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` | 连续多少分钟无进展判定卡死 |
|
| `--idle-restart-minutes N`(旧名 `--idle`) | `YUN_XUE_TANG_IDLE_RESTART_MINUTES` | `idleRestartMinutes` | `30` | 连续多少分钟无进展判定卡死 |
|
||||||
| `--prefer-short 0\|1` | `YUN_XUE_TANG_PREFER_SHORT` | `preferShort` | `1` | 是否优先短课程(时长正序) |
|
| `--prefer-short 0\|1` | `YUN_XUE_TANG_PREFER_SHORT` | `preferShort` | `1` | 是否优先短课程(时长正序) |
|
||||||
|
| `--points-mode 0\|1` | `YUN_XUE_TANG_POINTS_MODE` | `pointsMode` | `1` | 每日积分模式:整门课完成计 1 次,文档1/视频3/音频2/微课2,封顶即停 |
|
||||||
| `--headless 0\|1`(旧名 `--visible`) | `YUN_XUE_TANG_HEADLESS` | `headless` | `1` | `1` = 无头;`0` = 开有界面浏览器(仅本机调试;无图形会话时被忽略并强制无头) |
|
| `--headless 0\|1`(旧名 `--visible`) | `YUN_XUE_TANG_HEADLESS` | `headless` | `1` | `1` = 无头;`0` = 开有界面浏览器(仅本机调试;无图形会话时被忽略并强制无头) |
|
||||||
| `--origin URL` | `YUN_XUE_TANG_ORIGIN` | `origin` | `https://kfmic.yunxuetang.cn` | 站点根地址(换分公司环境时改这个) |
|
| `--origin URL` | `YUN_XUE_TANG_ORIGIN` | `origin` | `https://kfmic.yunxuetang.cn` | 站点根地址(换分公司环境时改这个) |
|
||||||
| `--url URL` | `YUN_XUE_TANG_URL` | `url` | `<origin>/login.html` | 起始页面 |
|
| `--url URL` | `YUN_XUE_TANG_URL` | `url` | `<origin>/login.html` | 起始页面 |
|
||||||
@@ -245,6 +257,9 @@ Windows 上要注意:`Ctrl+C` 会让运行器优雅收尾(暂停视频、停
|
|||||||
| `--extra-args "…"` | `YUN_XUE_TANG_EXTRA_ARGS` | `extraArgs` | 空 | 追加给浏览器的命令行参数(空格分隔) |
|
| `--extra-args "…"` | `YUN_XUE_TANG_EXTRA_ARGS` | `extraArgs` | 空 | 追加给浏览器的命令行参数(空格分隔) |
|
||||||
| `--log-file PATH`(旧名 `--log`) | `YUN_XUE_TANG_LOG_FILE` | `logFile` | `./run-logs/headless.log` | 日志文件路径 |
|
| `--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` | 单文件上限,超出轮转 |
|
| `--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-tui` | `YUN_XUE_TANG_TUI` | `tui` | 开 | `1`/`0`,是否在终端显示实时面板;stdout 不是 TTY 时自动关闭 |
|
||||||
| `--no-color` | `YUN_XUE_TANG_COLOR` | `color` | 开 | `1`/`0`,面板是否带 ANSI 颜色(也认 `NO_COLOR`) |
|
| `--no-color` | `YUN_XUE_TANG_COLOR` | `color` | 开 | `1`/`0`,面板是否带 ANSI 颜色(也认 `NO_COLOR`) |
|
||||||
| `--config PATH` | `YUN_XUE_TANG_CONFIG` | — | `./config/runner.config.mjs` | 指定另一个配置文件 |
|
| `--config PATH` | `YUN_XUE_TANG_CONFIG` | — | `./config/runner.config.mjs` | 指定另一个配置文件 |
|
||||||
@@ -262,7 +277,6 @@ Windows 上要注意:`Ctrl+C` 会让运行器优雅收尾(暂停视频、停
|
|||||||
```js
|
```js
|
||||||
// config/runner.config.mjs
|
// config/runner.config.mjs
|
||||||
export default {
|
export default {
|
||||||
maxCourses: 0, // 0 = 不限,一直刷到没有未学完的课
|
|
||||||
budgetMinutes: 0, // 0 = 不限运行时长
|
budgetMinutes: 0, // 0 = 不限运行时长
|
||||||
preferShort: true, // 时长正序选课
|
preferShort: true, // 时长正序选课
|
||||||
restartMinutes: 0, // 0 = 停下就退出
|
restartMinutes: 0, // 0 = 停下就退出
|
||||||
@@ -280,7 +294,55 @@ export default {
|
|||||||
- 个人机器的差异建议放 `runner.local.mjs`(已在 `.gitignore` 里)并用 `--config ./runner.local.mjs`
|
- 个人机器的差异建议放 `runner.local.mjs`(已在 `.gitignore` 里)并用 `--config ./runner.local.mjs`
|
||||||
- 配置文件里写 `username` / `password` 会被**忽略并告警**(凭据只认环境变量);写未知字段也会告警
|
- 配置文件里写 `username` / `password` 会被**忽略并告警**(凭据只认环境变量);写未知字段也会告警
|
||||||
|
|
||||||
退出码:`0` 正常收尾(达到 `maxCourses` / `budgetMinutes` / 无更多可学课程)、`1` 无进展卡死、
|
### 运行提醒(Bark)
|
||||||
|
|
||||||
|
无头运行器会在三个时机推 [Bark](https://github.com/Finb/Bark) 手机通知(浏览器端油猴脚本不推送):
|
||||||
|
|
||||||
|
- **开始运行**:进程启动、预检通过后推一条,带运行模式与预算
|
||||||
|
- **获得学分**:每刷完一门有学分的课推一条,带课程名、本门学分、本次累计
|
||||||
|
- **结束**:正常刷完 / 达到上限 / 长时间无进展 / 连续登录失败时推一条,带今日积分、完成门数、用时和结束原因
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"title": "云学堂助手:开始运行",
|
||||||
|
"body": "正在启动浏览器并自动登录\n模式:每日积分\n运行预算:不限"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"title": "云学堂助手:获得 6.52 学分",
|
||||||
|
"body": "课程「某某课程」\n本次累计 12.75 学分 · 已完成 3 门"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"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: 0, // 服务端保留秒数,0 = 永久保留
|
||||||
|
```
|
||||||
|
|
||||||
|
```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` 正常收尾(`budgetMinutes` 到点 / 今日积分完成 / 无更多可学课程)、`1` 无进展卡死、
|
||||||
`2` 环境或参数问题(缺构建产物、缺凭据、找不到浏览器、端口被占、参数写错)、`3` 连续 5 次登录失败(见 runner/)
|
`2` 环境或参数问题(缺构建产物、缺凭据、找不到浏览器、端口被占、参数写错)、`3` 连续 5 次登录失败(见 runner/)
|
||||||
(多半是密码错误或站点要求验证码)。
|
(多半是密码错误或站点要求验证码)。
|
||||||
|
|
||||||
@@ -307,6 +369,21 @@ export default {
|
|||||||
Node 22 与 **官方 google-chrome-stable**(不是发行版 chromium —— 后者不带 H.264/AAC,
|
Node 22 与 **官方 google-chrome-stable**(不是发行版 chromium —— 后者不带 H.264/AAC,
|
||||||
课程视频会一直停在 0 秒),并在构建阶段跑完 `npm run build`,所以镜像开箱即用。
|
课程视频会一直停在 0 秒),并在构建阶段跑完 `npm run build`,所以镜像开箱即用。
|
||||||
|
|
||||||
|
构建镜像推荐用仓库自带的脚本,它会把国内换源、按 `package.json` 版本打标签、构建后自检
|
||||||
|
这几件容易漏的事一趟做完(纯 `docker build` 当然也能用,下面第 1 步就是它展开后的样子):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run docker:build # 默认标签 <包名>:<版本号> + <包名>:latest
|
||||||
|
npm run docker:build -- --mirror # 国内网络:apt 换清华源、npm 换 npmmirror
|
||||||
|
npm run docker:build -- --check # 构建完顺手跑一次 --check 自检
|
||||||
|
npm run docker:build -- --dry-run # 只打印将要执行的 docker 命令,不构建
|
||||||
|
npm run docker:build -- --help # 全部选项(--tag / --platform / --no-cache / --pull / --chrome-url …)
|
||||||
|
Windows 下也可以直接双击 scripts\build-docker.cmd;Linux/macOS 用 ./scripts/build-docker.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
`APT_MIRROR` / `NPM_REGISTRY` / `CHROME_DEB_URL` 三个构建参数按 **命令行 > 环境变量 > 仓库根 `.env`**
|
||||||
|
的优先级取值,所以也可以把它们写进 `.env` 一次配好,之后直接 `npm run docker:build`。
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 1. 构建(首次约 3-5 分钟,主要是下 Chrome 的 deb)
|
# 1. 构建(首次约 3-5 分钟,主要是下 Chrome 的 deb)
|
||||||
docker build -t yun-xue-tang-assistant .
|
docker build -t yun-xue-tang-assistant .
|
||||||
@@ -318,7 +395,7 @@ docker run --rm yun-xue-tang-assistant --check
|
|||||||
docker run -d --name yun-xue-tang \
|
docker run -d --name yun-xue-tang \
|
||||||
-e YUN_XUE_TANG_USR='你的账号' \
|
-e YUN_XUE_TANG_USR='你的账号' \
|
||||||
-e YUN_XUE_TANG_PWD='你的密码' \
|
-e YUN_XUE_TANG_PWD='你的密码' \
|
||||||
-e YUN_XUE_TANG_MAX_COURSES=100 \
|
-e YUN_XUE_TANG_BUDGET_MINUTES=60 \
|
||||||
-v "$PWD/.run-profile:/app/.run-profile" \
|
-v "$PWD/.run-profile:/app/.run-profile" \
|
||||||
-v "$PWD/run-logs:/app/run-logs" \
|
-v "$PWD/run-logs:/app/run-logs" \
|
||||||
--shm-size=512m \
|
--shm-size=512m \
|
||||||
@@ -336,7 +413,7 @@ docker stop yun-xue-tang # SIGTERM → 暂停视频 → 停批量
|
|||||||
cp .env.example .env # 填 YUN_XUE_TANG_USR / YUN_XUE_TANG_PWD
|
cp .env.example .env # 填 YUN_XUE_TANG_USR / YUN_XUE_TANG_PWD
|
||||||
docker compose build
|
docker compose build
|
||||||
docker compose run --rm yun-xue-tang --check # 自检
|
docker compose run --rm yun-xue-tang --check # 自检
|
||||||
docker compose run --rm yun-xue-tang --max-courses 3 # 只刷 3 门,跑完就退
|
docker compose run --rm yun-xue-tang --budget-minutes 15 # 最多跑 15 分钟
|
||||||
docker compose up -d # 常驻
|
docker compose up -d # 常驻
|
||||||
docker compose logs -f
|
docker compose logs -f
|
||||||
docker compose down
|
docker compose down
|
||||||
@@ -399,12 +476,16 @@ src/ 业务脚本源码(拆成多个模块,日
|
|||||||
list.js 列表页 + 短课程优先
|
list.js 列表页 + 短课程优先
|
||||||
player.js 播放器 / 防挂机 / 课时切换
|
player.js 播放器 / 防挂机 / 课时切换
|
||||||
exam.js 考试自动空卷交卷
|
exam.js 考试自动空卷交卷
|
||||||
|
exam-plan.js 考试结果页处置决策(纯函数,可单测)
|
||||||
course.js 课程页主循环
|
course.js 课程页主循环
|
||||||
complete.js 完成 / 未完成重试
|
complete.js 完成 / 未完成重试 / 跳课
|
||||||
index.js 主循环 / 启动 / 调试入口
|
index.js 主循环 / 启动 / 调试入口
|
||||||
scripts/ 开发与运维脚本(不在构建产物里)
|
scripts/ 开发与运维脚本(不在构建产物里)
|
||||||
build.mjs esbuild 打包脚本(产物写回仓库根)
|
build.mjs esbuild 打包脚本(产物写回仓库根)
|
||||||
check.mjs 静态检查:node --check + 批处理纯 ASCII/CRLF 校验
|
check.mjs 静态检查:node --check + 批处理纯 ASCII/CRLF 校验
|
||||||
|
build-docker.mjs 构建镜像(换源 / 打标签 / 构建后自检,参数见 --help)
|
||||||
|
build-docker.cmd Windows 一键构建镜像(双击即可)
|
||||||
|
build-docker.sh Linux / macOS 构建镜像(转交 build-docker.mjs)
|
||||||
start-dev.cmd Windows 一键启动本地热加载服务(双击即可)
|
start-dev.cmd Windows 一键启动本地热加载服务(双击即可)
|
||||||
start-headless.cmd Windows 一键启动无头运行器(双击即可)
|
start-headless.cmd Windows 一键启动无头运行器(双击即可)
|
||||||
runner/ 无头运行器(Linux / Windows,无图形化环境)
|
runner/ 无头运行器(Linux / Windows,无图形化环境)
|
||||||
@@ -419,6 +500,7 @@ runner/ 无头运行器(Linux / Windows,无图形
|
|||||||
page.mjs 页面求值封装与注入后调用的表达式
|
page.mjs 页面求值封装与注入后调用的表达式
|
||||||
session.mjs 单次会话:起浏览器 / 注入 / 自动重登 / 崩溃自愈
|
session.mjs 单次会话:起浏览器 / 注入 / 自动重登 / 崩溃自愈
|
||||||
selfcheck.mjs --check 只读环境自检
|
selfcheck.mjs --check 只读环境自检
|
||||||
|
notify.mjs Bark 手机通知(开始运行 / 获得学分 / 收尾)
|
||||||
tui.mjs 终端面板(框线 + 进度条,q 退出,非 TTY 自动关闭)
|
tui.mjs 终端面板(框线 + 进度条,q 退出,非 TTY 自动关闭)
|
||||||
study.mjs 学习统计(本次播放时长 / 获得学分)
|
study.mjs 学习统计(本次播放时长 / 获得学分)
|
||||||
supervisor.mjs 崩溃重启循环与退出码
|
supervisor.mjs 崩溃重启循环与退出码
|
||||||
@@ -452,13 +534,16 @@ docs/
|
|||||||
| `yun-xue-tang-login-v1` | 勾选「记住密码」时的账号密码(base64 混淆,**不是加密**) |
|
| `yun-xue-tang-login-v1` | 勾选「记住密码」时的账号密码(base64 混淆,**不是加密**) |
|
||||||
| `yun-xue-tang-auto-play-enabled` | 「当前课程自动连播」开关 |
|
| `yun-xue-tang-auto-play-enabled` | 「当前课程自动连播」开关 |
|
||||||
| `yun-xue-tang-prefer-short` | 「优先短课程(时长正序)」开关(`1` / `0`) |
|
| `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-target-catalog-url` | 目标目录 URL:决定刷哪个学院/目录的课(短课程队列的缓存键也来自它) |
|
||||||
| `yun-xue-tang-auto-start-after-login` | 登录后自动开始刷课的一次性标记(5 分钟内有效) |
|
| `yun-xue-tang-auto-start-after-login` | 登录后自动开始刷课的一次性标记(5 分钟内有效) |
|
||||||
|
|
||||||
| `sessionStorage` 键(本次运行,关掉标签页即清空) | 内容 |
|
| `sessionStorage` 键(本次运行,关掉标签页即清空) | 内容 |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `yun-xue-tang-run-state-v3` | 本轮是否在跑、页码、当前课程、本轮已完成与待重试记录 |
|
| `yun-xue-tang-run-state-v3` | 本轮是否在跑、页码、当前课程、本轮已完成 / 待重试 / 已跳过(考试交不了)记录 |
|
||||||
| `yun-xue-tang-short-catalog-v1` | 短课程时长队列缓存(TTL 5 分钟) |
|
| `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` 里,
|
旧版本(v2.8.0 之前)把所有状态整块存在 `localStorage` 的 `yun-xue-tang-batch-v2` 里,
|
||||||
包括「是否在跑」。现在这个键只在启动时做一次性迁移:只迁进度(已完成书目、
|
包括「是否在跑」。现在这个键只在启动时做一次性迁移:只迁进度(已完成书目、
|
||||||
@@ -499,6 +584,11 @@ v2.6.0 新增「优先短课程(时长正序)」:真实站点读取 5148
|
|||||||
v2.8.0 状态分层重构:刷课开关不再进 localStorage(修「还没登录就开始刷课」)、字段名语义化、
|
v2.8.0 状态分层重构:刷课开关不再进 localStorage(修「还没登录就开始刷课」)、字段名语义化、
|
||||||
短课程模式下页码导航所有权归一到 `chooseShortCourse`(省掉每次多跳一页+白等 3.5 秒)。
|
短课程模式下页码导航所有权归一到 `chooseShortCourse`(省掉每次多跳一页+白等 3.5 秒)。
|
||||||
|
|
||||||
|
每日积分模式:整门课完成计 1 次(文档1 / 视频3 / 音频2 / 微课2),每次 3 分封顶 24 分;
|
||||||
|
多课时课程按今天实际学过的课时类型归类,只剩考试的老课不计分;先补文档/音频/微课单条内容,
|
||||||
|
视频靠课程;某类满额自动换下一类,四类都满或无内容即停。计数落 localStorage 并跨天清零,
|
||||||
|
面板与无头 TUI 都显示今日积分。离线回归见 `node dev/tests/points-test.mjs`(`npm run test:points`)。
|
||||||
|
|
||||||
v2.7.0 修复「进入课程有概率不自动播放」和「学完后不转下一门」:新增单视频/音频/课件播放页识别,
|
v2.7.0 修复「进入课程有概率不自动播放」和「学完后不转下一门」:新增单视频/音频/课件播放页识别,
|
||||||
完成判定同时支持 `已完成 x/y`、`已完成 N%`、`已完成学习`;真机复现、修复前后对比与回归结果见
|
完成判定同时支持 `已完成 x/y`、`已完成 N%`、`已完成学习`;真机复现、修复前后对比与回归结果见
|
||||||
[`docs/evidence/completion-next-evidence.txt`](docs/evidence/completion-next-evidence.txt)。
|
[`docs/evidence/completion-next-evidence.txt`](docs/evidence/completion-next-evidence.txt)。
|
||||||
|
|||||||
@@ -14,13 +14,13 @@
|
|||||||
*/
|
*/
|
||||||
export default {
|
export default {
|
||||||
// ---------- 选课 / 刷课策略 ----------
|
// ---------- 选课 / 刷课策略 ----------
|
||||||
/** 本次最多完成多少门课;0 = 不限(一直刷到没有未学完的课) */
|
|
||||||
maxCourses: 100,
|
|
||||||
/** 运行多少分钟后收尾退出;0 = 不限(适合 cron 定长跑时设成 60) */
|
/** 运行多少分钟后收尾退出;0 = 不限(适合 cron 定长跑时设成 60) */
|
||||||
budgetMinutes: 0,
|
budgetMinutes: 0,
|
||||||
/** 优先总时长最短的课程(正序);false = 按列表原顺序 */
|
/** 优先总时长最短的课程(正序);false = 按列表原顺序 */
|
||||||
preferShort: true,
|
preferShort: true,
|
||||||
/** 脚本自己停下后等多少分钟再开新一轮;0 = 直接退出。配合 --max 可以实现分段刷完 */
|
/** 每日积分模式:整门课完成计 1 次(文档1/视频3/音频2/微课2,每次3分),四类封顶即停;false = 普通刷课 */
|
||||||
|
pointsMode: true,
|
||||||
|
/** 脚本自己停下后等多少分钟再开新一轮;0 = 直接退出。配合 restartMinutes 可以分段刷完 */
|
||||||
restartMinutes: 0,
|
restartMinutes: 0,
|
||||||
/** 连续多少分钟没有任何进展就判定卡死并退出(0 = 用内置的 30 分钟) */
|
/** 连续多少分钟没有任何进展就判定卡死并退出(0 = 用内置的 30 分钟) */
|
||||||
idleRestartMinutes: 30,
|
idleRestartMinutes: 30,
|
||||||
@@ -47,6 +47,20 @@ export default {
|
|||||||
/** 单个日志文件上限(字节),超出后轮转成 .1 */
|
/** 单个日志文件上限(字节),超出后轮转成 .1 */
|
||||||
logMaxBytes: 5 * 1024 * 1024,
|
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 = 永久保留(不传 ttl 参数) */
|
||||||
|
barkTtl: 0,
|
||||||
|
|
||||||
// ---------- 终端面板 ----------
|
// ---------- 终端面板 ----------
|
||||||
/** 终端里显示实时面板(框线 + 进度条);false = 回到逐行日志。非 TTY(重定向/计划任务)时自动关闭 */
|
/** 终端里显示实时面板(框线 + 进度条);false = 回到逐行日志。非 TTY(重定向/计划任务)时自动关闭 */
|
||||||
tui: true,
|
tui: true,
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ node dev/tests/real-test.mjs --keep # 跑完不关浏览器,便于人工复
|
|||||||
```bash
|
```bash
|
||||||
npm run test:tui # 面板渲染 / 列宽 / 尺寸自适应
|
npm run test:tui # 面板渲染 / 列宽 / 尺寸自适应
|
||||||
npm run test:study # 学习时长与学分累计口径
|
npm run test:study # 学习时长与学分累计口径
|
||||||
|
npm run test:points # 每日积分:类型识别 / 封顶 / 去重 / 跨天清零 / 选类顺序
|
||||||
```
|
```
|
||||||
|
|
||||||
它用假 stdout 渲染真实帧,逐行量列宽,重点盯五件容易错的事:
|
它用假 stdout 渲染真实帧,逐行量列宽,重点盯五件容易错的事:
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* 考试结果页处置(src/exam-plan.js)自测:纯决策逻辑,不需要浏览器。
|
||||||
|
*
|
||||||
|
* 钉住的回归:重进课程时平台会恢复上次的考试结果页。那一页不是本页交的卷,
|
||||||
|
* 不能计入「空卷交卷」次数,否则 maxExamTries 失效且会在结果页↔课程页之间死循环。
|
||||||
|
*
|
||||||
|
* 用法:
|
||||||
|
* node dev/tests/exam-test.mjs
|
||||||
|
* npm run test:exam
|
||||||
|
*/
|
||||||
|
import { planExamResult } from '../../src/exam-plan.js';
|
||||||
|
|
||||||
|
let failed = 0;
|
||||||
|
function eq(actual, expect, name) {
|
||||||
|
if (actual === expect) console.log(' ✔ ' + name);
|
||||||
|
else {
|
||||||
|
failed++;
|
||||||
|
console.log(' ✘ ' + name + ' → 期望 ' + JSON.stringify(expect) +
|
||||||
|
',实际 ' + JSON.stringify(actual));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('考试结果页');
|
||||||
|
eq(planExamResult({ submitted: true, complete: false }), 'count', '本页交的卷、平台未记账 → 计一次空卷交卷');
|
||||||
|
eq(planExamResult({ submitted: true, complete: true }), 'complete', '本页交的卷、平台已记账 → 直接收课');
|
||||||
|
eq(planExamResult({ submitted: false, complete: false, staleTries: 0 }), 'reback',
|
||||||
|
'平台恢复的旧结果页 → 回考试说明页重进,不计交卷');
|
||||||
|
eq(planExamResult({ submitted: false, complete: false, staleTries: 2 }), 'skip',
|
||||||
|
'反复回不到考试说明页 → 跳过该课等人工');
|
||||||
|
eq(planExamResult({ submitted: false, complete: true }), 'complete',
|
||||||
|
'没交卷但平台已算完成 → 直接收课');
|
||||||
|
|
||||||
|
if (failed) {
|
||||||
|
console.log('\n失败 ' + failed + ' 项');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
console.log('\n全部通过');
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* Bark 完成提醒(runner/notify.mjs)自测:只验证地址拼接与文案,不发真实请求。
|
||||||
|
*
|
||||||
|
* 这两块错了都不会让运行器报错——只会在手机上收到一条打不开的链接或看不懂的文案,
|
||||||
|
* 而且往往要等到真正刷完那一刻才发现。用纯函数把格式钉死。
|
||||||
|
*
|
||||||
|
* 用法:
|
||||||
|
* node dev/tests/notify-test.mjs
|
||||||
|
* npm run test:notify
|
||||||
|
*/
|
||||||
|
import { buildBarkUrl, buildFinishMessage, buildStartMessage, buildCreditMessage } 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: '无更多可学课程',
|
||||||
|
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(done.body.split('\n').filter((l) => l.indexOf('完成') >= 0).length, 1, '完成门数只出现一次');
|
||||||
|
|
||||||
|
const pointsDone = buildFinishMessage({
|
||||||
|
kind: 'done',
|
||||||
|
finishReason: '可用内容已学完',
|
||||||
|
completed: 4,
|
||||||
|
elapsed: 1086,
|
||||||
|
points: { enabled: true, text: '今日积分 24/24 · 文档1/1 视频3/3 音频1/2 微课0/2' },
|
||||||
|
});
|
||||||
|
ok(pointsDone.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('开始 / 学分通知');
|
||||||
|
{
|
||||||
|
const start = buildStartMessage({ POINTS_MODE: true, BUDGET_MINUTES: 180 });
|
||||||
|
eq(start.title, '云学堂助手:开始运行', '开始运行标题');
|
||||||
|
ok(start.body.indexOf('模式:每日积分') >= 0, '开始通知带上运行模式');
|
||||||
|
ok(start.body.indexOf('运行预算:180 分钟') >= 0, '开始通知带上运行预算');
|
||||||
|
|
||||||
|
const startFree = buildStartMessage({ POINTS_MODE: false, BUDGET_MINUTES: 0 });
|
||||||
|
ok(startFree.body.indexOf('模式:普通刷课') >= 0 && startFree.body.indexOf('运行预算:不限') >= 0,
|
||||||
|
'普通刷课 + 不限预算');
|
||||||
|
|
||||||
|
const credit = buildCreditMessage({ course: '某课程', credit: 6.52, total: 12.75, completed: 3 });
|
||||||
|
eq(credit.title, '云学堂助手:获得 6.52 学分', '学分通知标题带本次学分数');
|
||||||
|
ok(credit.body.indexOf('课程「某课程」') >= 0, '学分通知带上课程名');
|
||||||
|
ok(credit.body.indexOf('本次累计 12.75 学分 · 已完成 3 门') >= 0, '学分通知带上累计与完成门数');
|
||||||
|
eq(buildCreditMessage({ credit: 1, total: 1 }).title, '云学堂助手:获得 1 学分', '整数学分不带小数点');
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('');
|
||||||
|
if (failed) {
|
||||||
|
console.log('✘ ' + failed + ' 项失败');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
console.log('✔ 全部通过');
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* 只读探测:打开「我的积分」页,抓它真实调的接口与返回字段。
|
||||||
|
*
|
||||||
|
* node dev/tests/points-api-probe.mjs
|
||||||
|
*
|
||||||
|
* 用现有 profile 里的登录态(不登录、不点课程、不动进度),
|
||||||
|
* 打印 /ssp/#/my/point 加载期间与积分/学时相关的 XHR 响应,
|
||||||
|
* 以及页面渲染出来的文本,用来确认「今日获得多少积分」该读哪个字段。
|
||||||
|
*/
|
||||||
|
import path from 'node:path';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { connect, httpJson, sleep } from '../../runner/cdp.mjs';
|
||||||
|
import { launchBrowser, resolveBrowser } from '../../runner/browser.mjs';
|
||||||
|
|
||||||
|
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
const ROOT = path.resolve(HERE, '..', '..');
|
||||||
|
const PORT = Number(process.env.YUN_XUE_TANG_CDP_PORT || 9340);
|
||||||
|
const ORIGIN = (process.env.YUN_XUE_TANG_ORIGIN || 'https://kfmic.yunxuetang.cn').replace(/\/+$/, '');
|
||||||
|
const TARGET = ORIGIN + '/ssp/#/my/point';
|
||||||
|
const LOGIN = ORIGIN + '/login.html';
|
||||||
|
const PROFILE = process.env.YUN_XUE_TANG_PROFILE_DIR
|
||||||
|
? path.resolve(ROOT, process.env.YUN_XUE_TANG_PROFILE_DIR)
|
||||||
|
: path.join(ROOT, '.run-profile');
|
||||||
|
|
||||||
|
const INTERESTING = /point|jf|score|credit|study|history|\/ssp\/rule|\/user\/point/i;
|
||||||
|
|
||||||
|
function trim(s, n = 1200) {
|
||||||
|
const t = String(s == null ? '' : s).replace(/\s+/g, ' ');
|
||||||
|
return t.length > n ? t.slice(0, n) + '…' : t;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log('[探测] 浏览器:' + resolveBrowser());
|
||||||
|
console.log('[探测] profile:' + PROFILE);
|
||||||
|
console.log('[探测] 页面:' + TARGET);
|
||||||
|
|
||||||
|
const browser = await launchBrowser({
|
||||||
|
binary: resolveBrowser(),
|
||||||
|
profileDir: PROFILE,
|
||||||
|
port: PORT,
|
||||||
|
headless: true,
|
||||||
|
log: (s) => console.log(s),
|
||||||
|
});
|
||||||
|
let cdp = null;
|
||||||
|
try {
|
||||||
|
const target = await httpJson(
|
||||||
|
'http://127.0.0.1:' + PORT + '/json/new?' + encodeURIComponent(LOGIN), 'PUT');
|
||||||
|
cdp = await connect(target.webSocketDebuggerUrl);
|
||||||
|
await cdp.send('Page.enable');
|
||||||
|
await cdp.send('Runtime.enable');
|
||||||
|
await cdp.send('Network.enable');
|
||||||
|
await cdp.send('Log.enable');
|
||||||
|
|
||||||
|
const reqs = new Map();
|
||||||
|
const hits = [];
|
||||||
|
const all = [];
|
||||||
|
cdp.onEvent((m) => {
|
||||||
|
if (m.method === 'Runtime.consoleAPICalled') {
|
||||||
|
const text = (m.params.args || []).map((a) => (a.value !== undefined ? a.value : a.description || '')).join(' ');
|
||||||
|
console.log('[console.' + m.params.type + '] ' + trim(text, 400));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (m.method === 'Log.entryAdded') {
|
||||||
|
console.log('[log.' + m.params.entry.level + '] ' + trim(m.params.entry.text, 400));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (m.method === 'Network.requestWillBeSent') {
|
||||||
|
const info = {
|
||||||
|
url: m.params.request.url,
|
||||||
|
method: m.params.request.method,
|
||||||
|
type: m.params.type,
|
||||||
|
headers: m.params.request.headers,
|
||||||
|
postData: m.params.request.postData,
|
||||||
|
};
|
||||||
|
reqs.set(m.params.requestId, info);
|
||||||
|
if (/XHR|Fetch/.test(info.type || '')) all.push(info);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (m.method === 'Network.responseReceived') {
|
||||||
|
const url = m.params.response.url || '';
|
||||||
|
if (!INTERESTING.test(url)) return;
|
||||||
|
const req = reqs.get(m.params.requestId) || {};
|
||||||
|
if (req.type && !/XHR|Fetch/.test(req.type)) return;
|
||||||
|
hits.push({
|
||||||
|
requestId: m.params.requestId,
|
||||||
|
url: url,
|
||||||
|
method: req.method || '',
|
||||||
|
status: m.params.response.status,
|
||||||
|
mime: m.params.response.mimeType,
|
||||||
|
headers: req.headers || {},
|
||||||
|
postData: req.postData || '',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await sleep(6000);
|
||||||
|
|
||||||
|
// 只登录,不启动刷课:注入脚本后自己填表 + 点「登录」,并清掉「登录后自动刷课」标记。
|
||||||
|
const usr = process.env.YUN_XUE_TANG_USR || '';
|
||||||
|
const pwd = process.env.YUN_XUE_TANG_PWD || '';
|
||||||
|
const scriptSrc = fs.readFileSync(path.join(ROOT, 'yun-xue-tang-assistant.user.js'), 'utf8');
|
||||||
|
await cdp.send('Runtime.evaluate', { expression: scriptSrc });
|
||||||
|
await sleep(1200);
|
||||||
|
const filled = await cdp.send('Runtime.evaluate', {
|
||||||
|
expression: `(function () {
|
||||||
|
var a = window.__yunXueTangAuto;
|
||||||
|
if (!a) return 'no-api';
|
||||||
|
try { localStorage.removeItem('yun-xue-tang-auto-start-after-login'); } catch (e) {}
|
||||||
|
var ok = a.fillLoginForm(${JSON.stringify(usr)}, ${JSON.stringify(pwd)});
|
||||||
|
try { a.checkLoginAgreement(); } catch (e) {}
|
||||||
|
try { a.doLoginAndStart(); } catch (e) {}
|
||||||
|
// doLoginAndStart 会写「登录后自动刷课」标记;这里立刻清掉,保证只登录不刷课
|
||||||
|
try { localStorage.removeItem('yun-xue-tang-auto-start-after-login'); } catch (e) {}
|
||||||
|
try { a.S.batchRunning = false; } catch (e) {}
|
||||||
|
return ok ? 'submitted' : 'no-fields';
|
||||||
|
})()`,
|
||||||
|
returnByValue: true,
|
||||||
|
});
|
||||||
|
console.log('[登录] 结果:' + filled.result.value);
|
||||||
|
await sleep(12000);
|
||||||
|
// 保险:登录页若把「自动刷课」标记写进 localStorage,这里再清一次并停批量
|
||||||
|
await cdp.send('Runtime.evaluate', {
|
||||||
|
expression: `(function () {
|
||||||
|
try { localStorage.removeItem('yun-xue-tang-auto-start-after-login'); } catch (e) {}
|
||||||
|
var a = window.__yunXueTangAuto;
|
||||||
|
if (a) { try { a.S.batchRunning = false; a.S.batchFinished = false; } catch (e) {} }
|
||||||
|
return true;
|
||||||
|
})()`,
|
||||||
|
});
|
||||||
|
|
||||||
|
hits.length = 0;
|
||||||
|
all.length = 0;
|
||||||
|
await cdp.send('Page.navigate', { url: TARGET });
|
||||||
|
await sleep(25000);
|
||||||
|
|
||||||
|
const state = await cdp.send('Runtime.evaluate', {
|
||||||
|
expression: `JSON.stringify((function () {
|
||||||
|
function findTok(s) {
|
||||||
|
try {
|
||||||
|
for (var i = 0; i < s.length; i++) {
|
||||||
|
var k = s.key(i), v = s.getItem(k) || '';
|
||||||
|
if (/eyJ[a-zA-Z0-9_-]{10,}/.test(v)) return k;
|
||||||
|
}
|
||||||
|
} catch (e) {}
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
href: location.href,
|
||||||
|
ready: document.readyState,
|
||||||
|
appLen: (document.getElementById('app') || {}).innerHTML ? document.getElementById('app').innerHTML.length : 0,
|
||||||
|
ls: Object.keys(localStorage || {}),
|
||||||
|
ss: Object.keys(sessionStorage || {}),
|
||||||
|
lsTok: findTok(localStorage),
|
||||||
|
ssTok: findTok(sessionStorage),
|
||||||
|
cookies: String(document.cookie || '').split(';').map(function (s) { return s.split('=')[0].trim(); }),
|
||||||
|
};
|
||||||
|
})())`,
|
||||||
|
returnByValue: true,
|
||||||
|
}).then((r) => JSON.parse(r.result.value || '{}')).catch(() => ({}));
|
||||||
|
console.log('\n[状态] ' + JSON.stringify(state));
|
||||||
|
|
||||||
|
const info = await cdp.send('Runtime.evaluate', {
|
||||||
|
expression: 'JSON.stringify({ href: location.href, title: document.title, text: document.body ? document.body.innerText : "" })',
|
||||||
|
returnByValue: true,
|
||||||
|
}).then((r) => JSON.parse(r.result.value || '{}')).catch(() => ({}));
|
||||||
|
console.log('\n[页面] ' + info.href + ' title=' + info.title);
|
||||||
|
console.log('[页面文本] ' + trim(info.text, 800));
|
||||||
|
|
||||||
|
// 用构建产物自己的平台台账逻辑再拉一次,验证 token / CORS / 折算链路
|
||||||
|
if (state.lsTok) {
|
||||||
|
await cdp.send('Runtime.evaluate', { expression: scriptSrc });
|
||||||
|
await sleep(1200);
|
||||||
|
const ledger = await cdp.send('Runtime.evaluate', {
|
||||||
|
expression: `(async function () {
|
||||||
|
var tk = localStorage.getItem('token') || '';
|
||||||
|
var h = { 'Content-Type': 'application/json;charset=UTF-8', source: '501', 'x-yxt-product': 'xxv2', token: tk };
|
||||||
|
var d0 = new Date();
|
||||||
|
var p2 = function (n) { return n < 10 ? '0' + n : '' + n; };
|
||||||
|
var day = d0.getFullYear() + '-' + p2(d0.getMonth() + 1) + '-' + p2(d0.getDate());
|
||||||
|
var body = JSON.stringify({
|
||||||
|
startDate: day + ' 00:00:00', endDate: day + ' 23:59:59',
|
||||||
|
sourceType: -1, optionType: 0, type: 1, userId: ''
|
||||||
|
});
|
||||||
|
var out = {};
|
||||||
|
async function probe(name, url, opts) {
|
||||||
|
try {
|
||||||
|
var r = await fetch(url, opts);
|
||||||
|
out[name] = { status: r.status, body: (await r.text()).slice(0, 400) };
|
||||||
|
} catch (e) { out[name] = { error: String(e) }; }
|
||||||
|
}
|
||||||
|
await probe('rules', 'https://api-phx-tc.yunxuetang.cn/ssp/rule/org', { headers: h });
|
||||||
|
await probe('rulesQ', 'https://api-phx-tc.yunxuetang.cn/ssp/rule/org?0=' + Math.random(), { headers: h });
|
||||||
|
await probe('ledger', 'https://api-phx-tc.yunxuetang.cn/ssp/point/history/self?limit=200&offset=0', { method: 'POST', headers: h, body: body });
|
||||||
|
// 统计历史台账里 nameType / actionType 的分布,判断能否据此归类
|
||||||
|
try {
|
||||||
|
var wide = JSON.stringify({
|
||||||
|
startDate: '2025-01-01 00:00:00', endDate: d0.getFullYear() + '-12-31 23:59:59',
|
||||||
|
sourceType: -1, optionType: 0, type: 1, userId: ''
|
||||||
|
});
|
||||||
|
var lr = await fetch('https://api-phx-tc.yunxuetang.cn/ssp/point/history/self?limit=200&offset=0', { method: 'POST', headers: h, body: wide });
|
||||||
|
var lj = await lr.json();
|
||||||
|
var combos = {};
|
||||||
|
for (var rec of (lj.datas || [])) {
|
||||||
|
if (Number(rec.sourceType) !== 1002) continue;
|
||||||
|
var k = [rec.nameType, rec.actionType, rec.point].join('/');
|
||||||
|
if (!combos[k]) combos[k] = { n: 0, samples: [] };
|
||||||
|
combos[k].n++;
|
||||||
|
if (combos[k].samples.length < 3) combos[k].samples.push(String(rec.remark || '').slice(0, 40));
|
||||||
|
}
|
||||||
|
out.combos = combos;
|
||||||
|
} catch (e) { out.combos = { error: String(e) }; }
|
||||||
|
var a = window.__yunXueTangAuto;
|
||||||
|
if (a) {
|
||||||
|
var d = await a.refreshPlatformPoints(a.points, { force: true });
|
||||||
|
out.platform = {
|
||||||
|
ok: d.ok, todayPoints: d.todayPoints, maxPoints: d.maxPoints, rules: d.rules,
|
||||||
|
recordCount: d.records ? d.records.length : 0, reason: d.reason,
|
||||||
|
};
|
||||||
|
out.counts = a.points.snapshot();
|
||||||
|
}
|
||||||
|
return JSON.stringify(out);
|
||||||
|
})()`,
|
||||||
|
awaitPromise: true,
|
||||||
|
returnByValue: true,
|
||||||
|
});
|
||||||
|
console.log('\n[台账] ' + trim(ledger.result.value, 3000));
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\n[XHR/Fetch] 共 ' + all.length + ' 条:');
|
||||||
|
const seen = new Set();
|
||||||
|
for (const r of all) {
|
||||||
|
if (seen.has(r.url)) continue;
|
||||||
|
seen.add(r.url);
|
||||||
|
console.log(' ' + r.method + ' ' + r.url);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('\n[接口] 命中 ' + hits.length + ' 条:'); for (const h of hits) {
|
||||||
|
console.log('\n--- ' + h.method + ' ' + h.status + ' ' + h.url);
|
||||||
|
const hdr = h.headers || {};
|
||||||
|
for (const [k, v] of Object.entries(hdr)) {
|
||||||
|
console.log(' ' + k + ': ' + String(v).slice(0, 120));
|
||||||
|
}
|
||||||
|
if (h.postData) console.log(' body: ' + trim(h.postData, 600));
|
||||||
|
try {
|
||||||
|
const body = await cdp.send('Network.getResponseBody', { requestId: h.requestId });
|
||||||
|
const text = body.base64Encoded ? Buffer.from(body.body, 'base64').toString('utf8') : body.body;
|
||||||
|
console.log(trim(text, 4000));
|
||||||
|
} catch (e) {
|
||||||
|
console.log('(响应体不可读:' + e.message + ')');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await cdp.send('Runtime.evaluate', {
|
||||||
|
expression: `JSON.stringify(performance.getEntriesByType('resource').map(function(e){return e.name;}).filter(function(u){return ${INTERESTING}.test(u);}))`,
|
||||||
|
returnByValue: true,
|
||||||
|
}).then((r) => JSON.parse(r.result.value || '[]')).catch(() => []);
|
||||||
|
console.log('\n[资源] ' + res.length + ' 条');
|
||||||
|
for (const u of res.slice(0, 60)) console.log(' ' + u);
|
||||||
|
} finally {
|
||||||
|
if (cdp) cdp.close();
|
||||||
|
await browser.kill();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((e) => {
|
||||||
|
console.error('[失败] ' + (e && e.stack ? e.stack : e));
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* 平台积分台账(src/points-platform.js)自测:
|
||||||
|
* 平台台账才是权威计数,这里钉死「按课程名归类」「用待对账记录兜底」「同一条不重复计」。
|
||||||
|
*
|
||||||
|
* 用法:
|
||||||
|
* node dev/tests/points-platform-test.mjs
|
||||||
|
*/
|
||||||
|
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); },
|
||||||
|
clear: () => mem.clear(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
globalThis.localStorage = fakeStorage();
|
||||||
|
|
||||||
|
const { applyLedger, rememberCourseAward } = await import('../../src/points-platform.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));
|
||||||
|
}
|
||||||
|
|
||||||
|
function tracker() {
|
||||||
|
const counts = { doc: 0, video: 0, audio: 0, micro: 0 };
|
||||||
|
const seen = new Set();
|
||||||
|
return {
|
||||||
|
counts,
|
||||||
|
record(type, id) {
|
||||||
|
if (seen.has(id)) return false;
|
||||||
|
seen.add(id);
|
||||||
|
counts[type] = (counts[type] || 0) + 1;
|
||||||
|
return true;
|
||||||
|
},
|
||||||
|
resetCounts() {
|
||||||
|
for (const k of Object.keys(counts)) counts[k] = 0;
|
||||||
|
seen.clear();
|
||||||
|
},
|
||||||
|
summary() { return ''; },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const p = (n) => (n < 10 ? '0' + n : '' + n);
|
||||||
|
const day = now.getFullYear() + '-' + p(now.getMonth() + 1) + '-' + p(now.getDate());
|
||||||
|
|
||||||
|
console.log('按课程名归类');
|
||||||
|
{
|
||||||
|
const t = tracker();
|
||||||
|
rememberCourseAward('课程 A', 'video');
|
||||||
|
const data = {
|
||||||
|
ok: true, day,
|
||||||
|
records: [{ id: '1', point: 3, remark: '课程 A', sourceType: 1002 }],
|
||||||
|
};
|
||||||
|
eq(applyLedger(data, t), 1, '平台入账 1 条');
|
||||||
|
eq(t.counts.video, 1, '计入视频');
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('台账 nameType 优先于标题');
|
||||||
|
{
|
||||||
|
const t = tracker();
|
||||||
|
const data = {
|
||||||
|
ok: true, day,
|
||||||
|
records: [{ id: '9', point: 3, remark: '不认识的标题', sourceType: 1002, nameType: 1008 }],
|
||||||
|
};
|
||||||
|
eq(applyLedger(data, t), 1, '靠 nameType 归类');
|
||||||
|
eq(t.counts.audio, 1, 'nameType 1008 = 音频');
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('平台用课时名时用待对账记录兜底');
|
||||||
|
{
|
||||||
|
const t = tracker();
|
||||||
|
rememberCourseAward('课程 B', 'doc');
|
||||||
|
const data = {
|
||||||
|
ok: true, day,
|
||||||
|
records: [{ id: '2', point: 3, remark: '第一节课时名', sourceType: 1002 }],
|
||||||
|
};
|
||||||
|
eq(applyLedger(data, t), 1, '兜底计入');
|
||||||
|
eq(t.counts.doc, 1, '计入文档');
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('同一条记录不重复计');
|
||||||
|
{
|
||||||
|
const t = tracker();
|
||||||
|
rememberCourseAward('课程 C', 'audio');
|
||||||
|
const data = {
|
||||||
|
ok: true, day,
|
||||||
|
records: [
|
||||||
|
{ id: '3', point: 3, remark: '课程 C', sourceType: 1002 },
|
||||||
|
{ id: '3', point: 3, remark: '课程 C', sourceType: 1002 },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
eq(applyLedger(data, t), 1, '同一 id 只计一次');
|
||||||
|
eq(applyLedger(data, t), 0, '再次应用不重复计');
|
||||||
|
eq(t.counts.audio, 1, '音频只计 1 次');
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('未登录 / 接口失败时不动计数');
|
||||||
|
{
|
||||||
|
const t = tracker();
|
||||||
|
eq(applyLedger({ ok: false, reason: 'no-token' }, t), 0, 'ok:false 直接跳过');
|
||||||
|
eq(t.counts.video, 0, '计数保持 0');
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('');
|
||||||
|
if (failed) {
|
||||||
|
console.log('✘ ' + failed + ' 项失败');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
console.log('✔ 全部通过');
|
||||||
@@ -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('每日积分自测:全部通过');
|
||||||
@@ -142,7 +142,29 @@ console.log('防重复计数');
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 5. 学分文本:浮点累加不出现 3.7499999
|
// 5. 学分事件:每次真正计入学分时产出 { course, credit },供 Bark 通知使用
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
console.log('学分事件');
|
||||||
|
{
|
||||||
|
const s = createStudyTracker({ now: clock().now });
|
||||||
|
let st = s.update({ course: 'A', credit: 2.5, completed: 0, video: video(false) });
|
||||||
|
eq(st.earned.length, 0, '只有学分、没完成时没有事件');
|
||||||
|
|
||||||
|
st = s.update({ course: 'A', credit: null, completed: 1, video: video(false) });
|
||||||
|
eq(st.earned.length, 1, '课程完成时产出一条事件');
|
||||||
|
eq(st.earned[0].course, 'A', '事件带课程名');
|
||||||
|
eq(st.earned[0].credit, 2.5, '事件带本门学分数');
|
||||||
|
eq(st.creditEarned, 2.5, '返回值里的累计学分同步更新');
|
||||||
|
|
||||||
|
st = s.update({ course: 'A', credit: null, completed: 1, video: video(false) });
|
||||||
|
eq(st.earned.length, 0, '同一门重复上报不重复产生事件');
|
||||||
|
|
||||||
|
st = s.update({ course: 'C', credit: null, completed: 2, video: video(false) });
|
||||||
|
eq(st.earned.length, 0, '没读到学分的课完成时不产生事件');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 6. 学分文本:浮点累加不出现 3.7499999
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
console.log('学分文本');
|
console.log('学分文本');
|
||||||
{
|
{
|
||||||
@@ -155,7 +177,7 @@ console.log('学分文本');
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 6. 摘要 / 空状态
|
// 7. 摘要 / 空状态
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
console.log('摘要与空状态');
|
console.log('摘要与空状态');
|
||||||
{
|
{
|
||||||
@@ -182,7 +204,7 @@ console.log('摘要与空状态');
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 7. reset:重开一轮(supervisor 重启的会话之间)要能清零
|
// 8. reset:重开一轮(supervisor 重启的会话之间)要能清零
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
console.log('重置');
|
console.log('重置');
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -119,7 +119,7 @@ const colored = makeFrame({
|
|||||||
lessons: 8,
|
lessons: 8,
|
||||||
video: { t: 812, d: 1320, paused: false, err: 0, src: 1 },
|
video: { t: 812, d: 1320, paused: false, err: 0, src: 1 },
|
||||||
});
|
});
|
||||||
tui.set({ phase: '刷课中', tone: 'ok', injected: 4, maxCourses: 10 });
|
tui.set({ phase: '刷课中', tone: 'ok', injected: 4 });
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
ok(colored.frame.includes('\x1b['), '彩色帧里确实有 ANSI 序列');
|
ok(colored.frame.includes('\x1b['), '彩色帧里确实有 ANSI 序列');
|
||||||
@@ -332,7 +332,6 @@ console.log('可视行换算');
|
|||||||
console.log('极端尺寸');
|
console.log('极端尺寸');
|
||||||
const narrow = makeFrame({ columns: 36, rows: 12, color: true, setup(tui) {
|
const narrow = makeFrame({ columns: 36, rows: 12, color: true, setup(tui) {
|
||||||
tui.snap({ course: '课程', completed: 3, doneCount: 17, lessons: 8, retryCount: 1, countdown: 812, video: { t: 812, d: 1320, paused: false, err: 0, src: 1 } });
|
tui.snap({ course: '课程', completed: 3, doneCount: 17, lessons: 8, retryCount: 1, countdown: 812, video: { t: 812, d: 1320, paused: false, err: 0, src: 1 } });
|
||||||
tui.set({ maxCourses: 10 });
|
|
||||||
}});
|
}});
|
||||||
for (const line of narrow.lines) {
|
for (const line of narrow.lines) {
|
||||||
ok(textWidth(stripAnsi(line)) <= 36, '36 列终端:行宽不超界', String(textWidth(stripAnsi(line))));
|
ok(textWidth(stripAnsi(line)) <= 36, '36 列终端:行宽不超界', String(textWidth(stripAnsi(line))));
|
||||||
|
|||||||
+14
-4
@@ -2,7 +2,7 @@
|
|||||||
# cp .env.example .env # 填账号密码(.env 已在 .gitignore 里,不会入库)
|
# cp .env.example .env # 填账号密码(.env 已在 .gitignore 里,不会入库)
|
||||||
# docker compose build
|
# docker compose build
|
||||||
# docker compose run --rm yun-xue-tang --check # 先自检(只读,不登录)
|
# docker compose run --rm yun-xue-tang --check # 先自检(只读,不登录)
|
||||||
# docker compose run --rm yun-xue-tang --max-courses 3 # 只刷 3 门,跑完就退
|
# docker compose run --rm yun-xue-tang --budget-minutes 15 # 最多跑 15 分钟
|
||||||
# docker compose up -d # 正式后台刷课
|
# docker compose up -d # 正式后台刷课
|
||||||
# docker compose logs -f # 跟随日志(也可 tail -f ./run-logs/headless.log)
|
# docker compose logs -f # 跟随日志(也可 tail -f ./run-logs/headless.log)
|
||||||
# docker compose down # 停(SIGTERM → 暂停视频 → 关浏览器)
|
# docker compose down # 停(SIGTERM → 暂停视频 → 关浏览器)
|
||||||
@@ -11,7 +11,13 @@
|
|||||||
# 这样 .env 不存在时也不会直接报错,入口脚本会降级成 --check。
|
# 这样 .env 不存在时也不会直接报错,入口脚本会降级成 --check。
|
||||||
services:
|
services:
|
||||||
yun-xue-tang:
|
yun-xue-tang:
|
||||||
build: .
|
build:
|
||||||
|
context: .
|
||||||
|
# apt / npm 镜像源可在 .env 里覆盖(APT_MIRROR / NPM_REGISTRY),留空则用默认官方源
|
||||||
|
args:
|
||||||
|
APT_MIRROR: "${APT_MIRROR:-}"
|
||||||
|
NPM_REGISTRY: "${NPM_REGISTRY:-}"
|
||||||
|
CHROME_DEB_URL: "${CHROME_DEB_URL:-}"
|
||||||
image: yun-xue-tang-assistant:latest
|
image: yun-xue-tang-assistant:latest
|
||||||
container_name: yun-xue-tang
|
container_name: yun-xue-tang
|
||||||
# 为什么不是 unless-stopped:运行器「刷完了」会以退出码 0 正常退出,
|
# 为什么不是 unless-stopped:运行器「刷完了」会以退出码 0 正常退出,
|
||||||
@@ -30,8 +36,12 @@ services:
|
|||||||
YUN_XUE_TANG_PWD: "${YUN_XUE_TANG_PWD:-}"
|
YUN_XUE_TANG_PWD: "${YUN_XUE_TANG_PWD:-}"
|
||||||
# 面板要求 stdout 是 TTY,后台跑必须关(默认就是关的,这里显式写出来防误改)
|
# 面板要求 stdout 是 TTY,后台跑必须关(默认就是关的,这里显式写出来防误改)
|
||||||
YUN_XUE_TANG_TUI: "0"
|
YUN_XUE_TANG_TUI: "0"
|
||||||
# 本次最多完成几门课;0 = 不限
|
# 本次最多刷多少分钟;0 = 不限
|
||||||
YUN_XUE_TANG_MAX_COURSES: "${YUN_XUE_TANG_MAX_COURSES:-100}"
|
YUN_XUE_TANG_BUDGET_MINUTES: "${YUN_XUE_TANG_BUDGET_MINUTES:-0}"
|
||||||
|
# 开始运行 / 获得学分 / 收尾时推 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:
|
volumes:
|
||||||
# 持久化登录态(cookie / localStorage):删掉该目录等于重置登录与进度缓存
|
# 持久化登录态(cookie / localStorage):删掉该目录等于重置登录与进度缓存
|
||||||
# 注意:与裸机运行共用同一个目录,容器内以 root 写入,宿主机上会是 root 所有
|
# 注意:与裸机运行共用同一个目录,容器内以 root 写入,宿主机上会是 root 所有
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
# 所有实际逻辑仍在 runner/headless.mjs 里,这里不复制任何业务判断,避免两处行为分叉。
|
# 所有实际逻辑仍在 runner/headless.mjs 里,这里不复制任何业务判断,避免两处行为分叉。
|
||||||
#
|
#
|
||||||
# docker run 镜像 → 没凭据则 --check(只读自检),有凭据则正式刷课
|
# docker run 镜像 → 没凭据则 --check(只读自检),有凭据则正式刷课
|
||||||
# docker run 镜像 --max-courses 3 → 参数原样透传给运行器
|
# docker run 镜像 --budget-minutes 15 → 参数原样透传给运行器
|
||||||
# docker run -it 镜像 sh → 进容器排查
|
# docker run -it 镜像 sh → 进容器排查
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -14,6 +14,12 @@
|
|||||||
"test:e2e:play": "node dev/tests/real-e2e.mjs --play",
|
"test:e2e:play": "node dev/tests/real-e2e.mjs --play",
|
||||||
"test:tui": "node dev/tests/tui-test.mjs",
|
"test:tui": "node dev/tests/tui-test.mjs",
|
||||||
"test:study": "node dev/tests/study-test.mjs",
|
"test:study": "node dev/tests/study-test.mjs",
|
||||||
|
"test:points": "node dev/tests/points-test.mjs",
|
||||||
|
"test:points-platform": "node dev/tests/points-platform-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",
|
||||||
"headless": "node runner/headless.mjs",
|
"headless": "node runner/headless.mjs",
|
||||||
"headless:check": "node runner/headless.mjs --check"
|
"headless:check": "node runner/headless.mjs --check"
|
||||||
},
|
},
|
||||||
|
|||||||
+12
-5
@@ -109,7 +109,9 @@ export function listCandidatePaths() {
|
|||||||
//
|
//
|
||||||
// 两套锁的名字不同:
|
// 两套锁的名字不同:
|
||||||
// POSIX SingletonLock / SingletonSocket / SingletonCookie,lock 是指向 hostname-pid 的符号链接,
|
// POSIX SingletonLock / SingletonSocket / SingletonCookie,lock 是指向 hostname-pid 的符号链接,
|
||||||
// 目标 pid 不存在即视为陈旧(还存在就说明真有浏览器在跑,不能动)。
|
// 目标 hostname-pid:主机名不是本机 → 一定是陈旧锁(容器重建后 hostname 会变,
|
||||||
|
// 而旧 pid 在新容器里常被别的进程复用);主机名相同且 pid 不存在 → 陈旧;
|
||||||
|
// pid 还活着才说明真有浏览器在跑,不能动。
|
||||||
// Windows 用普通的空文件 lockfile;Windows 上没法从文件反查 pid,
|
// Windows 用普通的空文件 lockfile;Windows 上没法从文件反查 pid,
|
||||||
// 所以由调用方先用 killProfileOrphans() 把残留进程收掉,再清文件。
|
// 所以由调用方先用 killProfileOrphans() 把残留进程收掉,再清文件。
|
||||||
export function cleanStaleSingleton(profileDir) {
|
export function cleanStaleSingleton(profileDir) {
|
||||||
@@ -124,13 +126,18 @@ export function cleanStaleSingleton(profileDir) {
|
|||||||
try {
|
try {
|
||||||
if (st.isSymbolicLink()) {
|
if (st.isSymbolicLink()) {
|
||||||
const target = fs.readlinkSync(p);
|
const target = fs.readlinkSync(p);
|
||||||
const m = /-(\d+)$/.exec(target);
|
const m = /^(.*)-(\d+)$/.exec(target);
|
||||||
const pid = m ? Number(m[1]) : 0;
|
const host = m ? m[1] : '';
|
||||||
|
const pid = m ? Number(m[2]) : 0;
|
||||||
|
// 锁里的主机名不是本机:上一个容器 / 另一台机器留下的残局。
|
||||||
|
// 容器重建后 hostname 变了,而旧 pid(如 19)在新容器里常常恰好被占用,
|
||||||
|
// 只看 pid 存活会误判成「浏览器还在跑」,导致锁永远清不掉。
|
||||||
|
const foreign = host !== '' && host !== os.hostname();
|
||||||
let alive = false;
|
let alive = false;
|
||||||
if (pid > 0) {
|
if (!foreign && pid > 0) {
|
||||||
try { process.kill(pid, 0); alive = true; } catch (e) { alive = false; }
|
try { process.kill(pid, 0); alive = true; } catch (e) { alive = false; }
|
||||||
}
|
}
|
||||||
if (alive) continue; // 真的有浏览器在跑,别动
|
if (alive) continue; // 真的是本机上活着的浏览器,别动
|
||||||
fs.unlinkSync(p);
|
fs.unlinkSync(p);
|
||||||
} else {
|
} else {
|
||||||
fs.unlinkSync(p);
|
fs.unlinkSync(p);
|
||||||
|
|||||||
+38
-14
@@ -23,9 +23,9 @@ export const SCRIPT_FILE = path.join(ROOT, 'yun-xue-tang-assistant.user.js');
|
|||||||
// 一层:内置默认值
|
// 一层:内置默认值
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
const DEFAULTS = {
|
const DEFAULTS = {
|
||||||
maxCourses: 0, // 0 = 不限(一直刷到没有未学完的课)
|
|
||||||
budgetMinutes: 0, // 0 = 不限
|
budgetMinutes: 0, // 0 = 不限
|
||||||
preferShort: true,
|
preferShort: true,
|
||||||
|
pointsMode: true, // 每日积分模式:整门课完成计 1 次,四类封顶后停止(文档1/视频3/音频2/微课2)
|
||||||
restartMinutes: 0, // 0 = 停下就退出
|
restartMinutes: 0, // 0 = 停下就退出
|
||||||
idleRestartMinutes: 30,
|
idleRestartMinutes: 30,
|
||||||
origin: 'https://kfmic.yunxuetang.cn',
|
origin: 'https://kfmic.yunxuetang.cn',
|
||||||
@@ -39,6 +39,12 @@ const DEFAULTS = {
|
|||||||
logMaxBytes: 5 * 1024 * 1024,
|
logMaxBytes: 5 * 1024 * 1024,
|
||||||
tui: true, // true = 交互式终端里启用面板;非 TTY 自动退化为逐行日志
|
tui: true, // true = 交互式终端里启用面板;非 TTY 自动退化为逐行日志
|
||||||
color: true, // false = 面板不用 ANSI 颜色(也认 NO_COLOR 环境变量)
|
color: true, // false = 面板不用 ANSI 颜色(也认 NO_COLOR 环境变量)
|
||||||
|
// Bark 推送:运行器在开始运行、每门课获得学分、收尾时各发一条手机通知。
|
||||||
|
// barkUrl 是含设备 key 的地址(https://api.day.app/<key>),留空 = 不推送。
|
||||||
|
// key 等价于「谁能往你手机推通知」,别提交到公开仓库;可用环境变量覆盖。
|
||||||
|
barkUrl: '',
|
||||||
|
barkGroup: '', // 通知分组(Bark App 里按组折叠),留空 = Bark 默认
|
||||||
|
barkTtl: 0, // 通知在 Bark 服务端保留多少秒;0 = 永久保留
|
||||||
};
|
};
|
||||||
|
|
||||||
const argv = process.argv.slice(2);
|
const argv = process.argv.slice(2);
|
||||||
@@ -49,7 +55,6 @@ const DEPRECATED = {
|
|||||||
};
|
};
|
||||||
/** 旧参数名 -> 配置字段(保持向后兼容,dev/tests/ 下的脚本还在用) */
|
/** 旧参数名 -> 配置字段(保持向后兼容,dev/tests/ 下的脚本还在用) */
|
||||||
const ALIASES = {
|
const ALIASES = {
|
||||||
'--max': 'maxCourses',
|
|
||||||
'--budget': 'budgetMinutes',
|
'--budget': 'budgetMinutes',
|
||||||
'--restart': 'restartMinutes',
|
'--restart': 'restartMinutes',
|
||||||
'--idle': 'idleRestartMinutes',
|
'--idle': 'idleRestartMinutes',
|
||||||
@@ -102,11 +107,11 @@ if (CONFIG_FILE) {
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 命令行解析:--key value / --key=value / --flag
|
// 命令行解析:--key value / --key=value / --flag
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
const BOOL_KEYS = ['preferShort', 'headless', 'check', 'tui', 'color'];
|
const BOOL_KEYS = ['preferShort', 'pointsMode', 'headless', 'check', 'tui', 'color'];
|
||||||
const NUM_KEYS = ['maxCourses', 'budgetMinutes', 'restartMinutes', 'idleRestartMinutes', 'port', 'logMaxBytes'];
|
const NUM_KEYS = ['budgetMinutes', 'restartMinutes', 'idleRestartMinutes', 'port', 'logMaxBytes', 'barkTtl'];
|
||||||
const STR_KEYS = ['origin', 'url', 'profile', 'logFile', 'chrome', 'extraArgs', 'config'];
|
const STR_KEYS = ['origin', 'url', 'profile', 'logFile', 'chrome', 'extraArgs', 'config', 'barkUrl', 'barkGroup'];
|
||||||
|
|
||||||
/** kebab-case → camelCase:--max-courses → maxCourses */
|
/** kebab-case → camelCase:--budget-minutes → budgetMinutes */
|
||||||
function toCamel(flag) {
|
function toCamel(flag) {
|
||||||
return flag.replace(/^--/, '').replace(/-([a-z])/g, (m, c) => c.toUpperCase());
|
return flag.replace(/^--/, '').replace(/-([a-z])/g, (m, c) => c.toUpperCase());
|
||||||
}
|
}
|
||||||
@@ -200,13 +205,13 @@ const envStr = (name, cur) => {
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
const merged = { ...DEFAULTS, ...fileConfig };
|
const merged = { ...DEFAULTS, ...fileConfig };
|
||||||
|
|
||||||
merged.maxCourses = envNum('YUN_XUE_TANG_MAX_COURSES', merged.maxCourses);
|
|
||||||
merged.budgetMinutes = envNum('YUN_XUE_TANG_BUDGET_MINUTES', merged.budgetMinutes);
|
merged.budgetMinutes = envNum('YUN_XUE_TANG_BUDGET_MINUTES', merged.budgetMinutes);
|
||||||
merged.restartMinutes = envNum('YUN_XUE_TANG_RESTART_MINUTES', merged.restartMinutes);
|
merged.restartMinutes = envNum('YUN_XUE_TANG_RESTART_MINUTES', merged.restartMinutes);
|
||||||
merged.idleRestartMinutes = envNum('YUN_XUE_TANG_IDLE_RESTART_MINUTES', merged.idleRestartMinutes);
|
merged.idleRestartMinutes = envNum('YUN_XUE_TANG_IDLE_RESTART_MINUTES', merged.idleRestartMinutes);
|
||||||
merged.port = envNum('YUN_XUE_TANG_CDP_PORT', merged.port);
|
merged.port = envNum('YUN_XUE_TANG_CDP_PORT', merged.port);
|
||||||
merged.logMaxBytes = envNum('YUN_XUE_TANG_LOG_MAX_BYTES', merged.logMaxBytes);
|
merged.logMaxBytes = envNum('YUN_XUE_TANG_LOG_MAX_BYTES', merged.logMaxBytes);
|
||||||
merged.preferShort = envBool('YUN_XUE_TANG_PREFER_SHORT', merged.preferShort);
|
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.headless = envBool('YUN_XUE_TANG_HEADLESS', merged.headless);
|
||||||
merged.origin = envStr('YUN_XUE_TANG_ORIGIN', merged.origin);
|
merged.origin = envStr('YUN_XUE_TANG_ORIGIN', merged.origin);
|
||||||
merged.url = envStr('YUN_XUE_TANG_URL', merged.url);
|
merged.url = envStr('YUN_XUE_TANG_URL', merged.url);
|
||||||
@@ -216,6 +221,9 @@ merged.chrome = envStr('YUN_XUE_TANG_CHROME_BIN', merged.chrome);
|
|||||||
merged.extraArgs = envStr('YUN_XUE_TANG_EXTRA_ARGS', merged.extraArgs);
|
merged.extraArgs = envStr('YUN_XUE_TANG_EXTRA_ARGS', merged.extraArgs);
|
||||||
merged.tui = envBool('YUN_XUE_TANG_TUI', merged.tui);
|
merged.tui = envBool('YUN_XUE_TANG_TUI', merged.tui);
|
||||||
merged.color = envBool('YUN_XUE_TANG_COLOR', merged.color);
|
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 = [];
|
const numBad = [];
|
||||||
@@ -238,11 +246,11 @@ for (const [key, raw] of Object.entries(cliRaw)) {
|
|||||||
const problems = [...numBad];
|
const problems = [...numBad];
|
||||||
if (numBad.length === 0) {
|
if (numBad.length === 0) {
|
||||||
if (!(merged.port >= 1 && merged.port <= 65535)) problems.push('port 必须在 1-65535 之间,收到 ' + merged.port);
|
if (!(merged.port >= 1 && merged.port <= 65535)) problems.push('port 必须在 1-65535 之间,收到 ' + merged.port);
|
||||||
if (!(merged.maxCourses >= 0)) problems.push('maxCourses 不能为负,收到 ' + merged.maxCourses);
|
|
||||||
if (!(merged.budgetMinutes >= 0)) problems.push('budgetMinutes 不能为负,收到 ' + merged.budgetMinutes);
|
if (!(merged.budgetMinutes >= 0)) problems.push('budgetMinutes 不能为负,收到 ' + merged.budgetMinutes);
|
||||||
if (!(merged.restartMinutes >= 0)) problems.push('restartMinutes 不能为负,收到 ' + merged.restartMinutes);
|
if (!(merged.restartMinutes >= 0)) problems.push('restartMinutes 不能为负,收到 ' + merged.restartMinutes);
|
||||||
if (!(merged.idleRestartMinutes >= 0)) problems.push('idleRestartMinutes 不能为负,收到 ' + merged.idleRestartMinutes);
|
if (!(merged.idleRestartMinutes >= 0)) problems.push('idleRestartMinutes 不能为负,收到 ' + merged.idleRestartMinutes);
|
||||||
if (!(merged.logMaxBytes >= 0)) problems.push('logMaxBytes 不能为负,收到 ' + merged.logMaxBytes);
|
if (!(merged.logMaxBytes >= 0)) problems.push('logMaxBytes 不能为负,收到 ' + merged.logMaxBytes);
|
||||||
|
if (!(merged.barkTtl >= 0)) problems.push('barkTtl 不能为负,收到 ' + merged.barkTtl);
|
||||||
}
|
}
|
||||||
if (unknownFlags.length) {
|
if (unknownFlags.length) {
|
||||||
const uniq = [...new Set(unknownFlags)];
|
const uniq = [...new Set(unknownFlags)];
|
||||||
@@ -270,8 +278,6 @@ export const START_URL = merged.url ? String(merged.url) : ORIGIN + '/login.html
|
|||||||
export const USR = process.env.YUN_XUE_TANG_USR || '';
|
export const USR = process.env.YUN_XUE_TANG_USR || '';
|
||||||
export const PWD = process.env.YUN_XUE_TANG_PWD || '';
|
export const PWD = process.env.YUN_XUE_TANG_PWD || '';
|
||||||
export const PORT = merged.port;
|
export const PORT = merged.port;
|
||||||
/** 本次最多完成几门课(0 = 不限) */
|
|
||||||
export const MAX_COURSES = merged.maxCourses;
|
|
||||||
/** 运行多少分钟后收尾(0 = 不限) */
|
/** 运行多少分钟后收尾(0 = 不限) */
|
||||||
export const BUDGET_MINUTES = merged.budgetMinutes;
|
export const BUDGET_MINUTES = merged.budgetMinutes;
|
||||||
export const PROFILE_DIR = merged.profile
|
export const PROFILE_DIR = merged.profile
|
||||||
@@ -285,6 +291,7 @@ export const WANT_VISIBLE = !merged.headless;
|
|||||||
export const VISIBLE = WANT_VISIBLE && hasDisplay();
|
export const VISIBLE = WANT_VISIBLE && hasDisplay();
|
||||||
|
|
||||||
export const PREFER_SHORT = merged.preferShort;
|
export const PREFER_SHORT = merged.preferShort;
|
||||||
|
export const POINTS_MODE = merged.pointsMode;
|
||||||
/** 脚本自己停下后等待多少分钟再开新一轮(0 = 直接退出) */
|
/** 脚本自己停下后等待多少分钟再开新一轮(0 = 直接退出) */
|
||||||
export const RESTART_MINUTES = merged.restartMinutes;
|
export const RESTART_MINUTES = merged.restartMinutes;
|
||||||
/** 连续多少分钟没有任何进展判定卡死 */
|
/** 连续多少分钟没有任何进展判定卡死 */
|
||||||
@@ -296,8 +303,21 @@ export const LOG_MAX_BYTES = merged.logMaxBytes;
|
|||||||
export const EXTRA_ARGS = String(merged.extraArgs || '').split(/\s+/).filter(Boolean);
|
export const EXTRA_ARGS = String(merged.extraArgs || '').split(/\s+/).filter(Boolean);
|
||||||
/** 配置文件里指定的浏览器路径(空 = 自动探测;优先级低于 YUN_XUE_TANG_CHROME_BIN,见 browser.mjs) */
|
/** 配置文件里指定的浏览器路径(空 = 自动探测;优先级低于 YUN_XUE_TANG_CHROME_BIN,见 browser.mjs) */
|
||||||
export const CHROME_BIN = merged.chrome || '';
|
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;
|
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 都生效 */
|
/** 面板是否带颜色:配置 / 环境变量 / 行业惯例的 NO_COLOR 都生效 */
|
||||||
export const COLOR = merged.color && !process.env.NO_COLOR;
|
export const COLOR = merged.color && !process.env.NO_COLOR;
|
||||||
|
|
||||||
@@ -326,15 +346,16 @@ export function describeRun() {
|
|||||||
checkOnly: CHECK_ONLY,
|
checkOnly: CHECK_ONLY,
|
||||||
headless: !VISIBLE,
|
headless: !VISIBLE,
|
||||||
port: PORT,
|
port: PORT,
|
||||||
maxCourses: MAX_COURSES > 0 ? MAX_COURSES : '不限',
|
|
||||||
budgetMinutes: BUDGET_MINUTES > 0 ? BUDGET_MINUTES : '不限',
|
budgetMinutes: BUDGET_MINUTES > 0 ? BUDGET_MINUTES : '不限',
|
||||||
preferShort: PREFER_SHORT,
|
preferShort: PREFER_SHORT,
|
||||||
|
pointsMode: POINTS_MODE,
|
||||||
restartMinutes: RESTART_MINUTES,
|
restartMinutes: RESTART_MINUTES,
|
||||||
idleRestartMinutes: IDLE_RESTART_MINUTES,
|
idleRestartMinutes: IDLE_RESTART_MINUTES,
|
||||||
profileDir: PROFILE_DIR,
|
profileDir: PROFILE_DIR,
|
||||||
logFile: LOG_FILE,
|
logFile: LOG_FILE,
|
||||||
tui: TUI,
|
tui: TUI,
|
||||||
color: COLOR,
|
color: COLOR,
|
||||||
|
bark: BARK_URL ? (maskBarkUrl(BARK_URL) + (BARK_GROUP ? '(分组 ' + BARK_GROUP + ')' : '')) : '(未配置)',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -342,9 +363,9 @@ export function describeRun() {
|
|||||||
export function helpText() {
|
export function helpText() {
|
||||||
const rows = [
|
const rows = [
|
||||||
['配置字段', '命令行', '环境变量', '当前生效', '说明'],
|
['配置字段', '命令行', '环境变量', '当前生效', '说明'],
|
||||||
['maxCourses', '--max-courses', 'YUN_XUE_TANG_MAX_COURSES', MAX_COURSES, '本次最多完成几门课;0 = 不限'],
|
|
||||||
['budgetMinutes', '--budget-minutes', 'YUN_XUE_TANG_BUDGET_MINUTES', BUDGET_MINUTES, '跑多少分钟后收尾;0 = 不限'],
|
['budgetMinutes', '--budget-minutes', 'YUN_XUE_TANG_BUDGET_MINUTES', BUDGET_MINUTES, '跑多少分钟后收尾;0 = 不限'],
|
||||||
['preferShort', '--prefer-short', 'YUN_XUE_TANG_PREFER_SHORT', PREFER_SHORT, '优先总时长最短的课程'],
|
['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 = 退出'],
|
['restartMinutes', '--restart-minutes', 'YUN_XUE_TANG_RESTART_MINUTES', RESTART_MINUTES, '脚本停下后等几分钟开新一轮;0 = 退出'],
|
||||||
['idleRestartMinutes', '--idle-restart-minutes', 'YUN_XUE_TANG_IDLE_RESTART_MINUTES', IDLE_RESTART_MINUTES, '多少分钟无进展判卡死'],
|
['idleRestartMinutes', '--idle-restart-minutes', 'YUN_XUE_TANG_IDLE_RESTART_MINUTES', IDLE_RESTART_MINUTES, '多少分钟无进展判卡死'],
|
||||||
['origin', '--origin', 'YUN_XUE_TANG_ORIGIN', ORIGIN, '站点根地址'],
|
['origin', '--origin', 'YUN_XUE_TANG_ORIGIN', ORIGIN, '站点根地址'],
|
||||||
@@ -358,6 +379,9 @@ export function helpText() {
|
|||||||
['color', '--no-color', 'YUN_XUE_TANG_COLOR', COLOR ? '开' : '关', '面板是否用 ANSI 颜色(也认 NO_COLOR)'],
|
['color', '--no-color', 'YUN_XUE_TANG_COLOR', COLOR ? '开' : '关', '面板是否用 ANSI 颜色(也认 NO_COLOR)'],
|
||||||
['logFile', '--log-file', 'YUN_XUE_TANG_LOG_FILE', LOG_FILE, '日志文件'],
|
['logFile', '--log-file', 'YUN_XUE_TANG_LOG_FILE', LOG_FILE, '日志文件'],
|
||||||
['logMaxBytes', '--log-max-bytes', 'YUN_XUE_TANG_LOG_MAX_BYTES', LOG_MAX_BYTES, '单文件上限,超出轮转'],
|
['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, '只做环境自检,不动进度'],
|
['(字段 check)', '--check', '', CHECK_ONLY, '只做环境自检,不动进度'],
|
||||||
['(无字段)', '--config', 'YUN_XUE_TANG_CONFIG', CONFIG_FILE || '(内置默认)', '指定配置文件路径'],
|
['(无字段)', '--config', 'YUN_XUE_TANG_CONFIG', CONFIG_FILE || '(内置默认)', '指定配置文件路径'],
|
||||||
];
|
];
|
||||||
@@ -378,11 +402,11 @@ export function helpText() {
|
|||||||
lines.push('');
|
lines.push('');
|
||||||
lines.push('示例:');
|
lines.push('示例:');
|
||||||
lines.push(' node runner/headless.mjs --check # 只做环境自检');
|
lines.push(' node runner/headless.mjs --check # 只做环境自检');
|
||||||
lines.push(' node runner/headless.mjs --max-courses 3 # 本次最多 3 门');
|
lines.push(' node runner/headless.mjs --budget-minutes 15 # 最多跑 15 分钟');
|
||||||
lines.push(' node runner/headless.mjs --headless 0 # 开有界面浏览器调试');
|
lines.push(' node runner/headless.mjs --headless 0 # 开有界面浏览器调试');
|
||||||
lines.push(' node runner/headless.mjs --no-tui # 不用面板,回到逐行日志');
|
lines.push(' node runner/headless.mjs --no-tui # 不用面板,回到逐行日志');
|
||||||
lines.push(' node runner/headless.mjs --config ./config/runner.config.mjs # 显式指定配置文件');
|
lines.push(' node runner/headless.mjs --config ./config/runner.config.mjs # 显式指定配置文件');
|
||||||
lines.push('');
|
lines.push('');
|
||||||
lines.push('旧参数名(仍然兼容):--max / --budget / --restart / --idle / --log / --log-max / --visible');
|
lines.push('旧参数名(仍然兼容):--budget / --restart / --idle / --log / --log-max / --visible');
|
||||||
return lines.join('\n');
|
return lines.join('\n');
|
||||||
}
|
}
|
||||||
+6
-2
@@ -7,7 +7,7 @@
|
|||||||
* 这个文件只做「组装」:解析参数 → 启动前预检 → 交给 supervisor 跑。
|
* 这个文件只做「组装」:解析参数 → 启动前预检 → 交给 supervisor 跑。
|
||||||
* 具体实现在同目录的模块里:
|
* 具体实现在同目录的模块里:
|
||||||
*
|
*
|
||||||
* config.mjs 参数与环境变量(--max / YUN_XUE_TANG_* 全部集中在这里)
|
* config.mjs 参数与环境变量(--budget / YUN_XUE_TANG_* 全部集中在这里)
|
||||||
* platform.mjs 平台差异(有无图形会话、沙箱参数、进程树收尾、端口排查命令)
|
* platform.mjs 平台差异(有无图形会话、沙箱参数、进程树收尾、端口排查命令)
|
||||||
* preflight.mjs 启动前检查(产物 / Node 版本 / 凭据 / 浏览器 / 端口)
|
* preflight.mjs 启动前检查(产物 / Node 版本 / 凭据 / 浏览器 / 端口)
|
||||||
* log.mjs 终端 + 文件日志(超上限轮转)
|
* log.mjs 终端 + 文件日志(超上限轮转)
|
||||||
@@ -17,6 +17,7 @@
|
|||||||
* page.mjs 注入后要调用的页面 JS 表达式 + page 求值封装
|
* page.mjs 注入后要调用的页面 JS 表达式 + page 求值封装
|
||||||
* session.mjs 单次会话:起浏览器 → 注入 → 自动登录 → 刷课 → 监控 → 收尾
|
* session.mjs 单次会话:起浏览器 → 注入 → 自动登录 → 刷课 → 监控 → 收尾
|
||||||
* selfcheck.mjs --check 的只读环境自检
|
* selfcheck.mjs --check 的只读环境自检
|
||||||
|
* notify.mjs Bark 手机通知(开始运行 / 获得学分 / 收尾)
|
||||||
* supervisor.mjs 崩溃重启循环与退出码
|
* supervisor.mjs 崩溃重启循环与退出码
|
||||||
* tui.mjs 交互式终端面板(框线 + 进度条,q 退出;非 TTY 自动关闭)
|
* tui.mjs 交互式终端面板(框线 + 进度条,q 退出;非 TTY 自动关闭)
|
||||||
*
|
*
|
||||||
@@ -31,7 +32,6 @@
|
|||||||
* 常用参数 / 环境变量:
|
* 常用参数 / 环境变量:
|
||||||
* --check 只自检:浏览器可启动、页面可访问、脚本可注入、视频编解码可用,
|
* --check 只自检:浏览器可启动、页面可访问、脚本可注入、视频编解码可用,
|
||||||
* 不登录、不点课程、不动进度
|
* 不登录、不点课程、不动进度
|
||||||
* --max N 本次最多完成 N 门课(0 = 不限,默认读脚本自身配置)
|
|
||||||
* --budget N 运行 N 分钟后收尾(0 = 不限,默认 0)
|
* --budget N 运行 N 分钟后收尾(0 = 不限,默认 0)
|
||||||
* --profile DIR 持久化 profile 目录(默认 ./.run-profile)
|
* --profile DIR 持久化 profile 目录(默认 ./.run-profile)
|
||||||
* --port N CDP 调试端口(默认 9336)
|
* --port N CDP 调试端口(默认 9336)
|
||||||
@@ -42,6 +42,7 @@
|
|||||||
* YUN_XUE_TANG_CHROME_BIN Chrome/Chromium 可执行文件路径(默认自动探测)
|
* YUN_XUE_TANG_CHROME_BIN Chrome/Chromium 可执行文件路径(默认自动探测)
|
||||||
* YUN_XUE_TANG_EXTRA_ARGS 追加给浏览器的命令行参数(空格分隔)
|
* YUN_XUE_TANG_EXTRA_ARGS 追加给浏览器的命令行参数(空格分隔)
|
||||||
* YUN_XUE_TANG_PREFER_SHORT 1/0,是否优先短课程(默认 1)
|
* 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_RESTART_MINUTES 脚本停止/无进展后等待多久重新开始(0 = 直接退出,默认 0)
|
||||||
* YUN_XUE_TANG_IDLE_RESTART_MINUTES 连续无进展多少分钟后判定卡死(默认 30)
|
* YUN_XUE_TANG_IDLE_RESTART_MINUTES 连续无进展多少分钟后判定卡死(默认 30)
|
||||||
* YUN_XUE_TANG_LOG_FILE 日志文件路径(默认 ./run-logs/headless.log)
|
* YUN_XUE_TANG_LOG_FILE 日志文件路径(默认 ./run-logs/headless.log)
|
||||||
@@ -49,6 +50,9 @@
|
|||||||
* YUN_XUE_TANG_HAS_DISPLAY 0/1,强制认定「有没有图形显示会话」(自动判断不准时用)
|
* YUN_XUE_TANG_HAS_DISPLAY 0/1,强制认定「有没有图形显示会话」(自动判断不准时用)
|
||||||
* YUN_XUE_TANG_TUI 0/1,是否启用终端面板(默认 1,非 TTY 时无效)
|
* YUN_XUE_TANG_TUI 0/1,是否启用终端面板(默认 1,非 TTY 时无效)
|
||||||
* YUN_XUE_TANG_COLOR 0/1,面板是否带颜色(也认 NO_COLOR)
|
* 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 连续登录失败
|
* 退出码:0 正常收尾 / 1 无进展卡死 / 2 环境或参数问题 / 3 连续登录失败
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -0,0 +1,155 @@
|
|||||||
|
// Bark 推送:运行器自己收尾时把结果发到手机。
|
||||||
|
//
|
||||||
|
// 覆盖三类事件(都只在 headless 运行器里发,浏览器端油猴脚本不推送):
|
||||||
|
// · 开始运行:「进程已经跑起来了」
|
||||||
|
// · 获得学分:每刷完一门有学分的课推一条
|
||||||
|
// · 收尾:正常刷完 / 长时间无进展 / 登录失败
|
||||||
|
// 手动 Ctrl+C 主动停止不推送:人就在键盘前,不需要再提醒一次。
|
||||||
|
// 通知是附加信息:发送失败只记告警,绝不影响退出码,也不阻塞下一次会话。
|
||||||
|
//
|
||||||
|
// Bark 接口:GET https://api.day.app/<key>/<title>/<body>?group=<分组>[&ttl=<秒>](省略 ttl = 永久保留)
|
||||||
|
|
||||||
|
import { formatCredit } from './study.mjs';
|
||||||
|
|
||||||
|
/** 单次请求超时: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') };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 启动通知:预检通过、浏览器即将启动时发一条,手机上能确认「程序真的跑起来了」 */
|
||||||
|
export function buildStartMessage(cfg) {
|
||||||
|
const c = cfg || {};
|
||||||
|
const lines = ['正在启动浏览器并自动登录'];
|
||||||
|
lines.push('模式:' + (c.POINTS_MODE ? '每日积分' : '普通刷课'));
|
||||||
|
const budget = Number(c.BUDGET_MINUTES) || 0;
|
||||||
|
lines.push('运行预算:' + (budget > 0 ? budget + ' 分钟' : '不限'));
|
||||||
|
return { title: '云学堂助手:开始运行', body: lines.join('\n') };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 学分通知:每刷完一门课发一条,带上本次累计学分与已完成门数 */
|
||||||
|
export function buildCreditMessage(event) {
|
||||||
|
const e = event || {};
|
||||||
|
const title = '云学堂助手:获得 ' + formatCredit(e.credit) + ' 学分';
|
||||||
|
const lines = [];
|
||||||
|
if (e.course) lines.push('课程「' + String(e.course) + '」');
|
||||||
|
let total = '本次累计 ' + formatCredit(e.total) + ' 学分';
|
||||||
|
if (e.completed != null) total += ' · 已完成 ' + (Number(e.completed) || 0) + ' 门';
|
||||||
|
lines.push(total);
|
||||||
|
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 时是空操作 */
|
||||||
|
function notifyWith(cfg, msg, io) {
|
||||||
|
if (!cfg || !cfg.BARK_URL) return Promise.resolve({ skipped: true });
|
||||||
|
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,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 开始运行通知 */
|
||||||
|
export function notifyRunStarted(cfg, io) {
|
||||||
|
return notifyWith(cfg, buildStartMessage(cfg), io);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 获得学分通知(每门刷完的课一条) */
|
||||||
|
export function notifyCreditEarned(cfg, event, io) {
|
||||||
|
return notifyWith(cfg, buildCreditMessage(event), io);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 收尾通知 */
|
||||||
|
export function notifyRunFinished(cfg, result, io) {
|
||||||
|
return notifyWith(cfg, buildFinishMessage(result), io);
|
||||||
|
}
|
||||||
+10
-8
@@ -63,14 +63,13 @@ export const EXPR_SELF_CHECK = `JSON.stringify((function () {
|
|||||||
};
|
};
|
||||||
})())`;
|
})())`;
|
||||||
|
|
||||||
/** 看护循环:判断是否需要注入 / 是否在登录页 / 当前 --max 生效值 */
|
/** 看护循环:判断是否需要注入 / 是否在登录页 */
|
||||||
export const EXPR_WATCH = `JSON.stringify({
|
export const EXPR_WATCH = `JSON.stringify({
|
||||||
href: location.href,
|
href: location.href,
|
||||||
ready: typeof window.__yunXueTangAuto === 'object',
|
ready: typeof window.__yunXueTangAuto === 'object',
|
||||||
onLogin: !!(window.__yunXueTangAuto && window.__yunXueTangAuto.isLoginPage()),
|
onLogin: !!(window.__yunXueTangAuto && window.__yunXueTangAuto.isLoginPage()),
|
||||||
hasPwd: !!document.querySelector('input[type=password]'),
|
hasPwd: !!document.querySelector('input[type=password]'),
|
||||||
bodyLen: (document.body && document.body.innerText || '').length,
|
bodyLen: (document.body && document.body.innerText || '').length,
|
||||||
maxCourses: (window.__yunXueTangAuto && window.__yunXueTangAuto.CFG) ? window.__yunXueTangAuto.CFG.maxCourses : null,
|
|
||||||
})`;
|
})`;
|
||||||
|
|
||||||
/** 主监控快照:课程、课时、进度、倒计时、视频状态 */
|
/** 主监控快照:课程、课时、进度、倒计时、视频状态 */
|
||||||
@@ -104,6 +103,8 @@ export const EXPR_SNAPSHOT = `JSON.stringify((function () {
|
|||||||
return m ? Number(m[1]) : null;
|
return m ? Number(m[1]) : null;
|
||||||
})(),
|
})(),
|
||||||
status: (document.getElementById('yun-xue-tang-status') || {}).textContent || '',
|
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,
|
doneCount: Object.keys(a.S.completedTitles || {}).length,
|
||||||
retryCount: Object.keys(a.S.courseRetries || {}).length,
|
retryCount: Object.keys(a.S.courseRetries || {}).length,
|
||||||
retryWait: (a.retryWaitSeconds ? a.retryWaitSeconds() : 0),
|
retryWait: (a.retryWaitSeconds ? a.retryWaitSeconds() : 0),
|
||||||
@@ -123,6 +124,8 @@ export const EXPR_FINAL_STATS = `JSON.stringify((function () {
|
|||||||
completed: a.S.completedThisRun,
|
completed: a.S.completedThisRun,
|
||||||
doneCount: Object.keys(a.S.completedTitles || {}).length,
|
doneCount: Object.keys(a.S.completedTitles || {}).length,
|
||||||
retryCount: Object.keys(a.S.courseRetries || {}).length,
|
retryCount: Object.keys(a.S.courseRetries || {}).length,
|
||||||
|
// 每日积分:收尾通知里要带上「今日积分 X/24 · 各类次数」
|
||||||
|
points: (a.points && a.points.snapshot ? a.points.snapshot() : null),
|
||||||
};
|
};
|
||||||
})())`;
|
})())`;
|
||||||
|
|
||||||
@@ -133,15 +136,14 @@ export const EXPR_PAUSE_AND_SAVE = `(function () {
|
|||||||
return true;
|
return true;
|
||||||
})()`;
|
})()`;
|
||||||
|
|
||||||
/** 把 maxCourses 同步到页面(0 = 不限,必须一并推送) */
|
/** 启动 / 接续批量刷课,同时同步「优先短课程」「每日积分」偏好 */
|
||||||
export const exprSetMaxCourses = (max) =>
|
export const exprStartBatch = (preferShort, pointsMode) => `(function () {
|
||||||
`(function(){ var a = window.__yunXueTangAuto; if (a && a.CFG) a.CFG.maxCourses = ${Number(max)}; return true; })()`;
|
|
||||||
|
|
||||||
/** 启动 / 接续批量刷课,同时同步「优先短课程」偏好 */
|
|
||||||
export const exprStartBatch = (preferShort) => `(function () {
|
|
||||||
var a = window.__yunXueTangAuto;
|
var a = window.__yunXueTangAuto;
|
||||||
try { localStorage.setItem('yun-xue-tang-prefer-short', '${preferShort ? '1' : '0'}'); } catch (e) {}
|
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.preferShortCourses = ${preferShort ? 'true' : 'false'};
|
||||||
|
a.state.pointsEnabled = ${pointsMode ? 'true' : 'false'};
|
||||||
|
try { a.points.setEnabled(${pointsMode ? 'true' : 'false'}); } catch (e) {}
|
||||||
a.startBatch();
|
a.startBatch();
|
||||||
return true;
|
return true;
|
||||||
})()`;
|
})()`;
|
||||||
|
|||||||
+38
-34
@@ -1,15 +1,16 @@
|
|||||||
// 单次会话:一个浏览器进程的生命周期。
|
// 单次会话:一个浏览器进程的生命周期。
|
||||||
//
|
//
|
||||||
// 顺序:起浏览器 → 建标签页 → 连 CDP → 转发页面日志 → 每 1.5 秒看护
|
// 顺序:起浏览器 → 建标签页 → 连 CDP → 转发页面日志 → 每 1.5 秒看护
|
||||||
// (补注入 / 自动重登 / 启动批量 / 同步 --max)→ 主监控(进度、卡死、退出条件)→ 收尾。
|
// (补注入 / 自动重登 / 启动批量)→ 主监控(进度、卡死、退出条件)→ 收尾。
|
||||||
// 崩溃或断线时直接抛错,由 supervisor.mjs 负责重建浏览器。
|
// 崩溃或断线时直接抛错,由 supervisor.mjs 负责重建浏览器。
|
||||||
import { connect, httpJson, sleep } from './cdp.mjs';
|
import { connect, httpJson, sleep } from './cdp.mjs';
|
||||||
import { launchBrowser } from './browser.mjs';
|
import { launchBrowser } from './browser.mjs';
|
||||||
import {
|
import {
|
||||||
createPage, EXPR_WATCH, EXPR_SNAPSHOT, EXPR_FINAL_STATS, EXPR_PAUSE_AND_SAVE,
|
createPage, EXPR_WATCH, EXPR_SNAPSHOT, EXPR_FINAL_STATS, EXPR_PAUSE_AND_SAVE,
|
||||||
exprSetMaxCourses, exprStartBatch, exprAutoLogin,
|
exprStartBatch, exprAutoLogin,
|
||||||
} from './page.mjs';
|
} from './page.mjs';
|
||||||
import { runSelfCheck } from './selfcheck.mjs';
|
import { runSelfCheck } from './selfcheck.mjs';
|
||||||
|
import { notifyCreditEarned } from './notify.mjs';
|
||||||
|
|
||||||
/** 看护循环间隔:既不能太密(CDP 往返),也要能及时补注入 */
|
/** 看护循环间隔:既不能太密(CDP 往返),也要能及时补注入 */
|
||||||
export const WATCHDOG_MS = 1500;
|
export const WATCHDOG_MS = 1500;
|
||||||
@@ -57,7 +58,6 @@ export async function runSession(o) {
|
|||||||
let loginLastAt = 0;
|
let loginLastAt = 0;
|
||||||
let finished = false;
|
let finished = false;
|
||||||
let finishReason = '';
|
let finishReason = '';
|
||||||
let limitReached = false;
|
|
||||||
let lastSig = '';
|
let lastSig = '';
|
||||||
let lastStateAt = Date.now();
|
let lastStateAt = Date.now();
|
||||||
let codecWarned = false;
|
let codecWarned = false;
|
||||||
@@ -65,8 +65,6 @@ export async function runSession(o) {
|
|||||||
// 拿不到主循环的控制流,必须把错误寄存下来,由主循环抛出。
|
// 拿不到主循环的控制流,必须把错误寄存下来,由主循环抛出。
|
||||||
let fatalError = null;
|
let fatalError = null;
|
||||||
const consoleErrors = [];
|
const consoleErrors = [];
|
||||||
/** 是否达到配置的上限(maxCourses=0 表示不限) */
|
|
||||||
const limitReachedByConfig = (completed) => cfg.MAX_COURSES > 0 && completed >= cfg.MAX_COURSES;
|
|
||||||
|
|
||||||
const page = {
|
const page = {
|
||||||
evalJS: null, json: null, tryEval: null,
|
evalJS: null, json: null, tryEval: null,
|
||||||
@@ -131,7 +129,7 @@ export async function runSession(o) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// ---------------- 看护循环 ----------------
|
// ---------------- 看护循环 ----------------
|
||||||
// 每 WATCHDOG_MS 跑一次:新 document 补注入;掉登录自动重登;启动/接续批量;同步 --max。
|
// 每 WATCHDOG_MS 跑一次:新 document 补注入;掉登录自动重登;启动/接续批量。
|
||||||
const tickWatchdog = async () => {
|
const tickWatchdog = async () => {
|
||||||
if (disconnected || stop.stopping) return;
|
if (disconnected || stop.stopping) return;
|
||||||
const s = await page.tryEval(EXPR_WATCH).then((v) => (v ? JSON.parse(v) : null));
|
const s = await page.tryEval(EXPR_WATCH).then((v) => (v ? JSON.parse(v) : null));
|
||||||
@@ -157,12 +155,6 @@ export async function runSession(o) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 运行策略同步到页面:maxCourses > 0 时覆盖脚本内置的 CFG.maxCourses;
|
|
||||||
// 配成 0 表示「不限」,也要推 0 过去,否则页面里仍是脚本自己的 10 门上限。
|
|
||||||
if (s.maxCourses !== null && s.maxCourses !== cfg.MAX_COURSES) {
|
|
||||||
await page.tryEval(exprSetMaxCourses(cfg.MAX_COURSES));
|
|
||||||
}
|
|
||||||
|
|
||||||
// 掉登录:用环境变量里的账号自动重登(限速 + 次数上限)
|
// 掉登录:用环境变量里的账号自动重登(限速 + 次数上限)
|
||||||
if (s.onLogin) {
|
if (s.onLogin) {
|
||||||
if (loginAttempts >= MAX_LOGIN_ATTEMPTS) {
|
if (loginAttempts >= MAX_LOGIN_ATTEMPTS) {
|
||||||
@@ -194,28 +186,25 @@ export async function runSession(o) {
|
|||||||
// 不会出现「浏览器重启后自动接着刷」或「未登录就报运行中」。
|
// 不会出现「浏览器重启后自动接着刷」或「未登录就报运行中」。
|
||||||
const raw = await page.tryEval(`JSON.stringify((function () {
|
const raw = await page.tryEval(`JSON.stringify((function () {
|
||||||
var a = window.__yunXueTangAuto;
|
var a = window.__yunXueTangAuto;
|
||||||
return { route: a.route(), batchRunning: a.S.batchRunning, batchFinished: a.S.batchFinished, completed: a.S.completedThisRun };
|
return { route: a.route(), batchRunning: a.S.batchRunning, batchFinished: a.S.batchFinished,
|
||||||
|
status: (document.getElementById('yun-xue-tang-status') || {}).textContent || '' };
|
||||||
})())`);
|
})())`);
|
||||||
if (!raw) return; // 路由跳转中,下一轮再试
|
if (!raw) return; // 路由跳转中,下一轮再试
|
||||||
const st = JSON.parse(raw);
|
const st = JSON.parse(raw);
|
||||||
|
|
||||||
if (st.batchFinished) {
|
if (st.batchFinished) {
|
||||||
if (limitReachedByConfig(st.completed)) {
|
// 完成门数由收尾日志和通知正文另行给出,这里只留页面给出的停止原因
|
||||||
limitReached = true;
|
finishReason = String(st.status || '').trim().slice(0, 120) ||
|
||||||
finishReason = '已完成 ' + st.completed + ' 门(达到上限 maxCourses=' + cfg.MAX_COURSES + ')';
|
(cfg.RESTART_MINUTES > 0 ? '无更多可学课程,稍后重新开始' : '无更多可学课程');
|
||||||
} else if (cfg.RESTART_MINUTES > 0) {
|
|
||||||
finishReason = '脚本已停止(本次完成 ' + st.completed + ' 门),按 YUN_XUE_TANG_RESTART_MINUTES 稍后重新开始';
|
|
||||||
} else {
|
|
||||||
finishReason = '脚本已停止(本次完成 ' + st.completed + ' 门;无更多可学课程或达到脚本内上限)';
|
|
||||||
}
|
|
||||||
finished = true;
|
finished = true;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!st.batchRunning && st.route !== 'other') {
|
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) {
|
if (ok) {
|
||||||
tui.set({ phase: '刷课中', tone: 'ok' });
|
tui.set({ phase: '刷课中', tone: 'ok' });
|
||||||
log('已启动列表刷课' + (cfg.PREFER_SHORT ? '(优先短课程)' : ''));
|
log('已启动列表刷课' + (cfg.PREFER_SHORT ? '(优先短课程)' : '') +
|
||||||
|
(cfg.POINTS_MODE ? '(每日积分模式)' : ''));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -236,9 +225,9 @@ export async function runSession(o) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
log('模式:无头 ' + (browser.headless ? 'headless' : '否') +
|
log('模式:无头 ' + (browser.headless ? 'headless' : '否') +
|
||||||
' 上限 ' + (cfg.MAX_COURSES > 0 ? cfg.MAX_COURSES + ' 门' : '不限') +
|
|
||||||
' 预算 ' + (cfg.BUDGET_MINUTES > 0 ? cfg.BUDGET_MINUTES + ' 分钟' : '不限') +
|
' 预算 ' + (cfg.BUDGET_MINUTES > 0 ? cfg.BUDGET_MINUTES + ' 分钟' : '不限') +
|
||||||
' 短课程优先 ' + (cfg.PREFER_SHORT ? '开' : '关') +
|
' 短课程优先 ' + (cfg.PREFER_SHORT ? '开' : '关') +
|
||||||
|
' 每日积分 ' + (cfg.POINTS_MODE ? '开' : '关') +
|
||||||
' 无进展 ' + cfg.IDLE_RESTART_MINUTES + ' 分钟');
|
' 无进展 ' + cfg.IDLE_RESTART_MINUTES + ' 分钟');
|
||||||
|
|
||||||
watchdog = setInterval(() => {
|
watchdog = setInterval(() => {
|
||||||
@@ -287,8 +276,8 @@ export async function runSession(o) {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
lastStateAt = Date.now();
|
lastStateAt = Date.now();
|
||||||
// 面板每一轮都刷(快照本身就是最新状态,不需要另算);未启用时是空操作
|
// 面板每一轮都刷(快照本身就是最新状态,不需要另算);面板未启用时也照常累计学时/学分
|
||||||
tui.snap(snap);
|
const study = tui.snap(snap);
|
||||||
if (!finishReason) {
|
if (!finishReason) {
|
||||||
if (snap.runFinished) tui.set({ phase: '脚本已停止', tone: 'ok' });
|
if (snap.runFinished) tui.set({ phase: '脚本已停止', tone: 'ok' });
|
||||||
else if (snap.retryWait > 0) tui.set({ phase: '等待重试', tone: 'warn' });
|
else if (snap.retryWait > 0) tui.set({ phase: '等待重试', tone: 'warn' });
|
||||||
@@ -296,6 +285,19 @@ export async function runSession(o) {
|
|||||||
else if (snap.route === 'list') tui.set({ phase: '列表页排队中', tone: 'info' });
|
else if (snap.route === 'list') tui.set({ phase: '列表页排队中', tone: 'info' });
|
||||||
else tui.set({ phase: '运行中', tone: 'info' });
|
else tui.set({ phase: '运行中', tone: 'info' });
|
||||||
}
|
}
|
||||||
|
// 每刷完一门课推一条学分提醒;study.earned 已经按课程去重,重试不会重复推
|
||||||
|
if (study && study.earned && study.earned.length && !stop.stopping) {
|
||||||
|
for (const ev of study.earned) {
|
||||||
|
tui.set({ phase: '发送 Bark 通知', tone: 'info' });
|
||||||
|
await notifyCreditEarned(cfg, {
|
||||||
|
course: ev.course,
|
||||||
|
credit: ev.credit,
|
||||||
|
total: study.creditEarned,
|
||||||
|
completed: snap.completed,
|
||||||
|
}, { log, warn });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
// 编解码器缺失:视频元素有源但解码错误(MEDIA_ERR_DECODE / SRC_NOT_SUPPORTED)
|
// 编解码器缺失:视频元素有源但解码错误(MEDIA_ERR_DECODE / SRC_NOT_SUPPORTED)
|
||||||
if (!codecWarned && snap.video && snap.video.src && snap.video.err >= 3) {
|
if (!codecWarned && snap.video && snap.video.src && snap.video.err >= 3) {
|
||||||
@@ -321,7 +323,7 @@ export async function runSession(o) {
|
|||||||
if (snap.lesson) parts.push('课时 ' + String(snap.lesson).slice(0, 24));
|
if (snap.lesson) parts.push('课时 ' + String(snap.lesson).slice(0, 24));
|
||||||
if (snap.summary && snap.summary.text) parts.push(String(snap.summary.text).slice(0, 24));
|
if (snap.summary && snap.summary.text) parts.push(String(snap.summary.text).slice(0, 24));
|
||||||
if (snap.countdown != null) parts.push('倒计时 ' + snap.countdown + 's');
|
if (snap.countdown != null) parts.push('倒计时 ' + snap.countdown + 's');
|
||||||
parts.push('本次完成 ' + snap.completed + (cfg.MAX_COURSES > 0 ? '/' + cfg.MAX_COURSES : ''));
|
parts.push('本次完成 ' + snap.completed);
|
||||||
if (snap.retryWait) parts.push('等待重试 ' + snap.retryWait + 's');
|
if (snap.retryWait) parts.push('等待重试 ' + snap.retryWait + 's');
|
||||||
else if (snap.retryCount) parts.push('待重试 ' + snap.retryCount);
|
else if (snap.retryCount) parts.push('待重试 ' + snap.retryCount);
|
||||||
log(parts.join(' '));
|
log(parts.join(' '));
|
||||||
@@ -332,16 +334,15 @@ export async function runSession(o) {
|
|||||||
log('✔ 已完成 ' + snap.completed + ' 门(累计记录 ' + snap.doneCount + ' 门)');
|
log('✔ 已完成 ' + snap.completed + ' 门(累计记录 ' + snap.doneCount + ' 门)');
|
||||||
}
|
}
|
||||||
|
|
||||||
// 到达上限 / 脚本停止 / 长时间无进展
|
// 脚本停止 / 长时间无进展
|
||||||
if (limitReachedByConfig(snap.completed)) {
|
if (snap.runFinished) {
|
||||||
limitReached = true;
|
// 标题已经说明「结束了」,这里只要有具体原因就够了
|
||||||
finishReason = '已完成 ' + snap.completed + ' 门(达到上限 maxCourses=' + cfg.MAX_COURSES + ')';
|
finishReason = String(snap.status || '').trim() || '页面脚本已停止';
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (snap.runFinished) { finishReason = '脚本已停止:' + (snap.status || '未知原因'); break; }
|
|
||||||
if (Date.now() - lastProgressAt > stallLimit) {
|
if (Date.now() - lastProgressAt > stallLimit) {
|
||||||
finishReason = '超过 ' + Math.round(stallLimit / 60000) + ' 分钟没有任何进展(最后停在 ' +
|
finishReason = '超过 ' + Math.round(stallLimit / 60000) + ' 分钟没有任何进展(最后停在 ' +
|
||||||
(snap.course || '列表') + '),退出等待重启';
|
(snap.course || '列表') + ')';
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -363,5 +364,8 @@ export async function runSession(o) {
|
|||||||
unregister();
|
unregister();
|
||||||
activeCleanup = null;
|
activeCleanup = null;
|
||||||
|
|
||||||
return { finishReason, limitReached, completed: final.completed || 0, elapsed, injected, ok: true };
|
return {
|
||||||
|
finishReason, completed: final.completed || 0, elapsed, injected, ok: true,
|
||||||
|
points: final.points || null,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
+13
-5
@@ -35,9 +35,10 @@ export function createStudyTracker(opts = {}) {
|
|||||||
* 传进来的快照字段可能缺失(页面刚跳转时就是半空的),所以全部按可选处理。
|
* 传进来的快照字段可能缺失(页面刚跳转时就是半空的),所以全部按可选处理。
|
||||||
*/
|
*/
|
||||||
function update(snap) {
|
function update(snap) {
|
||||||
if (!snap || snap.noApi) return get();
|
if (!snap || snap.noApi) return { ...get(), earned: [] };
|
||||||
const at = now();
|
const at = now();
|
||||||
const course = snap.course || '';
|
const course = snap.course || '';
|
||||||
|
const earned = [];
|
||||||
|
|
||||||
// ---- 学习时长:只算视频真的在播的时间 ----
|
// ---- 学习时长:只算视频真的在播的时间 ----
|
||||||
// 用「两次快照的真实间隔」而不是写死的轮询周期:CDP 往返偶尔会慢,
|
// 用「两次快照的真实间隔」而不是写死的轮询周期:CDP 往返偶尔会慢,
|
||||||
@@ -70,13 +71,15 @@ export function createStudyTracker(opts = {}) {
|
|||||||
const justDone = lastCourse || course;
|
const justDone = lastCourse || course;
|
||||||
if (justDone && creditOf.has(justDone) && !credited.has(justDone)) {
|
if (justDone && creditOf.has(justDone) && !credited.has(justDone)) {
|
||||||
credited.add(justDone);
|
credited.add(justDone);
|
||||||
creditEarned += creditOf.get(justDone);
|
const amount = creditOf.get(justDone);
|
||||||
|
creditEarned += amount;
|
||||||
|
earned.push({ course: justDone, credit: amount });
|
||||||
}
|
}
|
||||||
lastCompleted = completed;
|
lastCompleted = completed;
|
||||||
}
|
}
|
||||||
if (course) lastCourse = course;
|
if (course) lastCourse = course;
|
||||||
|
|
||||||
return get();
|
return { ...get(), earned };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 当前统计值(不会被外部改到内部状态) */
|
/** 当前统计值(不会被外部改到内部状态) */
|
||||||
@@ -93,13 +96,18 @@ export function createStudyTracker(opts = {}) {
|
|||||||
|
|
||||||
/** 学分文本:整数不带小数点,小数保留最多两位并去掉尾随 0 */
|
/** 学分文本:整数不带小数点,小数保留最多两位并去掉尾随 0 */
|
||||||
function creditText(value) {
|
function creditText(value) {
|
||||||
const v = value === undefined ? creditEarned : value;
|
return formatCredit(value === undefined ? creditEarned : value);
|
||||||
return String(Number(v.toFixed(2)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return { update, get, summary, creditText, reset() { studySeconds = 0; creditEarned = 0; credit = null; lastAt = 0; lastPlaying = false; lastCompleted = 0; lastCourse = ''; creditOf.clear(); credited.clear(); } };
|
return { update, get, summary, creditText, reset() { studySeconds = 0; creditEarned = 0; credit = null; lastAt = 0; lastPlaying = false; lastCompleted = 0; lastCourse = ''; creditOf.clear(); credited.clear(); } };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 学分文本:整数不带小数点,小数保留最多两位并去掉尾随 0 */
|
||||||
|
export function formatCredit(value) {
|
||||||
|
const v = Number(value) || 0;
|
||||||
|
return String(Number(v.toFixed(2)));
|
||||||
|
}
|
||||||
|
|
||||||
/** 秒 → 1:23:45 / 23:45(与面板显示保持一致,面板自己那份在 tui.mjs) */
|
/** 秒 → 1:23:45 / 23:45(与面板显示保持一致,面板自己那份在 tui.mjs) */
|
||||||
function fmt(sec) {
|
function fmt(sec) {
|
||||||
const s = Math.max(0, Math.round(Number(sec) || 0));
|
const s = Math.max(0, Math.round(Number(sec) || 0));
|
||||||
|
|||||||
+43
-4
@@ -8,6 +8,7 @@ import { runSession, disposeActiveSession } from './session.mjs';
|
|||||||
import { openLog } from './log.mjs';
|
import { openLog } from './log.mjs';
|
||||||
import { noDisplayReason, platformName } from './platform.mjs';
|
import { noDisplayReason, platformName } from './platform.mjs';
|
||||||
import { createTui } from './tui.mjs';
|
import { createTui } from './tui.mjs';
|
||||||
|
import { notifyRunStarted, notifyRunFinished } from './notify.mjs';
|
||||||
|
|
||||||
const RETRY_BASE_MS = 15000;
|
const RETRY_BASE_MS = 15000;
|
||||||
const RETRY_MAX_MS = 120000;
|
const RETRY_MAX_MS = 120000;
|
||||||
@@ -40,7 +41,6 @@ export async function runSupervisor(o) {
|
|||||||
else if (typeof stop.request === 'function') stop.request(reason);
|
else if (typeof stop.request === 'function') stop.request(reason);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
tui.set({ maxCourses: cfg.MAX_COURSES });
|
|
||||||
|
|
||||||
log('=== 云学堂助手 · 无头运行器' + (cfg.CHECK_ONLY ? '(自检)' : '') + ' 启动 ===');
|
log('=== 云学堂助手 · 无头运行器' + (cfg.CHECK_ONLY ? '(自检)' : '') + ' 启动 ===');
|
||||||
log('Node ' + process.version + ' ' + platformName + '/' + process.arch);
|
log('Node ' + process.version + ' ' + platformName + '/' + process.arch);
|
||||||
@@ -55,9 +55,38 @@ export async function runSupervisor(o) {
|
|||||||
}
|
}
|
||||||
if (!cfg.TUI && cfg.tuiDisabledReason) log('面板:' + cfg.tuiDisabledReason());
|
if (!cfg.TUI && cfg.tuiDisabledReason) log('面板:' + cfg.tuiDisabledReason());
|
||||||
tui.set({ phase: '启动中' });
|
tui.set({ phase: '启动中' });
|
||||||
|
if (!cfg.CHECK_ONLY) {
|
||||||
|
// 整个进程只发一次「开始运行」;配了 restartMinutes 时每轮会话重开不再推
|
||||||
|
tui.set({ phase: '发送 Bark 通知', tone: 'info' });
|
||||||
|
await notifyRunStarted(cfg, { log, warn });
|
||||||
|
}
|
||||||
|
|
||||||
let attempt = 0;
|
let attempt = 0;
|
||||||
let last = null;
|
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) => {
|
const finishTui = (phase, tone) => {
|
||||||
@@ -73,8 +102,12 @@ export async function runSupervisor(o) {
|
|||||||
last = await runSession({ ...o, cfg, tui });
|
last = await runSession({ ...o, cfg, tui });
|
||||||
if (stop.stopping) break;
|
if (stop.stopping) break;
|
||||||
if (cfg.CHECK_ONLY) break;
|
if (cfg.CHECK_ONLY) break;
|
||||||
// 正常结束:只有「脚本自己停了 / 无进展」且配了重启间隔才再来一轮
|
// 每轮会话自己结束就先推一次:配了 restartMinutes 时进程不会退出,
|
||||||
const restartable = !last.limitReached && cfg.RESTART_MINUTES > 0;
|
// 只在最终收尾推就等于永远不推。重复结论由 notify() 的识别键挡掉。
|
||||||
|
tui.set({ phase: '发送 Bark 通知', tone: 'info' });
|
||||||
|
await notify(finishResult(last));
|
||||||
|
// 正常结束:配了重启间隔就再来一轮
|
||||||
|
const restartable = cfg.RESTART_MINUTES > 0;
|
||||||
if (!restartable) break;
|
if (!restartable) break;
|
||||||
log('按 YUN_XUE_TANG_RESTART_MINUTES=' + cfg.RESTART_MINUTES + ' 等待后重新开始…');
|
log('按 YUN_XUE_TANG_RESTART_MINUTES=' + cfg.RESTART_MINUTES + ' 等待后重新开始…');
|
||||||
tui.set({ phase: '等待 ' + cfg.RESTART_MINUTES + ' 分钟后重开', tone: 'ok' });
|
tui.set({ phase: '等待 ' + cfg.RESTART_MINUTES + ' 分钟后重开', tone: 'ok' });
|
||||||
@@ -90,6 +123,8 @@ export async function runSupervisor(o) {
|
|||||||
tui.set({ phase: '会话异常,准备重试', tone: 'error' });
|
tui.set({ phase: '会话异常,准备重试', tone: 'error' });
|
||||||
// 连登 5 次失败基本都是密码错 / 要验证码,重试没意义,直接用专门的退出码结束
|
// 连登 5 次失败基本都是密码错 / 要验证码,重试没意义,直接用专门的退出码结束
|
||||||
if (e && e.message && /连续 \d+ 次登录失败/.test(e.message)) {
|
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');
|
finishTui('登录失败,检查账号密码 / 验证码', 'error');
|
||||||
return { exitCode: 3, last };
|
return { exitCode: 3, last };
|
||||||
}
|
}
|
||||||
@@ -103,10 +138,14 @@ export async function runSupervisor(o) {
|
|||||||
|
|
||||||
const stalled = !!(last && /没有任何进展/.test(last.finishReason || ''));
|
const stalled = !!(last && /没有任何进展/.test(last.finishReason || ''));
|
||||||
const exitCode = cfg.CHECK_ONLY ? (last && last.ok ? 0 : 1) : (stalled ? 1 : 0);
|
const exitCode = cfg.CHECK_ONLY ? (last && last.ok ? 0 : 1) : (stalled ? 1 : 0);
|
||||||
// 0 = 正常收尾(达到上限 / 预算 / 无更多课程);1 = 无进展卡死;3 = 连续登录失败
|
// 0 = 正常收尾(预算 / 积分完成 / 无更多课程);1 = 无进展卡死;3 = 连续登录失败
|
||||||
const phase = cfg.CHECK_ONLY
|
const phase = cfg.CHECK_ONLY
|
||||||
? (exitCode === 0 ? '自检通过' : '自检失败')
|
? (exitCode === 0 ? '自检通过' : '自检失败')
|
||||||
: stalled ? '退出:长时间无进展' : '正常收尾';
|
: stalled ? '退出:长时间无进展' : '正常收尾';
|
||||||
|
if (last) {
|
||||||
|
tui.set({ phase: '发送 Bark 通知', tone: 'info' });
|
||||||
|
await notify(finishResult(last));
|
||||||
|
}
|
||||||
finishTui(phase, exitCode === 0 ? 'ok' : (stalled ? 'warn' : 'error'));
|
finishTui(phase, exitCode === 0 ? 'ok' : (stalled ? 'warn' : 'error'));
|
||||||
|
|
||||||
log('=== 运行器退出 ===');
|
log('=== 运行器退出 ===');
|
||||||
|
|||||||
+12
-4
@@ -171,7 +171,6 @@ export function createTui(opts = {}) {
|
|||||||
summary: '',
|
summary: '',
|
||||||
countdown: null,
|
countdown: null,
|
||||||
completed: 0,
|
completed: 0,
|
||||||
maxCourses: 0,
|
|
||||||
doneCount: 0,
|
doneCount: 0,
|
||||||
retryCount: 0,
|
retryCount: 0,
|
||||||
retryWait: 0,
|
retryWait: 0,
|
||||||
@@ -181,6 +180,7 @@ export function createTui(opts = {}) {
|
|||||||
studySeconds: 0, // 学习时长:只累加视频真正在播的时间
|
studySeconds: 0, // 学习时长:只累加视频真正在播的时间
|
||||||
creditEarned: 0, // 获得学分:只算本次运行里完成(刷完)的课程
|
creditEarned: 0, // 获得学分:只算本次运行里完成(刷完)的课程
|
||||||
credit: null, // 当前课程可得多少学分(平台只在播放期间写在倒计时文案里)
|
credit: null, // 当前课程可得多少学分(平台只在播放期间写在倒计时文案里)
|
||||||
|
points: null, // 每日积分:{ enabled, total, max, progress, text }
|
||||||
injected: 0,
|
injected: 0,
|
||||||
logFile: opts.logFile || '',
|
logFile: opts.logFile || '',
|
||||||
startedAt: Date.now(),
|
startedAt: Date.now(),
|
||||||
@@ -263,8 +263,7 @@ export function createTui(opts = {}) {
|
|||||||
|
|
||||||
function countValue(width) {
|
function countValue(width) {
|
||||||
// 字段按重要性递降:本次/累计是骨架,其余在窄终端里从右往左丢,不硬截断
|
// 字段按重要性递降:本次/累计是骨架,其余在窄终端里从右往左丢,不硬截断
|
||||||
const parts = ['本次 ' + state.completed + (state.maxCourses > 0 ? '/' + state.maxCourses : ''),
|
const parts = ['本次 ' + state.completed, '累计 ' + state.doneCount];
|
||||||
'累计 ' + state.doneCount];
|
|
||||||
const extra = [];
|
const extra = [];
|
||||||
if (state.lessons) extra.push('课时数 ' + state.lessons);
|
if (state.lessons) extra.push('课时数 ' + state.lessons);
|
||||||
if (state.retryWait > 0) extra.push(C.yellow('等待重试 ' + state.retryWait + 's'));
|
if (state.retryWait > 0) extra.push(C.yellow('等待重试 ' + state.retryWait + 's'));
|
||||||
@@ -296,6 +295,10 @@ export function createTui(opts = {}) {
|
|||||||
const parts = [C.cyan('已学 ' + formatDuration(state.studySeconds))];
|
const parts = [C.cyan('已学 ' + formatDuration(state.studySeconds))];
|
||||||
parts.push(C.green('学分 ' + study.creditText(state.creditEarned)));
|
parts.push(C.green('学分 ' + study.creditText(state.creditEarned)));
|
||||||
const used = () => textWidth(parts.join(' · '));
|
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) {
|
if (state.credit != null) {
|
||||||
const now = '本门 ' + study.creditText(state.credit);
|
const now = '本门 ' + study.creditText(state.credit);
|
||||||
if (used() + 3 + textWidth(now) <= width) parts.push(now);
|
if (used() + 3 + textWidth(now) <= width) parts.push(now);
|
||||||
@@ -521,14 +524,18 @@ export function createTui(opts = {}) {
|
|||||||
},
|
},
|
||||||
/**
|
/**
|
||||||
* 用 session 的主监控快照刷新面板,顺便累计学习时长与学分(详细规则见 study.mjs)。
|
* 用 session 的主监控快照刷新面板,顺便累计学习时长与学分(详细规则见 study.mjs)。
|
||||||
|
* 面板关闭时也照常统计:学分明细要拿来发 Bark 通知,不能只在 TTY 下有。
|
||||||
|
* @returns {object|null} study.update() 的结果,含本次新增的学分事件
|
||||||
*/
|
*/
|
||||||
snap(s) {
|
snap(s) {
|
||||||
if (!enabled || !s || s.noApi) return;
|
if (!s || s.noApi) return null;
|
||||||
const pick = (v, d) => (v === undefined ? d : v);
|
const pick = (v, d) => (v === undefined ? d : v);
|
||||||
const st = study.update(s);
|
const st = study.update(s);
|
||||||
|
if (!enabled) return st;
|
||||||
state.studySeconds = st.studySeconds;
|
state.studySeconds = st.studySeconds;
|
||||||
state.creditEarned = st.creditEarned;
|
state.creditEarned = st.creditEarned;
|
||||||
state.credit = st.credit;
|
state.credit = st.credit;
|
||||||
|
state.points = s.points || null;
|
||||||
|
|
||||||
state.course = pick(s.course, '');
|
state.course = pick(s.course, '');
|
||||||
state.lesson = pick(s.lesson, '');
|
state.lesson = pick(s.lesson, '');
|
||||||
@@ -540,6 +547,7 @@ export function createTui(opts = {}) {
|
|||||||
state.retryWait = pick(s.retryWait, 0);
|
state.retryWait = pick(s.retryWait, 0);
|
||||||
state.lessons = pick(s.lessons, 0);
|
state.lessons = pick(s.lessons, 0);
|
||||||
state.video = s.video || null;
|
state.video = s.video || null;
|
||||||
|
return st;
|
||||||
},
|
},
|
||||||
render,
|
render,
|
||||||
redraw,
|
redraw,
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
@echo off
|
||||||
|
rem ---------------------------------------------------------------
|
||||||
|
rem This file must stay PURE ASCII and CRLF (see scripts\start-headless.cmd
|
||||||
|
rem for the full explanation: cmd.exe parses batch files byte-by-byte with
|
||||||
|
rem the current code page, so multi-byte chars / bare LF corrupt line offsets).
|
||||||
|
rem All Chinese messages come from the Node script instead.
|
||||||
|
rem
|
||||||
|
rem Usage:
|
||||||
|
rem scripts\build-docker.cmd build with default tags
|
||||||
|
rem scripts\build-docker.cmd --mirror --check build with CN mirrors, then self-check
|
||||||
|
rem scripts\build-docker.cmd --help list all options
|
||||||
|
rem ---------------------------------------------------------------
|
||||||
|
setlocal
|
||||||
|
chcp 65001 >nul
|
||||||
|
cd /d "%~dp0.."
|
||||||
|
title YunXueTang Assistant - docker build
|
||||||
|
|
||||||
|
where node >nul 2>nul
|
||||||
|
if errorlevel 1 goto no_node
|
||||||
|
|
||||||
|
node "scripts\build-docker.mjs" %*
|
||||||
|
set RC=%ERRORLEVEL%
|
||||||
|
if "%RC%"=="0" exit /b 0
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo [exit] code %RC% (0 ok 1 build failed 2 env/args problem)
|
||||||
|
pause
|
||||||
|
exit /b %RC%
|
||||||
|
|
||||||
|
:no_node
|
||||||
|
echo [error] node.exe not found. Install Node.js 22+ from https://nodejs.org/
|
||||||
|
pause
|
||||||
|
exit /b 2
|
||||||
@@ -0,0 +1,342 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
/**
|
||||||
|
* 构建 Docker 镜像的便捷入口。
|
||||||
|
*
|
||||||
|
* 为什么要有这层脚本,而不是让人手敲 `docker build`:
|
||||||
|
* 1. Dockerfile 里有三个构建参数(APT_MIRROR / NPM_REGISTRY / CHROME_DEB_URL),
|
||||||
|
* 国内机器几乎必须换源才能构建成功,但每次手写 `--build-arg` 又长又容易漏;
|
||||||
|
* 这里统一从命令行、环境变量、.env 三处按优先级取值。
|
||||||
|
* 2. 镜像标签跟着 package.json 的 version 走,顺手再打一个 latest;
|
||||||
|
* 版本号只在 package.json 维护一处,不靠人记。
|
||||||
|
* 3. 构建完能直接 `--check`(只读自检:不登录、不动进度),一步验证镜像真的能起来。
|
||||||
|
*
|
||||||
|
* 用法:
|
||||||
|
* npm run docker:build # 默认标签 = 包里版本号 + latest
|
||||||
|
* npm run docker:build -- --mirror # 一键换国内源(apt 清华 + npm npmmirror)
|
||||||
|
* npm run docker:build -- --check # 构建完立刻跑一次 --check 自检
|
||||||
|
* npm run docker:build -- --tag my/yxt:dev # 只打指定标签
|
||||||
|
* npm run docker:build -- --dry-run # 只打印将要执行的 docker 命令
|
||||||
|
* npm run docker:build -- --help
|
||||||
|
*
|
||||||
|
* 退出码与仓库其它脚本保持一致:0 成功 / 1 构建失败 / 2 环境或参数问题。
|
||||||
|
*/
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
|
||||||
|
/** 国内常用镜像源预设(--mirror 一键套用);Chrome 的 deb 没有公认镜像,只能由使用者用 --chrome-url 指定 */
|
||||||
|
const MIRROR_PRESET = {
|
||||||
|
apt: 'mirrors.tuna.tsinghua.edu.cn',
|
||||||
|
npm: 'https://registry.npmmirror.com',
|
||||||
|
};
|
||||||
|
|
||||||
|
const HELP = `构建云学堂助手 Docker 镜像
|
||||||
|
|
||||||
|
用法:node scripts/build-docker.mjs [选项]
|
||||||
|
|
||||||
|
选项:
|
||||||
|
-t, --tag <名称:标签> 镜像标签;可重复给多次。默认 <包名>:<package.json 版本> 加 <包名>:latest
|
||||||
|
--mirror 一键套用国内镜像源(apt = ${MIRROR_PRESET.apt},npm = ${MIRROR_PRESET.npm})
|
||||||
|
--apt-mirror <host> Debian 源地址,对应 Dockerfile 的 APT_MIRROR
|
||||||
|
--npm-registry <url> npm 源地址,对应 NPM_REGISTRY
|
||||||
|
--chrome-url <url> Chrome deb 直链,对应 CHROME_DEB_URL(国内下不动 dl.google.com 时用)
|
||||||
|
--platform <平台> 如 linux/amd64、linux/arm64(默认用构建机架构)
|
||||||
|
--build-arg <K=V> 透传任意额外构建参数,可重复
|
||||||
|
--no-cache 不用构建缓存
|
||||||
|
--pull 先拉取最新的基础镜像
|
||||||
|
--check 构建成功后跑一次 \`docker run --rm <镜像> --check\` 自检
|
||||||
|
--dry-run 只打印 docker 命令,不真正构建
|
||||||
|
-h, --help 显示本帮助
|
||||||
|
|
||||||
|
取值优先级:命令行 > 同名环境变量 > 仓库根目录 .env > 默认值
|
||||||
|
(只从 .env 读 APT_MIRROR / NPM_REGISTRY / CHROME_DEB_URL 三个键,凭据类变量一律不读)
|
||||||
|
|
||||||
|
示例:
|
||||||
|
node scripts/build-docker.mjs --mirror --check
|
||||||
|
node scripts/build-docker.mjs -t yun-xue-tang-assistant:test --no-cache
|
||||||
|
APT_MIRROR=mirrors.aliyun.com node scripts/build-docker.mjs
|
||||||
|
`;
|
||||||
|
|
||||||
|
/** 解析成 { options, error } —— 手写解析而非引入依赖,仓库唯一的 devDependency 是 esbuild */
|
||||||
|
function parseArgs(argv) {
|
||||||
|
const opts = {
|
||||||
|
tags: [],
|
||||||
|
mirror: false,
|
||||||
|
aptMirror: '',
|
||||||
|
npmRegistry: '',
|
||||||
|
chromeUrl: '',
|
||||||
|
platform: '',
|
||||||
|
buildArgs: [],
|
||||||
|
noCache: false,
|
||||||
|
pull: false,
|
||||||
|
check: false,
|
||||||
|
dryRun: false,
|
||||||
|
help: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
const needValue = (i, name) => {
|
||||||
|
const v = argv[i + 1];
|
||||||
|
if (v === undefined || v.startsWith('-')) {
|
||||||
|
throw new Error(`选项 ${name} 需要一个值`);
|
||||||
|
}
|
||||||
|
return v;
|
||||||
|
};
|
||||||
|
|
||||||
|
for (let i = 0; i < argv.length; i++) {
|
||||||
|
const arg = argv[i];
|
||||||
|
// 支持 --key=value 与 --key value 两种写法
|
||||||
|
const eq = arg.indexOf('=');
|
||||||
|
const key = arg.startsWith('--') && eq > 0 ? arg.slice(0, eq) : arg;
|
||||||
|
const inline = arg.startsWith('--') && eq > 0 ? arg.slice(eq + 1) : null;
|
||||||
|
const take = (name) => (inline !== null ? inline : needValue(i, name));
|
||||||
|
const takeAndSkip = (name) => {
|
||||||
|
const v = take(name);
|
||||||
|
if (inline === null) i++;
|
||||||
|
return v;
|
||||||
|
};
|
||||||
|
|
||||||
|
switch (key) {
|
||||||
|
case '-t':
|
||||||
|
case '--tag': {
|
||||||
|
const v = takeAndSkip(key);
|
||||||
|
if (!v.trim()) throw new Error('镜像标签不能为空');
|
||||||
|
opts.tags.push(v.trim());
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case '--mirror':
|
||||||
|
opts.mirror = true;
|
||||||
|
break;
|
||||||
|
case '--apt-mirror':
|
||||||
|
opts.aptMirror = takeAndSkip(key);
|
||||||
|
break;
|
||||||
|
case '--npm-registry':
|
||||||
|
opts.npmRegistry = takeAndSkip(key);
|
||||||
|
break;
|
||||||
|
case '--chrome-url':
|
||||||
|
opts.chromeUrl = takeAndSkip(key);
|
||||||
|
break;
|
||||||
|
case '--platform':
|
||||||
|
opts.platform = takeAndSkip(key);
|
||||||
|
break;
|
||||||
|
case '--build-arg':
|
||||||
|
opts.buildArgs.push(takeAndSkip(key));
|
||||||
|
break;
|
||||||
|
case '--no-cache':
|
||||||
|
opts.noCache = true;
|
||||||
|
break;
|
||||||
|
case '--pull':
|
||||||
|
opts.pull = true;
|
||||||
|
break;
|
||||||
|
case '--check':
|
||||||
|
opts.check = true;
|
||||||
|
break;
|
||||||
|
case '--dry-run':
|
||||||
|
opts.dryRun = true;
|
||||||
|
break;
|
||||||
|
case '-h':
|
||||||
|
case '--help':
|
||||||
|
opts.help = true;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new Error(`未知选项:${arg}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return opts;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 极简 .env 解析:只认 KEY=VALUE / KEY="VALUE",忽略注释与空行 */
|
||||||
|
function readDotEnv(file) {
|
||||||
|
const out = {};
|
||||||
|
if (!fs.existsSync(file)) return out;
|
||||||
|
let text = '';
|
||||||
|
try {
|
||||||
|
text = fs.readFileSync(file, 'utf8');
|
||||||
|
} catch {
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
for (const raw of text.split(/\r?\n/)) {
|
||||||
|
const line = raw.trim();
|
||||||
|
if (!line || line.startsWith('#')) continue;
|
||||||
|
const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
|
||||||
|
if (!m) continue;
|
||||||
|
let v = m[2].trim();
|
||||||
|
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
|
||||||
|
v = v.slice(1, -1);
|
||||||
|
}
|
||||||
|
out[m[1]] = v;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readPackage(file) {
|
||||||
|
try {
|
||||||
|
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error(`读不出 ${path.relative(ROOT, file)}:${e.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 把参数数组还原成可以直接粘进终端的命令行(仅用于日志展示) */
|
||||||
|
function quote(argv) {
|
||||||
|
return argv
|
||||||
|
.map((a) => (/^[\w@%+=:,./-]+$/.test(a) ? a : `'${a.replace(/'/g, `'\\''`)}'`))
|
||||||
|
.join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
function run(cmd, args, { capture = false } = {}) {
|
||||||
|
return spawnSync(cmd, args, {
|
||||||
|
cwd: ROOT,
|
||||||
|
stdio: capture ? ['ignore', 'pipe', 'pipe'] : 'inherit',
|
||||||
|
encoding: 'utf8',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function main() {
|
||||||
|
let opts;
|
||||||
|
try {
|
||||||
|
opts = parseArgs(process.argv.slice(2));
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[错误] ' + e.message);
|
||||||
|
console.error('用 --help 查看用法。');
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (opts.help) {
|
||||||
|
process.stdout.write(HELP);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!fs.existsSync(path.join(ROOT, 'Dockerfile'))) {
|
||||||
|
console.error('[错误] 找不到 Dockerfile,请在仓库根目录运行。');
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 1. 检查 docker 是否可用(CLI 缺失和守护进程没起来,处理方式完全不同,分开报) ----
|
||||||
|
// --dry-run 只打印命令、不真的构建,所以这里只警告不拦截,方便在没有 docker 的机器上预览
|
||||||
|
const cli = run('docker', ['--version'], { capture: true });
|
||||||
|
const cliOk = !cli.error && cli.status === 0;
|
||||||
|
if (!cliOk) {
|
||||||
|
const msg = '找不到可用的 docker 命令,请先安装 Docker Desktop / Docker Engine。';
|
||||||
|
if (!opts.dryRun) {
|
||||||
|
console.error('[错误] ' + msg);
|
||||||
|
if (cli.stderr) console.error(String(cli.stderr).trim());
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
console.log('[警告] ' + msg + '(dry-run 继续)');
|
||||||
|
} else {
|
||||||
|
console.log('[环境] ' + String(cli.stdout).trim());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 守护进程没启动时,docker build 会报一长串语焉不详的连接错误,这里提前拦下
|
||||||
|
if (cliOk) {
|
||||||
|
const daemon = run('docker', ['info', '--format', '{{.ServerVersion}}'], { capture: true });
|
||||||
|
if (daemon.status !== 0) {
|
||||||
|
const detail = String(daemon.stderr || '').trim();
|
||||||
|
if (!opts.dryRun) {
|
||||||
|
console.error('[错误] docker 守护进程未运行(Docker Desktop 没启动 / 当前用户没权限连 socket)。');
|
||||||
|
if (detail) console.error(detail);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
console.log('[警告] docker 守护进程未运行(dry-run 继续)');
|
||||||
|
} else {
|
||||||
|
console.log('[环境] 守护进程 ' + String(daemon.stdout).trim());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 2. 收集构建参数:命令行 > 环境变量 > .env > 默认 ----
|
||||||
|
const pkg = readPackage(path.join(ROOT, 'package.json'));
|
||||||
|
const dotenv = readDotEnv(path.join(ROOT, '.env'));
|
||||||
|
const pick = (cliValue, envKey) =>
|
||||||
|
cliValue || process.env[envKey] || dotenv[envKey] || '';
|
||||||
|
|
||||||
|
let aptMirror = pick(opts.aptMirror, 'APT_MIRROR');
|
||||||
|
let npmRegistry = pick(opts.npmRegistry, 'NPM_REGISTRY');
|
||||||
|
const chromeUrl = pick(opts.chromeUrl, 'CHROME_DEB_URL');
|
||||||
|
if (opts.mirror) {
|
||||||
|
// --mirror 只填空位,不覆盖使用者显式给的值
|
||||||
|
if (!aptMirror) aptMirror = MIRROR_PRESET.apt;
|
||||||
|
if (!npmRegistry) npmRegistry = MIRROR_PRESET.npm;
|
||||||
|
}
|
||||||
|
|
||||||
|
const buildArgs = [];
|
||||||
|
if (aptMirror) buildArgs.push('--build-arg', 'APT_MIRROR=' + aptMirror);
|
||||||
|
if (npmRegistry) buildArgs.push('--build-arg', 'NPM_REGISTRY=' + npmRegistry);
|
||||||
|
if (chromeUrl) buildArgs.push('--build-arg', 'CHROME_DEB_URL=' + chromeUrl);
|
||||||
|
// 额外的 --build-arg 放最后,允许覆盖上面的预设
|
||||||
|
for (const kv of opts.buildArgs) buildArgs.push('--build-arg', kv);
|
||||||
|
|
||||||
|
// ---- 3. 标签:没给就按 package.json 的版本号打 version + latest ----
|
||||||
|
const repoName = (pkg.name || 'yun-xue-tang-assistant').toLowerCase();
|
||||||
|
const version = pkg.version || 'dev';
|
||||||
|
const tags = opts.tags.length ? opts.tags : [`${repoName}:${version}`, `${repoName}:latest`];
|
||||||
|
|
||||||
|
const args = ['build'];
|
||||||
|
if (opts.platform) args.push('--platform', opts.platform);
|
||||||
|
if (opts.noCache) args.push('--no-cache');
|
||||||
|
if (opts.pull) args.push('--pull');
|
||||||
|
for (const t of tags) args.push('-t', t);
|
||||||
|
args.push(...buildArgs, '.');
|
||||||
|
|
||||||
|
const cmdline = 'docker ' + quote(args);
|
||||||
|
console.log('[构建] 镜像标签:' + tags.join('、'));
|
||||||
|
console.log('[构建] 上下文:' + ROOT);
|
||||||
|
if (aptMirror) console.log('[构建] APT_MIRROR = ' + aptMirror);
|
||||||
|
if (npmRegistry) console.log('[构建] NPM_REGISTRY = ' + npmRegistry);
|
||||||
|
if (chromeUrl) console.log('[构建] CHROME_DEB_URL= ' + chromeUrl);
|
||||||
|
if (!chromeUrl) console.log('[构建] CHROME_DEB_URL 未指定,将从 dl.google.com 下载(国内网络可能失败,见 README 常见问题)');
|
||||||
|
console.log('[构建] 命令:' + cmdline);
|
||||||
|
console.log('[构建] 首次构建约 3-5 分钟(主要是下 Chrome 的 deb),后续走缓存会快很多。\n');
|
||||||
|
|
||||||
|
if (opts.dryRun) {
|
||||||
|
console.log('[dry-run] 未执行构建。');
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 4. 真正构建 ----
|
||||||
|
const build = run('docker', args);
|
||||||
|
if (build.error) {
|
||||||
|
console.error('[错误] 启动 docker build 失败:' + build.error.message);
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
if (build.status !== 0) {
|
||||||
|
console.error('\n[失败] 构建未通过(退出码 ' + build.status + ')。常见原因:');
|
||||||
|
console.error(' · 拉不到 Chrome deb → 加 --chrome-url <你的镜像地址>,或先配好代理');
|
||||||
|
console.error(' · apt / npm 太慢 → 加 --mirror 换国内源');
|
||||||
|
console.error(' · 依赖变了但缓存没失效 → 加 --no-cache 重来一次');
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
const primary = tags[0];
|
||||||
|
console.log('\n[完成] 已构建:' + tags.join('、'));
|
||||||
|
|
||||||
|
// ---- 5. 可选自检:只读,不登录、不动课程进度,用来确认镜像真的能起来 ----
|
||||||
|
if (opts.check) {
|
||||||
|
console.log('[自检] 运行 docker run --rm ' + primary + ' --check ...\n');
|
||||||
|
const chk = run('docker', ['run', '--rm', primary, '--check']);
|
||||||
|
if (chk.status !== 0) {
|
||||||
|
console.error('\n[失败] 镜像自检未通过(退出码 ' + chk.status + ')。');
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
console.log('\n[自检] 通过:镜像内的 Node、Chrome、构建产物都可用。');
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`
|
||||||
|
下一步:
|
||||||
|
# 自检(不需要账号,只读)
|
||||||
|
docker run --rm ${primary} --check
|
||||||
|
|
||||||
|
# 正式刷课(凭据只走环境变量,别写进镜像)
|
||||||
|
docker run -d --name yun-xue-tang \\
|
||||||
|
-e YUN_XUE_TANG_USR='账号' -e YUN_XUE_TANG_PWD='密码' \\
|
||||||
|
-v "$PWD/.run-profile:/app/.run-profile" -v "$PWD/run-logs:/app/run-logs" \\
|
||||||
|
--shm-size=512m --restart on-failure:3 ${primary}
|
||||||
|
|
||||||
|
# 或用 compose(账号写在 .env 里):cp .env.example .env && docker compose up -d
|
||||||
|
`);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
process.exit(main());
|
||||||
Executable
+11
@@ -0,0 +1,11 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# 构建 Docker 镜像的薄封装(Linux / macOS 用)。
|
||||||
|
# 所有逻辑都在 scripts/build-docker.mjs 里,这里只负责切到仓库根目录再转交。
|
||||||
|
#
|
||||||
|
# ./scripts/build-docker.sh 默认标签
|
||||||
|
# ./scripts/build-docker.sh --mirror --check 国内源 + 构建后自检
|
||||||
|
# ./scripts/build-docker.sh --help
|
||||||
|
set -e
|
||||||
|
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||||
|
cd "$ROOT"
|
||||||
|
exec node scripts/build-docker.mjs "$@"
|
||||||
@@ -9,7 +9,7 @@ rem
|
|||||||
rem Usage:
|
rem Usage:
|
||||||
rem scripts\start-headless.cmd use config\runner.config.mjs
|
rem scripts\start-headless.cmd use config\runner.config.mjs
|
||||||
rem scripts\start-headless.cmd --help print all options
|
rem scripts\start-headless.cmd --help print all options
|
||||||
rem scripts\start-headless.cmd --max 3 command line overrides config file
|
rem scripts\start-headless.cmd --budget-minutes 15 command line overrides config file
|
||||||
rem ---------------------------------------------------------------
|
rem ---------------------------------------------------------------
|
||||||
setlocal
|
setlocal
|
||||||
chcp 65001 >nul
|
chcp 65001 >nul
|
||||||
|
|||||||
+31
-9
@@ -47,20 +47,42 @@ export function completeCurrent() {
|
|||||||
pauseAllMedia();
|
pauseAllMedia();
|
||||||
|
|
||||||
console.log(TAG, '课程完成:', title, '第', S.completedThisRun, '门,返回列表选下一门');
|
console.log(TAG, '课程完成:', title, '第', S.completedThisRun, '门,返回列表选下一门');
|
||||||
|
// 不按门数设上限:每日积分模式由 pointsDone() 决定何时收尾,
|
||||||
const limit = CFG.maxCourses > 0 ? CFG.maxCourses : Infinity;
|
// 一门课只有考试、没产出积分时也要继续找下一门。
|
||||||
if (S.completedThisRun >= limit) {
|
|
||||||
S.batchRunning = false;
|
|
||||||
S.batchFinished = true;
|
|
||||||
saveRunState();
|
|
||||||
setStatus('本次已完成 ' + S.completedThisRun + ' 门,已停止。可重新勾选开始新一轮。');
|
|
||||||
} else {
|
|
||||||
setStatus('课程完成:' + truncate(title, 26) + '(本次 ' + S.completedThisRun + ')');
|
setStatus('课程完成:' + truncate(title, 26) + '(本次 ' + S.completedThisRun + ')');
|
||||||
}
|
|
||||||
// 完成后的返回列表不能被 5 秒节流吞掉
|
// 完成后的返回列表不能被 5 秒节流吞掉
|
||||||
later(function () { goToList(true); }, 1200);
|
later(function () { goToList(true); }, 1200);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 这门课在本轮是否已被判为「无法自动完成」而跳过(目前只有考试交不了的情况)
|
||||||
|
export function courseSkipped(title) {
|
||||||
|
const t = norm(title);
|
||||||
|
return !!(t && (S.skippedCourses || {})[t]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 跳过这门课,继续下一门。
|
||||||
|
// 只用于「重试也不会好」的确定性失败:考试空卷交卷后平台始终不记账、
|
||||||
|
// 结果页又回不到考试说明页。继续按 failCurrent 退避重试只会反复进同一门课,
|
||||||
|
// 最后停下整轮刷课,其它 5000 多门课也跟着停——所以这里记下原因、本轮不再选它,
|
||||||
|
// 由人工事后处理这门考试。记录只活在本次会话(sessionStorage),重启会重新尝试。
|
||||||
|
export function skipCurrent(reason) {
|
||||||
|
const title = recordTitle();
|
||||||
|
const key = norm(title);
|
||||||
|
if (key) S.skippedCourses[key] = { reason: reason, at: Date.now() };
|
||||||
|
S.activeCourse = null;
|
||||||
|
S.coursePhase = PHASE_IDLE;
|
||||||
|
S.awaitingListReturn = true;
|
||||||
|
R.retryWaitUntil = 0;
|
||||||
|
R.retryTitle = '';
|
||||||
|
// 下一门课重新拉平台实时状态;被跳过的课仍在平台未学完列表里,靠 skippedCourses 排除
|
||||||
|
invalidateShortCatalog();
|
||||||
|
saveRunState();
|
||||||
|
setStatus('已跳过「' + truncate(title || '当前课程', 20) + '」:' + reason + '(继续下一门)');
|
||||||
|
console.warn(TAG, '跳过课程:', title, reason);
|
||||||
|
updatePanel();
|
||||||
|
later(function () { goToList(true); }, 1200);
|
||||||
|
}
|
||||||
|
|
||||||
// 课程没学完(不是「跳过」,是「重试」):
|
// 课程没学完(不是「跳过」,是「重试」):
|
||||||
// 同一门课最多重试 CFG.maxCourseRetries 次,退避等待后重新进这门课;
|
// 同一门课最多重试 CFG.maxCourseRetries 次,退避等待后重新进这门课;
|
||||||
// 超过次数才停止整轮刷课并明确提示——不会把这门课悄悄拉黑、换下一门。
|
// 超过次数才停止整轮刷课并明确提示——不会把这门课悄悄拉黑、换下一门。
|
||||||
|
|||||||
+2
-1
@@ -6,7 +6,6 @@ export const CFG = {
|
|||||||
startClickCooldownMs: 3000, // 「开始学习」重复点击冷却(3 秒内没起播就补点)
|
startClickCooldownMs: 3000, // 「开始学习」重复点击冷却(3 秒内没起播就补点)
|
||||||
entryGraceMs: 30000, // 进课后标题/课程 id 尚未就绪的宽限,避免慢加载被误判为「课程不一致」
|
entryGraceMs: 30000, // 进课后标题/课程 id 尚未就绪的宽限,避免慢加载被误判为「课程不一致」
|
||||||
stuckMs: 5 * 60 * 1000, // 连续多久没有计时进展就放弃当前课程
|
stuckMs: 5 * 60 * 1000, // 连续多久没有计时进展就放弃当前课程
|
||||||
maxCourses: 10, // 本次最多完成多少门;0 = 不限
|
|
||||||
maxCourseRetries: 5, // 同一门课最多重试多少次(不跳过课程,超次数就停下整轮刷课)
|
maxCourseRetries: 5, // 同一门课最多重试多少次(不跳过课程,超次数就停下整轮刷课)
|
||||||
courseRetryDelayMs: 30000, // 首次重试前的等待;之后每次翻倍,最长 5 分钟
|
courseRetryDelayMs: 30000, // 首次重试前的等待;之后每次翻倍,最长 5 分钟
|
||||||
alignToFirstIncomplete: true, // 进入课程先从「第一个未学完的课时」学起;false = 沿用平台上次位置
|
alignToFirstIncomplete: true, // 进入课程先从「第一个未学完的课时」学起;false = 沿用平台上次位置
|
||||||
@@ -29,7 +28,9 @@ export const LS_PENDING = 'yun-xue-tang-auto-start-after-login';
|
|||||||
// ---- sessionStorage:本次进度 + 本次运行状态(换标签页/重启即作废) ----
|
// ---- sessionStorage:本次进度 + 本次运行状态(换标签页/重启即作废) ----
|
||||||
export const SS_RUN_STATE = 'yun-xue-tang-run-state-v3';
|
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_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 SHORT_CATALOG_TTL = 5 * 60 * 1000;
|
||||||
|
export const POINTS_INVENTORY_TTL = 5 * 60 * 1000;
|
||||||
|
|
||||||
// 旧版本把「进度 + 运行意图」整块塞进 localStorage,只用于一次性迁移(迁移后即删除)
|
// 旧版本把「进度 + 运行意图」整块塞进 localStorage,只用于一次性迁移(迁移后即删除)
|
||||||
export const LEGACY_LS_BATCH = 'yun-xue-tang-batch-v2';
|
export const LEGACY_LS_BATCH = 'yun-xue-tang-batch-v2';
|
||||||
|
|||||||
+83
-1
@@ -1,6 +1,10 @@
|
|||||||
// ======== 课程页 ========
|
// ======== 课程页 ========
|
||||||
import { CFG, TAG } from './config.js';
|
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 {
|
||||||
|
platformMode, rememberCourseAward, noteCourseCompleted, refreshPlatformPoints,
|
||||||
|
} from './points-platform.js';
|
||||||
import { goToList, mediaPage } from './route.js';
|
import { goToList, mediaPage } from './route.js';
|
||||||
import { courseIdFromUrl, norm, textOf, truncate, findVisibleClickable } from './utils.js';
|
import { courseIdFromUrl, norm, textOf, truncate, findVisibleClickable } from './utils.js';
|
||||||
import { later } from './lifecycle.js';
|
import { later } from './lifecycle.js';
|
||||||
@@ -15,6 +19,67 @@ import {
|
|||||||
import { examTick, examPhase } from './exam.js';
|
import { examTick, examPhase } from './exam.js';
|
||||||
import { completeCurrent, failCurrent } from './complete.js';
|
import { completeCurrent, failCurrent } from './complete.js';
|
||||||
|
|
||||||
|
// ---- 每日积分:整门课完成才计 1 次 ----
|
||||||
|
// 多课时课程按「整门课」算一次任务,不按节数累计:
|
||||||
|
// 逐节只记住今天学过的类型,等整门课(含考试)完成时才计分。
|
||||||
|
// 类型在播放期间就按 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.lessonTypes[pointLessonId(key)] = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 记下「这门课今天确实学了一节」,类型留给整门课完成时计分。
|
||||||
|
// 只剩考试、今天没学内容的老课不会留下类型,因此不产出积分。
|
||||||
|
function markLessonStudied(key) {
|
||||||
|
if (!state.pointsEnabled) return '';
|
||||||
|
const id = pointLessonId(key);
|
||||||
|
const type = R.lessonTypes[id] || detectLessonType({ hash: location.hash });
|
||||||
|
if (!type) return '';
|
||||||
|
R.coursePointType = type;
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 整门课完成 → 计 1 次。同一门课当天只计一次(去重键 courseId|course)。
|
||||||
|
// 平台台账可用时以平台为准:先记下课程类型,等平台真的入账后再计入。
|
||||||
|
function recordCoursePoint() {
|
||||||
|
if (!state.pointsEnabled) return '';
|
||||||
|
const key = R.waitLessonKey || R.lastLessonKey || '';
|
||||||
|
const type = R.coursePointType || R.lessonTypes[pointLessonId(key)] || '';
|
||||||
|
if (!type) return '';
|
||||||
|
|
||||||
|
if (platformMode() === 'platform') {
|
||||||
|
const title = (S.activeCourse && S.activeCourse.title) || courseTitle() || '';
|
||||||
|
rememberCourseAward(title, type);
|
||||||
|
noteCourseCompleted();
|
||||||
|
refreshPlatformPoints(points, { force: true });
|
||||||
|
// 平台入账有延迟:完成后再补拉两次
|
||||||
|
later(function () { refreshPlatformPoints(points, { force: true }); }, 8000);
|
||||||
|
later(function () { refreshPlatformPoints(points, { force: true }); }, 25000);
|
||||||
|
setStatus('整门课完成,等待平台记账:' + pointLabel(type));
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 平台接口不可用(未登录 / 跨域):退回本地计数
|
||||||
|
if (!points.record(type, pointLessonId('course'))) return '';
|
||||||
|
const text = points.snapshot().text;
|
||||||
|
console.log(TAG, '积分 +3:' + pointLabel(type) + '(整门课完成 · ' + text + ')');
|
||||||
|
setStatus('积分 +3:' + pointLabel(type) + '(' + text + ')');
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
|
||||||
export function courseTick() {
|
export function courseTick() {
|
||||||
R.listWithCurrentSince = 0;
|
R.listWithCurrentSince = 0;
|
||||||
if (!S.activeCourse) {
|
if (!S.activeCourse) {
|
||||||
@@ -50,6 +115,13 @@ export function courseTick() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 换了一门课就清掉「今天学过什么类型」,整门课完成时只按本课的类型计分
|
||||||
|
const pointCourseKey = curId || urlId || '';
|
||||||
|
if (R.coursePointCourseId !== pointCourseKey) {
|
||||||
|
R.coursePointCourseId = pointCourseKey;
|
||||||
|
R.coursePointType = '';
|
||||||
|
}
|
||||||
|
|
||||||
if (S.coursePhase !== PHASE_LEARNING) {
|
if (S.coursePhase !== PHASE_LEARNING) {
|
||||||
S.coursePhase = PHASE_LEARNING;
|
S.coursePhase = PHASE_LEARNING;
|
||||||
saveRunState();
|
saveRunState();
|
||||||
@@ -86,6 +158,8 @@ export function courseTick() {
|
|||||||
if (!examPhase() && !isSummaryComplete() && enterPendingExamLesson()) return;
|
if (!examPhase() && !isSummaryComplete() && enterPendingExamLesson()) return;
|
||||||
|
|
||||||
// 6) 整门课程是否已完成 / 平台是否刚记录了一节
|
// 6) 整门课程是否已完成 / 平台是否刚记录了一节
|
||||||
|
// 先把当前课时的类型记下来,后面平台记账/课程完成时才知道该给哪一类计分。
|
||||||
|
rememberLessonType(readActiveLessonKey());
|
||||||
const summary = readSummary();
|
const summary = readSummary();
|
||||||
const prevSummaryX = R.lastSummary ? R.lastSummary.x : -1;
|
const prevSummaryX = R.lastSummary ? R.lastSummary.x : -1;
|
||||||
if (summary) {
|
if (summary) {
|
||||||
@@ -95,6 +169,7 @@ export function courseTick() {
|
|||||||
const confirmed = !!(R.lastSummary && R.lastSummary.complete);
|
const confirmed = !!(R.lastSummary && R.lastSummary.complete);
|
||||||
R.lastSummary = summary;
|
R.lastSummary = summary;
|
||||||
if (confirmed) {
|
if (confirmed) {
|
||||||
|
recordCoursePoint();
|
||||||
completeCurrent();
|
completeCurrent();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -108,6 +183,9 @@ export function courseTick() {
|
|||||||
const curKey = readActiveLessonKey();
|
const curKey = readActiveLessonKey();
|
||||||
R.lastSummary = summary;
|
R.lastSummary = summary;
|
||||||
|
|
||||||
|
// 平台刚记录了一节 → 只记住这一节的类型,整门课完成时才计分
|
||||||
|
if (!isMedia && summary.kind !== 'percent') markLessonStudied(prevKey);
|
||||||
|
|
||||||
// 单视频/音频页的百分比是播放进度,不是「一节学完」,不能据此切节
|
// 单视频/音频页的百分比是播放进度,不是「一节学完」,不能据此切节
|
||||||
if (!isMedia && summary.kind !== 'percent' && (!prevKey || curKey === prevKey)) {
|
if (!isMedia && summary.kind !== 'percent' && (!prevKey || curKey === prevKey)) {
|
||||||
// 平台已记账但没有自动切节 → 脚本主动切下一节
|
// 平台已记账但没有自动切节 → 脚本主动切下一节
|
||||||
@@ -209,6 +287,7 @@ export function courseTick() {
|
|||||||
}
|
}
|
||||||
R.waitStart = 0;
|
R.waitStart = 0;
|
||||||
R.lastProgressAt = Date.now();
|
R.lastProgressAt = Date.now();
|
||||||
|
recordCoursePoint();
|
||||||
completeCurrent();
|
completeCurrent();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -219,6 +298,7 @@ export function courseTick() {
|
|||||||
R.lastLessonKey = newKey;
|
R.lastLessonKey = newKey;
|
||||||
R.doneLatchKey = '';
|
R.doneLatchKey = '';
|
||||||
R.lastProgressAt = Date.now();
|
R.lastProgressAt = Date.now();
|
||||||
|
markLessonStudied(R.waitLessonKey);
|
||||||
setStatus('已自动进入下一节');
|
setStatus('已自动进入下一节');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -227,6 +307,7 @@ export function courseTick() {
|
|||||||
if (!isMedia && s2 && s2.x > R.waitSummaryX) {
|
if (!isMedia && s2 && s2.x > R.waitSummaryX) {
|
||||||
R.waitStart = 0;
|
R.waitStart = 0;
|
||||||
R.lastProgressAt = Date.now();
|
R.lastProgressAt = Date.now();
|
||||||
|
markLessonStudied(R.waitLessonKey || R.lastLessonKey);
|
||||||
if (s2.complete) {
|
if (s2.complete) {
|
||||||
completeCurrent();
|
completeCurrent();
|
||||||
} else {
|
} else {
|
||||||
@@ -304,6 +385,7 @@ export function advanceLesson() {
|
|||||||
|
|
||||||
const s = readSummary();
|
const s = readSummary();
|
||||||
if (s && s.complete) {
|
if (s && s.complete) {
|
||||||
|
recordCoursePoint();
|
||||||
completeCurrent();
|
completeCurrent();
|
||||||
} else {
|
} else {
|
||||||
setStatus('没有找到下一节,等待课程完成…');
|
setStatus('没有找到下一节,等待课程完成…');
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
// ======== 考试结果页的处置决策(纯函数,便于单测) ========
|
||||||
|
//
|
||||||
|
// 交卷后平台会把课程恢复到「考试结果页」。重进课程时也会看到这一页,
|
||||||
|
// 但那次并不是本页刚交的卷 —— 以前把它当成一次空卷交卷,导致:
|
||||||
|
// · examEmptySubmits 虚增,maxExamTries 形同虚设(上限在结果分支之后才检查);
|
||||||
|
// · 结果页 → 回课程页 → 又被恢复到结果页,同一页反复「交卷」,进度永远不动。
|
||||||
|
//
|
||||||
|
// 只有本页确实点过「提交考试 / 确定交卷」,结果页才算一次真实交卷。
|
||||||
|
// 否则先回到考试说明页重新进入考试;回不去才跳过这门课,等人工处理。
|
||||||
|
export function planExamResult(ctx) {
|
||||||
|
const submitted = !!(ctx && ctx.submitted);
|
||||||
|
const complete = !!(ctx && ctx.complete);
|
||||||
|
|
||||||
|
if (submitted) return complete ? 'complete' : 'count';
|
||||||
|
// 没交卷但平台已算完成:不重进考试,直接收课
|
||||||
|
if (complete) return 'complete';
|
||||||
|
if ((Number(ctx && ctx.staleTries) || 0) >= 2) return 'skip';
|
||||||
|
return 'reback';
|
||||||
|
}
|
||||||
+79
-17
@@ -8,11 +8,12 @@ import { R, S, saveRunState } from './state.js';
|
|||||||
import { textOf, isVisible, courseIdFromUrl } from './utils.js';
|
import { textOf, isVisible, courseIdFromUrl } from './utils.js';
|
||||||
import { later } from './lifecycle.js';
|
import { later } from './lifecycle.js';
|
||||||
import { setStatus } from './panel.js';
|
import { setStatus } from './panel.js';
|
||||||
import { failCurrent, completeCurrent } from './complete.js';
|
import { failCurrent, completeCurrent, skipCurrent } from './complete.js';
|
||||||
import { readSummary } from './player.js';
|
import { readSummary } from './player.js';
|
||||||
|
import { planExamResult } from './exam-plan.js';
|
||||||
|
|
||||||
// 只认「考试」相关文案:答题/测验/问卷仍按「需要人工处理」跳过
|
// 只认「考试」相关文案:答题/测验/问卷仍按「需要人工处理」跳过
|
||||||
const START_RE = /^(开始考试|继续考试|进入考试)$/;
|
const START_RE = /^(开始考试|继续考试|重新考试|进入考试)$/;
|
||||||
const SUBMIT_RE = /^(提交考试|提交试卷|交卷|交卷并退出)$/;
|
const SUBMIT_RE = /^(提交考试|提交试卷|交卷|交卷并退出)$/;
|
||||||
// 「交卷」类文案里只有考试独有的几个能用来判定「当前是考试答卷页」;
|
// 「交卷」类文案里只有考试独有的几个能用来判定「当前是考试答卷页」;
|
||||||
// 「提交试卷」同样会出现在答题/测验页上,不能拿来当考试标志(否则会误抢答题页)。
|
// 「提交试卷」同样会出现在答题/测验页上,不能拿来当考试标志(否则会误抢答题页)。
|
||||||
@@ -122,12 +123,13 @@ function confirmState() {
|
|||||||
|
|
||||||
// 手动刷课(自己点开的课)里出错不应该动队列,只停下并提示;
|
// 手动刷课(自己点开的课)里出错不应该动队列,只停下并提示;
|
||||||
// 批量刷课走 failCurrent(重试退避,超过次数才停止整轮)。
|
// 批量刷课走 failCurrent(重试退避,超过次数才停止整轮)。
|
||||||
function examAbort(reason, manual) {
|
// skip=true:重试也不会好的确定性失败(考试交不了),本轮跳过这门课继续下一门。
|
||||||
|
function examAbort(reason, manual, skip) {
|
||||||
if (manual) {
|
if (manual) {
|
||||||
setStatus('考试:' + reason);
|
setStatus('考试:' + reason);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
failCurrent(reason);
|
if (skip) skipCurrent(reason); else failCurrent(reason);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,6 +161,9 @@ export function backToCourse() {
|
|||||||
R.lastCountdown = null;
|
R.lastCountdown = null;
|
||||||
R.lastSummary = null;
|
R.lastSummary = null;
|
||||||
R.examLeaving = false;
|
R.examLeaving = false;
|
||||||
|
// 离开考试页后,再看到的结果页(平台恢复的)就不能再算一次交卷
|
||||||
|
R.examSubmitted = false;
|
||||||
|
R.examPreviewAt = 0;
|
||||||
try {
|
try {
|
||||||
const cur = location.href;
|
const cur = location.href;
|
||||||
if (!target || cur === target) {
|
if (!target || cur === target) {
|
||||||
@@ -175,8 +180,53 @@ export function backToCourse() {
|
|||||||
} catch (e) { /* ignore */ }
|
} catch (e) { /* ignore */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
function finishExam() {
|
// 结果页其实是平台恢复的旧结果(本页没交过卷):回考试说明页重新进入考试。
|
||||||
|
// 交卷后课程页会被恢复到考试结果页,若直接回课程页只会再次看到同一页,
|
||||||
|
// 于是「交卷 → 回课程 → 又是结果页」无限循环,课程进度却不动。
|
||||||
|
function backToPreview() {
|
||||||
|
R.examLeaving = false;
|
||||||
|
const btn = findClickableByText(/^返回考试说明页$/);
|
||||||
|
if (btn) {
|
||||||
|
setStatus('考试:返回考试说明页,重新进入考试…');
|
||||||
|
examClick(btn);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 说明页按钮也找不到:只能退回课程页重进考试节;
|
||||||
|
// 平台若又把我们恢复到结果页,examStaleResults 会累加,最终跳过这门课。
|
||||||
|
backToCourse();
|
||||||
|
}
|
||||||
|
|
||||||
|
function finishExam(manual) {
|
||||||
if (R.examLeaving) return;
|
if (R.examLeaving) return;
|
||||||
|
|
||||||
|
const s = readSummary();
|
||||||
|
const plan = planExamResult({
|
||||||
|
submitted: R.examSubmitted,
|
||||||
|
complete: !!(s && s.complete),
|
||||||
|
staleTries: R.examStaleResults,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (plan === 'complete') {
|
||||||
|
R.examLeaving = true;
|
||||||
|
setStatus('考试已交卷(未答题),课程已完成');
|
||||||
|
later(completeCurrent, 1500);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (plan === 'reback') {
|
||||||
|
R.examLeaving = true;
|
||||||
|
R.examStaleResults++;
|
||||||
|
console.log(TAG, '考试结果页不是本页交的卷(平台恢复的旧结果),返回说明页重新进入考试');
|
||||||
|
setStatus('考试结果为上次残留,返回考试说明页重新进入…');
|
||||||
|
later(backToPreview, 1500);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (plan === 'skip') {
|
||||||
|
return examAbort('考试结果页反复出现,无法重新进入考试,需手动处理', manual, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// plan === 'count':本页确实点了「提交考试/确定交卷」
|
||||||
R.examLeaving = true;
|
R.examLeaving = true;
|
||||||
const key = examCourseKey();
|
const key = examCourseKey();
|
||||||
if (!S.examEmptySubmits) S.examEmptySubmits = {};
|
if (!S.examEmptySubmits) S.examEmptySubmits = {};
|
||||||
@@ -185,16 +235,8 @@ function finishExam() {
|
|||||||
const times = S.examEmptySubmits[key];
|
const times = S.examEmptySubmits[key];
|
||||||
console.log(TAG, '考试已空卷交卷(第', times, '次),返回课程页继续学习');
|
console.log(TAG, '考试已空卷交卷(第', times, '次),返回课程页继续学习');
|
||||||
|
|
||||||
// 交卷后平台会立刻更新课程汇总;已经「已完成学习」就直接判这门课完成,不必再跳一轮
|
|
||||||
const s = readSummary();
|
|
||||||
if (s && s.complete) {
|
|
||||||
setStatus('考试已交卷(未答题),课程已完成');
|
|
||||||
later(completeCurrent, 1500);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (times >= Math.max(1, CFG.maxExamTries)) {
|
if (times >= Math.max(1, CFG.maxExamTries)) {
|
||||||
examAbort('已空卷交卷 ' + times + ' 次,仍未计入课程进度,请手动处理', false);
|
examAbort('已空卷交卷 ' + times + ' 次,仍未计入课程进度,需手动处理', manual, true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -216,6 +258,7 @@ export function examTick(manual) {
|
|||||||
R.examConfirms = 0;
|
R.examConfirms = 0;
|
||||||
R.examStarts = 0;
|
R.examStarts = 0;
|
||||||
R.examActionAt = 0;
|
R.examActionAt = 0;
|
||||||
|
R.examPreviewAt = 0;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -228,6 +271,10 @@ export function examTick(manual) {
|
|||||||
R.examConfirms = 0;
|
R.examConfirms = 0;
|
||||||
R.examStarts = 0;
|
R.examStarts = 0;
|
||||||
R.examPaperAt = 0;
|
R.examPaperAt = 0;
|
||||||
|
// 新一次考试从说明页/答卷页开始时,之前的「已交卷」标记作废;
|
||||||
|
// 进入结果页时必须保留——那是本页刚交卷产生的
|
||||||
|
if (phase === 'preview' || phase === 'paper') R.examSubmitted = false;
|
||||||
|
R.examPreviewAt = phase === 'preview' ? now : 0;
|
||||||
if (phase === 'preview') {
|
if (phase === 'preview') {
|
||||||
console.log(TAG, '检测到考试章节:进入考试后不答题,直接交卷');
|
console.log(TAG, '检测到考试章节:进入考试后不答题,直接交卷');
|
||||||
setStatus('检测到考试:进入考试后直接交卷…');
|
setStatus('检测到考试:进入考试后直接交卷…');
|
||||||
@@ -235,14 +282,15 @@ export function examTick(manual) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (phase === 'result') {
|
if (phase === 'result') {
|
||||||
finishExam();
|
finishExam(manual);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 同一门课空卷交卷次数上限:平台没记账时避免「进考试→交卷→再进考试」死循环
|
// 同一门课空卷交卷次数上限:平台没记账时避免「进考试→交卷→再进考试」死循环。
|
||||||
|
// 到上限就跳过这门课,继续下一门——再退避重试也只会重复同一份考卷。
|
||||||
const key = examCourseKey();
|
const key = examCourseKey();
|
||||||
if (examTriedTimes(key) >= Math.max(1, CFG.maxExamTries)) {
|
if (examTriedTimes(key) >= Math.max(1, CFG.maxExamTries)) {
|
||||||
return examAbort('已空卷交卷 ' + examTriedTimes(key) + ' 次,仍未计入课程进度,请手动处理', manual);
|
return examAbort('已空卷交卷 ' + examTriedTimes(key) + ' 次,仍未计入课程进度,需手动处理', manual, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (now - R.examActionAt < CFG.examClickCooldownMs) return true;
|
if (now - R.examActionAt < CFG.examClickCooldownMs) return true;
|
||||||
@@ -251,9 +299,14 @@ export function examTick(manual) {
|
|||||||
const root = examPreviewRoot();
|
const root = examPreviewRoot();
|
||||||
const btn = findClickableByText(START_RE, root) || findClickableByText(START_RE);
|
const btn = findClickableByText(START_RE, root) || findClickableByText(START_RE);
|
||||||
if (!btn) {
|
if (!btn) {
|
||||||
|
// 说明页可能永远不给「开始考试」(考试已用完次数/需人工),不能无限等
|
||||||
|
if (now - R.examPreviewAt > 30000) {
|
||||||
|
return examAbort('考试说明页没有「开始考试」按钮,需手动处理', manual, true);
|
||||||
|
}
|
||||||
setStatus('考试:未找到「开始考试」按钮,等待页面渲染…');
|
setStatus('考试:未找到「开始考试」按钮,等待页面渲染…');
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
R.examPreviewAt = 0;
|
||||||
R.examActionAt = now;
|
R.examActionAt = now;
|
||||||
R.examStarts++;
|
R.examStarts++;
|
||||||
if (R.examStarts > Math.max(3, CFG.maxExamTries + 3)) {
|
if (R.examStarts > Math.max(3, CFG.maxExamTries + 3)) {
|
||||||
@@ -273,6 +326,9 @@ export function examTick(manual) {
|
|||||||
const cs = confirmState();
|
const cs = confirmState();
|
||||||
if (cs.shown) {
|
if (cs.shown) {
|
||||||
if (!cs.btn) {
|
if (!cs.btn) {
|
||||||
|
if (now - R.examPaperAt > 30000) {
|
||||||
|
return examAbort('交卷确认框里没有「确定」按钮', manual);
|
||||||
|
}
|
||||||
setStatus('考试:交卷确认框里没找到「确定」按钮');
|
setStatus('考试:交卷确认框里没找到「确定」按钮');
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -281,6 +337,8 @@ export function examTick(manual) {
|
|||||||
if (R.examConfirms > 6) {
|
if (R.examConfirms > 6) {
|
||||||
return examAbort('交卷确认框点了多次仍未交卷', manual);
|
return examAbort('交卷确认框点了多次仍未交卷', manual);
|
||||||
}
|
}
|
||||||
|
// 只有真的点了交卷,之后看到的结果页才算一次空卷交卷
|
||||||
|
R.examSubmitted = true;
|
||||||
setStatus('考试:不答题,确认交卷…');
|
setStatus('考试:不答题,确认交卷…');
|
||||||
examClick(cs.btn);
|
examClick(cs.btn);
|
||||||
return true;
|
return true;
|
||||||
@@ -288,6 +346,9 @@ export function examTick(manual) {
|
|||||||
|
|
||||||
const sub = findClickableByText(SUBMIT_RE);
|
const sub = findClickableByText(SUBMIT_RE);
|
||||||
if (!sub) {
|
if (!sub) {
|
||||||
|
if (now - R.examPaperAt > 30000) {
|
||||||
|
return examAbort('答卷页没有「提交考试」按钮', manual);
|
||||||
|
}
|
||||||
setStatus('考试:等待「提交考试」按钮…');
|
setStatus('考试:等待「提交考试」按钮…');
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -296,6 +357,7 @@ export function examTick(manual) {
|
|||||||
}
|
}
|
||||||
R.examActionAt = now;
|
R.examActionAt = now;
|
||||||
R.examSubmits++;
|
R.examSubmits++;
|
||||||
|
R.examSubmitted = true;
|
||||||
setStatus('考试:不答题,直接交卷…');
|
setStatus('考试:不答题,直接交卷…');
|
||||||
examClick(sub);
|
examClick(sub);
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
+11
-5
@@ -1,7 +1,7 @@
|
|||||||
// ======== 主循环 ========
|
// ======== 主循环 ========
|
||||||
'use strict';
|
'use strict';
|
||||||
import { CFG, VERSION, TAG } from './config.js';
|
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 { every, later, onWindow } from './lifecycle.js';
|
||||||
import { courseIdFromUrl } from './utils.js';
|
import { courseIdFromUrl } from './utils.js';
|
||||||
import { route, mediaPage } from './route.js';
|
import { route, mediaPage } from './route.js';
|
||||||
@@ -12,13 +12,15 @@ import {
|
|||||||
chooseShortCourse, sortCardsByDuration, formatDuration,
|
chooseShortCourse, sortCardsByDuration, formatDuration,
|
||||||
pendingShortItems, scanCards, currentPage, maxPageNumber,
|
pendingShortItems, scanCards, currentPage, maxPageNumber,
|
||||||
startCourse, jumpToPage, nextPage,
|
startCourse, jumpToPage, nextPage,
|
||||||
|
ensurePointsInventory, pointsAvailability, pointsDone, pointsTarget, startStandalone,
|
||||||
} from './list.js';
|
} from './list.js';
|
||||||
import { courseTick, manualCourseTick } from './course.js';
|
import { courseTick, manualCourseTick } from './course.js';
|
||||||
import {
|
import {
|
||||||
stopBatch, retryCount, retryWaiting, retryWaitSeconds,
|
stopBatch, retryCount, retryWaiting, retryWaitSeconds,
|
||||||
completeCurrent, failCurrent,
|
completeCurrent, failCurrent, skipCurrent, courseSkipped,
|
||||||
} from './complete.js';
|
} from './complete.js';
|
||||||
import { examTick, examPhase } from './exam.js';
|
import { examTick, examPhase } from './exam.js';
|
||||||
|
import { refreshPlatformPoints, cachedPlatformPoints } from './points-platform.js';
|
||||||
import {
|
import {
|
||||||
hookAllVideos, readSummary, readCountdown, lessonItems,
|
hookAllVideos, readSummary, readCountdown, lessonItems,
|
||||||
findNextLessonElement, clickLesson, alignToFirstIncomplete,
|
findNextLessonElement, clickLesson, alignToFirstIncomplete,
|
||||||
@@ -76,8 +78,10 @@ if (window.top !== window.self) {
|
|||||||
try {
|
try {
|
||||||
Object.defineProperty(window, '__yunXueTangAuto', {
|
Object.defineProperty(window, '__yunXueTangAuto', {
|
||||||
value: {
|
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 覆盖本次运行的门数上限
|
// 平台积分台账:调试时可手动刷新(见 dev/tests/points-api-probe.mjs)
|
||||||
|
refreshPlatformPoints, cachedPlatformPoints,
|
||||||
|
// CFG 暴露给无头运行器:脚本内可调参数(重试次数、冷却等)
|
||||||
CFG,
|
CFG,
|
||||||
mediaPage, courseIdFromUrl,
|
mediaPage, courseIdFromUrl,
|
||||||
readCountdown, readSummary,
|
readCountdown, readSummary,
|
||||||
@@ -95,9 +99,11 @@ try {
|
|||||||
sortCardsByDuration, formatDuration,
|
sortCardsByDuration, formatDuration,
|
||||||
pendingShortItems, invalidateShortCatalog,
|
pendingShortItems, invalidateShortCatalog,
|
||||||
retryCount, retryWaiting, retryWaitSeconds,
|
retryCount, retryWaiting, retryWaitSeconds,
|
||||||
completeCurrent, failCurrent,
|
completeCurrent, failCurrent, skipCurrent, courseSkipped,
|
||||||
// 以下供开发/真机测试驱动内部路径使用:
|
// 以下供开发/真机测试驱动内部路径使用:
|
||||||
scanCards, currentPage, maxPageNumber, startCourse, jumpToPage, nextPage,
|
scanCards, currentPage, maxPageNumber, startCourse, jumpToPage, nextPage,
|
||||||
|
ensurePointsInventory, pointsAvailability, pointsDone, pointsTarget,
|
||||||
|
startStandalone,
|
||||||
listTick, courseTick, manualCourseTick,
|
listTick, courseTick, manualCourseTick,
|
||||||
loginFields, findLoginVm, checkLoginAgreement, setNativeValue,
|
loginFields, findLoginVm, checkLoginAgreement, setNativeValue,
|
||||||
saveCreds, loadCreds, clearSavedCreds,
|
saveCreds, loadCreds, clearSavedCreds,
|
||||||
|
|||||||
+259
-8
@@ -1,13 +1,17 @@
|
|||||||
// ======== 列表页 ========
|
// ======== 列表页 ========
|
||||||
import { SHORT_CATALOG_TTL, SS_SHORT_CATALOG, TAG } from './config.js';
|
|
||||||
import {
|
import {
|
||||||
R, S, state, saveRunState, setTargetCatalogUrl, resetCourseRuntime, invalidateShortCatalog,
|
SHORT_CATALOG_TTL, SS_SHORT_CATALOG, SS_POINTS_INVENTORY, POINTS_INVENTORY_TTL, TAG,
|
||||||
PHASE_ENTERING, PHASE_LEARNING, PHASE_IDLE,
|
} from './config.js';
|
||||||
|
import {
|
||||||
|
R, S, state, points, saveRunState, setTargetCatalogUrl, resetCourseRuntime,
|
||||||
|
invalidateShortCatalog, PHASE_ENTERING, PHASE_LEARNING, PHASE_IDLE,
|
||||||
} from './state.js';
|
} from './state.js';
|
||||||
|
import { apiTypeKey, detectLessonType, nextTarget, pointLabel, POINT_RULES } from './points.js';
|
||||||
|
import { cachedPlatformPoints, platformNoAward, refreshPlatformPoints } from './points-platform.js';
|
||||||
import { norm, textOf, truncate } from './utils.js';
|
import { norm, textOf, truncate } from './utils.js';
|
||||||
import { clickNode } from './player.js';
|
import { clickNode } from './player.js';
|
||||||
import { setStatus, updatePanel } from './panel.js';
|
import { setStatus, updatePanel } from './panel.js';
|
||||||
import { failCurrent, stopBatch } from './complete.js';
|
import { failCurrent, stopBatch, courseSkipped } from './complete.js';
|
||||||
import { retryWaiting, retryWaitSeconds } from './complete.js';
|
import { retryWaiting, retryWaitSeconds } from './complete.js';
|
||||||
|
|
||||||
export function scanCards() {
|
export function scanCards() {
|
||||||
@@ -352,13 +356,226 @@ 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;
|
||||||
|
// 平台台账说今天的学习积分已经到上限 → 以平台为准直接收尾
|
||||||
|
const p = cachedPlatformPoints();
|
||||||
|
if (p && p.ok && p.maxPoints > 0 && p.todayPoints >= p.maxPoints) return true;
|
||||||
|
return points.done(pointsAvailability());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pointsTarget() {
|
||||||
|
return nextTarget({
|
||||||
|
isFull: function (key) { return points.isFull(key); },
|
||||||
|
available: pointsAvailability(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// 进入单条文档/音频/微课:直接按 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() {
|
export function pendingShortItems() {
|
||||||
const cat = R.shortCatalog;
|
const cat = R.shortCatalog;
|
||||||
if (!cat) return [];
|
if (!cat) return [];
|
||||||
return cat.items.filter(function (item) {
|
return cat.items.filter(function (item) {
|
||||||
if (!item || !item.title) return false;
|
if (!item || !item.title) return false;
|
||||||
// 只排除「本轮已完成」;不再排除任何「失败/跳过」——没过就是重试,不是拉黑
|
// 只排除「本轮已完成」与「本轮已跳过(考试交不了)」;其它失败一律重试,不拉黑
|
||||||
if (S.completedTitles[item.title]) return false;
|
if (S.completedTitles[item.title] || courseSkipped(item.title)) return false;
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -450,7 +667,8 @@ export function chooseShortCourse(cards, pending) {
|
|||||||
} else {
|
} else {
|
||||||
const card = cardForShortItem(cards, target);
|
const card = cardForShortItem(cards, target);
|
||||||
if (card) {
|
if (card) {
|
||||||
if (card.status === '已学完' || S.completedTitles[card.title]) {
|
if (card.status === '已学完' || S.completedTitles[card.title] ||
|
||||||
|
courseSkipped(card.title)) {
|
||||||
// 缓存与实际状态不一致:剔除这一门,下一 tick 继续挑下一门
|
// 缓存与实际状态不一致:剔除这一门,下一 tick 继续挑下一门
|
||||||
forgetShortCourse(card.title);
|
forgetShortCourse(card.title);
|
||||||
return { wait: true };
|
return { wait: true };
|
||||||
@@ -604,10 +822,43 @@ export function listTick() {
|
|||||||
}
|
}
|
||||||
R.retryStatusSec = -1;
|
R.retryStatusSec = -1;
|
||||||
|
|
||||||
|
// 每日积分模式:先补文档/音频/微课的单条内容;视频额度靠课程里的视频课时。
|
||||||
|
// 四类都满额(或剩余类型确认没内容)就收尾,不再无意义地刷课。
|
||||||
|
if (state.pointsEnabled) {
|
||||||
|
// 每次到列表页都顺带刷新平台台账(内部有 20 秒缓存,不会刷爆接口)
|
||||||
|
refreshPlatformPoints(points);
|
||||||
|
const invStatus = ensurePointsInventory();
|
||||||
|
if (invStatus === 'loading') return;
|
||||||
|
if (platformNoAward()) {
|
||||||
|
stopBatch('平台连续 3 门课未入账,判定今日积分已满或没有可计分内容');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (pointsDone()) {
|
||||||
|
// 台账明细由面板和收尾通知单独展示,状态栏只留结论,避免同一段文字出现两遍
|
||||||
|
console.log(TAG, '今日积分:平台台账已达上限或可用内容已学完', points.summary());
|
||||||
|
stopBatch('可用内容已学完');
|
||||||
|
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) => {
|
const pending = cards.filter((c) => {
|
||||||
if (!c.title) return false;
|
if (!c.title) return false;
|
||||||
if (/已学完|已完成|已学习/.test(c.status)) return false;
|
if (/已学完|已完成|已学习/.test(c.status)) return false;
|
||||||
if (S.completedTitles[c.title]) return false;
|
if (S.completedTitles[c.title] || courseSkipped(c.title)) return false;
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -139,6 +139,7 @@ export function clearSavedCreds() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function startBatch() {
|
export function startBatch() {
|
||||||
|
const freshStart = !S.batchRunning;
|
||||||
if (S.batchFinished) {
|
if (S.batchFinished) {
|
||||||
S.completedThisRun = 0;
|
S.completedThisRun = 0;
|
||||||
S.batchFinished = false;
|
S.batchFinished = false;
|
||||||
@@ -147,6 +148,13 @@ export function startBatch() {
|
|||||||
R.retryWaitUntil = 0;
|
R.retryWaitUntil = 0;
|
||||||
R.retryTitle = '';
|
R.retryTitle = '';
|
||||||
}
|
}
|
||||||
|
if (freshStart) {
|
||||||
|
// 新一轮(含重启后重新开跑):考试相关的本轮记录也清零。
|
||||||
|
// 否则上次会话里的「已跳过 / 已交卷 N 次」会让这门课开跑就被跳过,
|
||||||
|
// 人工处理过考试也得不到重新尝试的机会。
|
||||||
|
S.skippedCourses = {};
|
||||||
|
S.examEmptySubmits = {};
|
||||||
|
}
|
||||||
S.batchRunning = true;
|
S.batchRunning = true;
|
||||||
// 开跑时丢掉旧的时长队列:第一门课也要按平台实时状态挑
|
// 开跑时丢掉旧的时长队列:第一门课也要按平台实时状态挑
|
||||||
invalidateShortCatalog();
|
invalidateShortCatalog();
|
||||||
|
|||||||
+7
-4
@@ -2,7 +2,7 @@
|
|||||||
// @name 云学堂助手
|
// @name 云学堂助手
|
||||||
// @namespace yun-xue-tang-assistant.local
|
// @namespace yun-xue-tang-assistant.local
|
||||||
// @version __YUN_XUE_TANG_VERSION__
|
// @version __YUN_XUE_TANG_VERSION__
|
||||||
// @description 云学堂助手:自动登录、从第一节顺序听课、自动切节、处理防挂机验证,并在课程列表页逐门自动刷课(单视频/音频课程也支持,含考试章节的课自动空卷交卷,学完自动进入下一门,可优先短课程;不跳过任何课程)
|
// @description 云学堂助手:自动登录、从第一节顺序听课、自动切节、处理防挂机验证,并在课程列表页逐门自动刷课(单视频/音频课程也支持,含考试章节的课自动空卷交卷,学完自动进入下一门,可优先短课程)
|
||||||
// @match *://kfmic.yunxuetang.cn/*
|
// @match *://kfmic.yunxuetang.cn/*
|
||||||
// @match *://*.yunxuetang.cn/*
|
// @match *://*.yunxuetang.cn/*
|
||||||
// @grant none
|
// @grant none
|
||||||
@@ -29,8 +29,8 @@
|
|||||||
* - 进入课程(列表刷课或自己点开)都会先对齐到「第一个未学完的课时」,即从第一章第一节起
|
* - 进入课程(列表刷课或自己点开)都会先对齐到「第一个未学完的课时」,即从第一章第一节起
|
||||||
* 顺序学习,不沿用平台上次停留的位置(否则前面的课时会被跳过,整门课永远学不完)。
|
* 顺序学习,不沿用平台上次停留的位置(否则前面的课时会被跳过,整门课永远学不完)。
|
||||||
* 切换成功与否以目录高亮为准:没切过去会重试并如实提示「未能切换」,不会假装已切换。
|
* 切换成功与否以目录高亮为准:没切过去会重试并如实提示「未能切换」,不会假装已切换。
|
||||||
* - 试跑稳定后,把 config.js 里的 CFG.maxCourses 改成 0 即可不限门数(会持续很久)。
|
* - 不按门数设上限:每日积分模式下整门课完成计 1 次,积分目标完成或没有可学内容时收尾。
|
||||||
* - 脚本不跳过任何课程:没有「跳过本课」,也不会把课程拉黑。某门课没学完(例如遇到
|
* - 脚本不跳过普通课程:没有「跳过本课」,也不会把课程拉黑。某门课没学完(例如遇到
|
||||||
* 需要人工完成的滑块/拼图验证、答题/测验章节、长时间无计时进展)就退避重试:
|
* 需要人工完成的滑块/拼图验证、答题/测验章节、长时间无计时进展)就退避重试:
|
||||||
* 30 秒起每次翻倍、最长 5 分钟,同一门课最多重试 CFG.maxCourseRetries 次,
|
* 30 秒起每次翻倍、最长 5 分钟,同一门课最多重试 CFG.maxCourseRetries 次,
|
||||||
* 超过才停下整轮刷课并在面板写明原因,等人工处理后点「一键刷课」接着跑。
|
* 超过才停下整轮刷课并在面板写明原因,等人工处理后点「一键刷课」接着跑。
|
||||||
@@ -39,7 +39,10 @@
|
|||||||
* - 防挂机验证(每 10 分钟一次、120 秒限时)会自动点「继续学习」。
|
* - 防挂机验证(每 10 分钟一次、120 秒限时)会自动点「继续学习」。
|
||||||
* - 考试章节支持:自动进入考试、不答题直接交卷(空白交卷)。交卷后平台会把考试节点
|
* - 考试章节支持:自动进入考试、不答题直接交卷(空白交卷)。交卷后平台会把考试节点
|
||||||
* 计入课程进度,含考试章节的课程也能学完。
|
* 计入课程进度,含考试章节的课程也能学完。
|
||||||
* 同一门课最多交卷 CFG.maxExamTries 次,超过仍没计入进度就按普通未完成退避重试。
|
* 只有本页真的点过「提交考试/确定交卷」,看到的结果页才算一次交卷;平台恢复的旧
|
||||||
|
* 结果页会先回考试说明页重新进入,避免在结果页和课程页之间空转。
|
||||||
|
* 同一门课最多交卷 CFG.maxExamTries 次,超过仍没计入进度、或考试页没有可点的
|
||||||
|
* 「开始考试/提交考试」时,本轮跳过这门课继续下一门(会写明原因),不再反复重进。
|
||||||
* - 验证码/滑块需要手动完成,脚本不会绕过。
|
* - 验证码/滑块需要手动完成,脚本不会绕过。
|
||||||
* - 课程/单位如有相关规定,请自行确认风险。
|
* - 课程/单位如有相关规定,请自行确认风险。
|
||||||
*
|
*
|
||||||
|
|||||||
+48
-4
@@ -1,6 +1,8 @@
|
|||||||
// ======== 面板 ========
|
// ======== 面板 ========
|
||||||
import { CFG, VERSION, LS_ENABLED, LS_PREFER_SHORT, SS_SHORT_CATALOG, PANEL_ID, TAG } from './config.js';
|
import { 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 { cachedPlatformPoints } from './points-platform.js';
|
||||||
import { route } from './route.js';
|
import { route } from './route.js';
|
||||||
import { isLoginPage, startBatch, doLoginAndStart, clearSavedCreds } from './login.js';
|
import { isLoginPage, startBatch, doLoginAndStart, clearSavedCreds } from './login.js';
|
||||||
|
|
||||||
@@ -14,6 +16,9 @@ let labelAuto = null;
|
|||||||
let labelBatch = null;
|
let labelBatch = null;
|
||||||
let labelShort = null;
|
let labelShort = null;
|
||||||
let cbPreferShort = null;
|
let cbPreferShort = null;
|
||||||
|
let labelPoints = null;
|
||||||
|
let cbPoints = null;
|
||||||
|
let pointsEl = null;
|
||||||
let cbAuto = null;
|
let cbAuto = null;
|
||||||
let loginBox = null;
|
let loginBox = null;
|
||||||
export let loginUserEl = null;
|
export let loginUserEl = null;
|
||||||
@@ -40,11 +45,16 @@ export function setStatus(text) {
|
|||||||
if (statusEl) statusEl.textContent = text;
|
if (statusEl) statusEl.textContent = text;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 面板上再带一份平台台账的真实今日积分,避免本地未归类的记录让数字偏小
|
||||||
|
function platformSuffix() {
|
||||||
|
const p = cachedPlatformPoints();
|
||||||
|
return p && p.ok ? ' · 平台 ' + p.todayPoints + '/' + p.maxPoints : '';
|
||||||
|
}
|
||||||
|
|
||||||
export function updatePanel() {
|
export function updatePanel() {
|
||||||
if (cbBatch) cbBatch.checked = S.batchRunning;
|
if (cbBatch) cbBatch.checked = S.batchRunning;
|
||||||
if (statsEl) {
|
if (statsEl) {
|
||||||
const limit = CFG.maxCourses > 0 ? CFG.maxCourses : '∞';
|
let text = '本次 ' + S.completedThisRun;
|
||||||
let text = '本次 ' + S.completedThisRun + '/' + limit;
|
|
||||||
const retryTitles = Object.keys(S.courseRetries || {}).length;
|
const retryTitles = Object.keys(S.courseRetries || {}).length;
|
||||||
if (retryTitles) text += ' · 待重试 ' + retryTitles;
|
if (retryTitles) text += ' · 待重试 ' + retryTitles;
|
||||||
if (R.retryWaitUntil && Date.now() < R.retryWaitUntil) {
|
if (R.retryWaitUntil && Date.now() < R.retryWaitUntil) {
|
||||||
@@ -58,13 +68,20 @@ export function updatePanel() {
|
|||||||
}
|
}
|
||||||
if (cbAuto) cbAuto.checked = state.autoPlayEnabled;
|
if (cbAuto) cbAuto.checked = state.autoPlayEnabled;
|
||||||
if (cbPreferShort) cbPreferShort.checked = state.preferShortCourses;
|
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() + platformSuffix() : '';
|
||||||
|
}
|
||||||
|
|
||||||
const onLogin = isLoginPage();
|
const onLogin = isLoginPage();
|
||||||
if (loginBox) loginBox.style.display = onLogin ? 'block' : 'none';
|
if (loginBox) loginBox.style.display = onLogin ? 'block' : 'none';
|
||||||
if (labelAuto) labelAuto.style.display = onLogin ? 'none' : 'flex';
|
if (labelAuto) labelAuto.style.display = onLogin ? 'none' : 'flex';
|
||||||
if (labelBatch) labelBatch.style.display = onLogin ? 'none' : 'flex';
|
if (labelBatch) labelBatch.style.display = onLogin ? 'none' : 'flex';
|
||||||
if (labelShort) labelShort.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 (statsEl) statsEl.style.display = onLogin ? 'none' : 'block';
|
||||||
|
if (pointsEl) pointsEl.style.display = onLogin ? 'none' : (state.pointsEnabled ? 'block' : 'none');
|
||||||
if (btnOne) {
|
if (btnOne) {
|
||||||
// 「停止刷课」只在播放页出现;列表页等位置始终显示「一键刷课」
|
// 「停止刷课」只在播放页出现;列表页等位置始终显示「一键刷课」
|
||||||
const onCourse = route() === 'course' && !!S.activeCourse;
|
const onCourse = route() === 'course' && !!S.activeCourse;
|
||||||
@@ -255,6 +272,27 @@ export function buildPanel() {
|
|||||||
labelShort.appendChild(cbPreferShort);
|
labelShort.appendChild(cbPreferShort);
|
||||||
labelShort.appendChild(document.createTextNode('优先短课程(时长正序)'));
|
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 次:文档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 = document.createElement('div');
|
||||||
statusEl.id = 'yun-xue-tang-status';
|
statusEl.id = 'yun-xue-tang-status';
|
||||||
statusEl.textContent = '待机';
|
statusEl.textContent = '待机';
|
||||||
@@ -264,6 +302,10 @@ export function buildPanel() {
|
|||||||
statsEl.id = 'yun-xue-tang-stats';
|
statsEl.id = 'yun-xue-tang-stats';
|
||||||
statsEl.style.cssText = 'margin-top:2px;color:#aaa;';
|
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');
|
const hint = document.createElement('div');
|
||||||
hint.textContent = '真实播放计时 · 保持窗口可见';
|
hint.textContent = '真实播放计时 · 保持窗口可见';
|
||||||
hint.style.cssText = 'margin-top:6px;color:#777;font-size:11px;';
|
hint.style.cssText = 'margin-top:6px;color:#777;font-size:11px;';
|
||||||
@@ -280,8 +322,10 @@ export function buildPanel() {
|
|||||||
box.appendChild(labelAuto);
|
box.appendChild(labelAuto);
|
||||||
box.appendChild(labelBatch);
|
box.appendChild(labelBatch);
|
||||||
box.appendChild(labelShort);
|
box.appendChild(labelShort);
|
||||||
|
box.appendChild(labelPoints);
|
||||||
box.appendChild(statusEl);
|
box.appendChild(statusEl);
|
||||||
box.appendChild(statsEl);
|
box.appendChild(statsEl);
|
||||||
|
box.appendChild(pointsEl);
|
||||||
box.appendChild(hint);
|
box.appendChild(hint);
|
||||||
box.appendChild(footer);
|
box.appendChild(footer);
|
||||||
document.documentElement.appendChild(box);
|
document.documentElement.appendChild(box);
|
||||||
|
|||||||
@@ -0,0 +1,255 @@
|
|||||||
|
// ======== 平台积分台账 ========
|
||||||
|
// 「我的积分」页 /ssp/#/my/point 背后的接口才是最直接的证据:
|
||||||
|
// GET /ssp/rule/org 各积分规则的每日上限(文档/视频/音频/微课)
|
||||||
|
// POST /ssp/point/history/self 今日积分明细
|
||||||
|
// 脚本不再假设「学完一门就该 +3」,只把平台真实入账的记录折算成积分。
|
||||||
|
//
|
||||||
|
// 鉴权:接口认 localStorage.token(登录后由平台写入),不用 cookie。
|
||||||
|
// 接口不可用(未登录 / 跨域 / 网络)时返回 ok:false,调用方退回本地计数。
|
||||||
|
import { norm } from './utils.js';
|
||||||
|
import { pointLabel } from './points.js';
|
||||||
|
|
||||||
|
const API = 'https://api-phx-tc.yunxuetang.cn/ssp/';
|
||||||
|
const RULE_CODES = { doc: 'SB1031', video: 'SB1032', audio: 'SB1033', micro: 'SB1034' };
|
||||||
|
// 台账里的 nameType 就是平台自己的课件类型:1006 文档 / 1007 视频 / 1008 音频 / 1009 微课
|
||||||
|
const NAME_TYPES = { 1006: 'doc', 1007: 'video', 1008: 'audio', 1009: 'micro' };
|
||||||
|
const CACHE_TTL = 20000;
|
||||||
|
const TAGS_KEY = 'yun-xue-tang-point-awards-v1';
|
||||||
|
const PENDING_TTL = 6 * 60 * 60 * 1000;
|
||||||
|
const NO_AWARD_LIMIT = 3;
|
||||||
|
|
||||||
|
let cache = null;
|
||||||
|
let inflight = null;
|
||||||
|
let mode = ''; // '' | 'platform' | 'local':首次刷新成功与否决定本次会话的计数方式
|
||||||
|
let completionsSinceAward = 0;
|
||||||
|
let lastLedgerCount = -1;
|
||||||
|
|
||||||
|
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 token() {
|
||||||
|
try { return localStorage.getItem('token') || ''; } catch (e) { return ''; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function platformAvailable() {
|
||||||
|
return !!token();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 首次刷新是否已经确定计数方式;未确定前调用方按本地模式处理 */
|
||||||
|
export function platformMode() {
|
||||||
|
return mode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function cachedPlatformPoints() {
|
||||||
|
return cache;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 平台连续多少门课没有新增入账记录(用于判断「积分其实已满」) */
|
||||||
|
export function platformNoAward() {
|
||||||
|
return mode === 'platform' && completionsSinceAward >= NO_AWARD_LIMIT;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 本地保存「课程名 -> 类型」和「等待对账的完成记录」----
|
||||||
|
|
||||||
|
function loadTags(day) {
|
||||||
|
try {
|
||||||
|
const o = JSON.parse(localStorage.getItem(TAGS_KEY) || '{}');
|
||||||
|
if (o && o.day === day) {
|
||||||
|
return {
|
||||||
|
day: day,
|
||||||
|
titles: o.titles && typeof o.titles === 'object' ? o.titles : {},
|
||||||
|
pending: Array.isArray(o.pending) ? o.pending : [],
|
||||||
|
unknown: o.unknown && typeof o.unknown === 'object' ? o.unknown : {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch (e) { /* ignore */ }
|
||||||
|
return { day: day, titles: {}, pending: [], unknown: {} };
|
||||||
|
}
|
||||||
|
|
||||||
|
function saveTags(t) {
|
||||||
|
try { localStorage.setItem(TAGS_KEY, JSON.stringify(t)); } catch (e) { /* ignore */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 整门课完成时记下「这门课算哪一类」,等平台台账入账后据此归类 */
|
||||||
|
export function rememberCourseAward(title, type) {
|
||||||
|
if (!title || !type) return;
|
||||||
|
const t = loadTags(dayKey(Date.now()));
|
||||||
|
t.titles[norm(title)] = type;
|
||||||
|
t.pending.push({ type: type, at: Date.now(), title: norm(title) });
|
||||||
|
if (t.pending.length > 50) t.pending = t.pending.slice(-50);
|
||||||
|
saveTags(t);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 一门课完成了(平台模式下用来判断「连续 N 门没有入账」) */
|
||||||
|
export function noteCourseCompleted() {
|
||||||
|
if (mode === 'platform') completionsSinceAward++;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把平台台账折算进本地计数器。纯逻辑,方便离线测试。
|
||||||
|
* @returns {number} 本次新增计入的条数
|
||||||
|
*/
|
||||||
|
export function applyLedger(data, tracker, opts = {}) {
|
||||||
|
if (!data || !data.ok) return 0;
|
||||||
|
const t = loadTags(data.day);
|
||||||
|
if (opts.reset) {
|
||||||
|
// 切换到平台模式时丢弃旧口径的本地计数,完全以台账重建
|
||||||
|
if (typeof tracker.resetCounts === 'function') tracker.resetCounts();
|
||||||
|
t.unknown = {};
|
||||||
|
}
|
||||||
|
let added = 0;
|
||||||
|
for (const r of data.records || []) {
|
||||||
|
const id = 'platform:' + r.id;
|
||||||
|
const key = norm(r.remark || '');
|
||||||
|
// 优先用平台台账自带的 nameType,它比标题/待对账记录都可靠
|
||||||
|
let type = NAME_TYPES[Number(r.nameType)] || '';
|
||||||
|
if (!type) type = key && t.titles[key] ? t.titles[key] : '';
|
||||||
|
if (type) {
|
||||||
|
// 这条记录已经对上类型了,把它对应的待对账记录撤掉,避免后面串号
|
||||||
|
const j = t.pending.findIndex((p) => p.title === key && p.type === type);
|
||||||
|
if (j >= 0) t.pending.splice(j, 1);
|
||||||
|
} else {
|
||||||
|
// 平台有时用课时名而不是课程名:把它归给最近一次还没对上的完成记录
|
||||||
|
const i = t.pending.findIndex((p) => Date.now() - (p.at || 0) < PENDING_TTL);
|
||||||
|
if (i >= 0) {
|
||||||
|
type = t.pending[i].type;
|
||||||
|
t.pending.splice(i, 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (type) {
|
||||||
|
if (tracker.record(type, id)) {
|
||||||
|
added++;
|
||||||
|
console.log('[云学堂助手] 积分 +' + r.point + '(平台入账):' + pointLabel(type) +
|
||||||
|
' · ' + tracker.summary());
|
||||||
|
}
|
||||||
|
} else if (!t.unknown[id]) {
|
||||||
|
t.unknown[id] = 1;
|
||||||
|
console.warn('[云学堂助手] 平台积分 +' + r.point + ' 未能归类:' + (r.remark || r.id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
saveTags(t);
|
||||||
|
return added;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 拉取 ----
|
||||||
|
|
||||||
|
async function getJson(url, opts) {
|
||||||
|
const res = await fetch(url, opts);
|
||||||
|
if (!res.ok) throw new Error('HTTP ' + res.status);
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchPlatformPoints(now) {
|
||||||
|
const tk = token();
|
||||||
|
const at = now || Date.now();
|
||||||
|
if (!tk) return { ok: false, at: at, reason: 'no-token' };
|
||||||
|
const day = dayKey(at);
|
||||||
|
// 平台网关要求 source 头(501 = PC 端);缺了会返回 400「请求头 source 为空」
|
||||||
|
const headers = {
|
||||||
|
'Content-Type': 'application/json;charset=UTF-8',
|
||||||
|
source: '501',
|
||||||
|
'x-yxt-product': 'xxv2',
|
||||||
|
token: tk,
|
||||||
|
};
|
||||||
|
const body = JSON.stringify({
|
||||||
|
startDate: day + ' 00:00:00',
|
||||||
|
endDate: day + ' 23:59:59',
|
||||||
|
sourceType: -1,
|
||||||
|
optionType: 0,
|
||||||
|
type: 1,
|
||||||
|
userId: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
const results = await Promise.all([
|
||||||
|
getJson(API + 'rule/org', { headers: headers }),
|
||||||
|
getJson(API + 'point/history/self?limit=200&offset=0', {
|
||||||
|
method: 'POST', headers: headers, body: body,
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
const rules = results[0];
|
||||||
|
const ledger = results[1];
|
||||||
|
|
||||||
|
const ruleMap = {};
|
||||||
|
for (const r of (rules && rules.datas) || []) {
|
||||||
|
if (!r || Number(r.enable) !== 1) continue;
|
||||||
|
for (const key of Object.keys(RULE_CODES)) {
|
||||||
|
if (r.code === RULE_CODES[key]) {
|
||||||
|
ruleMap[key] = {
|
||||||
|
cap: Math.max(0, Number(r.times) || 0),
|
||||||
|
point: Math.max(0, Number(r.point) || 0),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// sourceType 1002 = 在线学习;登录奖励等其它来源不算每日学习积分
|
||||||
|
const records = ((ledger && ledger.datas) || []).filter((r) =>
|
||||||
|
r && r.id && Number(r.point) > 0 && Number(r.sourceType) === 1002);
|
||||||
|
const todayPoints = records.reduce((n, r) => n + (Number(r.point) || 0), 0);
|
||||||
|
const maxPoints = Object.keys(ruleMap).reduce((n, k) => n + ruleMap[k].cap * ruleMap[k].point, 0);
|
||||||
|
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
at: at,
|
||||||
|
day: day,
|
||||||
|
rules: ruleMap,
|
||||||
|
records: records,
|
||||||
|
todayPoints: todayPoints,
|
||||||
|
maxPoints: maxPoints,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 刷新平台台账并折算进计数器。并发调用共用一个请求;失败不抛错。
|
||||||
|
* @param {object} tracker points.js 的 tracker(需要 record / resetCounts)
|
||||||
|
* @param {{force?:boolean}} [opts]
|
||||||
|
*/
|
||||||
|
export function refreshPlatformPoints(tracker, opts = {}) {
|
||||||
|
if (!force(opts) && cache && Date.now() - cache.at < CACHE_TTL) {
|
||||||
|
return Promise.resolve(cache);
|
||||||
|
}
|
||||||
|
if (inflight) return inflight;
|
||||||
|
inflight = fetchPlatformPoints().then((data) => {
|
||||||
|
cache = data;
|
||||||
|
if (data.ok) {
|
||||||
|
if (mode !== 'platform') {
|
||||||
|
mode = 'platform';
|
||||||
|
applyLedger(data, tracker, { reset: true });
|
||||||
|
} else {
|
||||||
|
applyLedger(data, tracker);
|
||||||
|
}
|
||||||
|
if (data.records.length > lastLedgerCount) completionsSinceAward = 0;
|
||||||
|
lastLedgerCount = data.records.length;
|
||||||
|
} else if (!mode) {
|
||||||
|
mode = 'local';
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}).catch((e) => {
|
||||||
|
cache = { ok: false, at: Date.now(), reason: e && e.message ? e.message : String(e) };
|
||||||
|
if (!mode) mode = 'local';
|
||||||
|
return cache;
|
||||||
|
}).finally(() => { inflight = null; });
|
||||||
|
return inflight;
|
||||||
|
}
|
||||||
|
|
||||||
|
function force(opts) {
|
||||||
|
return !!(opts && opts.force);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 某个类型在平台规则里是否启用/上限多少;没有平台数据时返回 null */
|
||||||
|
export function platformRule(key) {
|
||||||
|
if (!cache || !cache.ok) return null;
|
||||||
|
return cache.rules[key] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 全部启用规则加起来的每日积分上限;没有平台数据时返回 0 */
|
||||||
|
export function platformMaxPoints() {
|
||||||
|
if (!cache || !cache.ok) return 0;
|
||||||
|
return cache.maxPoints;
|
||||||
|
}
|
||||||
+277
@@ -0,0 +1,277 @@
|
|||||||
|
// ======== 每日积分模式 ========
|
||||||
|
// 平台按「学习完成」发积分,四类任务各有每日上限:
|
||||||
|
// 文档 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} [taskId] 当天去重键(建议 courseId|course / kngId|media);空串表示不去重
|
||||||
|
* @returns {boolean} 是否真的计入了
|
||||||
|
*/
|
||||||
|
function record(key, taskId) {
|
||||||
|
rollover();
|
||||||
|
if (!enabled) return false;
|
||||||
|
if (!ruleOf(key) || isFull(key)) return false;
|
||||||
|
if (taskId) {
|
||||||
|
if (state.seen[taskId]) return false;
|
||||||
|
state.seen[taskId] = 1;
|
||||||
|
}
|
||||||
|
state.counts[key] = count(key) + 1;
|
||||||
|
save();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 切换到平台台账口径时清零并重建 */
|
||||||
|
function resetCounts() {
|
||||||
|
rollover();
|
||||||
|
for (const rule of POINT_RULES) state.counts[rule.key] = 0;
|
||||||
|
state.seen = {};
|
||||||
|
save();
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
resetCounts,
|
||||||
|
};
|
||||||
|
}
|
||||||
+1
-1
@@ -17,7 +17,7 @@ export function route() {
|
|||||||
// 单媒体播放页(没有多课时目录):完成判定看进度百分比/「已完成学习」,
|
// 单媒体播放页(没有多课时目录):完成判定看进度百分比/「已完成学习」,
|
||||||
// 不需要找下一节。
|
// 不需要找下一节。
|
||||||
export function mediaPage() {
|
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 || '');
|
||||||
}
|
}
|
||||||
|
|
||||||
// 回列表页。
|
// 回列表页。
|
||||||
|
|||||||
@@ -13,11 +13,13 @@ import {
|
|||||||
CFG, LS_ENABLED, LS_PREFER_SHORT, LS_TARGET_CATALOG_URL,
|
CFG, LS_ENABLED, LS_PREFER_SHORT, LS_TARGET_CATALOG_URL,
|
||||||
SS_RUN_STATE, SS_SHORT_CATALOG, LEGACY_LS_BATCH,
|
SS_RUN_STATE, SS_SHORT_CATALOG, LEGACY_LS_BATCH,
|
||||||
} from './config.js';
|
} from './config.js';
|
||||||
|
import { createPointsTracker, LS_POINTS_MODE } from './points.js';
|
||||||
|
|
||||||
// ======== 用户偏好(localStorage) ========
|
// ======== 用户偏好(localStorage) ========
|
||||||
export const state = {
|
export const state = {
|
||||||
autoPlayEnabled: true, // 当前课程自动连播(自己点开的课)
|
autoPlayEnabled: true, // 当前课程自动连播(自己点开的课)
|
||||||
preferShortCourses: CFG.preferShortCourses, // 列表刷课时优先后时长更短的课程(正序)
|
preferShortCourses: CFG.preferShortCourses, // 列表刷课时优先后时长更短的课程(正序)
|
||||||
|
pointsEnabled: true, // 每日积分模式:整门课完成计 1 次,按课时类型封顶
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
state.autoPlayEnabled = localStorage.getItem(LS_ENABLED) !== '0';
|
state.autoPlayEnabled = localStorage.getItem(LS_ENABLED) !== '0';
|
||||||
@@ -26,6 +28,12 @@ try {
|
|||||||
const v = localStorage.getItem(LS_PREFER_SHORT);
|
const v = localStorage.getItem(LS_PREFER_SHORT);
|
||||||
if (v === '0' || v === '1') state.preferShortCourses = v === '1';
|
if (v === '0' || v === '1') state.preferShortCourses = v === '1';
|
||||||
} catch (e) { /* ignore */ }
|
} catch (e) { /* ignore */ }
|
||||||
|
try {
|
||||||
|
state.pointsEnabled = localStorage.getItem(LS_POINTS_MODE) !== '0';
|
||||||
|
} catch (e) { /* ignore */ }
|
||||||
|
|
||||||
|
// 每日积分计数落 localStorage(带日期,跨刷新/重启不丢,跨天自动清零)
|
||||||
|
export const points = createPointsTracker({ enabled: state.pointsEnabled });
|
||||||
|
|
||||||
// ======== 本次运行状态(sessionStorage) ========
|
// ======== 本次运行状态(sessionStorage) ========
|
||||||
export const PHASE_ENTERING = 'entering';
|
export const PHASE_ENTERING = 'entering';
|
||||||
@@ -54,6 +62,7 @@ export function defaultRunState() {
|
|||||||
// ---- 本轮记录 ----
|
// ---- 本轮记录 ----
|
||||||
completedTitles: {}, // 课程名 -> 完成时间戳(防平台记账延迟时重进同一门)
|
completedTitles: {}, // 课程名 -> 完成时间戳(防平台记账延迟时重进同一门)
|
||||||
courseRetries: {}, // 课程名 -> { n, reason, at }(未完成重试次数)
|
courseRetries: {}, // 课程名 -> { n, reason, at }(未完成重试次数)
|
||||||
|
skippedCourses: {}, // 课程名 -> { reason, at }(考试无法自动完成,本轮跳过)
|
||||||
examEmptySubmits: {}, // 课程 id -> 空卷交卷次数(防死循环)
|
examEmptySubmits: {}, // 课程 id -> 空卷交卷次数(防死循环)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -106,6 +115,7 @@ function restoreFrom(obj) {
|
|||||||
// ---- 本轮记录 ----
|
// ---- 本轮记录 ----
|
||||||
out.completedTitles = asMap(obj.completedTitles);
|
out.completedTitles = asMap(obj.completedTitles);
|
||||||
out.courseRetries = asMap(obj.courseRetries);
|
out.courseRetries = asMap(obj.courseRetries);
|
||||||
|
out.skippedCourses = asMap(obj.skippedCourses);
|
||||||
out.examEmptySubmits = asMap(obj.examEmptySubmits);
|
out.examEmptySubmits = asMap(obj.examEmptySubmits);
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
@@ -207,6 +217,9 @@ export const R = {
|
|||||||
// 考试(空卷交卷)自动处理状态
|
// 考试(空卷交卷)自动处理状态
|
||||||
examPhase: '', // '' | preview | paper | result
|
examPhase: '', // '' | preview | paper | result
|
||||||
examActionAt: 0, // 上次考试页内点击时间
|
examActionAt: 0, // 上次考试页内点击时间
|
||||||
|
examSubmitted: false, // 本页是否真的点过「提交考试/确定交卷」(区分残留结果页)
|
||||||
|
examPreviewAt: 0, // 进入考试说明页的时间(找不到「开始考试」时的超时)
|
||||||
|
examStaleResults: 0, // 本课遇到残留结果页并尝试重进的次数
|
||||||
examStarts: 0, // 本形态点了多少次「开始考试」
|
examStarts: 0, // 本形态点了多少次「开始考试」
|
||||||
examSubmits: 0, // 本形态点了多少次「提交考试」
|
examSubmits: 0, // 本形态点了多少次「提交考试」
|
||||||
examConfirms: 0, // 本形态点了多少次交卷确认「确定」
|
examConfirms: 0, // 本形态点了多少次交卷确认「确定」
|
||||||
@@ -243,6 +256,17 @@ export const R = {
|
|||||||
shortNoVmSince: 0,
|
shortNoVmSince: 0,
|
||||||
shortWarnedAt: 0,
|
shortWarnedAt: 0,
|
||||||
retryStatusSec: -1, // 「等待重试」提示上次写出的剩余秒数(只在变化时刷状态)
|
retryStatusSec: -1, // 「等待重试」提示上次写出的剩余秒数(只在变化时刷状态)
|
||||||
|
// 每日积分模式:当前课时的类型缓存(课时 id → doc/video/audio/micro),
|
||||||
|
// 以及文档/音频/微课的单条库存(视频靠课程里的课时,不单独存)
|
||||||
|
lessonTypes: {},
|
||||||
|
coursePointCourseId: '', // 「今天学过的类型」所属课程 id
|
||||||
|
coursePointType: '', // 这门课今天学过的类型,整门课完成时计一次
|
||||||
|
pointsInventory: null,
|
||||||
|
pointsInventoryLoading: false,
|
||||||
|
pointsInventoryFailedAt: 0,
|
||||||
|
pointsFetchStartedAt: 0,
|
||||||
|
pointsNoVmSince: 0,
|
||||||
|
pointsWarnedAt: 0,
|
||||||
};
|
};
|
||||||
|
|
||||||
// 丢掉时长队列缓存:下一次选课会重新调列表接口,拿平台实时的
|
// 丢掉时长队列缓存:下一次选课会重新调列表接口,拿平台实时的
|
||||||
@@ -259,6 +283,9 @@ export function invalidateShortCatalog() {
|
|||||||
export function resetCourseRuntime() {
|
export function resetCourseRuntime() {
|
||||||
R.lastLessonKey = '';
|
R.lastLessonKey = '';
|
||||||
R.doneLatchKey = '';
|
R.doneLatchKey = '';
|
||||||
|
R.lessonTypes = {};
|
||||||
|
R.coursePointCourseId = '';
|
||||||
|
R.coursePointType = '';
|
||||||
R.lastSummary = null;
|
R.lastSummary = null;
|
||||||
R.lastCountdown = null;
|
R.lastCountdown = null;
|
||||||
R.lastProgressAt = Date.now();
|
R.lastProgressAt = Date.now();
|
||||||
@@ -268,6 +295,9 @@ export function resetCourseRuntime() {
|
|||||||
R.quizChecked = false;
|
R.quizChecked = false;
|
||||||
R.examPhase = '';
|
R.examPhase = '';
|
||||||
R.examActionAt = 0;
|
R.examActionAt = 0;
|
||||||
|
R.examSubmitted = false;
|
||||||
|
R.examPreviewAt = 0;
|
||||||
|
R.examStaleResults = 0;
|
||||||
R.examStarts = 0;
|
R.examStarts = 0;
|
||||||
R.examSubmits = 0;
|
R.examSubmits = 0;
|
||||||
R.examConfirms = 0;
|
R.examConfirms = 0;
|
||||||
|
|||||||
+883
-40
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user