mirror of
https://github.com/keven1024/015.git
synced 2026-06-07 12:54:34 +00:00
Compare commits
208 Commits
0.0.8.1
...
0.11.0-rc.
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ac8b6f642b | ||
|
|
af6ca85ff5 | ||
|
|
02900ab1f9 | ||
|
|
bdf7894e9b | ||
|
|
a8f504f377 | ||
|
|
cf92a50c82 | ||
|
|
848a0ff71b | ||
|
|
2f3acc76cd | ||
|
|
c89d1b554f | ||
|
|
71737ebedc | ||
|
|
b735200418 | ||
|
|
6084acb0d5 | ||
|
|
a601964459 | ||
|
|
8758325da3 | ||
|
|
18ca80bb1b | ||
|
|
958ca799da | ||
|
|
9a9418c564 | ||
|
|
0cb30b6293 | ||
|
|
8828924a1f | ||
|
|
3275b8f68f | ||
|
|
95ef5d261b | ||
|
|
52d041b4c2 | ||
|
|
2ff06946e1 | ||
|
|
4c6a18c063 | ||
|
|
bbf6ea561d | ||
|
|
1449664ca5 | ||
|
|
4a3ec790b7 | ||
|
|
f4a28e369f | ||
|
|
833079d495 | ||
|
|
a63d55b61d | ||
|
|
46c6cd84b5 | ||
|
|
84e747a909 | ||
|
|
a24bf24271 | ||
|
|
1226a7948e | ||
|
|
1e446a0240 | ||
|
|
b023876e0f | ||
|
|
ec1d70637b | ||
|
|
6934bba7a1 | ||
|
|
2e5da4f7e9 | ||
|
|
d8704a8aa8 | ||
|
|
2273c589f6 | ||
|
|
a14628718c | ||
|
|
528df24988 | ||
|
|
2a42ca8cde | ||
|
|
6edb1fe222 | ||
|
|
c841d8e1a2 | ||
|
|
e8b5f98260 | ||
|
|
706464ce3c | ||
|
|
b52d4c3a51 | ||
|
|
e9fc260cbc | ||
|
|
e37402ff63 | ||
|
|
35654372a6 | ||
|
|
018d13ea78 | ||
|
|
0e0f6bb1c5 | ||
|
|
7ba7af6100 | ||
|
|
55eb50faab | ||
|
|
87d337c2a1 | ||
|
|
2fc2f4ccf7 | ||
|
|
10a82a1751 | ||
|
|
a5a01a667e | ||
|
|
907f77aa66 | ||
|
|
ae2fbcc216 | ||
|
|
f1dc65b1d0 | ||
|
|
881d8e111a | ||
|
|
58ba3f6d50 | ||
|
|
788ef8df57 | ||
|
|
d0021f9468 | ||
|
|
a99790c9b1 | ||
|
|
249b9f2350 | ||
|
|
6a7e8f85ac | ||
|
|
3f5f8b3c97 | ||
|
|
f8b5b82179 | ||
|
|
0d4d89d4ec | ||
|
|
2af28b6a50 | ||
|
|
a1808a64cc | ||
|
|
499b931c04 | ||
|
|
1298bf79d3 | ||
|
|
83f6be0486 | ||
|
|
17fa39b830 | ||
|
|
55949d1f76 | ||
|
|
d3e7760aea | ||
|
|
7566ddb5f2 | ||
|
|
78624b302d | ||
|
|
759318813c | ||
|
|
a91345f39c | ||
|
|
123b1ec4fb | ||
|
|
79887d6c6c | ||
|
|
f1f10de051 | ||
|
|
80d60cc0a0 | ||
|
|
30d0abc2b5 | ||
|
|
8d3675cfa1 | ||
|
|
cb6b0fae6a | ||
|
|
6631e1e1a2 | ||
|
|
625399bdd9 | ||
|
|
10b79615b7 | ||
|
|
7c38773451 | ||
|
|
976011697c | ||
|
|
c25b41e20e | ||
|
|
3c031dcee9 | ||
|
|
d6c54de659 | ||
|
|
72ca69330f | ||
|
|
7f74441f5d | ||
|
|
28abd8d1a2 | ||
|
|
c50bb5d0bf | ||
|
|
95ab8b97da | ||
|
|
d6880dbf00 | ||
|
|
c871c55f79 | ||
|
|
82e9292b66 | ||
|
|
1d86f2bdf6 | ||
|
|
52cc89a73d | ||
|
|
af9a5b45d2 | ||
|
|
b26821a504 | ||
|
|
560387d8f1 | ||
|
|
b69af056aa | ||
|
|
707ade5dd2 | ||
|
|
b4570c5961 | ||
|
|
60a588c92a | ||
|
|
47781ff374 | ||
|
|
7760697233 | ||
|
|
8f1ced62ac | ||
|
|
72560cf233 | ||
|
|
62443f38a4 | ||
|
|
5c264a4297 | ||
|
|
332fa7195f | ||
|
|
4ce68d91a8 | ||
|
|
78cfc3943c | ||
|
|
7772a935d7 | ||
|
|
7d204345cc | ||
|
|
f9251663a2 | ||
|
|
75c269b60e | ||
|
|
64126e7c4c | ||
|
|
f8a43c9b1f | ||
|
|
9aa52915b0 | ||
|
|
fe66240671 | ||
|
|
1635a31f33 | ||
|
|
67b1d07fbe | ||
|
|
ceb2d026d2 | ||
|
|
123178084a | ||
|
|
183297bd2c | ||
|
|
55900224ae | ||
|
|
a64fa95608 | ||
|
|
70fc2be02f | ||
|
|
e14eed73c4 | ||
|
|
4a8932f921 | ||
|
|
60831c779e | ||
|
|
7663e8eb0a | ||
|
|
fe6c832275 | ||
|
|
f1dec39851 | ||
|
|
59cd23daf7 | ||
|
|
7ca301e54d | ||
|
|
6d7dc6bc40 | ||
|
|
bde4e36e47 | ||
|
|
e5b5def6f0 | ||
|
|
ed7ac4e657 | ||
|
|
22637bcf6e | ||
|
|
3d8d1ccd3f | ||
|
|
ae7db9de02 | ||
|
|
6304dffa39 | ||
|
|
2ea2d89f44 | ||
|
|
b98853ebe1 | ||
|
|
e9d0848f87 | ||
|
|
155c697e53 | ||
|
|
301dcaf8b6 | ||
|
|
8f3bafcbfb | ||
|
|
b471972dd4 | ||
|
|
8c4c7b0471 | ||
|
|
9679a42be2 | ||
|
|
e43d27958d | ||
|
|
31c0736562 | ||
|
|
185f7a3503 | ||
|
|
90607aad7c | ||
|
|
e250202deb | ||
|
|
e8653a8e8b | ||
|
|
b4a4be09fa | ||
|
|
bfe9a8f3d6 | ||
|
|
a71cc5e919 | ||
|
|
18a626fd04 | ||
|
|
ca33fcc332 | ||
|
|
85c6b4582f | ||
|
|
9eaf06e7a8 | ||
|
|
0c980e8b6c | ||
|
|
831d9b2660 | ||
|
|
dd3ced5b03 | ||
|
|
d7d2a5c00b | ||
|
|
a82c894119 | ||
|
|
d4b0368ae2 | ||
|
|
f317e0f538 | ||
|
|
e17b1a04c5 | ||
|
|
04ebb22d35 | ||
|
|
552434e389 | ||
|
|
d5fc54de31 | ||
|
|
675a6e860a | ||
|
|
18a74b6545 | ||
|
|
313ce4455f | ||
|
|
208875841e | ||
|
|
35c5e1ccec | ||
|
|
6da3d9a15d | ||
|
|
23c33fc52e | ||
|
|
4f4139159e | ||
|
|
62463494b4 | ||
|
|
c8fd8c874b | ||
|
|
70d35a1a15 | ||
|
|
9e2a6411ec | ||
|
|
d8bc68b008 | ||
|
|
d2478dd23b | ||
|
|
99538c6fdb | ||
|
|
0f0814ce40 | ||
|
|
15922ea2df |
152
.claude/commands/opsx/apply.md
Normal file
152
.claude/commands/opsx/apply.md
Normal file
@@ -0,0 +1,152 @@
|
||||
---
|
||||
name: "OPSX: Apply"
|
||||
description: Implement tasks from an OpenSpec change (Experimental)
|
||||
category: Workflow
|
||||
tags: [workflow, artifacts, experimental]
|
||||
---
|
||||
|
||||
Implement tasks from an OpenSpec change.
|
||||
|
||||
**Input**: Optionally specify a change name (e.g., `/opsx:apply add-auth`). 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 use the **AskUserQuestion tool** to let the user select
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <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")
|
||||
- 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)
|
||||
- Progress (total, complete, remaining)
|
||||
- Task list with status
|
||||
- Dynamic instruction based on current state
|
||||
|
||||
**Handle states:**
|
||||
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx:continue`
|
||||
- If `state: "all_done"`: congratulate, suggest archive
|
||||
- Otherwise: proceed to implementation
|
||||
|
||||
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
|
||||
|
||||
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! You can archive this change with `/opsx:archive`.
|
||||
```
|
||||
|
||||
**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
|
||||
|
||||
**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
|
||||
157
.claude/commands/opsx/archive.md
Normal file
157
.claude/commands/opsx/archive.md
Normal file
@@ -0,0 +1,157 @@
|
||||
---
|
||||
name: "OPSX: Archive"
|
||||
description: Archive a completed change in the experimental workflow
|
||||
category: Workflow
|
||||
tags: [workflow, archive, experimental]
|
||||
---
|
||||
|
||||
Archive a completed change in the experimental workflow.
|
||||
|
||||
**Input**: Optionally specify a change name after `/opsx:archive` (e.g., `/opsx:archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no change name provided, prompt for selection**
|
||||
|
||||
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||
|
||||
Show only active changes (not already archived).
|
||||
Include the schema used for each change if available.
|
||||
|
||||
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||
|
||||
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
|
||||
- `artifacts`: List of artifacts with their status (`done` or other)
|
||||
|
||||
**If any artifacts are not `done`:**
|
||||
- Display warning listing incomplete artifacts
|
||||
- Prompt user for confirmation to continue
|
||||
- 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
|
||||
- Prompt user for confirmation to continue
|
||||
- Proceed if user confirms
|
||||
|
||||
**If no tasks file exists:** Proceed without task-related warning.
|
||||
|
||||
4. **Assess delta spec sync state**
|
||||
|
||||
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
|
||||
|
||||
**If delta specs exist:**
|
||||
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
|
||||
- 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"
|
||||
|
||||
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
|
||||
|
||||
5. **Perform the archive**
|
||||
|
||||
Create the archive directory if it doesn't exist:
|
||||
```bash
|
||||
mkdir -p openspec/changes/archive
|
||||
```
|
||||
|
||||
Generate target name using current date: `YYYY-MM-DD-<change-name>`
|
||||
|
||||
**Check if target already exists:**
|
||||
- If yes: Fail with error, suggest renaming existing archive or using different date
|
||||
- If no: Move the change directory to archive
|
||||
|
||||
```bash
|
||||
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
|
||||
```
|
||||
|
||||
6. **Display summary**
|
||||
|
||||
Show archive completion summary including:
|
||||
- Change name
|
||||
- Schema that was used
|
||||
- Archive location
|
||||
- Spec sync status (synced / sync skipped / no delta specs)
|
||||
- Note about any warnings (incomplete artifacts/tasks)
|
||||
|
||||
**Output On Success**
|
||||
|
||||
```
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
|
||||
**Specs:** ✓ Synced to main specs
|
||||
|
||||
All artifacts complete. All tasks complete.
|
||||
```
|
||||
|
||||
**Output On Success (No Delta Specs)**
|
||||
|
||||
```
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
|
||||
**Specs:** No delta specs
|
||||
|
||||
All artifacts complete. All tasks complete.
|
||||
```
|
||||
|
||||
**Output On Success With Warnings**
|
||||
|
||||
```
|
||||
## Archive Complete (with warnings)
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
|
||||
**Specs:** Sync skipped (user chose to skip)
|
||||
|
||||
**Warnings:**
|
||||
- Archived with 2 incomplete artifacts
|
||||
- Archived with 3 incomplete tasks
|
||||
- Delta spec sync was skipped (user chose to skip)
|
||||
|
||||
Review the archive if this was not intentional.
|
||||
```
|
||||
|
||||
**Output On Error (Archive Exists)**
|
||||
|
||||
```
|
||||
## Archive Failed
|
||||
|
||||
**Change:** <change-name>
|
||||
**Target:** openspec/changes/archive/YYYY-MM-DD-<name>/
|
||||
|
||||
Target archive directory already exists.
|
||||
|
||||
**Options:**
|
||||
1. Rename the existing archive
|
||||
2. Delete the existing archive if it's a duplicate
|
||||
3. Wait until a different date to archive
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Always prompt for change selection if not provided
|
||||
- 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, use the Skill tool to invoke `openspec-sync-specs` (agent-driven)
|
||||
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
|
||||
173
.claude/commands/opsx/explore.md
Normal file
173
.claude/commands/opsx/explore.md
Normal file
@@ -0,0 +1,173 @@
|
||||
---
|
||||
name: "OPSX: Explore"
|
||||
description: "Enter explore mode - think through ideas, investigate problems, clarify requirements"
|
||||
category: Workflow
|
||||
tags: [workflow, explore, experimental, thinking]
|
||||
---
|
||||
|
||||
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.
|
||||
|
||||
**Input**: The argument after `/opsx:explore` is whatever the user wants to think about. Could be:
|
||||
- A vague idea: "real-time collaboration"
|
||||
- A specific problem: "the auth system is getting unwieldy"
|
||||
- A change name: "add-dark-mode" (to explore in context of that change)
|
||||
- A comparison: "postgres vs sqlite for this"
|
||||
- Nothing (just enter explore mode)
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
|
||||
If the user mentioned a specific change name, read its artifacts for context.
|
||||
|
||||
### 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. **Read existing artifacts for context**
|
||||
- `openspec/changes/<name>/proposal.md`
|
||||
- `openspec/changes/<name>/design.md`
|
||||
- `openspec/changes/<name>/tasks.md`
|
||||
- etc.
|
||||
|
||||
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)
|
||||
|
||||
---
|
||||
|
||||
## 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 things crystallize, you might offer a summary - but it's 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
|
||||
106
.claude/commands/opsx/propose.md
Normal file
106
.claude/commands/opsx/propose.md
Normal file
@@ -0,0 +1,106 @@
|
||||
---
|
||||
name: "OPSX: Propose"
|
||||
description: Propose a new change - create it and generate all artifacts in one step
|
||||
category: Workflow
|
||||
tags: [workflow, artifacts, experimental]
|
||||
---
|
||||
|
||||
Propose a new change - create the change and generate all artifacts in one step.
|
||||
|
||||
I'll create a change with artifacts:
|
||||
- proposal.md (what & why)
|
||||
- design.md (how)
|
||||
- tasks.md (implementation steps)
|
||||
|
||||
When ready to implement, run /opsx:apply
|
||||
|
||||
---
|
||||
|
||||
**Input**: The argument after `/opsx:propose` is the change name (kebab-case), OR a description of what the user wants to build.
|
||||
|
||||
**Steps**
|
||||
|
||||
1. **If no input provided, ask what they want to build**
|
||||
|
||||
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
|
||||
> "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 at `openspec/changes/<name>/` 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 with their status and dependencies
|
||||
|
||||
4. **Create artifacts in sequence until apply-ready**
|
||||
|
||||
Use the **TodoWrite tool** 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
|
||||
- `outputPath`: Where to write the artifact
|
||||
- `dependencies`: Completed artifacts to read for context
|
||||
- Read any completed dependency files for context
|
||||
- Create the artifact file using `template` as the structure
|
||||
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
|
||||
- Show brief progress: "Created <artifact-id>"
|
||||
|
||||
b. **Continue until all `applyRequires` artifacts are complete**
|
||||
- After creating each artifact, re-run `openspec status --change "<name>" --json`
|
||||
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
|
||||
- Stop when all `applyRequires` artifacts are done
|
||||
|
||||
c. **If an artifact requires user input** (unclear context):
|
||||
- Use **AskUserQuestion tool** 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
|
||||
- What's ready: "All artifacts created! Ready for implementation."
|
||||
- Prompt: "Run `/opsx:apply` to start implementing."
|
||||
|
||||
**Artifact Creation Guidelines**
|
||||
|
||||
- Follow the `instruction` field from `openspec instructions` for each artifact type
|
||||
- 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 ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
|
||||
- Always read dependency artifacts before creating a new one
|
||||
- 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
|
||||
156
.claude/skills/openspec-apply-change/SKILL.md
Normal file
156
.claude/skills/openspec-apply-change/SKILL.md
Normal file
@@ -0,0 +1,156 @@
|
||||
---
|
||||
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.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
Implement tasks from an OpenSpec change.
|
||||
|
||||
**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 use the **AskUserQuestion tool** to let the user select
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <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")
|
||||
- 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
|
||||
|
||||
**Handle states:**
|
||||
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change
|
||||
- If `state: "all_done"`: congratulate, suggest archive
|
||||
- Otherwise: proceed to implementation
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
**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
|
||||
114
.claude/skills/openspec-archive-change/SKILL.md
Normal file
114
.claude/skills/openspec-archive-change/SKILL.md
Normal file
@@ -0,0 +1,114 @@
|
||||
---
|
||||
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.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
Archive a completed change in the experimental workflow.
|
||||
|
||||
**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. **If no change name provided, prompt for selection**
|
||||
|
||||
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||
|
||||
Show only active changes (not already archived).
|
||||
Include the schema used for each change if available.
|
||||
|
||||
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||
|
||||
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
|
||||
- `artifacts`: List of artifacts with their status (`done` or other)
|
||||
|
||||
**If any artifacts are not `done`:**
|
||||
- Display warning listing incomplete artifacts
|
||||
- Use **AskUserQuestion tool** to confirm user wants 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
|
||||
- Use **AskUserQuestion tool** to confirm user wants to proceed
|
||||
- Proceed if user confirms
|
||||
|
||||
**If no tasks file exists:** Proceed without task-related warning.
|
||||
|
||||
4. **Assess delta spec sync state**
|
||||
|
||||
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
|
||||
|
||||
**If delta specs exist:**
|
||||
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
|
||||
- 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"
|
||||
|
||||
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
|
||||
|
||||
5. **Perform the archive**
|
||||
|
||||
Create the archive directory if it doesn't exist:
|
||||
```bash
|
||||
mkdir -p openspec/changes/archive
|
||||
```
|
||||
|
||||
Generate target name using current date: `YYYY-MM-DD-<change-name>`
|
||||
|
||||
**Check if target already exists:**
|
||||
- If yes: Fail with error, suggest renaming existing archive or using different date
|
||||
- If no: Move the change directory to archive
|
||||
|
||||
```bash
|
||||
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<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**
|
||||
|
||||
```
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
|
||||
**Specs:** ✓ Synced to main specs (or "No delta specs" or "Sync skipped")
|
||||
|
||||
All artifacts complete. All tasks complete.
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Always prompt for change selection if not provided
|
||||
- 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, use openspec-sync-specs approach (agent-driven)
|
||||
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
|
||||
288
.claude/skills/openspec-explore/SKILL.md
Normal file
288
.claude/skills/openspec-explore/SKILL.md
Normal file
@@ -0,0 +1,288 @@
|
||||
---
|
||||
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.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
|
||||
### 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. **Read existing artifacts for context**
|
||||
- `openspec/changes/<name>/proposal.md`
|
||||
- `openspec/changes/<name>/design.md`
|
||||
- `openspec/changes/<name>/tasks.md`
|
||||
- etc.
|
||||
|
||||
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: /opsx: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
|
||||
110
.claude/skills/openspec-propose/SKILL.md
Normal file
110
.claude/skills/openspec-propose/SKILL.md
Normal file
@@ -0,0 +1,110 @@
|
||||
---
|
||||
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.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
Propose a new change - create the change and generate all artifacts in one step.
|
||||
|
||||
I'll create a change with artifacts:
|
||||
- proposal.md (what & why)
|
||||
- design.md (how)
|
||||
- tasks.md (implementation steps)
|
||||
|
||||
When ready to implement, run /opsx:apply
|
||||
|
||||
---
|
||||
|
||||
**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**
|
||||
|
||||
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
|
||||
> "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 at `openspec/changes/<name>/` 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 with their status and dependencies
|
||||
|
||||
4. **Create artifacts in sequence until apply-ready**
|
||||
|
||||
Use the **TodoWrite tool** 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
|
||||
- `outputPath`: Where to write the artifact
|
||||
- `dependencies`: Completed artifacts to read for context
|
||||
- Read any completed dependency files for context
|
||||
- Create the artifact file using `template` as the structure
|
||||
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
|
||||
- Show brief progress: "Created <artifact-id>"
|
||||
|
||||
b. **Continue until all `applyRequires` artifacts are complete**
|
||||
- After creating each artifact, re-run `openspec status --change "<name>" --json`
|
||||
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
|
||||
- Stop when all `applyRequires` artifacts are done
|
||||
|
||||
c. **If an artifact requires user input** (unclear context):
|
||||
- Use **AskUserQuestion tool** 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
|
||||
- What's ready: "All artifacts created! Ready for implementation."
|
||||
- Prompt: "Run `/opsx:apply` 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
|
||||
- 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 ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
|
||||
- Always read dependency artifacts before creating a new one
|
||||
- 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
|
||||
156
.codex/skills/openspec-apply-change/SKILL.md
Normal file
156
.codex/skills/openspec-apply-change/SKILL.md
Normal file
@@ -0,0 +1,156 @@
|
||||
---
|
||||
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.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
Implement tasks from an OpenSpec change.
|
||||
|
||||
**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 use the **AskUserQuestion tool** to let the user select
|
||||
|
||||
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <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")
|
||||
- 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
|
||||
|
||||
**Handle states:**
|
||||
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change
|
||||
- If `state: "all_done"`: congratulate, suggest archive
|
||||
- Otherwise: proceed to implementation
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
**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
|
||||
114
.codex/skills/openspec-archive-change/SKILL.md
Normal file
114
.codex/skills/openspec-archive-change/SKILL.md
Normal file
@@ -0,0 +1,114 @@
|
||||
---
|
||||
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.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
Archive a completed change in the experimental workflow.
|
||||
|
||||
**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. **If no change name provided, prompt for selection**
|
||||
|
||||
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
|
||||
|
||||
Show only active changes (not already archived).
|
||||
Include the schema used for each change if available.
|
||||
|
||||
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
|
||||
|
||||
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
|
||||
- `artifacts`: List of artifacts with their status (`done` or other)
|
||||
|
||||
**If any artifacts are not `done`:**
|
||||
- Display warning listing incomplete artifacts
|
||||
- Use **AskUserQuestion tool** to confirm user wants 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
|
||||
- Use **AskUserQuestion tool** to confirm user wants to proceed
|
||||
- Proceed if user confirms
|
||||
|
||||
**If no tasks file exists:** Proceed without task-related warning.
|
||||
|
||||
4. **Assess delta spec sync state**
|
||||
|
||||
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
|
||||
|
||||
**If delta specs exist:**
|
||||
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
|
||||
- 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"
|
||||
|
||||
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
|
||||
|
||||
5. **Perform the archive**
|
||||
|
||||
Create the archive directory if it doesn't exist:
|
||||
```bash
|
||||
mkdir -p openspec/changes/archive
|
||||
```
|
||||
|
||||
Generate target name using current date: `YYYY-MM-DD-<change-name>`
|
||||
|
||||
**Check if target already exists:**
|
||||
- If yes: Fail with error, suggest renaming existing archive or using different date
|
||||
- If no: Move the change directory to archive
|
||||
|
||||
```bash
|
||||
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<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**
|
||||
|
||||
```
|
||||
## Archive Complete
|
||||
|
||||
**Change:** <change-name>
|
||||
**Schema:** <schema-name>
|
||||
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
|
||||
**Specs:** ✓ Synced to main specs (or "No delta specs" or "Sync skipped")
|
||||
|
||||
All artifacts complete. All tasks complete.
|
||||
```
|
||||
|
||||
**Guardrails**
|
||||
- Always prompt for change selection if not provided
|
||||
- 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, use openspec-sync-specs approach (agent-driven)
|
||||
- If delta specs exist, always run the sync assessment and show the combined summary before prompting
|
||||
288
.codex/skills/openspec-explore/SKILL.md
Normal file
288
.codex/skills/openspec-explore/SKILL.md
Normal file
@@ -0,0 +1,288 @@
|
||||
---
|
||||
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.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
|
||||
### 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. **Read existing artifacts for context**
|
||||
- `openspec/changes/<name>/proposal.md`
|
||||
- `openspec/changes/<name>/design.md`
|
||||
- `openspec/changes/<name>/tasks.md`
|
||||
- etc.
|
||||
|
||||
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: /opsx: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
|
||||
110
.codex/skills/openspec-propose/SKILL.md
Normal file
110
.codex/skills/openspec-propose/SKILL.md
Normal file
@@ -0,0 +1,110 @@
|
||||
---
|
||||
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.
|
||||
license: MIT
|
||||
compatibility: Requires openspec CLI.
|
||||
metadata:
|
||||
author: openspec
|
||||
version: "1.0"
|
||||
generatedBy: "1.3.1"
|
||||
---
|
||||
|
||||
Propose a new change - create the change and generate all artifacts in one step.
|
||||
|
||||
I'll create a change with artifacts:
|
||||
- proposal.md (what & why)
|
||||
- design.md (how)
|
||||
- tasks.md (implementation steps)
|
||||
|
||||
When ready to implement, run /opsx:apply
|
||||
|
||||
---
|
||||
|
||||
**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**
|
||||
|
||||
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
|
||||
> "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 at `openspec/changes/<name>/` 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 with their status and dependencies
|
||||
|
||||
4. **Create artifacts in sequence until apply-ready**
|
||||
|
||||
Use the **TodoWrite tool** 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
|
||||
- `outputPath`: Where to write the artifact
|
||||
- `dependencies`: Completed artifacts to read for context
|
||||
- Read any completed dependency files for context
|
||||
- Create the artifact file using `template` as the structure
|
||||
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
|
||||
- Show brief progress: "Created <artifact-id>"
|
||||
|
||||
b. **Continue until all `applyRequires` artifacts are complete**
|
||||
- After creating each artifact, re-run `openspec status --change "<name>" --json`
|
||||
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
|
||||
- Stop when all `applyRequires` artifacts are done
|
||||
|
||||
c. **If an artifact requires user input** (unclear context):
|
||||
- Use **AskUserQuestion tool** 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
|
||||
- What's ready: "All artifacts created! Ready for implementation."
|
||||
- Prompt: "Run `/opsx:apply` 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
|
||||
- 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 ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
|
||||
- Always read dependency artifacts before creating a new one
|
||||
- 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
|
||||
31
.gitea/workflows/build.yaml
Normal file
31
.gitea/workflows/build.yaml
Normal file
@@ -0,0 +1,31 @@
|
||||
name: Build
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
build-test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
- name: Set build time
|
||||
id: build-time
|
||||
run: echo "time=$(date +%s)" >> $GITHUB_OUTPUT
|
||||
- name: build-app
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
push: false
|
||||
tags: 015-app:test
|
||||
build-args: |
|
||||
VERSION=${{ gitea.ref_name || github.ref_name }}
|
||||
BUILD_TIME=${{ steps.build-time.outputs.time }}
|
||||
- name: build-worker
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ./worker/Dockerfile
|
||||
push: false
|
||||
tags: 015-worker:test
|
||||
47
.gitea/workflows/lint.yaml
Normal file
47
.gitea/workflows/lint.yaml
Normal file
@@ -0,0 +1,47 @@
|
||||
name: Lint
|
||||
|
||||
on:
|
||||
push:
|
||||
|
||||
jobs:
|
||||
lint-front:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '24'
|
||||
- uses: pnpm/action-setup@v4
|
||||
with:
|
||||
cache: true
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pnpm install --frozen-lockfile
|
||||
- name: Run frontend lint
|
||||
run: pnpm lint:front
|
||||
|
||||
lint-backend:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.work'
|
||||
- name: Run golangci-lint
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
skip-cache: true
|
||||
working-directory: backend
|
||||
|
||||
lint-worker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.work'
|
||||
- name: Run golangci-lint
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
skip-cache: true
|
||||
working-directory: worker
|
||||
87
.gitea/workflows/publish.yaml
Normal file
87
.gitea/workflows/publish.yaml
Normal file
@@ -0,0 +1,87 @@
|
||||
name: Publish
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
build-app:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: docker/setup-qemu-action@v3
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
- uses: docker/login-action@v3
|
||||
with:
|
||||
username: fudaoyuanicu
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
- uses: docker/metadata-action@v5
|
||||
id: meta
|
||||
with:
|
||||
images: fudaoyuanicu/015-app
|
||||
tags: |
|
||||
type=semver,pattern={{version}}
|
||||
type=raw,value=edge,enable=${{ contains(github.ref_name, '-') }}
|
||||
type=raw,value=latest,enable=${{ !contains(github.ref_name, '-') }}
|
||||
- name: Set build time
|
||||
id: build-time
|
||||
run: |
|
||||
echo "time=$(date +%s)" >> $GITHUB_OUTPUT
|
||||
shell: bash
|
||||
- name: build-app
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
build-args: |
|
||||
VERSION=${{ gitea.ref_name || github.ref_name }}
|
||||
BUILD_TIME=${{ steps.build-time.outputs.time }}
|
||||
|
||||
build-worker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: docker/setup-qemu-action@v3
|
||||
- uses: docker/setup-buildx-action@v3
|
||||
- uses: docker/login-action@v3
|
||||
with:
|
||||
username: fudaoyuanicu
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
- uses: docker/metadata-action@v5
|
||||
id: meta
|
||||
with:
|
||||
images: fudaoyuanicu/015-worker
|
||||
tags: |
|
||||
type=semver,pattern={{version}}
|
||||
type=raw,value=edge,enable=${{ contains(github.ref_name, '-') }}
|
||||
type=raw,value=latest,enable=${{ !contains(github.ref_name, '-') }}
|
||||
- name: Set build time
|
||||
id: build-time
|
||||
run: |
|
||||
echo "time=$(date +%s)" >> $GITHUB_OUTPUT
|
||||
shell: bash
|
||||
- name: build-worker
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ./worker/Dockerfile
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [build-app, build-worker]
|
||||
if: ${{ !contains(github.ref_name, '-') }}
|
||||
steps:
|
||||
- name: Send deployment webhook
|
||||
run: |
|
||||
curl -X POST http://192.168.100.5:8364/v1/update \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer helloworld"
|
||||
BIN
.github/image/0.png
vendored
BIN
.github/image/0.png
vendored
Binary file not shown.
|
Before Width: | Height: | Size: 716 KiB After Width: | Height: | Size: 804 KiB |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -22,6 +22,7 @@ logs
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
/config.yaml
|
||||
|
||||
# Serwist
|
||||
/front/public/sw*
|
||||
@@ -30,3 +31,6 @@ logs
|
||||
# backend
|
||||
**/uploads/**
|
||||
**/tmp/**
|
||||
|
||||
# worker
|
||||
pkg/mail/out/
|
||||
|
||||
16
.vscode/launch.json
vendored
Normal file
16
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
// 使用 IntelliSense 了解相关属性。
|
||||
// 悬停以查看现有属性的描述。
|
||||
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Launch Backend",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "${workspaceFolder}/backend",
|
||||
"cwd": "${workspaceFolder}"
|
||||
}
|
||||
]
|
||||
}
|
||||
41
Dockerfile
41
Dockerfile
@@ -1,34 +1,31 @@
|
||||
FROM node:22-alpine AS front-base
|
||||
WORKDIR /app
|
||||
|
||||
# Install dependencies only when needed
|
||||
FROM front-base AS front-deps
|
||||
RUN apk add --no-cache gcompat
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
RUN corepack enable pnpm && pnpm i && pnpm --filter=015-front deploy dist
|
||||
|
||||
|
||||
FROM front-base AS front-builder
|
||||
WORKDIR /app
|
||||
COPY --from=front-deps /app/dist/ .
|
||||
RUN corepack enable pnpm && pnpm build
|
||||
RUN apk add --no-cache gcompat
|
||||
ENV CI=true
|
||||
COPY . .
|
||||
RUN corepack enable pnpm && pnpm i && pnpm --filter=015-front build && pnpm --dir pkg/mail export
|
||||
|
||||
FROM golang:1.24.3 AS backend-builder
|
||||
FROM golang:1.26.3 AS backend-builder
|
||||
WORKDIR /app
|
||||
# Download Go modules
|
||||
COPY backend/go.mod backend/go.sum ./
|
||||
RUN go env -w GO111MODULE=on && go env -w GOPROXY=https://goproxy.cn,direct && go mod download
|
||||
# Copy the source code. Note the slash at the end, as explained in
|
||||
# https://docs.docker.com/engine/reference/builder/#copy
|
||||
COPY backend/ .
|
||||
# Build
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -o backend
|
||||
# Workspace and module manifests for cache
|
||||
COPY go.work go.work.sum ./
|
||||
COPY backend/ ./backend/
|
||||
COPY worker/ ./worker/
|
||||
COPY pkg/ ./pkg/
|
||||
# Inject built email templates so Go can embed them
|
||||
COPY --from=front-builder /app/pkg/mail/out/ ./pkg/mail/out/
|
||||
RUN go env -w GO111MODULE=on && go env -w GOPROXY=https://goproxy.cn,direct && \
|
||||
go mod download
|
||||
# Build from workspace root so pkg/utils, pkg/models, pkg/services resolve
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -o backend-bin ./backend
|
||||
|
||||
|
||||
FROM front-base AS runner
|
||||
ARG VERSION
|
||||
ARG BUILD_TIME
|
||||
WORKDIR /app
|
||||
RUN apk add --no-cache curl openssl
|
||||
ENV NODE_ENV production
|
||||
|
||||
@@ -36,8 +33,8 @@ RUN addgroup --system --gid 1001 nodejs
|
||||
RUN adduser --system --uid 1001 nuxtjs
|
||||
|
||||
# Only `.output` folder is needed from the build stage
|
||||
COPY --from=front-builder --chown=nuxtjs:nodejs /app/.output/ ./
|
||||
COPY --from=backend-builder /app/backend /bin/backend
|
||||
COPY --from=front-builder --chown=nuxtjs:nodejs /app/front/.output/ ./
|
||||
COPY --from=backend-builder /app/backend-bin /bin/backend
|
||||
COPY 015.sh /app/015.sh
|
||||
|
||||
# Change the port and host
|
||||
|
||||
51
README-zh.md
51
README-zh.md
@@ -39,25 +39,19 @@
|
||||
📷 **图片处理** - 图片压缩、格式转换等处理功能
|
||||
🏷️ **下载控制** - 基于 JWT 的下载令牌管理系统
|
||||
|
||||
## 截图
|
||||
## 📸 截图预览
|
||||
|
||||
选择文件上传页面
|
||||

|
||||
| 选择文件上传页面 | 输入文本上传页面 |
|
||||
| ------------------------- | ------------------------- |
|
||||
|  |  |
|
||||
|
||||
输入文本上传页面
|
||||

|
||||
| 多选文件上传 | 文件上传进度热力图 |
|
||||
| ------------------------- | ------------------------- |
|
||||
|  |  |
|
||||
|
||||
选择文件上传页面 - 支持多选文件上传
|
||||

|
||||
|
||||
文件正在上传页面 - 类似Github的展示上传进度的文件热力图
|
||||

|
||||
|
||||
文件正在上传页面 - 类似 QbitTorrent 的展示文件上传进度的进度条
|
||||

|
||||
|
||||
文件上传成功页面
|
||||

|
||||
| 文件上传进度条 | 文件上传成功页面 |
|
||||
| ------------------------- | ------------------------- |
|
||||
|  |  |
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
@@ -67,14 +61,15 @@
|
||||
- config.example.yaml
|
||||
- docker-compose.yml
|
||||
|
||||
2. 把config.example.yaml配置完成后改为config.yaml
|
||||
|
||||
2. 把 config.example.yaml 配置完成后改为 config.yaml
|
||||
|
||||
3. 启动
|
||||
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
4. 访问 `http://localhost:8080`
|
||||
|
||||
## 🏗️ 技术架构
|
||||
|
||||
@@ -119,15 +114,15 @@ docker compose up -d
|
||||
015/
|
||||
├── front/ # 前端应用 (Vue 3 + Nuxt 3)
|
||||
│ ├── components/ # Vue 组件
|
||||
│ │ ├── pages/ # 页面路由
|
||||
│ │ ├── composables/ # 组合式函数
|
||||
│ │ ├── i18n/ # 国际化文件
|
||||
│ │ └── assets/ # 静态资源
|
||||
│ └── middleware/ # 中间件
|
||||
│ ├── pages/ # 页面路由
|
||||
│ ├── composables/ # 组合式函数
|
||||
│ ├── i18n/ # 国际化文件
|
||||
│ ├── assets/ # 静态资源
|
||||
│ ├── plugins/ # Nuxt 插件
|
||||
│ └── server/ # 服务端路由
|
||||
├── backend/ # 后端服务 (Go + Echo)
|
||||
│ ├── internal/ # 内部包
|
||||
│ │ ├── controllers/ # 控制器
|
||||
│ │ ├── models/ # 数据模型
|
||||
│ │ ├── services/ # 业务逻辑
|
||||
│ │ └── utils/ # 工具函数
|
||||
│ └── middleware/ # 中间件
|
||||
@@ -136,7 +131,7 @@ docker compose up -d
|
||||
│ │ ├── tasks/ # 任务处理器
|
||||
│ │ └── utils/ # 工具函数
|
||||
│ └── middleware/ # 中间件
|
||||
└── tmp/ # 临时文件
|
||||
└── pkg/ # 公共包
|
||||
```
|
||||
|
||||
## 🔧 开发指南
|
||||
@@ -175,19 +170,19 @@ cd worker && go build -o worker .
|
||||
- 前端计算哈希和秒传
|
||||
- 并发切片上传 (使用 Web Worker)
|
||||
- 文件上传/文本上传和分享
|
||||
- 支持多文件上传
|
||||
- 上传统计页面
|
||||
- 多语言支持
|
||||
- 最大上传限制
|
||||
- 后端队列系统和 Worker 处理文件
|
||||
- 断点续传 (后端计算已上传部分并返回)
|
||||
- 图片格式转换和压缩
|
||||
|
||||
### 计划功能 🚧
|
||||
|
||||
- 断点续传 (后端计算已上传部分并返回)
|
||||
- 图片格式转换和压缩
|
||||
- 图片 OCR 复制
|
||||
- 文档转 Markdown
|
||||
- 文本翻译/总结
|
||||
- 支持上传多文件
|
||||
|
||||
## 🤝 贡献指南
|
||||
|
||||
|
||||
70
README.md
70
README.md
@@ -41,23 +41,34 @@ English | [中文](README-zh.md)
|
||||
|
||||
## 📸 Screenshots
|
||||
|
||||
File selection upload page
|
||||

|
||||
| File Selection Upload Page | Text Input Upload Page |
|
||||
| -------------------------- | ------------------------- |
|
||||
|  |  |
|
||||
|
||||
Text input upload page
|
||||

|
||||
| Multiple File Upload | Upload Progress Heatmap |
|
||||
| -------------------------- | ------------------------- |
|
||||
|  |  |
|
||||
|
||||
File selection upload page - supports multiple file uploads
|
||||

|
||||
| Upload Progress Bar | Upload Success Page |
|
||||
| -------------------------- | ------------------------- |
|
||||
|  |  |
|
||||
|
||||
File uploading page - similar to GitHub's file heatmap showing upload progress
|
||||

|
||||
## 🚀 Quick Start
|
||||
|
||||
File uploading page - similar to qBittorrent's progress bar showing file upload progress
|
||||

|
||||
### Docker
|
||||
|
||||
File upload success page
|
||||

|
||||
1. Download files
|
||||
- config.example.yaml
|
||||
- docker-compose.yml
|
||||
|
||||
2. Rename config.example.yaml to config.yaml after configuration
|
||||
|
||||
3. Start
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
4. Visit `http://localhost:8080`
|
||||
|
||||
## 🏗️ Technical Architecture
|
||||
|
||||
@@ -96,36 +107,21 @@ File upload success page
|
||||
- **Redis Cache** - Share information and file metadata caching
|
||||
- **Queue System** - Asynchronous task processing queue
|
||||
|
||||
## 🚀 Quick Start
|
||||
|
||||
### Docker
|
||||
|
||||
1. Download files
|
||||
- config.example.yaml
|
||||
- docker-compose.yml
|
||||
|
||||
2. Rename config.example.yaml to config.yaml after configuration
|
||||
|
||||
3. Start
|
||||
```bash
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
## 📁 Project Structure
|
||||
|
||||
```
|
||||
015/
|
||||
├── front/ # Frontend application (Vue 3 + Nuxt 3)
|
||||
│ ├── components/ # Vue components
|
||||
│ │ ├── pages/ # Page routes
|
||||
│ │ ├── composables/ # Composable functions
|
||||
│ │ ├── i18n/ # Internationalization files
|
||||
│ │ └── assets/ # Static assets
|
||||
│ └── middleware/ # Middleware
|
||||
│ ├── pages/ # Page routes
|
||||
│ ├── composables/ # Composable functions
|
||||
│ ├── i18n/ # Internationalization files
|
||||
│ ├── assets/ # Static assets
|
||||
│ ├── plugins/ # Nuxt plugins
|
||||
│ └── server/ # Server-side routes
|
||||
├── backend/ # Backend service (Go + Echo)
|
||||
│ ├── internal/ # Internal packages
|
||||
│ │ ├── controllers/ # Controllers
|
||||
│ │ ├── models/ # Data models
|
||||
│ │ ├── services/ # Business logic
|
||||
│ │ └── utils/ # Utility functions
|
||||
│ └── middleware/ # Middleware
|
||||
@@ -134,7 +130,7 @@ docker compose up -d
|
||||
│ │ ├── tasks/ # Task processors
|
||||
│ │ └── utils/ # Utility functions
|
||||
│ └── middleware/ # Middleware
|
||||
└── tmp/ # Temporary files
|
||||
└── pkg/ # Shared packages
|
||||
```
|
||||
|
||||
## 🔧 Development Guide
|
||||
@@ -173,19 +169,19 @@ cd worker && go build -o worker .
|
||||
- Frontend hash calculation and instant transfer
|
||||
- Concurrent chunked upload (using Web Worker)
|
||||
- File upload/text upload and sharing
|
||||
- Multiple file upload support
|
||||
- Upload statistics page
|
||||
- Multi-language support
|
||||
- Maximum upload limits
|
||||
- Backend queue system and Worker file processing
|
||||
- Resume upload (backend calculates uploaded parts and returns)
|
||||
- Image format conversion and compression
|
||||
|
||||
### Planned Features 🚧
|
||||
|
||||
- Resume upload (backend calculates uploaded parts and returns)
|
||||
- Image format conversion and compression
|
||||
- Image OCR copy
|
||||
- Document to Markdown conversion
|
||||
- Text translation/summarization
|
||||
- Support for multiple file uploads
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
|
||||
55
backend/.air.toml
Normal file
55
backend/.air.toml
Normal file
@@ -0,0 +1,55 @@
|
||||
#:schema https://json.schemastore.org/any.json
|
||||
|
||||
root = "."
|
||||
testdata_dir = "testdata"
|
||||
tmp_dir = "tmp"
|
||||
|
||||
[build]
|
||||
args_bin = []
|
||||
bin = "./tmp/main"
|
||||
cmd = "go build -o ./tmp/main ."
|
||||
delay = 1000
|
||||
entrypoint = ["./tmp/main"]
|
||||
exclude_dir = ["assets", "tmp", "vendor", "testdata"]
|
||||
exclude_file = []
|
||||
exclude_regex = ["_test.go"]
|
||||
exclude_unchanged = false
|
||||
follow_symlink = false
|
||||
full_bin = ""
|
||||
include_dir = ["../pkg"]
|
||||
include_ext = ["go", "tpl", "tmpl", "html"]
|
||||
include_file = []
|
||||
kill_delay = "0s"
|
||||
log = "build-errors.log"
|
||||
poll = false
|
||||
poll_interval = 0
|
||||
post_cmd = []
|
||||
pre_cmd = []
|
||||
rerun = false
|
||||
rerun_delay = 500
|
||||
send_interrupt = false
|
||||
stop_on_error = false
|
||||
|
||||
[color]
|
||||
app = ""
|
||||
build = "yellow"
|
||||
main = "magenta"
|
||||
runner = "green"
|
||||
watcher = "cyan"
|
||||
|
||||
[log]
|
||||
main_only = false
|
||||
silent = false
|
||||
time = false
|
||||
|
||||
[misc]
|
||||
clean_on_exit = false
|
||||
|
||||
[proxy]
|
||||
app_port = 0
|
||||
enabled = false
|
||||
proxy_port = 0
|
||||
|
||||
[screen]
|
||||
clear_on_rebuild = false
|
||||
keep_scroll = true
|
||||
@@ -1,6 +1,6 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
FROM golang:1.24.3 AS builder
|
||||
FROM golang:1.25.5 AS builder
|
||||
|
||||
# Set destination for COPY
|
||||
WORKDIR /app
|
||||
|
||||
@@ -1,56 +1,36 @@
|
||||
module backend
|
||||
|
||||
go 1.24.0
|
||||
|
||||
toolchain go1.24.3
|
||||
go 1.25.5
|
||||
|
||||
require (
|
||||
dario.cat/mergo v1.0.2
|
||||
github.com/dustin/go-humanize v1.0.1
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
github.com/gorilla/sessions v1.4.0
|
||||
github.com/hibiken/asynq v0.25.1
|
||||
github.com/labstack/echo-contrib v0.17.4
|
||||
github.com/labstack/echo/v4 v4.13.4
|
||||
github.com/hibiken/asynq v0.26.0
|
||||
github.com/labstack/echo/v5 v5.0.1
|
||||
github.com/matoous/go-nanoid/v2 v2.1.0
|
||||
github.com/redis/go-redis/v9 v9.14.0
|
||||
github.com/samber/lo v1.51.0
|
||||
github.com/samber/lo v1.53.0
|
||||
github.com/spf13/cast v1.10.0
|
||||
github.com/spf13/viper v1.21.0
|
||||
github.com/stretchr/testify v1.11.1
|
||||
go.uber.org/zap v1.27.0
|
||||
golang.org/x/crypto v0.42.0
|
||||
golang.org/x/time v0.13.0
|
||||
go.uber.org/zap v1.27.1
|
||||
golang.org/x/crypto v0.49.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gorilla/context v1.1.2 // indirect
|
||||
github.com/gorilla/securecookie v1.1.2 // indirect
|
||||
github.com/labstack/gommon v0.4.2 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/redis/go-redis/v9 v9.18.0 // indirect
|
||||
github.com/robfig/cron/v3 v3.0.1 // indirect
|
||||
github.com/sagikazarmark/locafero v0.12.0 // indirect
|
||||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/valyala/bytebufferpool v1.0.0 // indirect
|
||||
github.com/valyala/fasttemplate v1.2.2 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/net v0.44.0 // indirect
|
||||
golang.org/x/sys v0.36.0 // indirect
|
||||
golang.org/x/text v0.29.0 // indirect
|
||||
google.golang.org/protobuf v1.36.9 // indirect
|
||||
golang.org/x/net v0.52.0 // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
golang.org/x/text v0.35.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
|
||||
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
@@ -10,97 +8,68 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
|
||||
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o=
|
||||
github.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM=
|
||||
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
|
||||
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
|
||||
github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=
|
||||
github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=
|
||||
github.com/hibiken/asynq v0.25.1 h1:phj028N0nm15n8O2ims+IvJ2gz4k2auvermngh9JhTw=
|
||||
github.com/hibiken/asynq v0.25.1/go.mod h1:pazWNOLBu0FEynQRBvHA26qdIKRSmfdIfUm4HdsLmXg=
|
||||
github.com/hibiken/asynq v0.26.0 h1:1Zxr92MlDnb1Zt/QR5g2vSCqUS03i95lUfqx5X7/wrw=
|
||||
github.com/hibiken/asynq v0.26.0/go.mod h1:Qk4e57bTnWDoyJ67VkchuV6VzSM9IQW2nPvAGuDyw58=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/labstack/echo-contrib v0.17.4 h1:g5mfsrJfJTKv+F5uNKCyrjLK7js+ZW6HTjg4FnDxxgk=
|
||||
github.com/labstack/echo-contrib v0.17.4/go.mod h1:9O7ZPAHUeMGTOAfg80YqQduHzt0CzLak36PZRldYrZ0=
|
||||
github.com/labstack/echo/v4 v4.13.4 h1:oTZZW+T3s9gAu5L8vmzihV7/lkXGZuITzTQkTEhcXEA=
|
||||
github.com/labstack/echo/v4 v4.13.4/go.mod h1:g63b33BZ5vZzcIUF8AtRH40DrTlXnx4UMC8rBdndmjQ=
|
||||
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
|
||||
github.com/labstack/gommon v0.4.2/go.mod h1:QlUFxVM+SNXhDL/Z7YhocGIBYOiwB0mXm1+1bAPHPyU=
|
||||
github.com/labstack/echo/v5 v5.0.1 h1:60L7x1KMWRIJuaFqvnEHH322g+YnsMWq5Rzaeo6lcP4=
|
||||
github.com/labstack/echo/v5 v5.0.1/go.mod h1:SyvlSdObGjRXeQfCCXW/sybkZdOOQZBmpKF0bvALaeo=
|
||||
github.com/matoous/go-nanoid/v2 v2.1.0 h1:P64+dmq21hhWdtvZfEAofnvJULaRR1Yib0+PnU669bE=
|
||||
github.com/matoous/go-nanoid/v2 v2.1.0/go.mod h1:KlbGNQ+FhrUNIHUxZdL63t7tl4LaPkZNpUULS8H4uVM=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.14.0 h1:u4tNCjXOyzfgeLN+vAZaW1xUooqWDqVEsZN0U01jfAE=
|
||||
github.com/redis/go-redis/v9 v9.14.0/go.mod h1:huWgSWd8mW6+m0VPhJjSSQ+d6Nh1VICQ6Q5lHuCH/Iw=
|
||||
github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
|
||||
github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
|
||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4=
|
||||
github.com/sagikazarmark/locafero v0.12.0/go.mod h1:sZh36u/YSZ918v0Io+U9ogLYQJ9tLLBmM4eneO6WwsI=
|
||||
github.com/samber/lo v1.51.0 h1:kysRYLbHy/MB7kQZf5DSN50JHmMsNEdeY24VzJFu7wI=
|
||||
github.com/samber/lo v1.51.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
|
||||
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
|
||||
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
|
||||
github.com/samber/lo v1.53.0 h1:t975lj2py4kJPQ6haz1QMgtId2gtmfktACxIXArw3HM=
|
||||
github.com/samber/lo v1.53.0/go.mod h1:4+MXEGsJzbKGaUEQFKBq2xtfuznW9oz/WrgyzMzRoM0=
|
||||
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
|
||||
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
|
||||
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
|
||||
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo=
|
||||
github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=
|
||||
github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
|
||||
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
|
||||
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
|
||||
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
|
||||
golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I=
|
||||
golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
|
||||
golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
||||
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
||||
golang.org/x/time v0.13.0 h1:eUlYslOIt32DgYD6utsuUeHs4d7AsEYLuIAdg7FlYgI=
|
||||
golang.org/x/time v0.13.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
||||
google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw=
|
||||
google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
|
||||
go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=
|
||||
go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
|
||||
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
|
||||
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
|
||||
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
|
||||
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"backend/internal/models"
|
||||
"backend/internal/utils"
|
||||
"encoding/json"
|
||||
"pkg/models"
|
||||
u "pkg/utils"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
"github.com/samber/lo"
|
||||
)
|
||||
|
||||
func GetAbout(c echo.Context) error {
|
||||
maxStorageSize, err := utils.GetFileSize(utils.GetEnv("upload.maximum"))
|
||||
func GetAbout(c *echo.Context) error {
|
||||
maxStorageSize, err := u.GetFileSize(u.GetEnv("upload.maximum"))
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
@@ -30,12 +31,12 @@ func GetAbout(c echo.Context) error {
|
||||
}, 0)
|
||||
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"bg_url": utils.GetEnv("about.bg_url"),
|
||||
"content": utils.GetEnvMapString("about.content"),
|
||||
"email": utils.GetEnv("about.email"),
|
||||
"name": utils.GetEnv("about.name"),
|
||||
"url": utils.GetEnv("about.url"),
|
||||
"avatar": utils.GetEnv("about.avatar"),
|
||||
"bg_url": u.GetEnv("about.bg_url"),
|
||||
"content": u.GetEnvMap("about.content"),
|
||||
"email": u.GetEnv("about.email"),
|
||||
"name": u.GetEnv("about.name"),
|
||||
"url": u.GetEnv("about.url"),
|
||||
"avatar": u.GetEnv("about.avatar"),
|
||||
"file": map[string]any{
|
||||
"maximun": maxStorageSize,
|
||||
"current": currentFileSize,
|
||||
|
||||
@@ -2,20 +2,53 @@ package controllers
|
||||
|
||||
import (
|
||||
"backend/internal/utils"
|
||||
u "pkg/utils"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
"github.com/samber/lo"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
func GetConfig(c echo.Context) error {
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"site_title": utils.GetEnvMapString("site.title"),
|
||||
"site_desc": utils.GetEnvMapString("site.desc"),
|
||||
"site_url": utils.GetEnv("site.url"),
|
||||
"site_icon": utils.GetEnvWithDefault("site.icon", "/logo.png"),
|
||||
"site_bg_url": utils.GetEnvWithDefault("site.bg_url", "https://img.fudaoyuan.icu/api/1/random/?scale_min=1.5&webp=true&md=false&format=302"),
|
||||
"version": utils.GetEnvWithDefault("VERSION", "dev"),
|
||||
"build_time": cast.ToInt(utils.GetEnvWithDefault("BUILD_TIME", cast.ToString(time.Now().Unix()))),
|
||||
var defaultEnabledFeatures = []string{
|
||||
"file-share",
|
||||
"text-share",
|
||||
}
|
||||
|
||||
func getEnabledKeys(config map[string]any) []string {
|
||||
return lo.FilterMap(lo.Entries(config), func(e lo.Entry[string, any], _ int) (string, bool) {
|
||||
node, ok := e.Value.(map[string]any)
|
||||
return e.Key, ok && cast.ToBool(node["enabled"])
|
||||
})
|
||||
}
|
||||
|
||||
func GetConfig(c *echo.Context) error {
|
||||
featureConfig := u.GetEnvMap("features")
|
||||
defaultFeatureConfig := lo.SliceToMap(defaultEnabledFeatures, func(item string) (string, any) {
|
||||
return item, map[string]any{
|
||||
"enabled": true,
|
||||
}
|
||||
})
|
||||
|
||||
featureConfig = lo.Assign(defaultFeatureConfig, featureConfig)
|
||||
features := getEnabledKeys(featureConfig)
|
||||
// textTranslateProviderConfig := u.GetEnvMap("features.text-translate.provider")
|
||||
// textTranslateProviders := getEnabledKeys(textTranslateProviderConfig)
|
||||
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"site_title": u.GetEnvMap("site.title"),
|
||||
"site_desc": u.GetEnvMap("site.desc"),
|
||||
"site_url": u.GetEnv("site.url"),
|
||||
"site_icon": u.GetEnvWithDefault("site.icon", "/logo.png"),
|
||||
"site_bg_url": u.GetEnvWithDefault("site.bg_url", "https://img.fudaoyuan.icu/api/1/random/?scale_min=1.5&webp=true&md=false&format=302"),
|
||||
"site_enable_bg": cast.ToBool(u.GetEnvWithDefault("site.enable_bg", "true")),
|
||||
"version": u.GetEnvWithDefault("VERSION", "dev"),
|
||||
"build_time": cast.ToInt(u.GetEnvWithDefault("BUILD_TIME", cast.ToString(time.Now().Unix()))),
|
||||
"features": features,
|
||||
"config": map[string]any{
|
||||
// "text-translate": map[string]any{
|
||||
// "provider": textTranslateProviders,
|
||||
// },
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"backend/internal/models"
|
||||
"backend/internal/utils"
|
||||
"backend/middleware"
|
||||
"errors"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"pkg/models"
|
||||
u "pkg/utils"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/labstack/echo/v5"
|
||||
"github.com/samber/lo"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
|
||||
@@ -18,31 +21,29 @@ type DownloadShareClaims struct {
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func DownloadShare(c echo.Context) error {
|
||||
cc := c.(*middleware.CustomContext)
|
||||
token := cc.FormValue("token")
|
||||
func DownloadShare(c *echo.Context) error {
|
||||
token := c.FormValue("token")
|
||||
if token == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("缺少token"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
claims := DownloadShareClaims{}
|
||||
t, err := jwt.ParseWithClaims(token, &claims, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(utils.GetEnv("share.download_secret")), nil
|
||||
return []byte(u.GetEnv("share.download_secret")), nil
|
||||
})
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
if err != nil || !t.Valid {
|
||||
return utils.HTTPErrorHandler(c, lo.Ternary(err != nil, err, ErrInvalidRequest))
|
||||
}
|
||||
if !t.Valid {
|
||||
return utils.HTTPErrorHandler(c, errors.New("token格式错误"))
|
||||
shareInfo, err := models.GetRedisShareInfo(claims.ShareId)
|
||||
if err != nil || shareInfo == nil {
|
||||
return utils.HTTPErrorHandler(c, lo.Ternary(err != nil, err, ErrShareNotFound))
|
||||
}
|
||||
shareInfo, _ := models.GetRedisShareInfo(claims.ShareId)
|
||||
|
||||
if shareInfo.Type == models.ShareTypeFile {
|
||||
fileInfo, _ := models.GetRedisFileInfo(shareInfo.Data)
|
||||
uploadPath, err := utils.GetUploadDirPath()
|
||||
uploadPath, err := u.GetUploadDirPath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return cc.Attachment(fmt.Sprintf("%s/%s", uploadPath, utils.GetFileId(fileInfo.FileHash, fileInfo.FileSize)), shareInfo.FileName)
|
||||
return c.Attachment(fmt.Sprintf("%s/%s", uploadPath, u.GetFileId(fileInfo.FileHash, fileInfo.FileSize)), shareInfo.FileName)
|
||||
}
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"data": shareInfo.Data,
|
||||
@@ -54,16 +55,14 @@ type VaildateShareProps struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func VaildateShare(c echo.Context) error {
|
||||
cc := c.(*middleware.CustomContext)
|
||||
|
||||
func VaildateShare(c *echo.Context) error {
|
||||
r := new(VaildateShareProps)
|
||||
if err := cc.Bind(r); err != nil {
|
||||
if err := c.Bind(r); err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
if r.ShareId == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("缺少分享ID"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
|
||||
shareInfo, err := models.GetRedisShareInfo(r.ShareId)
|
||||
@@ -71,79 +70,89 @@ func VaildateShare(c echo.Context) error {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if shareInfo == nil {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享不存在"))
|
||||
return utils.HTTPErrorHandler(c, ErrShareNotFound)
|
||||
}
|
||||
if shareInfo.Password != "" {
|
||||
if r.Password == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("缺少分享密码"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
hash, err := utils.GeneratePasswordHash(r.Password)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if hash != shareInfo.Password {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享密码错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidSharePassword)
|
||||
}
|
||||
}
|
||||
// 如果下载次数为0,则设置为-1 防止空值问题
|
||||
if shareInfo.ViewNum < 1 {
|
||||
return utils.HTTPErrorHandler(c, errors.New("下载次数不足"))
|
||||
}
|
||||
downloadWindow := utils.GetEnvWithDefault("share.download_window", "12")
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, DownloadShareClaims{
|
||||
ShareId: r.ShareId,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(cast.ToDuration(downloadWindow + "h"))),
|
||||
},
|
||||
})
|
||||
return u.WithLocker(context.Background(), "015:shareInfoMap:"+r.ShareId, 0, func(ctx context.Context) error {
|
||||
shareInfo, err := models.GetRedisShareInfo(r.ShareId)
|
||||
if err != nil || shareInfo == nil {
|
||||
return utils.HTTPErrorHandler(c, lo.Ternary(err != nil, err, ErrShareNotFound))
|
||||
}
|
||||
if shareInfo.ViewNum < 1 {
|
||||
return utils.HTTPErrorHandler(c, ErrInsufficientDownloadQuota)
|
||||
}
|
||||
downloadWindow := u.GetEnvWithDefault("share.download_window", "12")
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, DownloadShareClaims{
|
||||
ShareId: r.ShareId,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(cast.ToDuration(downloadWindow + "h"))),
|
||||
},
|
||||
})
|
||||
|
||||
// Sign and get the complete encoded token as a string using the secret
|
||||
downloadToken, err := token.SignedString([]byte(utils.GetEnv("share.download_secret")))
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if shareInfo.Type == models.ShareTypeFile {
|
||||
fileInfo, err := models.GetRedisFileInfo(shareInfo.Data)
|
||||
// Sign and get the complete encoded token as a string using the secret
|
||||
downloadToken, err := token.SignedString([]byte(u.GetEnv("share.download_secret")))
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if fileInfo == nil {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享文件不存在"))
|
||||
if shareInfo.Type == models.ShareTypeFile {
|
||||
fileInfo, err := models.GetRedisFileInfo(shareInfo.Data)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if fileInfo == nil {
|
||||
return utils.HTTPErrorHandler(c, ErrShareFileNotFound)
|
||||
}
|
||||
if fileInfo.FileType != models.FileTypeUpload {
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidShareFileState)
|
||||
}
|
||||
}
|
||||
if fileInfo.FileType != models.FileTypeUpload {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享文件状态错误"))
|
||||
// download_nums 必须放在创建token的时候减掉,不然多线程下载会导致多次减掉
|
||||
_, err = models.SetRedisShareInfo(r.ShareId, func(shareInfo *models.RedisShareInfo) *models.RedisShareInfo {
|
||||
shareInfo.ViewNum -= 1
|
||||
return shareInfo
|
||||
})
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
}
|
||||
// download_nums 必须放在创建token的时候减掉,不然多线程下载会导致多次减掉
|
||||
latestViewNum := shareInfo.ViewNum - 1
|
||||
// 如果下载次数为0,则设置为-1 防止空值问题
|
||||
if latestViewNum < 1 {
|
||||
latestViewNum = -1
|
||||
}
|
||||
models.SetRedisShareInfo(r.ShareId, models.RedisShareInfo{
|
||||
ViewNum: latestViewNum,
|
||||
})
|
||||
|
||||
// 统计分享数
|
||||
currentDate := time.Now().Format("2006-01-02")
|
||||
statData, _ := models.GetRedisStat(currentDate)
|
||||
if statData == nil {
|
||||
statData = &models.StatData{
|
||||
FileSize: 0,
|
||||
FileNum: 0,
|
||||
ShareNum: 0,
|
||||
DownloadNum: 0,
|
||||
// 统计分享数
|
||||
currentDate := time.Now().Format("2006-01-02")
|
||||
_, err = models.SetRedisStat(currentDate, func(stat *models.StatData) *models.StatData {
|
||||
stat.DownloadNum += 1
|
||||
return stat
|
||||
})
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
}
|
||||
statData.DownloadNum += 1
|
||||
models.SetRedisStat(currentDate, *statData)
|
||||
|
||||
if shareInfo.Type == models.ShareTypeFile {
|
||||
if len(shareInfo.NotifyEmails) > 0 || len(shareInfo.NotifyWebhooks) > 0 {
|
||||
payload, err := json.Marshal(map[string]string{
|
||||
"share_id": r.ShareId,
|
||||
"ip": c.RealIP(),
|
||||
})
|
||||
if err == nil {
|
||||
_, _ = u.GetQueueClient().Enqueue(asynq.NewTask("share:notify", payload))
|
||||
}
|
||||
}
|
||||
|
||||
if shareInfo.Type == models.ShareTypeFile {
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"token": downloadToken,
|
||||
})
|
||||
}
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"token": downloadToken,
|
||||
})
|
||||
}
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"token": downloadToken,
|
||||
})
|
||||
}
|
||||
|
||||
30
backend/internal/controllers/errors.go
Normal file
30
backend/internal/controllers/errors.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package controllers
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
// 通用错误(参数校验失败)
|
||||
ErrInvalidRequest = errors.New("InvalidRequest") // 调用接口参数错误
|
||||
|
||||
// 任务相关
|
||||
ErrTaskNotFound = errors.New("TaskNotFound") // 任务不存在
|
||||
ErrTaskExpired = errors.New("TaskExpired") // 任务已过期
|
||||
|
||||
// 文件上传相关
|
||||
ErrInsufficientStorage = errors.New("InsufficientStorage") // 存储空间不足
|
||||
ErrUploadTaskExpired = errors.New("UploadTaskExpired") // 上传任务已过期
|
||||
ErrInvalidUploadTaskState = errors.New("InvalidUploadTaskState") // 上传任务状态错误
|
||||
ErrInvalidFileSliceIndex = errors.New("InvalidFileSliceIndex") // 文件切片索引错误
|
||||
ErrInvalidFileSliceSize = errors.New("InvalidFileSliceSize") // 文件切片大小错误
|
||||
ErrIncompleteFileSlices = errors.New("IncompleteFileSlices") // 文件切片不完整
|
||||
ErrFileHashMismatch = errors.New("FileHashMismatch") // 文件Hash不一致
|
||||
|
||||
// 分享相关
|
||||
ErrShareFileNotFound = errors.New("ShareFileNotFound") // 分享文件不存在
|
||||
ErrInvalidShareFileState = errors.New("InvalidShareFileState") // 分享文件状态错误
|
||||
ErrShareNotFound = errors.New("ShareNotFound") // 分享不存在
|
||||
|
||||
// 下载相关
|
||||
ErrInvalidSharePassword = errors.New("InvalidSharePassword") // 分享密码错误
|
||||
ErrInsufficientDownloadQuota = errors.New("InsufficientDownloadQuota") // 下载次数不足
|
||||
)
|
||||
@@ -1,22 +1,21 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"backend/internal/models"
|
||||
"backend/internal/services"
|
||||
"backend/internal/utils"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"mime/multipart"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"pkg/models"
|
||||
s "pkg/services"
|
||||
u "pkg/utils"
|
||||
"time"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
func CreateUploadTask(c echo.Context) error {
|
||||
func CreateUploadTask(c *echo.Context) error {
|
||||
// cc := c.(*middleware.CustomContext)
|
||||
r := new(models.FileInfo)
|
||||
if err := c.Bind(r); err != nil {
|
||||
@@ -24,12 +23,23 @@ func CreateUploadTask(c echo.Context) error {
|
||||
}
|
||||
|
||||
if r.FileSize == 0 || r.MimeType == "" || r.FileHash == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("调用接口参数错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
fileId := u.GetFileId(r.FileHash, r.FileSize)
|
||||
fileInfo, err := models.GetRedisFileInfo(fileId)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
fileId := utils.GetFileId(r.FileHash, r.FileSize)
|
||||
fileInfo, _ := models.GetRedisFileInfo(fileId)
|
||||
|
||||
if fileInfo != nil {
|
||||
uploadPath, err := u.GetUploadDirPath()
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
sliceList, err := services.GetFileSliceList(fileId, uploadPath)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"size": fileInfo.FileSize,
|
||||
"mime_type": fileInfo.MimeType,
|
||||
@@ -38,9 +48,10 @@ func CreateUploadTask(c echo.Context) error {
|
||||
"expire": fileInfo.Expire,
|
||||
"id": fileId,
|
||||
"chunk_size": fileInfo.ChunkSize,
|
||||
"chunks": sliceList,
|
||||
})
|
||||
}
|
||||
maxStorageSize, err := utils.GetFileSize(utils.GetEnv("upload.maximum"))
|
||||
maxStorageSize, err := u.GetFileSize(u.GetEnv("upload.maximum"))
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
@@ -58,7 +69,7 @@ func CreateUploadTask(c echo.Context) error {
|
||||
totalSize += fileInfo.FileSize
|
||||
}
|
||||
if totalSize+r.FileSize > int64(maxStorageSize) {
|
||||
return utils.HTTPErrorHandler(c, errors.New("存储空间不足"))
|
||||
return utils.HTTPErrorHandler(c, ErrInsufficientStorage)
|
||||
}
|
||||
|
||||
ChunkSize := int64(0.25 * 1024 * 1024)
|
||||
@@ -66,43 +77,33 @@ func CreateUploadTask(c echo.Context) error {
|
||||
for r.FileSize/ChunkSize > 1000 {
|
||||
ChunkSize *= 2
|
||||
}
|
||||
uploadTaskExpire := int64(3600)
|
||||
newFileInfo := models.RedisFileInfo{
|
||||
FileType: models.FileTypeInit,
|
||||
FileInfo: models.FileInfo{
|
||||
redisFileInfo, err := models.SetRedisFileInfo(fileId, func(fileInfo *models.RedisFileInfo) *models.RedisFileInfo {
|
||||
fileInfo.FileType = models.FileTypeInit
|
||||
fileInfo.FileInfo = models.FileInfo{
|
||||
FileSize: r.FileSize,
|
||||
MimeType: r.MimeType,
|
||||
FileHash: r.FileHash,
|
||||
ChunkSize: ChunkSize,
|
||||
},
|
||||
CreatedAt: time.Now().Unix(),
|
||||
Expire: uploadTaskExpire,
|
||||
}
|
||||
err = models.SetRedisFileInfo(fileId, newFileInfo)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
client := utils.GetQueueClient()
|
||||
json, err := json.Marshal(map[string]any{
|
||||
"file_id": fileId,
|
||||
}
|
||||
return fileInfo
|
||||
})
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
_, err = client.Enqueue(asynq.NewTask("file:remove", json), asynq.ProcessIn(time.Duration(uploadTaskExpire)*time.Second))
|
||||
|
||||
err = s.SetFileRemoveTask(fileId, time.Duration(redisFileInfo.Expire)*time.Second)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"size": newFileInfo.FileSize,
|
||||
"mime_type": newFileInfo.MimeType,
|
||||
"hash": newFileInfo.FileHash,
|
||||
"type": newFileInfo.FileType,
|
||||
"expire": newFileInfo.Expire,
|
||||
"size": redisFileInfo.FileSize,
|
||||
"mime_type": redisFileInfo.MimeType,
|
||||
"hash": redisFileInfo.FileHash,
|
||||
"type": redisFileInfo.FileType,
|
||||
"expire": redisFileInfo.Expire,
|
||||
"id": fileId,
|
||||
"chunk_size": newFileInfo.ChunkSize,
|
||||
"chunk_size": redisFileInfo.ChunkSize,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -112,14 +113,14 @@ type UploadFileSliceProps struct {
|
||||
FileSlice *multipart.FileHeader `form:"file"`
|
||||
}
|
||||
|
||||
func UploadFileSlice(c echo.Context) error {
|
||||
func UploadFileSlice(c *echo.Context) error {
|
||||
r := new(UploadFileSliceProps)
|
||||
if err := c.Bind(r); err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
if r.FileId == "" || r.FileIndex == 0 || r.FileSlice == nil {
|
||||
return utils.HTTPErrorHandler(c, errors.New("调用接口参数错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
fileInfo, err := models.GetRedisFileInfo(r.FileId)
|
||||
if err != nil {
|
||||
@@ -128,18 +129,18 @@ func UploadFileSlice(c echo.Context) error {
|
||||
|
||||
now := time.Now().Unix()
|
||||
if fileInfo.CreatedAt+fileInfo.Expire < now {
|
||||
return utils.HTTPErrorHandler(c, errors.New("上传任务已过期"))
|
||||
return utils.HTTPErrorHandler(c, ErrUploadTaskExpired)
|
||||
}
|
||||
|
||||
if fileInfo.FileType != models.FileTypeInit {
|
||||
return utils.HTTPErrorHandler(c, errors.New("上传任务状态错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidUploadTaskState)
|
||||
}
|
||||
if r.FileIndex > ((fileInfo.FileSize / fileInfo.ChunkSize) + 1) {
|
||||
return utils.HTTPErrorHandler(c, errors.New("文件切片索引错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidFileSliceIndex)
|
||||
}
|
||||
|
||||
if r.FileSlice.Size > fileInfo.ChunkSize {
|
||||
return utils.HTTPErrorHandler(c, errors.New("文件切片大小错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidFileSliceSize)
|
||||
}
|
||||
|
||||
// 打开文件
|
||||
@@ -147,9 +148,14 @@ func UploadFileSlice(c echo.Context) error {
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
defer file.Close()
|
||||
defer file.Close() //nolint:errcheck
|
||||
|
||||
if err := services.CreateFileSlice(file, r.FileId, r.FileIndex); err != nil {
|
||||
uploadPath, err := u.GetUploadDirPath()
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
if _, err := services.CreateFileSlice(r.FileId, uploadPath, file, r.FileIndex); err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
@@ -162,14 +168,14 @@ type FinishUploadTaskProps struct {
|
||||
FileId string `json:"id"`
|
||||
}
|
||||
|
||||
func FinishUploadTask(c echo.Context) error {
|
||||
func FinishUploadTask(c *echo.Context) error {
|
||||
r := new(FinishUploadTaskProps)
|
||||
if err := c.Bind(r); err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
if r.FileId == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("文件ID不能为空"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
|
||||
fileInfo, err := models.GetRedisFileInfo(r.FileId)
|
||||
@@ -178,64 +184,68 @@ func FinishUploadTask(c echo.Context) error {
|
||||
}
|
||||
|
||||
if fileInfo.FileType != models.FileTypeInit {
|
||||
return utils.HTTPErrorHandler(c, errors.New("上传任务状态错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidUploadTaskState)
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
if fileInfo.CreatedAt+fileInfo.Expire < now {
|
||||
return utils.HTTPErrorHandler(c, errors.New("上传任务已过期"))
|
||||
return utils.HTTPErrorHandler(c, ErrUploadTaskExpired)
|
||||
}
|
||||
|
||||
// 合并文件切片
|
||||
uploadPath, _ := utils.GetUploadDirPath()
|
||||
slicesPath := filepath.Join(uploadPath, fmt.Sprintf("%s_%s", r.FileId, "tmp"))
|
||||
uploadPath, err := u.GetUploadDirPath()
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
fileSliceList, err := services.GetFileSliceList(r.FileId, uploadPath)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
if len(fileSliceList) != int(math.Ceil(float64(fileInfo.FileSize)/float64(fileInfo.ChunkSize))) {
|
||||
return utils.HTTPErrorHandler(c, ErrIncompleteFileSlices)
|
||||
}
|
||||
|
||||
// 最终合并后的文件路径
|
||||
mergeFilePath := filepath.Join(uploadPath, r.FileId)
|
||||
if err := services.MergeFileSlices(slicesPath, mergeFilePath); err != nil {
|
||||
mergeFilePath, err := services.MergeFileSlices(r.FileId, uploadPath)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
// 计算文件MD5
|
||||
// 计算文件SHA1
|
||||
file, err := os.Open(mergeFilePath)
|
||||
if err != nil {
|
||||
file.Close()
|
||||
os.Remove(mergeFilePath)
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
defer file.Close() //nolint:errcheck
|
||||
|
||||
file_hash, err := u.GetFileSHA1(file)
|
||||
if err != nil || file_hash != fileInfo.FileHash {
|
||||
defer os.Remove(mergeFilePath) //nolint:errcheck
|
||||
if err == nil {
|
||||
return utils.HTTPErrorHandler(c, ErrFileHashMismatch)
|
||||
}
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
file_hash, err := utils.GetFileMd5(file)
|
||||
|
||||
if err != nil {
|
||||
file.Close()
|
||||
os.Remove(mergeFilePath)
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
|
||||
if file_hash != fileInfo.FileHash {
|
||||
file.Close()
|
||||
os.Remove(mergeFilePath)
|
||||
return utils.HTTPErrorHandler(c, errors.New("文件MD5不一致"))
|
||||
}
|
||||
defer file.Close()
|
||||
// 更新文件信息
|
||||
models.SetRedisFileInfo(r.FileId, models.RedisFileInfo{
|
||||
FileType: models.FileTypeUpload,
|
||||
fileInfo, err = models.SetRedisFileInfo(r.FileId, func(fileInfo *models.RedisFileInfo) *models.RedisFileInfo {
|
||||
fileInfo.FileType = models.FileTypeUpload
|
||||
return fileInfo
|
||||
})
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
// 统计
|
||||
currentDate := time.Now().Format("2006-01-02")
|
||||
statData, _ := models.GetRedisStat(currentDate)
|
||||
if statData == nil {
|
||||
statData = &models.StatData{
|
||||
FileSize: 0,
|
||||
FileNum: 0,
|
||||
ShareNum: 0,
|
||||
DownloadNum: 0,
|
||||
}
|
||||
_, err = models.SetRedisStat(currentDate, func(stat *models.StatData) *models.StatData {
|
||||
stat.FileSize += fileInfo.FileSize
|
||||
stat.FileNum += 1
|
||||
return stat
|
||||
})
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
statData.FileSize += fileInfo.FileSize
|
||||
statData.FileNum += 1
|
||||
models.SetRedisStat(currentDate, *statData)
|
||||
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"size": fileInfo.FileSize,
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"backend/internal/models"
|
||||
"backend/internal/utils"
|
||||
"backend/middleware"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"pkg/models"
|
||||
u "pkg/utils"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
gonanoid "github.com/matoous/go-nanoid/v2"
|
||||
"github.com/spf13/cast"
|
||||
)
|
||||
@@ -24,28 +23,31 @@ type CreateShareProps struct {
|
||||
}
|
||||
|
||||
type ShareConfig struct {
|
||||
ExpireAt int `json:"expire_time"` // 分钟
|
||||
ViewNum int64 `json:"download_nums"`
|
||||
HasPassword bool `json:"has_password"`
|
||||
Password string `json:"password"`
|
||||
HasNotify bool `json:"has_notify"`
|
||||
NotifyEmail []string `json:"notify_email"`
|
||||
HasPickupCode bool `json:"has_pickup_code"`
|
||||
ExpireAt int `json:"expire_time"` // 分钟
|
||||
ViewNum int64 `json:"download_nums"`
|
||||
HasPassword bool `json:"has_password"`
|
||||
Password string `json:"password"`
|
||||
HasNotify bool `json:"has_notify"`
|
||||
NotifyTypes []string `json:"notify_types"`
|
||||
NotifyEmails []string `json:"notify_emails"`
|
||||
NotifyWebhooks []models.NotifyWebhook `json:"notify_webhooks"`
|
||||
Locale string `json:"locale"`
|
||||
HasPickupCode bool `json:"has_pickup_code"`
|
||||
}
|
||||
|
||||
func CreateShareInfo(c echo.Context) error {
|
||||
cc := c.(*middleware.CustomContext)
|
||||
func CreateShareInfo(c *echo.Context) error {
|
||||
owner, _ := echo.ContextGet[string](c, "auth")
|
||||
|
||||
r := new(CreateShareProps)
|
||||
if err := cc.Bind(r); err != nil {
|
||||
if err := c.Bind(r); err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if r.Config.ExpireAt < 1 {
|
||||
return utils.HTTPErrorHandler(c, errors.New("非法的分享过期时间"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
ExpireTime := time.Now().Add(time.Duration(r.Config.ExpireAt) * time.Minute)
|
||||
if r.Data == "" || (r.Type != models.ShareTypeFile && r.Type != models.ShareTypeText) || ExpireTime.Before(time.Now()) || r.Config.ViewNum < 1 {
|
||||
return utils.HTTPErrorHandler(c, errors.New("调用接口参数错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
|
||||
id, err := gonanoid.New()
|
||||
@@ -59,10 +61,10 @@ func CreateShareInfo(c echo.Context) error {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if fileInfo == nil {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享文件不存在"))
|
||||
return utils.HTTPErrorHandler(c, ErrShareFileNotFound)
|
||||
}
|
||||
if fileInfo.FileType != models.FileTypeUpload {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享文件状态错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidShareFileState)
|
||||
}
|
||||
}
|
||||
password := ""
|
||||
@@ -74,17 +76,45 @@ func CreateShareInfo(c echo.Context) error {
|
||||
password = hash
|
||||
}
|
||||
|
||||
models.SetRedisShareInfo(id, models.RedisShareInfo{
|
||||
Data: r.Data,
|
||||
Type: r.Type,
|
||||
CreatedAt: time.Now().Unix(),
|
||||
Owner: cc.Auth.(string),
|
||||
ViewNum: r.Config.ViewNum,
|
||||
Password: password,
|
||||
// NotifyEmail: r.Config.NotifyEmail,
|
||||
FileName: r.FileName,
|
||||
ExpireAt: ExpireTime.Unix(),
|
||||
var notifyEmails []string
|
||||
var notifyWebhooks []models.NotifyWebhook
|
||||
if r.Config.HasNotify {
|
||||
hasEmail, hasWebhook := false, false
|
||||
for _, nt := range r.Config.NotifyTypes {
|
||||
switch nt {
|
||||
case "email":
|
||||
hasEmail = true
|
||||
case "webhook":
|
||||
hasWebhook = true
|
||||
default:
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
}
|
||||
if hasEmail {
|
||||
notifyEmails = r.Config.NotifyEmails
|
||||
}
|
||||
if hasWebhook {
|
||||
notifyWebhooks = r.Config.NotifyWebhooks
|
||||
}
|
||||
}
|
||||
|
||||
_, err = models.SetRedisShareInfo(id, func(shareInfo *models.RedisShareInfo) *models.RedisShareInfo {
|
||||
shareInfo.Data = r.Data
|
||||
shareInfo.Type = r.Type
|
||||
shareInfo.CreatedAt = time.Now().Unix()
|
||||
shareInfo.Owner = owner
|
||||
shareInfo.ViewNum = r.Config.ViewNum
|
||||
shareInfo.Password = password
|
||||
shareInfo.FileName = r.FileName
|
||||
shareInfo.NotifyEmails = notifyEmails
|
||||
shareInfo.NotifyWebhooks = notifyWebhooks
|
||||
shareInfo.Locale = r.Config.Locale
|
||||
shareInfo.ExpireAt = ExpireTime.Unix()
|
||||
return shareInfo
|
||||
})
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
var pickupCode string
|
||||
if r.Config.HasPickupCode {
|
||||
for {
|
||||
@@ -106,14 +136,17 @@ func CreateShareInfo(c echo.Context) error {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
shareIDs = append(shareIDs, id)
|
||||
models.SetRedisFileShareRelational(r.Data, shareIDs)
|
||||
client := utils.GetQueueClient()
|
||||
err = models.SetRedisFileShareRelational(r.Data, shareIDs)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
client := u.GetQueueClient()
|
||||
json, err := json.Marshal(map[string]any{"share_id": id, "file_id": r.Data})
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
// 这里延时分享过期时间基础上加下载窗口期后1小时删除,防止用户过期前几分钟才开始下载,下载一半文件不见了
|
||||
downloadWindow := utils.GetEnvWithDefault("share.download_window", "12")
|
||||
downloadWindow := u.GetEnvWithDefault("share.download_window", "12")
|
||||
deleteTime := time.Duration(r.Config.ExpireAt)*time.Minute + cast.ToDuration(downloadWindow+"h") + 1*time.Hour
|
||||
_, err = client.Enqueue(asynq.NewTask("share:remove", json), asynq.ProcessIn(deleteTime))
|
||||
if err != nil {
|
||||
@@ -123,17 +156,13 @@ func CreateShareInfo(c echo.Context) error {
|
||||
|
||||
// 统计分享数
|
||||
currentDate := time.Now().Format("2006-01-02")
|
||||
statData, _ := models.GetRedisStat(currentDate)
|
||||
if statData == nil {
|
||||
statData = &models.StatData{
|
||||
FileSize: 0,
|
||||
FileNum: 0,
|
||||
ShareNum: 0,
|
||||
DownloadNum: 0,
|
||||
}
|
||||
_, err = models.SetRedisStat(currentDate, func(stat *models.StatData) *models.StatData {
|
||||
stat.ShareNum += 1
|
||||
return stat
|
||||
})
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
statData.ShareNum += 1
|
||||
models.SetRedisStat(currentDate, *statData)
|
||||
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"id": id,
|
||||
@@ -148,11 +177,10 @@ type GetShareProps struct {
|
||||
ShareId string `param:"id"`
|
||||
}
|
||||
|
||||
func GetShareInfo(c echo.Context) error {
|
||||
cc := c.(*middleware.CustomContext)
|
||||
shareId := cc.Param("id")
|
||||
func GetShareInfo(c *echo.Context) error {
|
||||
shareId := c.Param("id")
|
||||
if shareId == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("缺少分享ID"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
|
||||
shareInfo, err := models.GetRedisShareInfo(shareId)
|
||||
@@ -160,7 +188,7 @@ func GetShareInfo(c echo.Context) error {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if shareInfo == nil || shareInfo.ViewNum < 1 {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享不存在"))
|
||||
return utils.HTTPErrorHandler(c, ErrShareNotFound)
|
||||
}
|
||||
|
||||
if shareInfo.Type == models.ShareTypeFile {
|
||||
@@ -169,10 +197,10 @@ func GetShareInfo(c echo.Context) error {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if fileInfo == nil {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享文件不存在"))
|
||||
return utils.HTTPErrorHandler(c, ErrShareFileNotFound)
|
||||
}
|
||||
if fileInfo.FileType != models.FileTypeUpload {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享文件状态错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidShareFileState)
|
||||
}
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"id": shareId,
|
||||
@@ -198,18 +226,17 @@ func GetShareInfo(c echo.Context) error {
|
||||
})
|
||||
}
|
||||
|
||||
func GetShareByPickupCode(c echo.Context) error {
|
||||
cc := c.(*middleware.CustomContext)
|
||||
pickupCode := cc.Param("code")
|
||||
func GetShareByPickupCode(c *echo.Context) error {
|
||||
pickupCode := c.Param("code")
|
||||
if pickupCode == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("缺少提取码"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
shareId, err := models.GetRedisPickupData(strings.ToUpper(pickupCode))
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if shareId == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("分享不存在"))
|
||||
return utils.HTTPErrorHandler(c, ErrShareNotFound)
|
||||
}
|
||||
return utils.HTTPSuccessHandler(c, map[string]any{
|
||||
"share_id": shareId,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"backend/internal/models"
|
||||
"backend/internal/utils"
|
||||
"encoding/json"
|
||||
"pkg/models"
|
||||
u "pkg/utils"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -26,7 +27,7 @@ type QueueChartData struct {
|
||||
Failed int `json:"failed"`
|
||||
}
|
||||
|
||||
func GetStat(c echo.Context) error {
|
||||
func GetStat(c *echo.Context) error {
|
||||
statInfoMap, err := models.GetRedisStatAll()
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
@@ -47,7 +48,7 @@ func GetStat(c echo.Context) error {
|
||||
}
|
||||
}
|
||||
|
||||
queueInspector := utils.GetQueueInspector()
|
||||
queueInspector := u.GetQueueInspector()
|
||||
queues, err := queueInspector.History("default", QueueHistoryDays)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
|
||||
@@ -1,38 +1,37 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"backend/internal/models"
|
||||
"backend/internal/controllers/task"
|
||||
"backend/internal/utils"
|
||||
"backend/middleware"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"pkg/models"
|
||||
u "pkg/utils"
|
||||
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
type GenCompressImageRequest struct {
|
||||
FileId string `json:"file_id"`
|
||||
var handleTaskMap = map[string]func(c *echo.Context) ([]byte, error){
|
||||
"image:compress": task.HandleImageCompress,
|
||||
"image:convert": task.HandleImageConvert,
|
||||
"text:translate": task.HandleTextTranslate,
|
||||
}
|
||||
|
||||
func GenCompressImage(c echo.Context) error {
|
||||
cc := c.(*middleware.CustomContext)
|
||||
r := new(GenCompressImageRequest)
|
||||
if err := cc.Bind(r); err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
func CreateTask(c *echo.Context) error {
|
||||
taskType := c.Param("type")
|
||||
if taskType == "" {
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
|
||||
if r.FileId == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("调用接口参数错误"))
|
||||
handleTask, ok := handleTaskMap[taskType]
|
||||
if !ok {
|
||||
return utils.HTTPErrorHandler(c, ErrTaskNotFound)
|
||||
}
|
||||
client := utils.GetQueueClient()
|
||||
json, err := json.Marshal(map[string]any{
|
||||
"file_id": r.FileId,
|
||||
})
|
||||
json, err := handleTask(c)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
info, err := client.Enqueue(asynq.NewTask("image:compress", json), asynq.MaxRetry(3))
|
||||
|
||||
client := u.GetQueueClient()
|
||||
info, err := client.Enqueue(asynq.NewTask(taskType, json), asynq.MaxRetry(3))
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
@@ -42,11 +41,10 @@ func GenCompressImage(c echo.Context) error {
|
||||
})
|
||||
}
|
||||
|
||||
func GetCompressImage(c echo.Context) error {
|
||||
cc := c.(*middleware.CustomContext)
|
||||
taskId := cc.Param("id")
|
||||
func GetTask(c *echo.Context) error {
|
||||
taskId := c.Param("id")
|
||||
if taskId == "" {
|
||||
return utils.HTTPErrorHandler(c, errors.New("调用接口参数错误"))
|
||||
return utils.HTTPErrorHandler(c, ErrInvalidRequest)
|
||||
}
|
||||
|
||||
taskInfo, err := models.GetRedisTaskInfo(taskId)
|
||||
@@ -54,11 +52,11 @@ func GetCompressImage(c echo.Context) error {
|
||||
return utils.HTTPErrorHandler(c, err)
|
||||
}
|
||||
if taskInfo == nil {
|
||||
client := utils.GetQueueInspector()
|
||||
client := u.GetQueueInspector()
|
||||
|
||||
queneTaskInfo, err := client.GetTaskInfo("default", taskId)
|
||||
if err != nil {
|
||||
return utils.HTTPErrorHandler(c, errors.New("任务已过期"))
|
||||
return utils.HTTPErrorHandler(c, ErrTaskExpired)
|
||||
}
|
||||
stateMap := map[asynq.TaskState]string{
|
||||
asynq.TaskStateActive: "processing",
|
||||
7
backend/internal/controllers/task/errors.go
Normal file
7
backend/internal/controllers/task/errors.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package task
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrInvalidRequest = errors.New("InvalidRequest")
|
||||
)
|
||||
53
backend/internal/controllers/task/image.go
Normal file
53
backend/internal/controllers/task/image.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
type BaseImageRequest struct {
|
||||
FileId string `json:"file_id"`
|
||||
}
|
||||
|
||||
func HandleImageCompress(c *echo.Context) ([]byte, error) {
|
||||
r := new(BaseImageRequest)
|
||||
if err := c.Bind(r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if r.FileId == "" {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
json, err := json.Marshal(map[string]any{
|
||||
"file_id": r.FileId,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return json, nil
|
||||
}
|
||||
|
||||
type ImageConvertRequest struct {
|
||||
BaseImageRequest
|
||||
TargetExt string `json:"target_ext"`
|
||||
}
|
||||
|
||||
func HandleImageConvert(c *echo.Context) ([]byte, error) {
|
||||
r := new(ImageConvertRequest)
|
||||
if err := c.Bind(r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if r.FileId == "" || r.TargetExt == "" {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
json, err := json.Marshal(map[string]any{
|
||||
"file_id": r.FileId,
|
||||
"target_ext": r.TargetExt,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return json, nil
|
||||
}
|
||||
45
backend/internal/controllers/task/text.go
Normal file
45
backend/internal/controllers/task/text.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
var validProviders = map[string]bool{
|
||||
"google": true,
|
||||
"microsoft": true,
|
||||
"deeplx": true,
|
||||
"deepseek": true,
|
||||
}
|
||||
|
||||
var validSources = map[string]bool{
|
||||
"auto": true,
|
||||
"zh-CN": true,
|
||||
"en": true,
|
||||
"ja": true,
|
||||
"ko": true,
|
||||
}
|
||||
|
||||
type TranslateTextRequest struct {
|
||||
Text string `json:"text"`
|
||||
Source string `json:"source"`
|
||||
Target string `json:"target"`
|
||||
Provider string `json:"provider"`
|
||||
}
|
||||
|
||||
func HandleTextTranslate(c *echo.Context) ([]byte, error) {
|
||||
r := new(TranslateTextRequest)
|
||||
if err := c.Bind(r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if r.Text == "" || r.Target == "" || !validProviders[r.Provider] || !validSources[r.Source] {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
return json.Marshal(map[string]any{
|
||||
"text": r.Text,
|
||||
"source": r.Source,
|
||||
"target": r.Target,
|
||||
"provider": r.Provider,
|
||||
})
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"backend/internal/utils"
|
||||
"encoding/json"
|
||||
|
||||
"dario.cat/mergo"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type FileInfo struct {
|
||||
FileSize int64 `json:"size"`
|
||||
MimeType string `json:"mime_type"`
|
||||
FileHash string `json:"hash"`
|
||||
ChunkSize int64 `json:"chunk_size"`
|
||||
}
|
||||
|
||||
type FileType string
|
||||
|
||||
const (
|
||||
FileTypeInit FileType = "init"
|
||||
FileTypeUpload FileType = "already"
|
||||
)
|
||||
|
||||
type RedisFileInfo struct {
|
||||
FileInfo
|
||||
FileType FileType `json:"type"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
Expire int64 `json:"expire"` // 只有上传文件(init)的时候有这个字段
|
||||
}
|
||||
|
||||
func GetRedisFileInfo(fileId string) (*RedisFileInfo, error) {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
fileInfoUnmarshalData, err := rdb.HGet(ctx, "015:fileInfoMap", fileId).Result()
|
||||
if err == redis.Nil {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var fileInfoData RedisFileInfo
|
||||
if err := json.Unmarshal([]byte(fileInfoUnmarshalData), &fileInfoData); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &fileInfoData, nil
|
||||
}
|
||||
|
||||
func SetRedisFileInfo(fileId string, fileInfo RedisFileInfo) error {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
old_fileInfo, err := GetRedisFileInfo(fileId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if old_fileInfo != nil {
|
||||
mergo.Merge(&fileInfo, old_fileInfo)
|
||||
}
|
||||
jsonData, _ := json.Marshal(fileInfo)
|
||||
_, err = rdb.HSet(ctx, "015:fileInfoMap", fileId, string(jsonData)).Result()
|
||||
return err
|
||||
}
|
||||
|
||||
func GetRedisFileInfoAll() (map[string]string, error) {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
return rdb.HGetAll(ctx, "015:fileInfoMap").Result()
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"backend/internal/utils"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func GetRedisFileShareRelational(fileId string) ([]string, error) {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
fileShareRelationalUnmarshalData, err := rdb.HGet(ctx, "015:fileShareRelational", fileId).Result()
|
||||
if err == redis.Nil {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var shareIDs []string
|
||||
if err := json.Unmarshal([]byte(fileShareRelationalUnmarshalData), &shareIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return shareIDs, nil
|
||||
}
|
||||
|
||||
func SetRedisFileShareRelational(fileId string, shareIDs []string) error {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
jsonData, _ := json.Marshal(shareIDs)
|
||||
_, err := rdb.HSet(ctx, "015:fileShareRelational", fileId, string(jsonData)).Result()
|
||||
return err
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"backend/internal/utils"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func GetRedisPickupData(pickupCode string) (string, error) {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
ShareId, err := rdb.Get(ctx, fmt.Sprintf("015:pickupCode:%s", pickupCode)).Result()
|
||||
if err == redis.Nil {
|
||||
return "", nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return ShareId, nil
|
||||
}
|
||||
|
||||
func SetRedisPickupData(pickupCode string, shareId string) (bool, error) {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
ok, err := rdb.SetNX(ctx, fmt.Sprintf("015:pickupCode:%s", pickupCode), shareId, time.Until(time.Now().Add(24*time.Hour))).Result()
|
||||
return ok, err
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"backend/internal/utils"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"dario.cat/mergo"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type RedisShareInfo struct {
|
||||
// Id string `json:"id"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
Owner string `json:"owner"`
|
||||
Type ShareType `json:"type"`
|
||||
Data string `json:"data"` // 分享数据 文件分享为文件id 文本分享为文本内容
|
||||
ExpireAt int64 `json:"expire_time"`
|
||||
ViewNum int64 `json:"download_nums"`
|
||||
Password string `json:"password"`
|
||||
NotifyEmail []string `json:"notify_email"`
|
||||
FileName string `json:"file_name"`
|
||||
// PickupCode bool `json:"pickup_code"`
|
||||
}
|
||||
|
||||
type ShareType string
|
||||
|
||||
const (
|
||||
ShareTypeFile ShareType = "file"
|
||||
ShareTypeText ShareType = "text"
|
||||
)
|
||||
|
||||
func GetRedisShareInfo(shareId string) (*RedisShareInfo, error) {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
shareInfo := rdb.Get(ctx, fmt.Sprintf("015:shareInfoMap:%s", shareId))
|
||||
shareInfoUnmarshalData, err := shareInfo.Result()
|
||||
ttl, _ := rdb.TTL(ctx, fmt.Sprintf("015:shareInfoMap:%s", shareId)).Result()
|
||||
if err == redis.Nil {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var shareInfoData RedisShareInfo
|
||||
|
||||
if err := json.Unmarshal([]byte(shareInfoUnmarshalData), &shareInfoData); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
shareInfoData.ExpireAt = time.Now().Add(ttl).Unix()
|
||||
return &shareInfoData, nil
|
||||
}
|
||||
|
||||
func SetRedisShareInfo(shareId string, shareInfo RedisShareInfo) error {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
old_shareInfo, err := GetRedisShareInfo(shareId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if old_shareInfo != nil {
|
||||
mergo.Merge(&shareInfo, old_shareInfo)
|
||||
}
|
||||
jsonData, _ := json.Marshal(shareInfo)
|
||||
_, err = rdb.Set(ctx, fmt.Sprintf("015:shareInfoMap:%s", shareId), string(jsonData), time.Until(time.Unix(shareInfo.ExpireAt, 0))).Result()
|
||||
return err
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"backend/internal/utils"
|
||||
"encoding/json"
|
||||
|
||||
"dario.cat/mergo"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// 统计数据结构
|
||||
type StatData struct {
|
||||
FileSize int64 `json:"file_size"` // 文件大小
|
||||
FileNum int64 `json:"file_num"` // 文件数量
|
||||
ShareNum int64 `json:"share_num"` // 分享数量
|
||||
DownloadNum int64 `json:"download_num"` // 下载数量
|
||||
}
|
||||
|
||||
func GetRedisStat(key string) (*StatData, error) {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
statUnmarshalData, err := rdb.HGet(ctx, "015:stat", key).Result()
|
||||
if err == redis.Nil {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var stat StatData
|
||||
if err := json.Unmarshal([]byte(statUnmarshalData), &stat); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &stat, nil
|
||||
}
|
||||
|
||||
func SetRedisStat(key string, stat StatData) error {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
old_stat, err := GetRedisStat(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if old_stat != nil {
|
||||
mergo.Merge(&stat, old_stat)
|
||||
}
|
||||
jsonData, _ := json.Marshal(stat)
|
||||
_, err = rdb.HSet(ctx, "015:stat", key, string(jsonData)).Result()
|
||||
return err
|
||||
}
|
||||
|
||||
func GetRedisStatAll() (map[string]string, error) {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
return rdb.HGetAll(ctx, "015:stat").Result()
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"backend/internal/utils"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func GetRedisTaskInfo(taskId string) (*map[string]any, error) {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
taskInfo := rdb.Get(ctx, fmt.Sprintf("015:taskInfoMap:%s", taskId))
|
||||
taskInfoUnmarshalData, err := taskInfo.Result()
|
||||
if err == redis.Nil {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var taskInfoData map[string]any
|
||||
|
||||
if err := json.Unmarshal([]byte(taskInfoUnmarshalData), &taskInfoData); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &taskInfoData, nil
|
||||
}
|
||||
|
||||
func SetRedisTaskInfo(taskId string, taskInfo map[string]any) error {
|
||||
rdb, ctx := utils.GetRedisClient()
|
||||
jsonData, _ := json.Marshal(taskInfo)
|
||||
_, err := rdb.Set(ctx, fmt.Sprintf("015:taskInfoMap:%s", taskId), jsonData, time.Hour).Result()
|
||||
return err
|
||||
}
|
||||
@@ -1,89 +1,84 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"backend/internal/utils"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func CreateFileSlice(fileSlice io.Reader, fileId string, fileIndex int64) error {
|
||||
uploadPath, err := utils.GetUploadDirPath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
func CreateFileSlice(fileId string, uploadPath string, fileSlice io.Reader, fileIndex int64) (string, error) {
|
||||
filePath := filepath.Join(uploadPath, fmt.Sprintf("%s_%s", fileId, "tmp"))
|
||||
if err := os.MkdirAll(filePath, 0755); err != nil {
|
||||
return err
|
||||
return "", err
|
||||
}
|
||||
|
||||
dst, err := os.Create(filepath.Join(filePath, fmt.Sprintf("%d", fileIndex)))
|
||||
if err != nil {
|
||||
return err
|
||||
return "", err
|
||||
}
|
||||
defer dst.Close()
|
||||
defer dst.Close() //nolint:errcheck
|
||||
|
||||
if _, err = io.Copy(dst, fileSlice); err != nil {
|
||||
return err
|
||||
return "", err
|
||||
}
|
||||
|
||||
return nil
|
||||
return filePath, nil
|
||||
}
|
||||
|
||||
// MergeFileSlices 合并文件切片
|
||||
func MergeFileSlices(slicesPath string, mergeFilePath string) error {
|
||||
// 创建最终文件
|
||||
destFile, err := os.Create(mergeFilePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建合并文件失败: %v", err)
|
||||
}
|
||||
defer destFile.Close()
|
||||
|
||||
// 读取目录下的所有文件
|
||||
func GetFileSliceList(fileId string, uploadPath string) ([]int, error) {
|
||||
slicesPath := filepath.Join(uploadPath, fmt.Sprintf("%s_%s", fileId, "tmp"))
|
||||
files, err := os.ReadDir(slicesPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取切片目录失败: %v", err)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return nil, fmt.Errorf("读取切片目录失败: %v", err)
|
||||
}
|
||||
|
||||
// 按照索引排序文件切片
|
||||
sliceFiles := make([]string, len(files))
|
||||
fileSliceList := []int{}
|
||||
for _, file := range files {
|
||||
index, err := strconv.Atoi(file.Name())
|
||||
if err != nil {
|
||||
return fmt.Errorf("无效的切片文件名: %v", err)
|
||||
return nil, fmt.Errorf("无效的切片文件名: %v", err)
|
||||
}
|
||||
sliceFiles[index-1] = filepath.Join(slicesPath, file.Name())
|
||||
fileSliceList = append(fileSliceList, index)
|
||||
}
|
||||
sort.Ints(fileSliceList)
|
||||
return fileSliceList, nil
|
||||
}
|
||||
|
||||
// MergeFileSlices 合并文件切片
|
||||
func MergeFileSlices(fileId string, uploadPath string) (string, error) {
|
||||
mergeFilePath := filepath.Join(uploadPath, fileId)
|
||||
slicesPath := filepath.Join(uploadPath, fmt.Sprintf("%s_%s", fileId, "tmp"))
|
||||
defer os.RemoveAll(slicesPath) //nolint:errcheck
|
||||
// 创建最终文件
|
||||
destFile, err := os.Create(mergeFilePath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("创建合并文件失败: %v", err)
|
||||
}
|
||||
defer destFile.Close() //nolint:errcheck
|
||||
|
||||
fileSliceList, err := GetFileSliceList(fileId, uploadPath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 合并文件
|
||||
buffer := make([]byte, 4*1024*1024) // 4MB buffer
|
||||
for _, sliceFile := range sliceFiles {
|
||||
sf, err := os.Open(sliceFile)
|
||||
for _, index := range fileSliceList {
|
||||
sliceFilePath := filepath.Join(slicesPath, fmt.Sprintf("%d", index))
|
||||
sf, err := os.Open(sliceFilePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("打开切片文件失败: %v", err)
|
||||
return "", fmt.Errorf("打开切片文件失败: %v", err)
|
||||
}
|
||||
|
||||
for {
|
||||
n, err := sf.Read(buffer)
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
sf.Close()
|
||||
return fmt.Errorf("读取切片文件失败: %v", err)
|
||||
}
|
||||
|
||||
if _, err := destFile.Write(buffer[:n]); err != nil {
|
||||
sf.Close()
|
||||
return fmt.Errorf("写入合并文件失败: %v", err)
|
||||
}
|
||||
if _, err := io.CopyBuffer(destFile, sf, buffer); err != nil {
|
||||
sf.Close() //nolint:errcheck
|
||||
return "", fmt.Errorf("合并切片文件失败: %v", err)
|
||||
}
|
||||
if err := sf.Close(); err != nil {
|
||||
return "", fmt.Errorf("关闭切片文件失败: %v", err)
|
||||
}
|
||||
|
||||
sf.Close()
|
||||
}
|
||||
defer os.RemoveAll(slicesPath)
|
||||
return nil
|
||||
return mergeFilePath, nil
|
||||
}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
package utils
|
||||
|
||||
import "github.com/hibiken/asynq"
|
||||
|
||||
func GetQueueClient() *asynq.Client {
|
||||
opt := RedisURI2AsynqOpt(GetEnv("redis.url"))
|
||||
return asynq.NewClient(opt)
|
||||
}
|
||||
|
||||
func GetQueueInspector() *asynq.Inspector {
|
||||
opt := RedisURI2AsynqOpt(GetEnv("redis.url"))
|
||||
return asynq.NewInspector(opt)
|
||||
}
|
||||
|
||||
func RedisURI2AsynqOpt(uri string) asynq.RedisConnOpt {
|
||||
opt, err := asynq.ParseRedisURI(GetEnv("redis.url"))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return opt
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var v *viper.Viper
|
||||
|
||||
func init() {
|
||||
InitEnv()
|
||||
}
|
||||
|
||||
func InitEnv() {
|
||||
if v != nil {
|
||||
return
|
||||
}
|
||||
v = viper.New()
|
||||
v.SetConfigName("config.yaml")
|
||||
v.SetConfigType("yaml")
|
||||
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
v.AddConfigPath(".")
|
||||
v.AddConfigPath("../")
|
||||
v.AutomaticEnv()
|
||||
v.WatchConfig()
|
||||
err := v.ReadInConfig()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
// if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
|
||||
// // 只有当错误不是"配置文件未找到"时才 panic
|
||||
// panic(err)
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
func GetEnv(key string) string {
|
||||
InitEnv()
|
||||
return v.GetString(key)
|
||||
}
|
||||
|
||||
func GetEnvWithDefault(key string, defaultValue string) string {
|
||||
value := v.GetString(key)
|
||||
if value == "" {
|
||||
return defaultValue
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func GetEnvMapString(key string) map[string]string {
|
||||
InitEnv()
|
||||
return v.GetStringMapString(key)
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/md5"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
humanize "github.com/dustin/go-humanize"
|
||||
)
|
||||
|
||||
func GetFileId(fileHash string, fileSize int64) string {
|
||||
return fmt.Sprintf("%s_%d", fileHash, fileSize)
|
||||
}
|
||||
|
||||
func GetFileMd5(file io.Reader) (string, error) {
|
||||
|
||||
const bufferSize = 1024 * 1000 // 1MB
|
||||
|
||||
hash := md5.New()
|
||||
for buf, reader := make([]byte, bufferSize), bufio.NewReader(file); ; {
|
||||
n, err := reader.Read(buf)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
|
||||
hash.Write(buf[:n])
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%x", hash.Sum(nil)), nil
|
||||
}
|
||||
|
||||
func GetUploadDirPath() (string, error) {
|
||||
basepath, err := os.Getwd()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
finalPath := filepath.Join(basepath, "uploads")
|
||||
uploadPath := GetEnvWithDefault("upload.path", finalPath)
|
||||
if err := os.MkdirAll(uploadPath, 0755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return uploadPath, nil
|
||||
}
|
||||
|
||||
func GetFileSize(size string) (uint64, error) {
|
||||
return humanize.ParseBytes(size)
|
||||
}
|
||||
@@ -3,43 +3,39 @@ package utils
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
type Option interface {
|
||||
applyTo(*HTTPBaseResponse)
|
||||
}
|
||||
|
||||
type HTTPBaseResponse struct {
|
||||
code int
|
||||
message string
|
||||
data map[string]any
|
||||
}
|
||||
|
||||
type HTTPBaseResponseProps func(props *HTTPBaseResponse) error
|
||||
type HTTPBaseResponseProps func(props *HTTPBaseResponse)
|
||||
|
||||
type WithCode int
|
||||
|
||||
func (o WithCode) applyTo(props *HTTPBaseResponse) {
|
||||
props.code = int(o)
|
||||
func WithCode(data int) HTTPBaseResponseProps {
|
||||
return func(props *HTTPBaseResponse) {
|
||||
props.code = data
|
||||
}
|
||||
}
|
||||
|
||||
type WithMessage string
|
||||
|
||||
func (o WithMessage) applyTo(props *HTTPBaseResponse) {
|
||||
props.message = string(o)
|
||||
func WithMessage(data string) HTTPBaseResponseProps {
|
||||
return func(props *HTTPBaseResponse) {
|
||||
props.message = data
|
||||
}
|
||||
}
|
||||
|
||||
type WithData map[string]any
|
||||
|
||||
func (o WithData) applyTo(props *HTTPBaseResponse) {
|
||||
props.data = o
|
||||
func WithData(data map[string]any) HTTPBaseResponseProps {
|
||||
return func(props *HTTPBaseResponse) {
|
||||
props.data = data
|
||||
}
|
||||
}
|
||||
|
||||
func HTTPBaseHandler(c echo.Context, options ...Option) error {
|
||||
func HTTPBaseHandler(c *echo.Context, options ...HTTPBaseResponseProps) error {
|
||||
props := HTTPBaseResponse{code: http.StatusOK, message: "success", data: map[string]any{}}
|
||||
for _, option := range options {
|
||||
option.applyTo(&props)
|
||||
option(&props)
|
||||
}
|
||||
|
||||
return c.JSON(props.code, map[string]any{
|
||||
@@ -49,10 +45,12 @@ func HTTPBaseHandler(c echo.Context, options ...Option) error {
|
||||
})
|
||||
}
|
||||
|
||||
func HTTPSuccessHandler(c echo.Context, data map[string]any, options ...HTTPBaseResponseProps) error {
|
||||
return HTTPBaseHandler(c, WithData(data))
|
||||
func HTTPSuccessHandler(c *echo.Context, data map[string]any, options ...HTTPBaseResponseProps) error {
|
||||
options = append([]HTTPBaseResponseProps{WithData(data)}, options...)
|
||||
return HTTPBaseHandler(c, options...)
|
||||
}
|
||||
|
||||
func HTTPErrorHandler(c echo.Context, err error, options ...HTTPBaseResponseProps) error {
|
||||
return HTTPBaseHandler(c, WithMessage(err.Error()), WithCode(http.StatusBadRequest))
|
||||
func HTTPErrorHandler(c *echo.Context, err error, options ...HTTPBaseResponseProps) error {
|
||||
options = append([]HTTPBaseResponseProps{WithMessage(err.Error()), WithCode(http.StatusBadRequest)}, options...)
|
||||
return HTTPBaseHandler(c, options...)
|
||||
}
|
||||
|
||||
@@ -3,14 +3,19 @@ package utils
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"pkg/utils"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrPasswordSaltNotSet = errors.New("PasswordSaltNotSet")
|
||||
)
|
||||
|
||||
func GeneratePasswordHash(password string) (string, error) {
|
||||
salt := GetEnv("share.password_salt")
|
||||
salt := utils.GetEnv("share.password_salt")
|
||||
if salt == "" {
|
||||
return "", errors.New("请配置PASSWORD_SALT")
|
||||
return "", ErrPasswordSaltNotSet
|
||||
}
|
||||
hash := argon2.IDKey([]byte(password), []byte(salt), 1, 64*1024, 4, 32)
|
||||
return fmt.Sprintf("%x", hash), nil
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var rdb *redis.Client = InitRedis()
|
||||
var ctx = context.Background()
|
||||
|
||||
func InitRedis() *redis.Client {
|
||||
opt, err := redis.ParseURL(GetEnv("redis.url"))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return redis.NewClient(opt)
|
||||
}
|
||||
|
||||
func GetRedisClient() (*redis.Client, context.Context) {
|
||||
return rdb, ctx
|
||||
}
|
||||
16
backend/internal/utils/session.go
Normal file
16
backend/internal/utils/session.go
Normal file
@@ -0,0 +1,16 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/gorilla/sessions"
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
func GetSession(c *echo.Context, name string) (*sessions.Session, error) {
|
||||
store, err := echo.ContextGet[sessions.Store](c, "_session_store")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get session store: %w", err)
|
||||
}
|
||||
return store.Get(c.Request(), name)
|
||||
}
|
||||
@@ -1,12 +1,10 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"backend/internal/controllers"
|
||||
"backend/internal/utils"
|
||||
"backend/middleware"
|
||||
"fmt"
|
||||
"pkg/utils"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
@@ -18,30 +16,27 @@ func main() {
|
||||
} else {
|
||||
logger, _ = zap.NewDevelopment()
|
||||
}
|
||||
defer logger.Sync()
|
||||
defer logger.Sync() //nolint:errcheck
|
||||
zap.ReplaceGlobals(logger)
|
||||
// redis
|
||||
if err := utils.InitRedis(); err != nil {
|
||||
logger.Fatal("redis init failed", zap.Error(err))
|
||||
panic(err)
|
||||
}
|
||||
if err := utils.InitAsynq(); err != nil {
|
||||
logger.Fatal("asynq init failed", zap.Error(err))
|
||||
panic(err)
|
||||
}
|
||||
|
||||
e := echo.New()
|
||||
e.Use(middleware.ContextMiddleware())
|
||||
e.Use(middleware.SessionMiddleware())
|
||||
e.Use(middleware.AuthMiddleware())
|
||||
e.Use(middleware.RateLimiterMiddleware())
|
||||
e.Use(middleware.LoggerMiddleware())
|
||||
for _, middleware := range middlewares {
|
||||
e.Use(middleware())
|
||||
}
|
||||
|
||||
e.POST("/file/create", controllers.CreateUploadTask)
|
||||
e.POST("/file/slice", controllers.UploadFileSlice)
|
||||
e.POST("/file/finish", controllers.FinishUploadTask)
|
||||
e.GET("/share/:id", controllers.GetShareInfo)
|
||||
e.POST("/share", controllers.CreateShareInfo)
|
||||
e.GET("/download", controllers.DownloadShare)
|
||||
e.POST("/download", controllers.VaildateShare)
|
||||
e.GET("/share/pickup/:code", controllers.GetShareByPickupCode)
|
||||
|
||||
e.POST("/image/compress", controllers.GenCompressImage)
|
||||
e.GET("/image/compress/:id", controllers.GetCompressImage)
|
||||
|
||||
e.GET("/stat", controllers.GetStat)
|
||||
e.GET("/config", controllers.GetConfig)
|
||||
e.GET("/about", controllers.GetAbout)
|
||||
e.Logger.Fatal(e.Start(fmt.Sprintf(":%s", utils.GetEnvWithDefault("api.port", "5001"))))
|
||||
for _, route := range routes {
|
||||
e.Match(route.Method, route.Path, route.Handler)
|
||||
}
|
||||
if err := e.Start(fmt.Sprintf(":%s", utils.GetEnvWithDefault("api.port", "5001"))); err != nil {
|
||||
logger.Fatal("server failed", zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
14
backend/middleware.go
Normal file
14
backend/middleware.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"backend/middleware"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
var middlewares = []func() echo.MiddlewareFunc{
|
||||
middleware.SessionMiddleware,
|
||||
middleware.AuthMiddleware,
|
||||
middleware.RateLimiterMiddleware,
|
||||
middleware.LoggerMiddleware,
|
||||
}
|
||||
@@ -1,17 +1,18 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"backend/internal/utils"
|
||||
|
||||
"github.com/gorilla/sessions"
|
||||
"github.com/labstack/echo-contrib/session"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
gonanoid "github.com/matoous/go-nanoid/v2"
|
||||
)
|
||||
|
||||
// CustomMiddleware 创建自定义中间件
|
||||
func AuthMiddleware() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
sess, err := session.Get("session", c)
|
||||
return func(c *echo.Context) error {
|
||||
sess, err := utils.GetSession(c, "session")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -30,11 +31,8 @@ func AuthMiddleware() echo.MiddlewareFunc {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
cc := c.(*CustomContext)
|
||||
cc.Auth = sess.Values["auth"]
|
||||
// 将自定义上下文传递给下一个处理器
|
||||
return next(cc)
|
||||
c.Set("auth", sess.Values["auth"])
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
// CustomContext 扩展 echo.Context 以添加自定义功能
|
||||
type CustomContext struct {
|
||||
echo.Context
|
||||
Auth interface{}
|
||||
}
|
||||
|
||||
// NewCustomContext 创建自定义上下文的构造函数
|
||||
func NewCustomContext(c echo.Context) *CustomContext {
|
||||
return &CustomContext{
|
||||
Context: c,
|
||||
}
|
||||
}
|
||||
|
||||
// ContextMiddleware 中间件用于将标准 echo.Context 转换为 CustomContext
|
||||
func ContextMiddleware() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
cc := NewCustomContext(c)
|
||||
return next(cc)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v4/middleware"
|
||||
"github.com/labstack/echo/v5"
|
||||
"github.com/labstack/echo/v5/middleware"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
@@ -10,7 +10,7 @@ func LoggerMiddleware() echo.MiddlewareFunc {
|
||||
return middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
|
||||
LogURI: true,
|
||||
LogStatus: true,
|
||||
LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error {
|
||||
LogValuesFunc: func(c *echo.Context, v middleware.RequestLoggerValues) error {
|
||||
zap.L().Info("request",
|
||||
zap.String("url", v.URI),
|
||||
zap.Int("status", v.Status),
|
||||
|
||||
@@ -5,9 +5,8 @@ import (
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
echo_middleware "github.com/labstack/echo/v4/middleware"
|
||||
"golang.org/x/time/rate"
|
||||
"github.com/labstack/echo/v5"
|
||||
echo_middleware "github.com/labstack/echo/v5/middleware"
|
||||
)
|
||||
|
||||
type RateSkiper struct {
|
||||
@@ -23,22 +22,22 @@ var RateSkipList = []RateSkiper{
|
||||
|
||||
func RateLimiterMiddleware() echo.MiddlewareFunc {
|
||||
config := echo_middleware.RateLimiterConfig{
|
||||
Skipper: func(e echo.Context) bool {
|
||||
Skipper: func(e *echo.Context) bool {
|
||||
path := e.Path()
|
||||
r := e.Request()
|
||||
return slices.Contains(RateSkipList, RateSkiper{Path: path, Method: r.Method})
|
||||
},
|
||||
Store: echo_middleware.NewRateLimiterMemoryStoreWithConfig(
|
||||
echo_middleware.RateLimiterMemoryStoreConfig{Rate: rate.Limit(10), Burst: 30, ExpiresIn: 3 * time.Minute},
|
||||
echo_middleware.RateLimiterMemoryStoreConfig{Rate: 10, Burst: 30, ExpiresIn: 3 * time.Minute},
|
||||
),
|
||||
IdentifierExtractor: func(ctx echo.Context) (string, error) {
|
||||
IdentifierExtractor: func(ctx *echo.Context) (string, error) {
|
||||
id := ctx.RealIP()
|
||||
return id, nil
|
||||
},
|
||||
ErrorHandler: func(context echo.Context, err error) error {
|
||||
ErrorHandler: func(context *echo.Context, err error) error {
|
||||
return context.JSON(http.StatusForbidden, nil)
|
||||
},
|
||||
DenyHandler: func(context echo.Context, identifier string, err error) error {
|
||||
DenyHandler: func(context *echo.Context, identifier string, err error) error {
|
||||
return context.JSON(http.StatusTooManyRequests, nil)
|
||||
},
|
||||
}
|
||||
|
||||
@@ -2,10 +2,15 @@ package middleware
|
||||
|
||||
import (
|
||||
"github.com/gorilla/sessions"
|
||||
"github.com/labstack/echo-contrib/session"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
func SessionMiddleware() echo.MiddlewareFunc {
|
||||
return session.Middleware(sessions.NewCookieStore([]byte("secret")))
|
||||
store := sessions.NewCookieStore([]byte("secret")) // TODO: 从配置中获取密钥
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c *echo.Context) error {
|
||||
c.Set("_session_store", store)
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
33
backend/route.go
Normal file
33
backend/route.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"backend/internal/controllers"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
)
|
||||
|
||||
type Route struct {
|
||||
Method []string
|
||||
Path string
|
||||
Handler func(c *echo.Context) error
|
||||
}
|
||||
|
||||
var routes = []Route{
|
||||
{Method: []string{"POST"}, Path: "/file/create", Handler: controllers.CreateUploadTask},
|
||||
{Method: []string{"POST"}, Path: "/file/slice", Handler: controllers.UploadFileSlice},
|
||||
{Method: []string{"POST"}, Path: "/file/finish", Handler: controllers.FinishUploadTask},
|
||||
|
||||
{Method: []string{"GET"}, Path: "/share/:id", Handler: controllers.GetShareInfo},
|
||||
{Method: []string{"POST"}, Path: "/share", Handler: controllers.CreateShareInfo},
|
||||
|
||||
{Method: []string{"GET"}, Path: "/download", Handler: controllers.DownloadShare},
|
||||
{Method: []string{"POST"}, Path: "/download", Handler: controllers.VaildateShare},
|
||||
{Method: []string{"GET"}, Path: "/share/pickup/:code", Handler: controllers.GetShareByPickupCode},
|
||||
|
||||
{Method: []string{"GET"}, Path: "/stat", Handler: controllers.GetStat},
|
||||
{Method: []string{"GET"}, Path: "/config", Handler: controllers.GetConfig},
|
||||
{Method: []string{"GET"}, Path: "/about", Handler: controllers.GetAbout},
|
||||
|
||||
{Method: []string{"POST"}, Path: "/task/:type", Handler: controllers.CreateTask},
|
||||
{Method: []string{"GET"}, Path: "/task/:id", Handler: controllers.GetTask},
|
||||
}
|
||||
@@ -6,7 +6,9 @@ import (
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"backend/internal/utils"
|
||||
|
||||
"github.com/labstack/echo/v5"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
@@ -17,7 +19,7 @@ func TestHTTPSuccessHandler(t *testing.T) {
|
||||
c := e.NewContext(req, rec)
|
||||
|
||||
data := map[string]interface{}{"result": "success"}
|
||||
err := HTTPSuccessHandler(c, data)
|
||||
err := utils.HTTPSuccessHandler(c, data)
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.Equal(t, http.StatusOK, rec.Code)
|
||||
@@ -40,7 +42,7 @@ func TestHTTPErrorHandler(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
c := e.NewContext(req, rec)
|
||||
|
||||
err := HTTPErrorHandler(c, assert.AnError)
|
||||
err := utils.HTTPErrorHandler(c, assert.AnError)
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.Equal(t, http.StatusBadRequest, rec.Code)
|
||||
@@ -1,30 +1,31 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"os"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"backend/internal/utils"
|
||||
u "pkg/utils"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestGeneratePasswordHash(t *testing.T) {
|
||||
// 保存原始环境变量
|
||||
originalSalt := os.Getenv("share.password_salt")
|
||||
defer os.Setenv("share.password_salt", originalSalt)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
password string
|
||||
salt string
|
||||
expectError bool
|
||||
errorMsg string
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "share.password_salt未配置",
|
||||
password: "testpassword",
|
||||
salt: "",
|
||||
expectError: true,
|
||||
errorMsg: "请配置share.password_salt",
|
||||
err: utils.ErrPasswordSaltNotSet,
|
||||
},
|
||||
{
|
||||
name: "正常生成哈希",
|
||||
@@ -37,21 +38,23 @@ func TestGeneratePasswordHash(t *testing.T) {
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// 设置环境变量
|
||||
if tt.salt != "" {
|
||||
os.Setenv("share.password_salt", tt.salt)
|
||||
} else {
|
||||
os.Unsetenv("share.password_salt")
|
||||
}
|
||||
u.InitTestViper(u.EnvOption{
|
||||
ConfigData: bytes.NewBuffer([]byte(fmt.Sprintf(`
|
||||
share:
|
||||
password_salt: %s
|
||||
`, tt.salt))),
|
||||
})
|
||||
u.SetEnv("share.password_salt", tt.salt)
|
||||
|
||||
hash, err := GeneratePasswordHash(tt.password)
|
||||
hash, err := utils.GeneratePasswordHash(tt.password)
|
||||
|
||||
if tt.expectError {
|
||||
if err == nil {
|
||||
t.Errorf("期望错误,但得到了 nil")
|
||||
return
|
||||
}
|
||||
if err.Error() != tt.errorMsg {
|
||||
t.Errorf("期望错误信息 '%s',但得到了 '%s'", tt.errorMsg, err.Error())
|
||||
if err != tt.err {
|
||||
t.Errorf("期望错误信息 '%s',但得到了 '%s'", tt.err.Error(), err.Error())
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -16,6 +16,17 @@ redis:
|
||||
# (必填)redis 地址
|
||||
url: redis://redis:6379/0
|
||||
|
||||
# 实例功能配置
|
||||
features:
|
||||
file-share:
|
||||
enabled: true
|
||||
text-share:
|
||||
enabled: true
|
||||
file-image-compress:
|
||||
enabled: true
|
||||
file-image-convert:
|
||||
enabled: true
|
||||
|
||||
# 站点基本信息
|
||||
site:
|
||||
# 必填,对应你的公网域名
|
||||
|
||||
@@ -2,14 +2,16 @@
|
||||
import { useQuery } from '@tanstack/vue-query'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import getFileSize from '~/lib/getFileSize'
|
||||
import SparkMD5 from 'spark-md5'
|
||||
import useMyAppConfig from '@/composables/useMyAppConfig'
|
||||
import { useFeatureMeta } from '@/composables/useFeatureMeta'
|
||||
import Progress from '~/components/ui/progress/Progress.vue'
|
||||
import renderI18n from '~/lib/renderI18n'
|
||||
import { I18nT } from 'vue-i18n'
|
||||
import { calcNativeHash } from '~/lib/calcFileHash'
|
||||
|
||||
const { locale } = useI18n()
|
||||
const appConfig = useMyAppConfig()
|
||||
const featureMeta = useFeatureMeta()
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['about'],
|
||||
queryFn: async () => {
|
||||
@@ -32,9 +34,12 @@ const { data, isLoading } = useQuery({
|
||||
})
|
||||
const { t } = useI18n()
|
||||
|
||||
const genUserAvatar = (email: string) => {
|
||||
return `https://www.gravatar.com/avatar/${SparkMD5.hash(email)}?d=retro`
|
||||
}
|
||||
const { state: userAvatar } = useAsyncState(async () => {
|
||||
if (!data?.value?.email) return null
|
||||
const buffer = new TextEncoder().encode(data?.value?.email)
|
||||
const hash = await calcNativeHash(buffer)
|
||||
return `https://www.gravatar.com/avatar/${hash}?d=retro`
|
||||
}, null)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -52,14 +57,14 @@ const genUserAvatar = (email: string) => {
|
||||
<div class="flex flex-col gap-2 items-center">
|
||||
<div class="text-xl">{{ renderI18n(appConfig?.site_title ?? {}, 'en', locale) }}</div>
|
||||
<div class="text-sm opacity-75 text-center px-5">
|
||||
<I18nT keypath="about.powerBy" tag="span">
|
||||
<I18nT keypath="page.about.powerBy" tag="span">
|
||||
<NuxtLink href="https://github.com/keven1024/015" target="_blank" class="text-primary hover:underline">015</NuxtLink>
|
||||
</I18nT>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="font-semibold">{{ t('about.systemInfo') }}</div>
|
||||
<div class="font-semibold">{{ t('page.about.systemInfo') }}</div>
|
||||
<template v-if="isLoading">
|
||||
<div class="flex flex-row gap-2">
|
||||
<Skeleton class="w-full h-20 rounded-xl" v-for="i in 2" :key="i" />
|
||||
@@ -68,7 +73,7 @@ const genUserAvatar = (email: string) => {
|
||||
<template v-else>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-2">
|
||||
<div class="rounded-xl bg-white/50 flex-1 flex flex-col p-3 gap-2">
|
||||
<div class="opacity-75 text-xs">{{ t('about.admin') }}</div>
|
||||
<div class="opacity-75 text-xs">{{ t('page.about.admin') }}</div>
|
||||
<div
|
||||
class="flex flex-row gap-2 items-center cursor-pointer"
|
||||
@click="
|
||||
@@ -86,7 +91,7 @@ const genUserAvatar = (email: string) => {
|
||||
"
|
||||
>
|
||||
<Avatar class="size-10">
|
||||
<AvatarImage v-if="!!data?.avatar || !!data?.email" :src="data?.avatar || genUserAvatar(data?.email as string)" />
|
||||
<AvatarImage v-if="!!data?.avatar || !!data?.email" :src="data?.avatar || (userAvatar as string)" />
|
||||
<AvatarFallback class="bg-black/10 font-bold">
|
||||
{{ data?.name?.charAt(0)?.toUpperCase() }}
|
||||
</AvatarFallback>
|
||||
@@ -98,7 +103,7 @@ const genUserAvatar = (email: string) => {
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-xl bg-white/50 flex-1 flex flex-col p-3 gap-2">
|
||||
<div class="opacity-75 text-xs">{{ t('about.storage') }}</div>
|
||||
<div class="opacity-75 text-xs">{{ t('page.about.storage') }}</div>
|
||||
<div class="text-right flex flex-row items-baseline">
|
||||
<span class="text-lg font-semibold">{{ getFileSize(data?.file?.current ?? 0) }}</span>
|
||||
<span class="text-md opacity-75">/ {{ getFileSize(data?.file?.maximun ?? 0) }}</span>
|
||||
@@ -107,6 +112,29 @@ const genUserAvatar = (email: string) => {
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-if="isLoading">
|
||||
<Skeleton class="w-full h-24 rounded-xl" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<div class="rounded-xl bg-white/50 flex flex-col p-3 gap-3">
|
||||
<div class="font-semibold">{{ t('page.about.enabledFeatures') }}</div>
|
||||
<div v-if="featureMeta.length" class="flex flex-row flex-wrap gap-2">
|
||||
<div
|
||||
v-for="feature in featureMeta"
|
||||
:key="feature.key"
|
||||
class="flex flex-row items-center gap-2 rounded-full bg-black/5 px-2 py-1 text-sm font-medium"
|
||||
>
|
||||
<div class="flex size-6 items-center justify-center rounded-full text-black/80" :style="feature.style">
|
||||
<component :is="feature.icon" class="size-3.5" />
|
||||
</div>
|
||||
<span>{{ feature.label }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="text-sm opacity-75">
|
||||
{{ t('page.about.enabledFeaturesEmpty') }}
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-if="isLoading">
|
||||
<Skeleton class="w-full h-16 rounded-xl" />
|
||||
</template>
|
||||
@@ -115,7 +143,7 @@ const genUserAvatar = (email: string) => {
|
||||
<Accordion type="single" collapsible>
|
||||
<AccordionItem value="about">
|
||||
<AccordionTrigger>
|
||||
<span class="font-semibold">{{ t('about.about') }}</span>
|
||||
<span class="font-semibold">{{ t('page.about.about') }}</span>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent>
|
||||
<MarkdownRender class="max-w-full" :markdown="renderI18n(data?.content ?? {}, 'en', locale) ?? ''" />
|
||||
|
||||
@@ -1,34 +1,34 @@
|
||||
<script setup lang="ts">
|
||||
import { CurveType } from '@unovis/ts'
|
||||
import { AreaChart } from '@/components/ui/chart-area'
|
||||
import { cx } from 'class-variance-authority'
|
||||
import { useQuery } from '@tanstack/vue-query'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import AboutChartTooltip from '@/components/AboutChartTooltip.vue'
|
||||
import dayjs from 'dayjs'
|
||||
import { filesize } from 'filesize'
|
||||
import { times } from 'lodash-es'
|
||||
import type { ChartConfig } from '@/components/ui/chart'
|
||||
import { VisArea, VisAxis, VisLine, VisXYContainer } from '@unovis/vue'
|
||||
import { ChartContainer, ChartTooltip, ChartCrosshair, ChartLegendContent, componentToString, ChartTooltipContent } from '@/components/ui/chart'
|
||||
|
||||
interface StatChartData {
|
||||
file_size: number
|
||||
file_num: number
|
||||
share_num: number
|
||||
download_num: number
|
||||
date: string
|
||||
date: Date
|
||||
}
|
||||
|
||||
interface QueueChartData {
|
||||
processed: number
|
||||
failed: number
|
||||
date: string
|
||||
date: Date
|
||||
}
|
||||
|
||||
type ChartDataItem = StatChartData | QueueChartData
|
||||
|
||||
type ChartConfig = {
|
||||
type AreaChartConfig = {
|
||||
data: ChartDataItem[]
|
||||
index: string
|
||||
categories: string[]
|
||||
colors: string[]
|
||||
config: ChartConfig
|
||||
}
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
@@ -51,28 +51,28 @@ const { t } = useI18n()
|
||||
const chartTabs = computed(() => {
|
||||
return [
|
||||
{
|
||||
label: t('about.file'),
|
||||
label: t('page.about.file'),
|
||||
value: 'storage',
|
||||
total: data.value?.chart?.storage
|
||||
? Object.values(data.value.chart.storage).reduce((acc: number, curr: StatChartData) => acc + curr.file_num, 0)
|
||||
: 0,
|
||||
},
|
||||
{
|
||||
label: t('about.share'),
|
||||
label: t('page.about.share'),
|
||||
value: 'share',
|
||||
total: data.value?.chart?.storage
|
||||
? Object.values(data.value.chart.storage).reduce((acc: number, curr: StatChartData) => acc + curr.share_num, 0)
|
||||
: 0,
|
||||
},
|
||||
{
|
||||
label: t('about.download'),
|
||||
label: t('page.about.download'),
|
||||
value: 'download',
|
||||
total: data.value?.chart?.storage
|
||||
? Object.values(data.value.chart.storage).reduce((acc: number, curr: StatChartData) => acc + curr.download_num, 0)
|
||||
: 0,
|
||||
},
|
||||
{
|
||||
label: t('about.task'),
|
||||
label: t('page.about.task'),
|
||||
value: 'queue',
|
||||
total: data.value?.chart?.queue
|
||||
? Object.values(data.value.chart.queue).reduce((acc: number, curr: QueueChartData) => acc + curr.processed + curr.failed, 0)
|
||||
@@ -82,12 +82,12 @@ const chartTabs = computed(() => {
|
||||
})
|
||||
|
||||
const currentChartTab = ref<'storage' | 'queue' | 'share' | 'download'>('storage')
|
||||
const currentChartData = computed((): ChartConfig => {
|
||||
const currentChartData = computed((): AreaChartConfig => {
|
||||
const { storage, queue } = data.value?.chart || {}
|
||||
if (currentChartTab.value === 'queue') {
|
||||
const queueData = times(30, (i) => {
|
||||
return {
|
||||
date: dayjs().subtract(i, 'day').format('YYYY-MM-DD'),
|
||||
date: dayjs().subtract(i, 'day').toDate(),
|
||||
processed: queue?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.processed || 0,
|
||||
failed: queue?.[dayjs().subtract(i, 'day').format('YYYY-MM-DD')]?.failed || 0,
|
||||
}
|
||||
@@ -95,12 +95,14 @@ const currentChartData = computed((): ChartConfig => {
|
||||
return {
|
||||
data: queueData,
|
||||
index: 'date' as const,
|
||||
categories: ['processed', 'failed'] as const,
|
||||
colors: ['#4ade80', '#f87171'],
|
||||
config: {
|
||||
processed: { color: '#4ade80', label: t('page.about.processed') },
|
||||
failed: { color: '#f87171', label: t('page.about.failed') },
|
||||
},
|
||||
}
|
||||
}
|
||||
const storageData = times(30, (i) => {
|
||||
const base = { date: dayjs().subtract(i, 'day').format('YYYY-MM-DD') }
|
||||
const base = { date: dayjs().subtract(i, 'day').toDate() }
|
||||
if (currentChartTab.value === 'share') {
|
||||
return {
|
||||
...base,
|
||||
@@ -120,31 +122,37 @@ const currentChartData = computed((): ChartConfig => {
|
||||
}
|
||||
})
|
||||
|
||||
let categories = ['file_size', 'file_num']
|
||||
if (currentChartTab.value === 'share') {
|
||||
categories = ['share_num']
|
||||
return {
|
||||
data: storageData as ChartDataItem[],
|
||||
index: 'date' as const,
|
||||
config: {
|
||||
share_num: { color: '#ea580c', label: t('page.about.share') },
|
||||
},
|
||||
}
|
||||
}
|
||||
if (currentChartTab.value === 'download') {
|
||||
categories = ['download_num']
|
||||
}
|
||||
let colors = ['#38bdf8', '#a78bfa']
|
||||
if (currentChartTab.value === 'share') {
|
||||
colors = ['#ea580c']
|
||||
}
|
||||
if (currentChartTab.value === 'download') {
|
||||
colors = ['#a3e635']
|
||||
return {
|
||||
data: storageData as ChartDataItem[],
|
||||
index: 'date' as const,
|
||||
config: {
|
||||
download_num: { color: '#a3e635', label: t('page.about.download') },
|
||||
},
|
||||
}
|
||||
}
|
||||
return {
|
||||
data: storageData as ChartDataItem[],
|
||||
index: 'date' as const,
|
||||
categories,
|
||||
colors,
|
||||
config: {
|
||||
file_size: { color: '#38bdf8', label: t('page.about.fileSize') },
|
||||
file_num: { color: '#a78bfa', label: t('page.about.fileNum') },
|
||||
},
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="font-semibold">{{ t('about.analysis') }}</div>
|
||||
<div class="font-semibold">{{ t('page.about.analysis') }}</div>
|
||||
<template v-if="isLoading">
|
||||
<div class="flex flex-row gap-2">
|
||||
<Skeleton class="w-full h-96 rounded-xl" />
|
||||
@@ -167,21 +175,58 @@ const currentChartData = computed((): ChartConfig => {
|
||||
<div class="text-lg font-semibold">{{ tab.total }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<AreaChart
|
||||
v-if="currentChartData"
|
||||
class="h-64 w-full"
|
||||
:key="currentChartTab"
|
||||
:index="currentChartData.index"
|
||||
:data="currentChartData.data"
|
||||
:categories="currentChartData.categories"
|
||||
:show-grid-line="false"
|
||||
:show-legend="false"
|
||||
:show-y-axis="true"
|
||||
:show-x-axis="true"
|
||||
:colors="currentChartData.colors"
|
||||
:custom-tooltip="AboutChartTooltip"
|
||||
:curve-type="CurveType.CatmullRom"
|
||||
/>
|
||||
<ChartContainer :config="currentChartData.config" class="h-64 w-full p-5" :cursor="false">
|
||||
<VisXYContainer :data="currentChartData.data" :x-domain="[dayjs().toDate(), dayjs().subtract(29, 'day').toDate()]">
|
||||
<VisArea
|
||||
:key="currentChartTab"
|
||||
:x="(d: ChartDataItem) => d.date"
|
||||
:y="Object.keys(currentChartData.config).map((key) => (d: ChartDataItem) => d?.[key as keyof ChartDataItem])"
|
||||
:color="Object.values(currentChartData.config).map((c) => c.color)"
|
||||
:opacity="0.6"
|
||||
/>
|
||||
<VisLine
|
||||
:key="currentChartTab"
|
||||
:x="(d: ChartDataItem) => d.date"
|
||||
:y="Object.keys(currentChartData.config).map((key) => (d: ChartDataItem) => d?.[key as keyof ChartDataItem])"
|
||||
:color="Object.values(currentChartData.config).map((c) => c.color)"
|
||||
:line-width="1"
|
||||
/>
|
||||
<VisAxis
|
||||
:key="currentChartTab"
|
||||
type="x"
|
||||
:tick-line="false"
|
||||
:domain-line="false"
|
||||
:grid-line="false"
|
||||
:num-ticks="6"
|
||||
:tick-format="
|
||||
(d: Date) => {
|
||||
return dayjs(d).format('MMM')
|
||||
}
|
||||
"
|
||||
:tick-values="currentChartData.data.map((d) => d.date)"
|
||||
/>
|
||||
<ChartTooltip />
|
||||
<ChartCrosshair
|
||||
:key="currentChartTab"
|
||||
:template="
|
||||
componentToString(currentChartData.config, ChartTooltipContent, {
|
||||
class: 'w-[14rem]',
|
||||
labelFormatter: (d) => {
|
||||
return dayjs(d).format('MM-DD')
|
||||
},
|
||||
valueFormatter: (value, key) => {
|
||||
if (key === 'file_size' && typeof value === 'number') {
|
||||
return filesize(value)
|
||||
}
|
||||
return String(value)
|
||||
},
|
||||
})
|
||||
"
|
||||
:color="(d: any, i: number) => Object.values(currentChartData.config).map((c) => c.color as string)[i]"
|
||||
/>
|
||||
</VisXYContainer>
|
||||
<ChartLegendContent />
|
||||
</ChartContainer>
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import getFileSize from '~/lib/getFileSize'
|
||||
|
||||
const props = defineProps<{
|
||||
data: { name: string; value: string; color: string }[]
|
||||
title: string
|
||||
}>()
|
||||
const dataKeyMap = {
|
||||
file_size: {
|
||||
'zh-CN': '文件大小',
|
||||
en: 'File Size',
|
||||
},
|
||||
file_num: {
|
||||
'zh-CN': '文件数量',
|
||||
en: 'File Num',
|
||||
},
|
||||
processed: {
|
||||
'zh-CN': '处理数量',
|
||||
en: 'Processed',
|
||||
},
|
||||
failed: {
|
||||
'zh-CN': '失败数量',
|
||||
en: 'Failed',
|
||||
},
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="rounded-md bg-white p-2 flex flex-col gap-2">
|
||||
<div class="text-sm font-medium">{{ title }}</div>
|
||||
<div v-for="(item, index) in data" :key="index">
|
||||
<div class="flex flex-row items-center gap-2">
|
||||
<div class="h-5 w-2 rounded-full" :style="{ backgroundColor: item.color ?? '#222' }"></div>
|
||||
<div class="text-xs font-medium">
|
||||
{{ dataKeyMap?.[item.name as keyof typeof dataKeyMap]?.['en'] ?? item.name }}
|
||||
</div>
|
||||
<div class="text-sm">
|
||||
{{ ['file_size']?.includes(item?.name) ? getFileSize(item.value) : item.value }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
29
front/components/BaseCard.vue
Normal file
29
front/components/BaseCard.vue
Normal file
@@ -0,0 +1,29 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{
|
||||
title?: string
|
||||
showBackButton?: boolean
|
||||
}>()
|
||||
const router = useRouter()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="rounded-xl p-5 bg-white/50 backdrop-blur-xl w-full lg:w-200">
|
||||
<div v-if="title" class="flex flex-row justify-between">
|
||||
<h1 class="text-xl font-normal">{{ title }}</h1>
|
||||
<Button
|
||||
v-if="!!showBackButton"
|
||||
variant="outline"
|
||||
class="bg-white/70"
|
||||
size="icon"
|
||||
@click="
|
||||
() => {
|
||||
router.push('/')
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideHome class="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,19 +1,21 @@
|
||||
<script lang="ts" setup>
|
||||
import { VisSingleContainer, VisDonut } from '@unovis/vue'
|
||||
import { withDefaults, defineProps } from 'vue'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
value?: number
|
||||
size?: number
|
||||
color?: string
|
||||
}>(), {
|
||||
value: 0,
|
||||
size: 40,
|
||||
color: '#06b6d4'
|
||||
})
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
value?: number
|
||||
size?: number
|
||||
color?: string
|
||||
}>(),
|
||||
{
|
||||
value: 0,
|
||||
size: 40,
|
||||
color: '#06b6d4',
|
||||
}
|
||||
)
|
||||
const data = computed(() => {
|
||||
const progress = Math.min(Math.max(props.value, 0), 100)
|
||||
return [progress, 100 - progress ]
|
||||
return [progress, 100 - progress]
|
||||
})
|
||||
const getValue = (d: number) => d
|
||||
const getColor = (d: number, i: number) => [props?.color, 'transparent'][i]
|
||||
|
||||
32
front/components/CopyButton.vue
Normal file
32
front/components/CopyButton.vue
Normal file
@@ -0,0 +1,32 @@
|
||||
<script setup lang="ts">
|
||||
import { Button } from '@/components/ui/button'
|
||||
import asyncWait from '~/lib/asyncWait'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { LucideCheck, LucideCopy } from 'lucide-vue-next'
|
||||
|
||||
const isCopy = ref(false)
|
||||
const props = defineProps<{
|
||||
value: string
|
||||
}>()
|
||||
const { copy } = useClipboard()
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Button
|
||||
variant="outline"
|
||||
class="transition-all duration-300"
|
||||
size="icon"
|
||||
@click="
|
||||
async () => {
|
||||
await copy(props?.value)
|
||||
isCopy = true
|
||||
toast.success(t('common.copySuccess'))
|
||||
await asyncWait(3000)
|
||||
isCopy = false
|
||||
}
|
||||
"
|
||||
>
|
||||
<component :is="isCopy ? LucideCheck : LucideCopy" class="size-1/2" />
|
||||
</Button>
|
||||
</template>
|
||||
@@ -1,22 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
LucideShare,
|
||||
LucideImage,
|
||||
LucideBot,
|
||||
LucideLanguages,
|
||||
LucideFileText,
|
||||
LucideImageMinus,
|
||||
LucideArrowRightLeft,
|
||||
LucideImagePlus,
|
||||
LucideAudioLines,
|
||||
LucideListMusic,
|
||||
} from 'lucide-vue-next'
|
||||
import { cx } from 'class-variance-authority'
|
||||
import { isObject } from 'lodash-es'
|
||||
import showDrawer from '@/lib/showDrawer'
|
||||
import FileShareHandle from '@/components/Preprocessing/FileShareHandle.vue'
|
||||
import ImageConvertHandle from '@/components/Preprocessing/ImageConvertHandle.vue'
|
||||
import { useFeatureMeta, type FeatureKey } from '@/composables/useFeatureMeta'
|
||||
import type { FileShareHandleProps } from '../Preprocessing/types'
|
||||
const { t } = useI18n()
|
||||
|
||||
const props = defineProps<{
|
||||
hide: () => void
|
||||
file: File[]
|
||||
@@ -24,33 +12,25 @@ const props = defineProps<{
|
||||
}>()
|
||||
|
||||
const isImage = computed(() => props.file.every((r) => r?.type?.startsWith('image/')))
|
||||
const isVideo = computed(() => props.file.every((r) => r?.type?.startsWith('video/')))
|
||||
const isAudio = computed(() => props.file.every((r) => r?.type?.startsWith('audio/')))
|
||||
const isMedia = computed(() => isImage.value || isVideo.value || isAudio.value)
|
||||
|
||||
const isPDF = computed(() => props.file.every((r) => r?.type?.startsWith('application/pdf')))
|
||||
const isDOC = computed(() => props.file.every((r) => r?.type?.startsWith('application/msword')))
|
||||
const isXLS = computed(() => props.file.every((r) => r?.type?.startsWith('application/vnd.ms-excel')))
|
||||
const isPPT = computed(() => props.file.every((r) => r?.type?.startsWith('application/vnd.ms-powerpoint')))
|
||||
const isDocument = computed(() => isPDF.value || isDOC.value || isXLS.value || isPPT.value)
|
||||
const actions = [
|
||||
{
|
||||
label: t('file.handleType.file-share'),
|
||||
icon: LucideShare,
|
||||
className: 'bg-green-300',
|
||||
onClick: () => {
|
||||
showDrawer({
|
||||
render: ({ hide }) => h(FileShareHandle, { ...props, hide }),
|
||||
})
|
||||
},
|
||||
const featureMeta = useFeatureMeta()
|
||||
|
||||
type ActionHandler = {
|
||||
condition?: () => boolean
|
||||
onClick: () => void
|
||||
}
|
||||
|
||||
const actionHandlers: Partial<Record<FeatureKey, ActionHandler>> = {
|
||||
'file-share': {
|
||||
onClick: () => showDrawer({ render: ({ hide }) => h(FileShareHandle, { ...props, hide }) }),
|
||||
},
|
||||
isImage.value && {
|
||||
label: t('file.handleType.file-image-compress'),
|
||||
icon: LucideImageMinus,
|
||||
className: 'bg-red-300',
|
||||
onClick: () => {
|
||||
props.onFileHandle({ type: 'file-image-compress', config: {} })
|
||||
},
|
||||
'file-image-compress': {
|
||||
condition: () => isImage.value,
|
||||
onClick: () => props.onFileHandle({ type: 'file-image-compress', config: {} }),
|
||||
},
|
||||
'file-image-convert': {
|
||||
condition: () => isImage.value,
|
||||
onClick: () => showDrawer({ render: ({ hide }) => h(ImageConvertHandle, { ...props, hide }) }),
|
||||
},
|
||||
// isImage.value && {
|
||||
// label: '图片翻译', icon: LucideLanguages, className: 'bg-orange-300', onClick: () => {
|
||||
@@ -77,19 +57,24 @@ const actions = [
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
]?.filter(isObject) as {
|
||||
label: string
|
||||
icon: any
|
||||
className: string
|
||||
onClick: () => void
|
||||
}[]
|
||||
}
|
||||
|
||||
const actions = computed(() =>
|
||||
featureMeta.value
|
||||
.filter((meta) => {
|
||||
const { key } = meta || {}
|
||||
const handler = actionHandlers?.[key]
|
||||
return handler && (!handler.condition || handler.condition())
|
||||
})
|
||||
.map((meta) => ({ ...meta, onClick: actionHandlers[meta.key]!.onClick }))
|
||||
)
|
||||
</script>
|
||||
<template>
|
||||
<div class="flex flex-col gap-5 p-5">
|
||||
<div class="flex flex-col gap-5 p-5 overflow-x-auto">
|
||||
<div class="flex flex-row gap-2">
|
||||
<div
|
||||
v-for="item in actions"
|
||||
:key="item.label"
|
||||
:key="item.key"
|
||||
class="flex flex-col items-center gap-2 max-w-20"
|
||||
@click="
|
||||
() => {
|
||||
@@ -98,7 +83,7 @@ const actions = [
|
||||
}
|
||||
"
|
||||
>
|
||||
<div :class="cx('size-14 flex justify-center items-center rounded-full mx-3', item?.className)">
|
||||
<div class="size-14 flex justify-center items-center rounded-full mx-3" :style="item?.style">
|
||||
<component :is="item?.icon" />
|
||||
</div>
|
||||
<div class="text-xs truncate w-full text-center">{{ item?.label }}</div>
|
||||
|
||||
@@ -1,41 +1,29 @@
|
||||
<script setup lang="ts">
|
||||
import { cx } from "class-variance-authority";
|
||||
import { cx } from 'class-variance-authority'
|
||||
import type { Locale } from '@intlify/core-base'
|
||||
|
||||
const { availableLocales, setLocale, locale: currentLocale, t } = useI18n();
|
||||
const route = useRoute();
|
||||
const props = defineProps<{
|
||||
hide: () => void
|
||||
}>()
|
||||
|
||||
const localeMap = {
|
||||
"zh-CN": "简体中文",
|
||||
en: "English",
|
||||
// 'ja': '日本語',
|
||||
// 'ko': '한국어',
|
||||
// 'fr': 'Français',
|
||||
// 'de': 'Deutsch',
|
||||
};
|
||||
const { locales, setLocale, locale: currentLocale, t } = useI18n()
|
||||
|
||||
const switchLocale = async (locale: string) => {
|
||||
await setLocale(locale as keyof typeof localeMap);
|
||||
navigateTo(route.path, {
|
||||
external: true,
|
||||
});
|
||||
};
|
||||
const switchLocale = async (locale: Locale) => {
|
||||
await setLocale(locale)
|
||||
props.hide()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-1 py-2">
|
||||
<div class="text-xl font-bold mb-3">{{ t("i18n.switchLocale") }}</div>
|
||||
<div
|
||||
v-for="locale in availableLocales"
|
||||
:key="locale"
|
||||
:class="
|
||||
cx(
|
||||
'rounded-md hover:bg-black/10 p-2 cursor-pointer',
|
||||
currentLocale === locale && 'bg-black/10 font-bold',
|
||||
)
|
||||
"
|
||||
@click="() => switchLocale(locale)"
|
||||
>
|
||||
{{ localeMap?.[locale as keyof typeof localeMap] }}
|
||||
<div class="flex flex-col gap-1 py-2">
|
||||
<div class="text-xl font-bold mb-3">{{ t('i18n.switchLocale') }}</div>
|
||||
<div
|
||||
v-for="locale in locales"
|
||||
:key="locale.code"
|
||||
:class="cx('rounded-md hover:bg-black/10 p-2 cursor-pointer', currentLocale === locale.code && 'bg-black/10 font-bold')"
|
||||
@click="() => switchLocale(locale.code)"
|
||||
>
|
||||
{{ locale.name }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -4,6 +4,7 @@ import FormButton from '@/components/Field/FormButton.vue'
|
||||
import InputField from '@/components/Field/InputField.vue'
|
||||
import type { FormContext, GenericObject } from 'vee-validate'
|
||||
import { toast } from 'vue-sonner'
|
||||
const { t } = useI18n()
|
||||
const props = defineProps<{
|
||||
share_id: string
|
||||
hide: any
|
||||
@@ -15,14 +16,14 @@ const handleSubmit = async (form: FormContext<GenericObject, GenericObject>) =>
|
||||
const password = form.values.password
|
||||
const token = await getShareToken(props.share_id, { password })
|
||||
if (!token) {
|
||||
toast.error('密码错误')
|
||||
toast.error(t('page.shareView.passwall.passwordError'))
|
||||
form.resetForm()
|
||||
return
|
||||
}
|
||||
props?.hide(token)
|
||||
return
|
||||
} catch (error) {
|
||||
toast.error('密码错误')
|
||||
toast.error(t('page.shareView.passwall.passwordError'))
|
||||
form.resetForm()
|
||||
}
|
||||
}
|
||||
@@ -31,9 +32,9 @@ const handleSubmit = async (form: FormContext<GenericObject, GenericObject>) =>
|
||||
<template>
|
||||
<VeeForm>
|
||||
<div class="flex flex-col gap-5">
|
||||
<div class="text-xl font-bold">输入密码</div>
|
||||
<InputField name="password" type="password" rules="required" placeholder="请输入密码" />
|
||||
<FormButton @click="handleSubmit">提交</FormButton>
|
||||
<div class="text-xl font-bold">{{ t('page.shareView.passwall.title') }}</div>
|
||||
<InputField name="password" type="password" rules="required" :placeholder="t('page.shareView.passwall.passwordPlaceholder')" />
|
||||
<FormButton @click="handleSubmit">{{ t('btn.submit') }}</FormButton>
|
||||
</div>
|
||||
</VeeForm>
|
||||
</template>
|
||||
|
||||
@@ -18,7 +18,7 @@ const handleSubmit = async (form: FormContext<GenericObject, GenericObject>) =>
|
||||
}
|
||||
}>(`/api/share/pickup/${code}`)
|
||||
if (!data.data.share_id) {
|
||||
toast.error(t('pickup.codeError'))
|
||||
toast.error(t('page.upload.pickup.codeError'))
|
||||
form.resetForm()
|
||||
return
|
||||
}
|
||||
@@ -29,7 +29,7 @@ const handleSubmit = async (form: FormContext<GenericObject, GenericObject>) =>
|
||||
})
|
||||
return
|
||||
} catch (error) {
|
||||
toast.error(t('pickup.codeError'))
|
||||
toast.error(t('page.upload.pickup.codeError'))
|
||||
form.resetForm()
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,7 @@ const handleSubmit = async (form: FormContext<GenericObject, GenericObject>) =>
|
||||
<template>
|
||||
<VeeForm>
|
||||
<div class="flex flex-col gap-5">
|
||||
<div class="text-xl font-bold">{{ t('pickup.title') }}</div>
|
||||
<div class="text-xl font-bold">{{ t('page.upload.pickup.title') }}</div>
|
||||
<PinInputField
|
||||
name="code"
|
||||
:rules="
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
<script setup lang="ts">
|
||||
import QRCode from "qrcode";
|
||||
import QRCode from 'qrcode'
|
||||
const { t } = useI18n()
|
||||
const props = defineProps<{
|
||||
hide: () => void;
|
||||
data: any;
|
||||
}>();
|
||||
hide: () => void
|
||||
data: any
|
||||
}>()
|
||||
const { state } = useAsyncState(async () => {
|
||||
return await QRCode.toDataURL(props.data);
|
||||
}, null);
|
||||
return await QRCode.toDataURL(props.data)
|
||||
}, null)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-5">
|
||||
<div class="text-xl font-bold">分享二维码</div>
|
||||
<div class="flex flex-row justify-center">
|
||||
<img :src="state" v-if="!!state" />
|
||||
<Skeleton class="size-20" v-else />
|
||||
<div class="flex flex-col gap-5">
|
||||
<div class="text-xl font-bold">{{ t('page.result.qrCode.title') }}</div>
|
||||
<div class="flex flex-row justify-center">
|
||||
<img :src="state" v-if="!!state" />
|
||||
<Skeleton class="size-20" v-else />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1,74 +1,77 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
LucideShare,
|
||||
LucideImage,
|
||||
LucideBot,
|
||||
LucideLanguages,
|
||||
} from "lucide-vue-next";
|
||||
import { cx } from "class-variance-authority";
|
||||
import showDrawer from "@/lib/showDrawer";
|
||||
import TextShareHandle from "@/components/Preprocessing/TextShareHandle.vue";
|
||||
import showDrawer from '@/lib/showDrawer'
|
||||
import TextShareHandle from '@/components/Preprocessing/TextShareHandle.vue'
|
||||
import { useFeatureMeta, type FeatureKey } from '@/composables/useFeatureMeta'
|
||||
|
||||
const props = defineProps<{
|
||||
hide: () => void;
|
||||
text: string;
|
||||
onTextHandle: ({ type, config }: { type: string; config: any }) => void;
|
||||
}>();
|
||||
const { t } = useI18n();
|
||||
const actions = [
|
||||
{
|
||||
label: t("text.handleType.text-share"),
|
||||
icon: LucideShare,
|
||||
className: "bg-green-300",
|
||||
onClick: () => {
|
||||
showDrawer({
|
||||
render: ({ hide }) => h(TextShareHandle, { ...props, hide }),
|
||||
});
|
||||
hide: () => void
|
||||
text: string
|
||||
onTextHandle: ({ type, config }: { type: string; config: any }) => void
|
||||
}>()
|
||||
|
||||
const featureMeta = useFeatureMeta()
|
||||
|
||||
type ActionHandler = {
|
||||
condition?: () => boolean
|
||||
onClick: () => void
|
||||
}
|
||||
|
||||
const actionHandlers: Partial<Record<FeatureKey, ActionHandler>> = {
|
||||
'text-share': {
|
||||
onClick: () => showDrawer({ render: ({ hide }) => h(TextShareHandle, { ...props, hide }) }),
|
||||
},
|
||||
},
|
||||
// {
|
||||
// label: '生成配图', icon: LucideImage, className: 'bg-red-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
// {
|
||||
// label: '问大模型', icon: LucideBot, className: 'bg-blue-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
// {
|
||||
// label: '文本翻译', icon: LucideLanguages, className: 'bg-orange-300', onClick: () => {
|
||||
// console.log('复制链接')
|
||||
// }
|
||||
// },
|
||||
];
|
||||
// 'text-translate': {
|
||||
// onClick: () =>
|
||||
// props.onTextHandle({
|
||||
// type: 'text-translate',
|
||||
// config: {
|
||||
// source: 'auto',
|
||||
// },
|
||||
// }),
|
||||
// },
|
||||
// 'text-image-generate': {
|
||||
// label: '生成配图', icon: LucideImage, className: 'bg-red-300',
|
||||
// onClick: () => { console.log('复制链接') }
|
||||
// },
|
||||
// 'text-ai-ask': {
|
||||
// label: '问大模型', icon: LucideBot, className: 'bg-blue-300',
|
||||
// onClick: () => { console.log('复制链接') }
|
||||
// },
|
||||
// 'text-translate': {
|
||||
// label: '文本翻译', icon: LucideLanguages, className: 'bg-orange-300',
|
||||
// onClick: () => { console.log('复制链接') }
|
||||
// },
|
||||
}
|
||||
|
||||
const actions = computed(() =>
|
||||
featureMeta.value
|
||||
.filter((meta) => {
|
||||
const { key } = meta || {}
|
||||
const handler = actionHandlers?.[key]
|
||||
return handler && (!handler.condition || handler.condition())
|
||||
})
|
||||
.map((meta) => ({ ...meta, onClick: actionHandlers[meta.key]!.onClick }))
|
||||
)
|
||||
</script>
|
||||
<template>
|
||||
<div class="flex flex-col gap-5 p-5">
|
||||
<div class="flex flex-row gap-2">
|
||||
<div
|
||||
v-for="item in actions"
|
||||
:key="item.label"
|
||||
class="flex flex-col items-center gap-2 max-w-20"
|
||||
@click="
|
||||
() => {
|
||||
props?.hide();
|
||||
item?.onClick();
|
||||
}
|
||||
"
|
||||
>
|
||||
<div
|
||||
:class="
|
||||
cx(
|
||||
'size-14 flex justify-center items-center rounded-full mx-3',
|
||||
item?.className,
|
||||
)
|
||||
"
|
||||
>
|
||||
<component :is="item?.icon" />
|
||||
<div class="flex flex-col gap-5 p-5 overflow-x-auto">
|
||||
<div class="flex flex-row gap-2">
|
||||
<div
|
||||
v-for="item in actions"
|
||||
:key="item.key"
|
||||
class="flex flex-col items-center gap-2 max-w-20"
|
||||
@click="
|
||||
() => {
|
||||
props?.hide()
|
||||
item?.onClick()
|
||||
}
|
||||
"
|
||||
>
|
||||
<div class="size-14 flex justify-center items-center rounded-full mx-3" :style="item?.style">
|
||||
<component :is="item?.icon" />
|
||||
</div>
|
||||
<div class="text-xs truncate w-full text-center">{{ item?.label }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-xs truncate w-full text-center">{{ item?.label }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -12,14 +12,25 @@ const props = defineProps<{
|
||||
}>()
|
||||
const { value, setValue } = useField<File[]>(props?.name, props?.rules)
|
||||
const { t } = useI18n()
|
||||
|
||||
const filterOutSameFile = (files: File[] | undefined, targetFile: File[] | undefined) => {
|
||||
return files?.filter((file) => !targetFile?.some((r) => r?.name === file?.name && r?.type === file?.type && r?.size === file?.size)) || []
|
||||
}
|
||||
|
||||
useEventListener(document, 'paste', (evt: ClipboardEvent) => {
|
||||
const { files } = evt.clipboardData || {}
|
||||
if (files?.length) {
|
||||
setValue([...filterOutSameFile(value?.value, Array.from(files)), ...Array.from(files)])
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<FileUpload
|
||||
@onChange="
|
||||
(file) => {
|
||||
(files) => {
|
||||
// 这里没hash,我们姑且认为name和size,type都一样的为同一个文件
|
||||
setValue([...(value?.filter((r) => r?.name !== file?.name || r?.type !== file?.type || r?.size !== file?.size) || []), file])
|
||||
setValue([...filterOutSameFile(value, files), ...files])
|
||||
}
|
||||
"
|
||||
v-slot="{ isOverDropZone }"
|
||||
@@ -41,9 +52,7 @@ const { t } = useI18n()
|
||||
@click="
|
||||
(e: any) => {
|
||||
e.stopPropagation()
|
||||
setValue(
|
||||
value?.filter((r) => r?.name !== item?.name || r?.type !== item?.type || r?.size !== item?.size) || []
|
||||
)
|
||||
setValue(filterOutSameFile(value, [item]))
|
||||
}
|
||||
"
|
||||
>
|
||||
@@ -56,14 +65,14 @@ const { t } = useI18n()
|
||||
<div class="size-16 flex justify-center items-center rounded-xl bg-white/80">
|
||||
<PlusIcon class="size-7" />
|
||||
</div>
|
||||
<div class="mb-3">{{ t('file.addMore') }}</div>
|
||||
<div class="mb-3">{{ t('page.upload.file.addMore') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<LucideUpload class="size-10" />
|
||||
<div class="text-sm select-none">
|
||||
{{ t('file.uploadFilePlaceholder') }}
|
||||
{{ t('page.upload.file.uploadFilePlaceholder') }}
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
<template>
|
||||
<Field :name="props.name" v-slot="{ field }">
|
||||
<div class="flex flex-col gap-2">
|
||||
<Label v-if="props.label">{{ props.label }}</Label>
|
||||
<Input v-bind="{ ...field, ...$attrs }" />
|
||||
</div>
|
||||
</Field>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import type { RuleExpression } from 'vee-validate'
|
||||
|
||||
const props = defineProps<{
|
||||
name: string
|
||||
label?: string
|
||||
rules?: RuleExpression<string>
|
||||
}>()
|
||||
|
||||
const { value, errorMessage } = useField<string>(props.name, props.rules)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-2">
|
||||
<Label v-if="props.label">{{ props.label }}</Label>
|
||||
<Input v-model="value" :aria-invalid="!!errorMessage || undefined" v-bind="$attrs" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
37
front/components/Field/InputGroupField.vue
Normal file
37
front/components/Field/InputGroupField.vue
Normal file
@@ -0,0 +1,37 @@
|
||||
<script setup lang="ts">
|
||||
import { Label } from '@/components/ui/label'
|
||||
import type { RuleExpression } from 'vee-validate'
|
||||
const props = defineProps<{
|
||||
name: string
|
||||
label?: string
|
||||
rules?: RuleExpression<string[]>
|
||||
}>()
|
||||
const { t } = useI18n()
|
||||
const { value, setValue, errorMessage } = useField<string[]>(props.name, props?.rules)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-2">
|
||||
<Label v-if="label">{{ label }}</Label>
|
||||
<div v-for="(item, index) in value" class="flex flex-row gap-2 items-center">
|
||||
<Input
|
||||
:model-value="item"
|
||||
@update:model-value="(v: string | number) => setValue(value.map((o, i) => (i === index ? String(v) : o)))"
|
||||
:aria-invalid="!!errorMessage || undefined"
|
||||
v-bind="$attrs"
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="bg-red-500/10 text-red-500 hover:bg-red-500 hover:text-white"
|
||||
@click="setValue(value.filter((_, i) => i !== index))"
|
||||
>
|
||||
<LucideTrash class="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<Button class="self-start" size="sm" @click="() => setValue([...(value || []), ''])">
|
||||
<LucidePlus class="size-4" />
|
||||
{{ t('common.add') }}
|
||||
</Button>
|
||||
</div>
|
||||
</template>
|
||||
102
front/components/Field/KvInputGroupField.vue
Normal file
102
front/components/Field/KvInputGroupField.vue
Normal file
@@ -0,0 +1,102 @@
|
||||
<script setup lang="ts">
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { AutocompleteAnchor, AutocompleteContent, AutocompleteInput, AutocompleteItem, AutocompleteRoot, AutocompleteViewport } from 'reka-ui'
|
||||
import type { Component } from 'vue'
|
||||
import InputField from '../Field/InputField.vue'
|
||||
|
||||
type KvInputValueComponentConfig = [(key: string) => boolean, Component]
|
||||
|
||||
type KvInputConfig = {
|
||||
key?: {
|
||||
placeholder?: string
|
||||
enum?: string[]
|
||||
}
|
||||
value?: {
|
||||
placeholder?: string
|
||||
component?: KvInputValueComponentConfig[]
|
||||
default?: Component
|
||||
}
|
||||
}
|
||||
|
||||
const defaultConfig = {
|
||||
key: {},
|
||||
value: {
|
||||
default: InputField,
|
||||
},
|
||||
} satisfies Required<KvInputConfig>
|
||||
|
||||
const props = defineProps<{
|
||||
name: string
|
||||
label?: string
|
||||
config?: KvInputConfig
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const config = computed(() => {
|
||||
return {
|
||||
key: { ...defaultConfig.key, ...(props.config?.key ?? {}) },
|
||||
value: { ...defaultConfig.value, ...(props.config?.value ?? {}) },
|
||||
}
|
||||
})
|
||||
|
||||
const { value, setValue } = useField<[string, string][]>(props.name)
|
||||
|
||||
const updateKey = (index: number, nextKey: string | number) => {
|
||||
const next = [...(value.value ?? [])]
|
||||
next[index] = [String(nextKey), next[index]?.[1] ?? '']
|
||||
setValue(next)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-2">
|
||||
<Label v-if="label">{{ label }}</Label>
|
||||
<div v-for="([key, _], index) in value" class="flex flex-row gap-2 items-center">
|
||||
<AutocompleteRoot class="basis-40 relative" :model-value="String(key ?? '')" @update:model-value="(v) => updateKey(index, v)">
|
||||
<AutocompleteAnchor>
|
||||
<AutocompleteInput
|
||||
class="w-full placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm"
|
||||
:placeholder="config.key.placeholder"
|
||||
>
|
||||
</AutocompleteInput>
|
||||
</AutocompleteAnchor>
|
||||
<AutocompleteContent
|
||||
v-if="config.key?.enum"
|
||||
class="bg-popover border rounded-md shadow-md z-50 w-(--reka-autocomplete-trigger-width) absolute inset-x-0"
|
||||
>
|
||||
<AutocompleteViewport class="p-1">
|
||||
<AutocompleteItem
|
||||
v-for="opt in config.key?.enum"
|
||||
:key="opt"
|
||||
:value="opt"
|
||||
class="relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-highlighted:bg-accent data-highlighted:text-accent-foreground"
|
||||
>
|
||||
{{ opt }}
|
||||
</AutocompleteItem>
|
||||
</AutocompleteViewport>
|
||||
</AutocompleteContent>
|
||||
</AutocompleteRoot>
|
||||
<div class="flex-1">
|
||||
<component
|
||||
:is="config.value.component?.find(([isMatchCom]) => isMatchCom(key))?.[1] ?? config.value.default"
|
||||
:name="`${props.name}[${index}][1]`"
|
||||
:placeholder="config.value.placeholder"
|
||||
class="w-full"
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="bg-red-500/10 text-red-500 hover:bg-red-500 hover:text-white"
|
||||
@click="() => setValue(value?.filter((_, i) => i !== index))"
|
||||
>
|
||||
<LucideTrash class="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<Button type="button" class="self-start" size="sm" @click="() => setValue([...(value ?? []), ['', '']])">
|
||||
<LucidePlus class="size-4" />
|
||||
{{ t('common.add') }}
|
||||
</Button>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,13 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import type { RuleExpression } from 'vee-validate'
|
||||
type SelectValue = string | number
|
||||
const props = defineProps<{
|
||||
@@ -19,13 +11,14 @@ const props = defineProps<{
|
||||
label?: string
|
||||
value: SelectValue
|
||||
}[]
|
||||
class?: string
|
||||
}>()
|
||||
const { value } = useField<SelectValue>(props.name, props?.rules)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Select v-model="value">
|
||||
<SelectTrigger>
|
||||
<SelectTrigger :class="class">
|
||||
<SelectValue :placeholder="placeholder" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
@@ -37,4 +30,4 @@ const { value } = useField<SelectValue>(props.name, props?.rules)
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
25
front/components/Field/TextareaField.vue
Normal file
25
front/components/Field/TextareaField.vue
Normal file
@@ -0,0 +1,25 @@
|
||||
<script setup lang="ts">
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
name: string
|
||||
label?: string
|
||||
placeholder?: string
|
||||
rows?: number
|
||||
}>(),
|
||||
{
|
||||
rows: 3,
|
||||
}
|
||||
)
|
||||
|
||||
const { value } = useField<string>(props.name)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-2">
|
||||
<Label v-if="label">{{ label }}</Label>
|
||||
<Textarea v-model="value" :placeholder="placeholder" :rows="rows" v-bind="$attrs" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,38 +1,19 @@
|
||||
<script setup lang="ts">
|
||||
import { cx } from 'class-variance-authority'
|
||||
export type filePreview = {
|
||||
type: string
|
||||
name: string
|
||||
size: number
|
||||
}
|
||||
|
||||
import { LucideFileAudio, LucideFileVideo, LucideFile, LucideFileCode, LucideFileArchive, LucideFileText } from 'lucide-vue-next'
|
||||
import type { filePreview } from './Index.vue'
|
||||
|
||||
const props = defineProps<{
|
||||
file: File | filePreview
|
||||
class?: string
|
||||
}>()
|
||||
const imageUrl = computed(() => {
|
||||
if (props?.file?.type?.startsWith('image/') && props?.file instanceof File) {
|
||||
return URL.createObjectURL(props?.file)
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (imageUrl.value) {
|
||||
URL.revokeObjectURL(imageUrl.value)
|
||||
}
|
||||
})
|
||||
|
||||
const fileIcon = computed(() => {
|
||||
const [baseType, type] = props?.file?.type?.split('/')
|
||||
if (baseType === 'video') {
|
||||
return LucideFileVideo
|
||||
}
|
||||
// if (baseType === 'video') {
|
||||
// return LucideFileVideo
|
||||
// }
|
||||
if (baseType === 'audio') {
|
||||
return LucideFileAudio
|
||||
}
|
||||
if (baseType === 'text' || ['json', 'ld+json', 'html']?.includes(type)) {
|
||||
if (baseType === 'text' || ['json', 'ld+json', 'html']?.includes(type ?? '')) {
|
||||
return LucideFileCode
|
||||
}
|
||||
if (
|
||||
@@ -44,11 +25,11 @@ const fileIcon = computed(() => {
|
||||
'vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'vnd.ms-powerpoint',
|
||||
'vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
].includes(type)
|
||||
].includes(type ?? '')
|
||||
) {
|
||||
return LucideFileText
|
||||
}
|
||||
if (['zip', 'vnd.rar', 'x-tar', 'gz', 'bz2', 'x-7z-compressed'].includes(type)) {
|
||||
if (['zip', 'vnd.rar', 'x-tar', 'gz', 'bz2', 'x-7z-compressed'].includes(type ?? '')) {
|
||||
return LucideFileArchive
|
||||
}
|
||||
return LucideFile
|
||||
@@ -56,12 +37,5 @@ const fileIcon = computed(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="!!imageUrl" class="flex max-w-30 max-h-20">
|
||||
<div class="object-contain m-auto h-full">
|
||||
<img :src="imageUrl" class="w-full h-full border border-black/20 rounded" />
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!imageUrl" :class="cx('flex justify-center items-center rounded-xl bg-white/80 size-16', props?.class)">
|
||||
<component :is="fileIcon" class="size-[62.5%]" />
|
||||
</div>
|
||||
<component :is="fileIcon" />
|
||||
</template>
|
||||
29
front/components/FileIcon/Image.vue
Normal file
29
front/components/FileIcon/Image.vue
Normal file
@@ -0,0 +1,29 @@
|
||||
<script setup lang="ts">
|
||||
import { isHeic, heicTo } from 'heic-to'
|
||||
|
||||
const props = defineProps<{
|
||||
file: File
|
||||
}>()
|
||||
|
||||
const { state: imageUrl } = useAsyncState(async () => {
|
||||
let blob: Blob = props?.file
|
||||
if (await isHeic(props?.file)) {
|
||||
blob = await heicTo({
|
||||
blob: props?.file,
|
||||
type: 'image/jpeg',
|
||||
quality: 1,
|
||||
})
|
||||
}
|
||||
return URL.createObjectURL(blob)
|
||||
}, null)
|
||||
|
||||
onUnmounted(() => {
|
||||
if (imageUrl.value) {
|
||||
URL.revokeObjectURL(imageUrl.value)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<img v-if="!!imageUrl" :src="imageUrl" />
|
||||
</template>
|
||||
61
front/components/FileIcon/Index.vue
Normal file
61
front/components/FileIcon/Index.vue
Normal file
@@ -0,0 +1,61 @@
|
||||
<script setup lang="ts">
|
||||
import { cx } from 'class-variance-authority'
|
||||
import FileIcon from './File.vue'
|
||||
import ImageIcon from './Image.vue'
|
||||
import VideoIcon from './Video.vue'
|
||||
import { fileTypeFromBuffer } from 'file-type'
|
||||
|
||||
export type filePreview = {
|
||||
type: string
|
||||
name: string
|
||||
size: number
|
||||
}
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
file: File | filePreview
|
||||
class?: string
|
||||
size?: 'sm' | 'md' | 'lg'
|
||||
}>(),
|
||||
{
|
||||
size: 'md',
|
||||
}
|
||||
)
|
||||
const isFile = computed(() => props?.file instanceof File)
|
||||
const { state: fileType } = useAsyncState(async () => {
|
||||
if (!isFile.value) {
|
||||
return null
|
||||
}
|
||||
if (!!props?.file?.type) {
|
||||
return props?.file?.type
|
||||
}
|
||||
const { mime } = (await fileTypeFromBuffer(await (props?.file as File)?.arrayBuffer())) || {}
|
||||
return mime
|
||||
}, null)
|
||||
|
||||
const isImage = computed(() => isFile.value && fileType.value?.startsWith('image/'))
|
||||
const isVideo = computed(() => isFile.value && fileType.value?.startsWith('video/'))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="isImage || isVideo" :class="cx('flex overflow-hidden', size === 'sm' && 'max-w-20 max-h-16', size === 'md' && 'max-w-30 max-h-20')">
|
||||
<component
|
||||
:is="isImage ? ImageIcon : VideoIcon"
|
||||
:file="props?.file as File"
|
||||
class="block max-w-full max-h-full object-contain border border-black/20 rounded"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
:class="
|
||||
cx(
|
||||
'flex justify-center items-center bg-white/80',
|
||||
size === 'sm' && 'size-7 rounded-md',
|
||||
size === 'md' && 'size-16 rounded-xl',
|
||||
props?.class
|
||||
)
|
||||
"
|
||||
>
|
||||
<component :is="FileIcon" :file="props?.file" class="size-[62.5%]" />
|
||||
</div>
|
||||
</template>
|
||||
27
front/components/FileIcon/Video.vue
Normal file
27
front/components/FileIcon/Video.vue
Normal file
@@ -0,0 +1,27 @@
|
||||
<script setup lang="ts">
|
||||
import getVideoFileThumbnail from '@/lib/getVideoFileThumbnail'
|
||||
|
||||
const props = defineProps<{
|
||||
file: File
|
||||
}>()
|
||||
|
||||
const { state: thumbnailUrl } = useAsyncState(async () => {
|
||||
if (props.file.type.startsWith('video/')) {
|
||||
return await getVideoFileThumbnail(props.file)
|
||||
}
|
||||
return null
|
||||
}, null)
|
||||
|
||||
onUnmounted(() => {
|
||||
if (!!thumbnailUrl.value) {
|
||||
URL.revokeObjectURL(thumbnailUrl.value)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="thumbnailUrl" class="relative grayscale-50 overflow-hidden">
|
||||
<img :src="thumbnailUrl" class="object-contain block max-w-full max-h-full" />
|
||||
<LucidePlay class="size-[40%] absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-white" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts" setup>
|
||||
import getFileSize from '~/lib/getFileSize'
|
||||
import type { filePreview } from './FileIcon.vue'
|
||||
import type { filePreview } from './FileIcon/Index.vue'
|
||||
const props = defineProps<{
|
||||
value: File | filePreview
|
||||
}>()
|
||||
|
||||
@@ -3,63 +3,63 @@ import { useDropZone } from '@vueuse/core'
|
||||
const dropZoneRef = ref()
|
||||
|
||||
const props = defineProps<{
|
||||
accept?: string[]
|
||||
accept?: string[]
|
||||
}>()
|
||||
|
||||
const accept = computed(() => (props?.accept || ['*'])?.join(','))
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'onChange', file: File): void
|
||||
(e: 'onChange', file: File[]): void
|
||||
}>()
|
||||
|
||||
const { isOverDropZone } = useDropZone(dropZoneRef, {
|
||||
onDrop: (file) => {
|
||||
if (file?.[0]) {
|
||||
emit('onChange', file?.[0])
|
||||
}
|
||||
},
|
||||
// 指定要接收的数据类型
|
||||
dataTypes: (types) => {
|
||||
for (const type of types) {
|
||||
for (const acceptType of accept.value.split(',')) {
|
||||
if (acceptType === '*') {
|
||||
return true
|
||||
onDrop: (file) => {
|
||||
if (!!file && file?.length > 0) {
|
||||
emit('onChange', file)
|
||||
}
|
||||
if (acceptType?.endsWith('*')) {
|
||||
const [acceptTypePrefix,] = acceptType?.split('/')
|
||||
if (!acceptTypePrefix) {
|
||||
return true
|
||||
}
|
||||
if (type?.startsWith(acceptTypePrefix)) {
|
||||
return true
|
||||
}
|
||||
},
|
||||
// 指定要接收的数据类型
|
||||
dataTypes: (types) => {
|
||||
for (const type of types) {
|
||||
for (const acceptType of accept.value.split(',')) {
|
||||
if (acceptType === '*') {
|
||||
return true
|
||||
}
|
||||
if (acceptType?.endsWith('*')) {
|
||||
const [acceptTypePrefix] = acceptType?.split('/')
|
||||
if (!acceptTypePrefix) {
|
||||
return true
|
||||
}
|
||||
if (type?.startsWith(acceptTypePrefix)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if (acceptType === type) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
if (acceptType === type) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
},
|
||||
// 控制多文件拖放
|
||||
multiple: false,
|
||||
// 是否阻止未处理事件的默认行为
|
||||
preventDefaultForUnhandled: false,
|
||||
return false
|
||||
},
|
||||
// 控制多文件拖放
|
||||
multiple: true,
|
||||
// 是否阻止未处理事件的默认行为
|
||||
preventDefaultForUnhandled: false,
|
||||
})
|
||||
|
||||
const { open, onChange } = useFileDialog({
|
||||
accept: accept.value, // Set to accept only image files
|
||||
directory: false,
|
||||
accept: accept.value, // Set to accept only image files
|
||||
directory: false,
|
||||
})
|
||||
onChange((files) => {
|
||||
if (files?.[0]) {
|
||||
emit('onChange', files?.[0])
|
||||
}
|
||||
if (!!files && files?.length > 0) {
|
||||
emit('onChange', Array.from(files))
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="dropZoneRef" @click="open">
|
||||
<slot :isOverDropZone="isOverDropZone" />
|
||||
</div>
|
||||
</template>
|
||||
<div ref="dropZoneRef" @click="() => open()">
|
||||
<slot :isOverDropZone="isOverDropZone" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -12,3 +12,5 @@ watchEffect(() => {
|
||||
dayjs.locale(locale.value.toLowerCase())
|
||||
})
|
||||
</script>
|
||||
|
||||
<template></template>
|
||||
|
||||
@@ -1,35 +1,44 @@
|
||||
<script setup lang="ts">
|
||||
import { Drawer, DrawerContent } from '@/components/ui/drawer'
|
||||
import { createVNode } from 'vue'
|
||||
import type { VNode } from 'vue'
|
||||
import useStore from '@/composables/useStore'
|
||||
import { isFunction } from 'lodash-es'
|
||||
|
||||
type DrawerOnclose<T = unknown> = (data?: T) => Promise<void>
|
||||
type DrawerRender<T = unknown> = VNode | ((props: { hide: DrawerOnclose<T> }) => VNode)
|
||||
export type DrawerItem<T = unknown> = {
|
||||
render?: DrawerRender<T>
|
||||
onClose: DrawerOnclose<T>
|
||||
key: string
|
||||
visible: boolean
|
||||
}
|
||||
|
||||
const store = useStore()
|
||||
const currentDrawer = computed(() => store.drawer?.[store.drawer?.length - 1])
|
||||
|
||||
const render = computed(() => currentDrawer?.value?.render)
|
||||
const hide = computed(() => currentDrawer?.value?.onClose)
|
||||
const Children = () =>
|
||||
render.value
|
||||
? createVNode(render.value, {
|
||||
hide: hide?.value,
|
||||
})
|
||||
: null
|
||||
const Children = ({ drawer }: { drawer: DrawerItem }) => {
|
||||
if (!drawer.render) {
|
||||
return null
|
||||
}
|
||||
return isFunction(drawer.render) ? drawer.render({ hide: drawer.onClose }) : drawer.render
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Drawer
|
||||
:open="!!store.drawer?.[store.drawer?.length - 1]"
|
||||
v-for="item in store.drawer"
|
||||
:key="item.key"
|
||||
:open="item.visible"
|
||||
@update:open="
|
||||
(open) => {
|
||||
if (!open && store?.drawer?.length && hide) {
|
||||
hide()
|
||||
if (!open) {
|
||||
item.onClose()
|
||||
}
|
||||
}
|
||||
"
|
||||
>
|
||||
<DrawerContent>
|
||||
<div class="mx-auto w-full max-w-lg pb-10 px-3">
|
||||
<Children />
|
||||
<div class="mx-auto min-w-lg max-w-[80vw] pb-10 px-3">
|
||||
<Children :drawer="item" />
|
||||
</div>
|
||||
</DrawerContent>
|
||||
</Drawer>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts" setup>
|
||||
import VeeForm from '@/components/VeeForm.vue'
|
||||
import FileUploadInputFileView from './FileUploadInputFileView.vue'
|
||||
import FileUploadProgressView from './FileUploadProgressView.vue'
|
||||
import FileUploadProgressView from './FileUploadProgressView/index.vue'
|
||||
import ResultIndexView from '@/components/Result/ResultIndexView.vue'
|
||||
|
||||
const fileStepList = [
|
||||
@@ -16,19 +16,26 @@ const renderComponent = computed(() => {
|
||||
return fileStepList.find((item) => item.key === step.value)?.component
|
||||
})
|
||||
const formRef = ref<InstanceType<typeof VeeForm>>()
|
||||
watch(() => step.value, (newVal) => {
|
||||
if (newVal === 'input') {
|
||||
formRef.value?.form?.resetForm()
|
||||
formRef.value?.form?.setValues({ file: null })
|
||||
watch(
|
||||
() => step.value,
|
||||
(newVal) => {
|
||||
if (newVal === 'input') {
|
||||
formRef.value?.form?.resetForm()
|
||||
formRef.value?.form?.setValues({ file: null })
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
</script>
|
||||
<template>
|
||||
<VeeForm ref="formRef" v-slot="{ values }" :keepValues="true">
|
||||
<div class="rounded-xl p-5 bg-white/50 backdrop-blur-xl w-full lg:w-200">
|
||||
<component :is="renderComponent" :data="values" @change="(key: string) => {
|
||||
step = key
|
||||
}" />
|
||||
</div>
|
||||
<component
|
||||
:is="renderComponent"
|
||||
:data="values"
|
||||
@change="
|
||||
(key: string) => {
|
||||
step = key
|
||||
}
|
||||
"
|
||||
/>
|
||||
</VeeForm>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
@@ -1,42 +1,39 @@
|
||||
<script lang="ts" setup>
|
||||
import showDrawer from "@/lib/showDrawer";
|
||||
import FileShareDrawer from "@/components/Drawer/FileShareDrawer.vue";
|
||||
import FileUploadField from "@/components/Field/FileUploadField.vue";
|
||||
import FormButton from "@/components/Field/FormButton.vue";
|
||||
import PickupShareBtn from "@/components/PickupShareBtn.vue";
|
||||
import showDrawer from '@/lib/showDrawer'
|
||||
import FileShareDrawer from '@/components/Drawer/FileShareDrawer.vue'
|
||||
import FileUploadField from '@/components/Field/FileUploadField.vue'
|
||||
import FormButton from '@/components/Field/FormButton.vue'
|
||||
import PickupShareBtn from '@/components/PickupShareBtn.vue'
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: "change", key: string): void;
|
||||
}>();
|
||||
(e: 'change', key: string): void
|
||||
}>()
|
||||
|
||||
const { t } = useI18n();
|
||||
const { t } = useI18n()
|
||||
|
||||
const handleFormSubmit = async (form: any) => {
|
||||
const { file } = form?.values || {};
|
||||
showDrawer({
|
||||
render: ({ hide }) =>
|
||||
h(FileShareDrawer, {
|
||||
hide,
|
||||
file,
|
||||
onFileHandle: ({ type, config }) => {
|
||||
form.setFieldValue("handle_type", type);
|
||||
form.setFieldValue("config", config);
|
||||
emit("change", "progress");
|
||||
},
|
||||
}),
|
||||
});
|
||||
};
|
||||
const { file } = form?.values || {}
|
||||
showDrawer({
|
||||
render: ({ hide }) =>
|
||||
h(FileShareDrawer, {
|
||||
hide,
|
||||
file,
|
||||
onFileHandle: ({ type, config }) => {
|
||||
form.setFieldValue('handle_type', type)
|
||||
form.setFieldValue('config', config)
|
||||
emit('change', 'progress')
|
||||
},
|
||||
}),
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="gap-5 flex flex-col">
|
||||
<div class="text-xl font-normal">{{ t("file.uploadFile") }}</div>
|
||||
<FileUploadField name="file" rules="required" />
|
||||
<div class="flex flex-row gap-3">
|
||||
<FormButton @click="handleFormSubmit">
|
||||
<LucideShare class="size-4" />{{ t("btn.submit") }}
|
||||
</FormButton>
|
||||
<PickupShareBtn />
|
||||
</div>
|
||||
</div>
|
||||
<BaseCard class="gap-5 flex flex-col" :title="t('page.upload.file.uploadFile')">
|
||||
<FileUploadField name="file" rules="required" />
|
||||
<div class="flex flex-row gap-3">
|
||||
<FormButton @click="handleFormSubmit"> <LucideShare class="size-4" />{{ t('btn.submit') }} </FormButton>
|
||||
<PickupShareBtn />
|
||||
</div>
|
||||
</BaseCard>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
<script setup lang="ts">
|
||||
import getFileSize from '~/lib/getFileSize'
|
||||
import { clamp } from 'lodash-es'
|
||||
import FileUploadBlockProgressView from '@/components/FileUploadBlockProgressView.vue'
|
||||
import FileUploadHeatMapView from '@/components/FileUploadHeatMapView.vue'
|
||||
import type { SelectedFile, Uploadfile } from './types'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const props = defineProps<{
|
||||
uploadfiles: Uploadfile[]
|
||||
selectedFile: SelectedFile
|
||||
}>()
|
||||
const selectedUploadfile = computed(() => props.uploadfiles.find((item) => item.fileId === props.selectedFile))
|
||||
const selectedUploadfileChunk = computed(() => Object.values(selectedUploadfile.value?.uploadInfo?.chunks || {}))
|
||||
const selectedUploadfileViewMode = ref<'progress' | 'heatmap'>('progress')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="col-span-4 flex flex-col bg-white/80 rounded-xl p-3 gap-5" v-if="selectedFile">
|
||||
<div class="flex flex-row gap-2 items-center">
|
||||
<LucideInfo class="size-4" />
|
||||
{{ t('page.progress.file.uploadDetails') }}
|
||||
</div>
|
||||
<div class="grid grid-cols-3 text-sm gap-3">
|
||||
<div>
|
||||
{{ t('page.progress.file.chunk') }}: {{ selectedUploadfile?.uploadInfo?.chunkLength }} x
|
||||
{{ getFileSize(selectedUploadfile?.uploadInfo?.ChunkSize as number) }}
|
||||
</div>
|
||||
<div class="truncate col-span-2">Hash: {{ selectedUploadfile?.hash }}</div>
|
||||
<div>{{ t('page.progress.file.completed') }}: {{ selectedUploadfileChunk?.filter((r) => r.status === 'success')?.length || 0 }}</div>
|
||||
<div>{{ t('page.progress.file.discarded') }}: {{ selectedUploadfileChunk?.filter((r) => r.status === 'error')?.length || 0 }}</div>
|
||||
<div>
|
||||
{{ t('page.progress.file.pending') }}:
|
||||
{{ (selectedUploadfile?.uploadInfo?.chunkLength || 0) - (selectedUploadfileChunk?.length || 0) }}
|
||||
</div>
|
||||
<div class="col-span-3 flex flex-row justify-between items-center">
|
||||
<div class="text-md font-bold">
|
||||
{{ selectedUploadfileViewMode === 'progress' ? t('page.progress.file.chunkProgress') : t('page.progress.file.chunkHeatmap') }}
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
class="ml-auto text-xs"
|
||||
@click="selectedUploadfileViewMode = selectedUploadfileViewMode === 'progress' ? 'heatmap' : 'progress'"
|
||||
>
|
||||
<LucideArrowDownUp class="size-4" />
|
||||
{{ selectedUploadfileViewMode === 'progress' ? t('page.progress.file.heatmap') : t('page.progress.file.progressBar') }}
|
||||
</Button>
|
||||
</div>
|
||||
<div class="h-7 col-span-3 flex flex-row gap-2 items-center" v-if="selectedUploadfileViewMode === 'progress'">
|
||||
<div class="flex-1 h-full">
|
||||
<FileUploadBlockProgressView :data="selectedUploadfile?.uploadInfo" />
|
||||
</div>
|
||||
{{ clamp(((selectedUploadfileChunk?.length || 0) / (selectedUploadfile?.uploadInfo?.chunkLength || 0)) * 100, 0, 100)?.toFixed(2) }}%
|
||||
</div>
|
||||
<div v-if="selectedUploadfileViewMode === 'heatmap'" class="col-span-3 bg-black/5 rounded p-2">
|
||||
<FileUploadHeatMapView :size="12" :data="selectedUploadfile?.uploadInfo" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,18 @@
|
||||
<script setup lang="ts">
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
<template>
|
||||
<div class="flex flex-col gap-2 pt-3">
|
||||
<div class="text-xl font-bold">{{ t('page.progress.file.uploadSpeedInfo.title') }}</div>
|
||||
<div class="opacity-75">
|
||||
<i18n-t keypath="page.progress.file.uploadSpeedInfo.desc.base">
|
||||
<template #chunkNum>
|
||||
<b>{{ t('page.progress.file.uploadSpeedInfo.desc.chunkNum') }}</b>
|
||||
</template>
|
||||
<template #chunkSize>
|
||||
<b>{{ t('page.progress.file.uploadSpeedInfo.desc.chunkSize') }}</b>
|
||||
</template>
|
||||
</i18n-t>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,78 @@
|
||||
<script setup lang="ts">
|
||||
import type { Uploadfile } from './types'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { uploadfiles } = defineProps<{
|
||||
uploadfiles: Uploadfile[]
|
||||
}>()
|
||||
const totalTaskStatus = computed(() => {
|
||||
if (uploadfiles.some((r) => r.status === 'start')) {
|
||||
return 'start'
|
||||
}
|
||||
if (uploadfiles.some((r) => r.status === 'pause')) {
|
||||
return 'pause'
|
||||
}
|
||||
return 'disabled'
|
||||
})
|
||||
const totalUploadProgress = computed(() => {
|
||||
const successCount = uploadfiles.reduce((acc, curr) => {
|
||||
const { status, uploadInfo } = curr || {}
|
||||
if (status === 'finish') return acc
|
||||
const { chunks } = uploadInfo || {}
|
||||
return acc + Object.entries(chunks || {}).filter(([index, chunk]) => chunk.status === 'success').length
|
||||
}, 0)
|
||||
const totalCount = uploadfiles.reduce((acc, curr) => {
|
||||
const { status, uploadInfo } = curr || {}
|
||||
if (status === 'finish') return acc
|
||||
const { chunkLength } = uploadInfo || {}
|
||||
return acc + (chunkLength || 0)
|
||||
}, 0)
|
||||
return ((successCount || 0) / (totalCount || 0)) * 100
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="rounded-xl col-span-4 md:col-span-1 bg-white/80 h-32 md:h-auto md:aspect-square flex flex-col gap-2 relative overflow-hidden">
|
||||
<div class="absolute top-0 left-0 w-full h-full z-[0] flex flex-col justify-end">
|
||||
<div class="w-full bg-green-100 border-t border-green-500" :style="`height: ${totalUploadProgress || 0}%`"></div>
|
||||
</div>
|
||||
<div class="flex flex-col gap-2 justify-between p-3 h-full relative z-[1]">
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="text-xs opacity-70">{{ t('page.progress.file.totalUploadProgress') }}</div>
|
||||
<div class="text-4xl font-bold">{{ (totalUploadProgress || 0).toFixed(1) }}%</div>
|
||||
</div>
|
||||
<div class="flex flex-row gap-2">
|
||||
<Button
|
||||
class="aspect-square hover:text-white p-0 bg-green-200 hover:bg-green-300 text-green-500"
|
||||
:disabled="['start', 'disabled'].includes(totalTaskStatus)"
|
||||
@click="
|
||||
() => {
|
||||
uploadfiles.forEach((r) => {
|
||||
r.status = 'start'
|
||||
})
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucidePlay class="size-1/2" />
|
||||
</Button>
|
||||
<Button
|
||||
class="aspect-square hover:text-white p-0 bg-orange-200 hover:bg-orange-300 text-orange-500"
|
||||
:disabled="['pause', 'disabled'].includes(totalTaskStatus)"
|
||||
@click="
|
||||
() => {
|
||||
uploadfiles.forEach((r) => {
|
||||
r.status = 'pause'
|
||||
})
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideSquare class="size-1/2" />
|
||||
</Button>
|
||||
<!-- <Button class="aspect-square bg-blue-200 hover:bg-blue-300 text-blue-500 hover:text-white p-0">
|
||||
<LucideSettings class="size-1/2" />
|
||||
</Button> -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,60 @@
|
||||
<script setup lang="ts">
|
||||
import dayjs from 'dayjs'
|
||||
import { motion } from 'motion-v'
|
||||
import getFileSize from '~/lib/getFileSize'
|
||||
import showDrawer from '~/lib/showDrawer'
|
||||
import FileUploadSpeedInfoView from './FileUploadSpeedInfoView.vue'
|
||||
import { clamp } from 'lodash-es'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const props = defineProps<{
|
||||
speedChartData: Record<string, { fileId: string; index: number; value: number }[]>
|
||||
}>()
|
||||
const speedChartList = ref<{ timestamp: number; value: number }[]>([])
|
||||
useIntervalFn(() => {
|
||||
speedChartList.value.push({
|
||||
timestamp: dayjs().unix() - 1,
|
||||
value: props.speedChartData[dayjs().unix() - 1]?.reduce((acc, curr) => acc + curr.value, 0) ?? 0,
|
||||
})
|
||||
if (speedChartList.value.length > 60) {
|
||||
speedChartList.value.shift()
|
||||
}
|
||||
}, 1000)
|
||||
|
||||
const handleShowSpeedInfo = () => {
|
||||
showDrawer({
|
||||
render: ({ hide }) => h(FileUploadSpeedInfoView, { hide }),
|
||||
})
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<div class="rounded-xl p-3 bg-white/80 flex flex-col gap-2 col-span-4 md:col-span-3 h-32 md:h-auto">
|
||||
<div class="flex flex-col gap-1">
|
||||
<div @click="handleShowSpeedInfo" class="flex flex-row gap-1 items-center text-xs opacity-70">
|
||||
{{ t('page.progress.file.totalUploadProgress') }}
|
||||
<LucideInfo class="size-3" />
|
||||
</div>
|
||||
<div class="text-2xl font-bold">
|
||||
{{ `${getFileSize(speedChartData[dayjs().unix() - 1]?.reduce((acc, curr) => acc + curr.value, 0) ?? 0) ?? 0}/s` }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-1 relative overflow-hidden flex flex-row gap-0.5 justify-end items-end">
|
||||
<motion.div
|
||||
class="w-2 shrink-0 bg-primary relative"
|
||||
:style="{
|
||||
height: `${clamp((i.value / Math.max(...(speedChartList?.map((r) => r.value) || [1]))) * 100, 1, 100)}%`,
|
||||
}"
|
||||
:layoutId="String(i.timestamp)"
|
||||
v-for="i in speedChartList"
|
||||
:key="i.timestamp"
|
||||
:initial="{ x: 10, opacity: 0 }"
|
||||
:animate="{ x: 0, opacity: 1 }"
|
||||
:transition="{ duration: 1 }"
|
||||
>
|
||||
</motion.div>
|
||||
<!-- <BarChart class="h-full" :data="data" index="time" :categories="['value']" :showTooltip="false"
|
||||
:showLegend="false" :showXAxis="false" :showYAxis="false" :showGrid="false" :groupMaxWidth="10" /> -->
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,21 +1,26 @@
|
||||
<script setup lang="ts">
|
||||
import { LucidePlay, LucideSettings, LucideSquare } from 'lucide-vue-next'
|
||||
import { LucideSquare, LucideInfo, LucideFolders, LucideArrowUpFromLine, LucideCircleX, LucideCheckCircle, LucideLoaderCircle } from 'lucide-vue-next'
|
||||
import Button from '@/components/ui/button/Button.vue'
|
||||
import FileUploadBlockProgressView from '@/components/FileUploadBlockProgressView.vue'
|
||||
import { motion } from 'motion-v'
|
||||
|
||||
import getFileSize from '~/lib/getFileSize'
|
||||
import { cx } from 'class-variance-authority'
|
||||
import asyncWorker from '@/lib/asyncWorker'
|
||||
import calcFileHashWorker from '@/lib/calcFileHashWorker?worker'
|
||||
import { clamp, get, groupBy, isEmpty, isNumber, isString, sample, shuffle, times } from 'lodash-es'
|
||||
import { detectSupportedEngines } from '@/lib/calcFileHash'
|
||||
import { clamp, get, isEmpty, isNumber, sample, shuffle, throttle, times } from 'lodash-es'
|
||||
import { nanoid } from 'nanoid'
|
||||
import { toast } from 'vue-sonner'
|
||||
import dayjs from 'dayjs'
|
||||
import showDrawer from '~/lib/showDrawer'
|
||||
import FileUploadTotalSpeedView from './FileUploadTotalSpeedView.vue'
|
||||
import FileUploadTotalProgressControlView from './FileUploadTotalProgressControlView.vue'
|
||||
import FileUploadSpeedInfoView from './FileUploadSpeedInfoView.vue'
|
||||
import getFileChunk from '~/lib/getFileChunk'
|
||||
import type { FileHandleKey } from '~/components/Preprocessing/types'
|
||||
import asyncWait from '@/lib/asyncWait'
|
||||
import axios from 'axios'
|
||||
import type { SelectedFile, Uploadfile } from './types'
|
||||
import FileUploadDetailView from './FileUploadDetailView.vue'
|
||||
|
||||
const props = defineProps<{
|
||||
data: { file: File[]; config: Record<string, any>; handle_type: FileHandleKey }
|
||||
@@ -24,81 +29,17 @@ const emit = defineEmits<{
|
||||
(e: 'change', key: string): void
|
||||
}>()
|
||||
const form = useFormContext()
|
||||
const { t } = useI18n()
|
||||
|
||||
const selectedFile = ref()
|
||||
const uploadfiles = ref<
|
||||
{
|
||||
fileId: string
|
||||
id?: string // 后端文件id
|
||||
file: File
|
||||
status: 'start' | 'pause' | 'finish' | 'error'
|
||||
hash?: string
|
||||
procressType: 'hash' | 'create' | 'upload' | 'finish'
|
||||
uploadInfo?: {
|
||||
chunks: Record<number, { status: 'success' | 'error' | 'processing'; createdAt: number }>
|
||||
chunkLength: number
|
||||
ChunkSize: number
|
||||
}
|
||||
queue: {
|
||||
taskId: string
|
||||
taskType: 'hash' | 'create' | 'chunk' | 'upload' | 'finish'
|
||||
queueType: 'sync' | 'async' // sync任务禁止并发
|
||||
index?: number
|
||||
retry?: number
|
||||
}[]
|
||||
}[]
|
||||
>([])
|
||||
const selectedUploadfile = computed(() => uploadfiles.value.find((item) => item.fileId === selectedFile.value))
|
||||
const selectedUploadfileChunk = computed(() => Object.values(selectedUploadfile.value?.uploadInfo?.chunks || {}))
|
||||
const selectedUploadfileViewMode = ref<'progress' | 'heatmap'>('progress')
|
||||
const selectedFile = ref<SelectedFile>(null)
|
||||
const uploadfiles = ref<Uploadfile[]>([])
|
||||
|
||||
const procressTaskList = ref<Map<string, any>>(new Map())
|
||||
const activeTaskList = computed(() => uploadfiles.value.filter((r) => r.queue.length > 0 && r.status === 'start'))
|
||||
const activeTaskAllQueue = computed(() => activeTaskList.value.flatMap((r) => r.queue))
|
||||
const batchNum = ref(3)
|
||||
|
||||
const totalTaskStatus = computed(() => {
|
||||
if (uploadfiles.value.some((r) => r.status === 'start')) {
|
||||
return 'start'
|
||||
}
|
||||
if (uploadfiles.value.some((r) => r.status === 'pause')) {
|
||||
return 'pause'
|
||||
}
|
||||
return 'disabled'
|
||||
})
|
||||
const totalUploadProgress = computed(() => {
|
||||
const successCount = uploadfiles.value.reduce((acc, curr) => {
|
||||
const { status, uploadInfo } = curr || {}
|
||||
if (status === 'finish') return acc
|
||||
const { chunks } = uploadInfo || {}
|
||||
return acc + Object.entries(chunks || {}).filter(([index, chunk]) => chunk.status === 'success').length
|
||||
}, 0)
|
||||
const totalCount = uploadfiles.value.reduce((acc, curr) => {
|
||||
const { status, uploadInfo } = curr || {}
|
||||
if (status === 'finish') return acc
|
||||
const { chunkLength } = uploadInfo || {}
|
||||
return acc + (chunkLength || 0)
|
||||
}, 0)
|
||||
return ((successCount || 0) / (totalCount || 0)) * 100
|
||||
})
|
||||
|
||||
const counter = useInterval(1000)
|
||||
const speedChartData = ref<Record<number, { createdAt: number; value: number }[]>>({})
|
||||
watch(counter, () => {
|
||||
const speed = uploadfiles.value?.flatMap((item) => {
|
||||
const { chunks, ChunkSize } = item?.uploadInfo || {}
|
||||
return Object.entries(chunks || {})
|
||||
.filter(([index, chunk]) => chunk.status === 'success' && dayjs().unix() - 60 < chunk.createdAt)
|
||||
?.map(([index, chunk]) => {
|
||||
const { createdAt } = chunk || {}
|
||||
return {
|
||||
createdAt,
|
||||
value: ChunkSize || 0,
|
||||
}
|
||||
})
|
||||
})
|
||||
speedChartData.value = groupBy(speed, 'createdAt')
|
||||
})
|
||||
const speedChartData = ref<Record<number, { fileId: string; index: number; value: number }[]>>({})
|
||||
|
||||
onMounted(() => {
|
||||
props.data.file.forEach((file) => {
|
||||
@@ -136,10 +77,10 @@ const { error, execute, isLoading } = useAsyncState(
|
||||
|
||||
if (queueType === 'async') {
|
||||
if (!!retry && retry >= 3) {
|
||||
toast.error('上传错误', {
|
||||
description: `文件 ${file?.file?.name} 的${index}分块经过多次尝试依然上传失败, 我们已经终止该文件上传`,
|
||||
toast.error(t('page.progress.file.uploadError'), {
|
||||
description: t('page.progress.file.chunkUploadFailed', [file?.file?.name, index]),
|
||||
})
|
||||
uploadfiles.value[uploadFileIndex].status = 'error'
|
||||
uploadfiles.value[uploadFileIndex]!.status = 'error'
|
||||
return
|
||||
}
|
||||
uploadfiles.value[uploadFileIndex]?.queue.shift()
|
||||
@@ -170,14 +111,14 @@ const { error, execute, isLoading } = useAsyncState(
|
||||
// todo 重新加入队列
|
||||
if (queueType === 'async') {
|
||||
uploadfiles.value[uploadFileIndex]?.queue.push({ ...task, retry: (task?.retry || 0) + 1 })
|
||||
toast.warning('上传错误', {
|
||||
description: `文件 ${file?.file?.name} 的${index}分块上传失败, 我们将在稍后再次尝试上传`,
|
||||
toast.warning(t('page.progress.file.uploadError'), {
|
||||
description: t('page.progress.file.chunkUploadRetry', [file?.file?.name, index]),
|
||||
})
|
||||
}
|
||||
if (queueType === 'sync') {
|
||||
uploadfiles.value[uploadFileIndex].status = 'error'
|
||||
toast.error('上传错误', {
|
||||
description: `文件${file?.file?.name}上传失败, 请重试`,
|
||||
uploadfiles.value[uploadFileIndex]!.status = 'error'
|
||||
toast.error(t('page.progress.file.uploadError'), {
|
||||
description: t('page.progress.file.fileUploadFailed', [file?.file?.name]),
|
||||
})
|
||||
}
|
||||
} finally {
|
||||
@@ -197,11 +138,20 @@ watchEffect(async () => {
|
||||
}
|
||||
})
|
||||
|
||||
const LARGE_FILE_THRESHOLD = 500 * 1024 * 1024 // 500 MB
|
||||
|
||||
const handleHash = async (fileId: string) => {
|
||||
const uploadfile = uploadfiles.value.find((item) => item.fileId === fileId)
|
||||
if (!uploadfile?.file) return
|
||||
uploadfile.procressType = 'hash'
|
||||
const res = await asyncWorker(calcFileHashWorker, { data: { file: uploadfile.file } })
|
||||
const supportedEngines = detectSupportedEngines()
|
||||
if (supportedEngines.length === 0) {
|
||||
throw new Error(t('page.progress.file.hashEngineNotFound'))
|
||||
}
|
||||
const preferredEngine = uploadfile.file.size >= LARGE_FILE_THRESHOLD ? 'wasm' : 'native'
|
||||
const res = await asyncWorker(calcFileHashWorker, {
|
||||
data: { file: uploadfile.file, engine: supportedEngines.includes(preferredEngine) ? preferredEngine : supportedEngines?.[0] },
|
||||
})
|
||||
const { hash } = res?.data || {}
|
||||
uploadfile.hash = hash
|
||||
}
|
||||
@@ -218,6 +168,7 @@ const handleCreate = async (fileId: string) => {
|
||||
id: string
|
||||
type: 'init' | 'already'
|
||||
chunk_size: number
|
||||
chunks: number[]
|
||||
}
|
||||
}>('/api/file/create', {
|
||||
method: 'POST',
|
||||
@@ -227,10 +178,10 @@ const handleCreate = async (fileId: string) => {
|
||||
hash,
|
||||
},
|
||||
})
|
||||
const { id, chunk_size, type: createType } = createData?.data || {}
|
||||
const { id, chunk_size, type: createType, chunks = [] } = createData?.data || {}
|
||||
uploadfile.id = id
|
||||
uploadfile.uploadInfo = {
|
||||
chunks: {},
|
||||
chunks: Object.fromEntries(chunks.map((index: number) => [index - 1, { status: 'success', createdAt: dayjs().unix() }])),
|
||||
chunkLength: Math.ceil(size / chunk_size),
|
||||
ChunkSize: chunk_size,
|
||||
}
|
||||
@@ -277,17 +228,18 @@ const handleUpload = async (fileId: string, index: number) => {
|
||||
formData.append('file', new Blob([chunk]))
|
||||
formData.append('index', (index + 1).toString())
|
||||
formData.append('id', id)
|
||||
const res = await $fetch<{
|
||||
code: number
|
||||
}>('/api/file/slice', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
const { data: res } = await axios.post('/api/file/slice', formData, {
|
||||
onUploadProgress: throttle((progressEvent) => {
|
||||
const { rate } = progressEvent || {}
|
||||
const timestamp = dayjs().unix()
|
||||
speedChartData.value[timestamp] = [...(speedChartData.value[timestamp] || []), { fileId, index, value: rate || 0 }]
|
||||
}, 1000),
|
||||
})
|
||||
const { code } = res || {}
|
||||
if (code !== 200) {
|
||||
throw new Error('上传失败')
|
||||
throw new Error(t('page.progress.file.uploadFailed'))
|
||||
}
|
||||
uploadfile.uploadInfo!.chunks[index].status = 'success'
|
||||
uploadfile.uploadInfo!.chunks![index]!.status = 'success'
|
||||
if (Object.entries(uploadfile.uploadInfo!.chunks || {}).filter(([index, chunk]) => chunk.status === 'success').length === chunkLength) {
|
||||
uploadfile.queue.push({ taskType: 'finish', queueType: 'sync', taskId: nanoid() })
|
||||
}
|
||||
@@ -307,7 +259,7 @@ const handleFinish = async (fileId: string) => {
|
||||
},
|
||||
})
|
||||
if (res?.code !== 200) {
|
||||
throw new Error('上传失败')
|
||||
throw new Error(t('page.progress.file.uploadFailed'))
|
||||
}
|
||||
uploadfile.status = 'finish'
|
||||
}
|
||||
@@ -341,102 +293,29 @@ const handleShowSpeedInfo = () => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="grid grid-cols-4 gap-5">
|
||||
<div class="rounded-xl p-3 bg-white/80 flex flex-col gap-2 col-span-4 md:col-span-3 h-32 md:h-auto">
|
||||
<div class="flex flex-col gap-1">
|
||||
<div @click="handleShowSpeedInfo" class="flex flex-row gap-1 items-center text-xs opacity-70">
|
||||
总上传进度
|
||||
<LucideInfo class="size-3" />
|
||||
</div>
|
||||
<div class="text-2xl font-bold">
|
||||
{{
|
||||
`${
|
||||
getFileSize(
|
||||
Object.entries(speedChartData)
|
||||
?.filter((r) => dayjs().unix() - 60 < parseInt(r[0]))
|
||||
?.reduce((acc, curr) => acc + curr[1]?.reduce((_acc, _curr) => _acc + _curr.value, 0), 0) / 60
|
||||
) ?? 0
|
||||
}/s`
|
||||
}}
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-1 relative overflow-hidden flex flex-row gap-0.5 justify-end items-end">
|
||||
<motion.div
|
||||
class="w-2 shrink-0 bg-primary relative"
|
||||
:style="{
|
||||
height: `${(i[1]?.reduce((acc, curr) => acc + curr.value, 0) / Math.max(...Object.entries(speedChartData)?.map((r) => r[1]?.reduce((acc, curr) => acc + curr.value, 0)))) * 100}%`,
|
||||
}"
|
||||
:layoutId="i[0]"
|
||||
v-for="i in Object.entries(speedChartData)"
|
||||
:key="i[0]"
|
||||
:initial="{ x: 10, opacity: 0 }"
|
||||
:animate="{ x: 0, opacity: 1 }"
|
||||
:transition="{ duration: 1 }"
|
||||
>
|
||||
</motion.div>
|
||||
<!-- <BarChart class="h-full" :data="data" index="time" :categories="['value']" :showTooltip="false"
|
||||
:showLegend="false" :showXAxis="false" :showYAxis="false" :showGrid="false" :groupMaxWidth="10" /> -->
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-xl col-span-4 md:col-span-1 bg-white/80 h-32 md:h-auto md:aspect-square flex flex-col gap-2 relative overflow-hidden">
|
||||
<div class="absolute top-0 left-0 w-full h-full z-[0] flex flex-col justify-end">
|
||||
<div class="w-full bg-green-100 border-t border-green-500" :style="`height: ${totalUploadProgress || 0}%`"></div>
|
||||
</div>
|
||||
<div class="flex flex-col gap-2 justify-between p-3 h-full relative z-[1]">
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="text-xs opacity-70">总上传进度</div>
|
||||
<div class="text-4xl font-bold">{{ (totalUploadProgress || 0).toFixed(1) }}%</div>
|
||||
</div>
|
||||
<div class="flex flex-row gap-2">
|
||||
<Button
|
||||
class="aspect-square hover:text-white p-0 bg-green-200 hover:bg-green-300 text-green-500"
|
||||
:disabled="['start', 'disabled'].includes(totalTaskStatus)"
|
||||
@click="
|
||||
() => {
|
||||
uploadfiles.forEach((r) => {
|
||||
r.status = 'start'
|
||||
})
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucidePlay class="size-1/2" />
|
||||
</Button>
|
||||
<Button
|
||||
class="aspect-square hover:text-white p-0 bg-orange-200 hover:bg-orange-300 text-orange-500"
|
||||
:disabled="['pause', 'disabled'].includes(totalTaskStatus)"
|
||||
@click="
|
||||
() => {
|
||||
uploadfiles.forEach((r) => {
|
||||
r.status = 'pause'
|
||||
})
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideSquare class="size-1/2" />
|
||||
</Button>
|
||||
<!-- <Button class="aspect-square bg-blue-200 hover:bg-blue-300 text-blue-500 hover:text-white p-0">
|
||||
<LucideSettings class="size-1/2" />
|
||||
</Button> -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<BaseCard class="grid grid-cols-4 gap-5">
|
||||
<FileUploadTotalSpeedView :speedChartData="speedChartData" />
|
||||
<FileUploadTotalProgressControlView :uploadfiles="uploadfiles" />
|
||||
<div class="col-span-4 flex flex-col bg-white/80 rounded-xl p-3 text-md gap-5">
|
||||
<div>文件列表</div>
|
||||
<div class="flex flex-row gap-2 items-center">
|
||||
<LucideFolders class="size-4" />
|
||||
{{ t('page.progress.file.fileList') }}
|
||||
</div>
|
||||
<div class="flex flex-col -mx-3 text-sm">
|
||||
<div class="grid grid-cols-[2fr_6rem_6rem] md:grid-cols-[2fr_6rem_6rem_4fr] gap-2 border-b border-black/20 pb-2 px-3">
|
||||
<div>文件名</div>
|
||||
<div>文件大小</div>
|
||||
<div>{{ t('page.progress.file.fileName') }}</div>
|
||||
<div>{{ t('page.progress.file.fileSize') }}</div>
|
||||
<div @click="handleShowSpeedInfo" class="flex flex-row gap-1 items-center">
|
||||
上传速度
|
||||
{{ t('page.progress.file.uploadSpeed') }}
|
||||
<LucideInfo class="size-3" />
|
||||
</div>
|
||||
<div class="hidden md:block">进度</div>
|
||||
<div class="hidden md:block">{{ t('page.progress.file.progress') }}</div>
|
||||
</div>
|
||||
<div
|
||||
:class="
|
||||
cx(
|
||||
'grid grid-cols-[2fr_6rem_6rem] md:grid-cols-[2fr_6rem_6rem_4fr] gap-2 py-2 border-b border-black/20 items-center hover:bg-primary/30 px-3 cursor-pointer',
|
||||
selectedFile === item?.fileId && 'bg-primary text-white hover:!bg-primary'
|
||||
selectedFile === item?.fileId && 'bg-primary text-white hover:bg-primary!'
|
||||
)
|
||||
"
|
||||
v-for="(item, index) in uploadfiles"
|
||||
@@ -459,9 +338,9 @@ const handleShowSpeedInfo = () => {
|
||||
(e: Event) => {
|
||||
e.stopPropagation()
|
||||
if (item?.status === 'start') {
|
||||
uploadfiles[index].status = 'pause'
|
||||
uploadfiles[index]!.status = 'pause'
|
||||
} else {
|
||||
uploadfiles[index].status = 'start'
|
||||
uploadfiles[index]!.status = 'start'
|
||||
}
|
||||
}
|
||||
"
|
||||
@@ -475,26 +354,26 @@ const handleShowSpeedInfo = () => {
|
||||
</div>
|
||||
<div>{{ getFileSize(item?.file?.size) }}</div>
|
||||
<div>
|
||||
{{
|
||||
`${getFileSize(
|
||||
(Object.entries(item?.uploadInfo?.chunks || {})?.filter(
|
||||
([, chunk]) => chunk.status === 'success' && dayjs().unix() - 60 < chunk.createdAt
|
||||
)?.length /
|
||||
60) *
|
||||
(item?.uploadInfo?.ChunkSize || 0)
|
||||
)} /s`
|
||||
}}
|
||||
<template v-if="item?.status === 'start' && item?.procressType === 'upload'">
|
||||
{{
|
||||
`${getFileSize(
|
||||
Object.entries(speedChartData)
|
||||
?.filter(([key, value]) => value.some((r) => r.fileId === item?.fileId) && dayjs().unix() - 1 === Number(key))
|
||||
?.reduce((acc, curr) => acc + curr[1]?.reduce((acc, curr) => acc + curr.value, 0), 0) ?? 0
|
||||
)} /s`
|
||||
}}
|
||||
</template>
|
||||
</div>
|
||||
<div
|
||||
class="flex flex-row gap-2 items-center col-span-3 md:col-span-1"
|
||||
v-if="['hash', 'create', 'chunk']?.includes(item?.procressType)"
|
||||
>
|
||||
<LucideLoaderCircle class="size-4 animate-spin" />
|
||||
<div>正在{{ item?.procressType }}中...</div>
|
||||
<div>{{ t(`page.progress.file.processing.${item?.procressType}`) }}</div>
|
||||
</div>
|
||||
<div class="flex flex-row gap-2 items-center col-span-3 md:col-span-1" v-if="item?.procressType === 'finish'">
|
||||
{{ item?.status === 'finish' ? '云端已有相同hash文件, 秒传成功' : null }}
|
||||
{{ item?.status === 'error' ? '上传失败,请稍后重试' : null }}
|
||||
{{ item?.status === 'finish' ? t('page.progress.file.instantUploadSuccess') : null }}
|
||||
{{ item?.status === 'error' ? t('page.progress.file.uploadFailedRetry') : null }}
|
||||
</div>
|
||||
<div class="flex flex-row gap-2 items-center col-span-3 md:col-span-1" v-if="item?.procressType === 'upload'">
|
||||
<div class="rounded-full bg-white/50 w-full h-2 overflow-hidden border border-white">
|
||||
@@ -526,44 +405,6 @@ const handleShowSpeedInfo = () => {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-span-4 flex flex-col bg-white/80 rounded-xl p-3 gap-5" v-if="selectedFile">
|
||||
<div>上传详情</div>
|
||||
<div class="grid grid-cols-3 text-sm gap-3">
|
||||
<div>
|
||||
区块: {{ selectedUploadfile?.uploadInfo?.chunkLength }} x {{ getFileSize(selectedUploadfile?.uploadInfo?.ChunkSize as number) }}
|
||||
</div>
|
||||
<div class="truncate col-span-2">hash: {{ selectedUploadfile?.hash }}</div>
|
||||
<div>已完成: {{ selectedUploadfileChunk?.filter((r) => r.status === 'success')?.length || 0 }}</div>
|
||||
<div>已丢弃: {{ selectedUploadfileChunk?.filter((r) => r.status === 'error')?.length || 0 }}</div>
|
||||
<div>
|
||||
待完成:
|
||||
{{ (selectedUploadfile?.uploadInfo?.chunkLength || 0) - (selectedUploadfileChunk?.length || 0) }}
|
||||
</div>
|
||||
<div class="col-span-3 flex flex-row justify-between items-center">
|
||||
<div class="text-md font-bold">{{ selectedUploadfileViewMode === 'progress' ? '区块进度条' : '区块热力图' }}</div>
|
||||
<Button
|
||||
size="sm"
|
||||
class="ml-auto text-xs"
|
||||
@click="selectedUploadfileViewMode = selectedUploadfileViewMode === 'progress' ? 'heatmap' : 'progress'"
|
||||
>
|
||||
<LucideArrowDownUp class="size-4" />
|
||||
{{ selectedUploadfileViewMode === 'progress' ? '热力图' : '进度条' }}
|
||||
</Button>
|
||||
</div>
|
||||
<div class="h-7 col-span-3 flex flex-row gap-2 items-center" v-if="selectedUploadfileViewMode === 'progress'">
|
||||
<div class="flex-1 h-full">
|
||||
<FileUploadBlockProgressView :data="selectedUploadfile?.uploadInfo" />
|
||||
</div>
|
||||
{{
|
||||
clamp(((selectedUploadfileChunk?.length || 0) / (selectedUploadfile?.uploadInfo?.chunkLength || 0)) * 100, 0, 100)?.toFixed(
|
||||
2
|
||||
)
|
||||
}}%
|
||||
</div>
|
||||
<div v-if="selectedUploadfileViewMode === 'heatmap'" class="col-span-3 bg-black/5 rounded p-2">
|
||||
<FileUploadHeatMapView :size="12" :data="selectedUploadfile?.uploadInfo" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<FileUploadDetailView :uploadfiles="uploadfiles" :selectedFile="selectedFile" />
|
||||
</BaseCard>
|
||||
</template>
|
||||
24
front/components/Home/File/FileUploadProgressView/types.ts
Normal file
24
front/components/Home/File/FileUploadProgressView/types.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
type Uploadfile = {
|
||||
fileId: string
|
||||
id?: string // 后端文件id
|
||||
file: File
|
||||
status: 'start' | 'pause' | 'finish' | 'error'
|
||||
hash?: string
|
||||
procressType: 'hash' | 'create' | 'upload' | 'finish'
|
||||
uploadInfo?: {
|
||||
chunks: Record<number, { status: 'success' | 'error' | 'processing'; createdAt: number }>
|
||||
chunkLength: number
|
||||
ChunkSize: number
|
||||
}
|
||||
queue: {
|
||||
taskId: string
|
||||
taskType: 'hash' | 'create' | 'chunk' | 'upload' | 'finish'
|
||||
queueType: 'sync' | 'async' // sync任务禁止并发
|
||||
index?: number
|
||||
retry?: number
|
||||
}[]
|
||||
}
|
||||
|
||||
type SelectedFile = string | null
|
||||
|
||||
export type { Uploadfile, SelectedFile }
|
||||
@@ -1,8 +0,0 @@
|
||||
<template>
|
||||
<div class="flex flex-col gap-2 pt-3">
|
||||
<div class="text-xl font-bold">上传速度如何计算</div>
|
||||
<div class="opacity-75">
|
||||
上传速度根据当前秒上传了 <b>文件区块的数量</b> * <b>每个文件区块的大小</b> 估算而来,可能与真实上传速度有一定的误差,仅供参考
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -14,19 +14,26 @@ const renderComponent = computed(() => {
|
||||
return textStepList.find((item) => item.key === step.value)?.component
|
||||
})
|
||||
const formRef = ref<InstanceType<typeof VeeForm>>()
|
||||
watch(() => step.value, (newVal) => {
|
||||
if (newVal === 'input') {
|
||||
formRef.value?.form?.resetForm()
|
||||
// formRef.value?.form?.setValues({ file: null })
|
||||
watch(
|
||||
() => step.value,
|
||||
(newVal) => {
|
||||
if (newVal === 'input') {
|
||||
formRef.value?.form?.resetForm()
|
||||
// formRef.value?.form?.setValues({ file: null })
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
</script>
|
||||
<template>
|
||||
<VeeForm ref="formRef" v-slot="{ values }" :keepValues="true">
|
||||
<div class="rounded-xl p-5 bg-white/50 backdrop-blur-xl w-full lg:w-200">
|
||||
<component :is="renderComponent" :data="values" @change="(key: string) => {
|
||||
step = key
|
||||
}" />
|
||||
</div>
|
||||
<component
|
||||
:is="renderComponent"
|
||||
:data="values"
|
||||
@change="
|
||||
(key: string) => {
|
||||
step = key
|
||||
}
|
||||
"
|
||||
/>
|
||||
</VeeForm>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
@@ -21,13 +21,12 @@ const handleTextShare = ({ type, config }: { type: string; config: any }) => {
|
||||
}
|
||||
</script>
|
||||
<template>
|
||||
<div class="gap-5 flex flex-col">
|
||||
<div class="text-xl font-normal">{{ t('text.uploadText') }}</div>
|
||||
<BaseCard class="gap-5 flex flex-col" :title="t('page.upload.text.uploadText')">
|
||||
<div class="relative">
|
||||
<MarkdownInputField
|
||||
name="text"
|
||||
:placeholder="t('text.uploadTextPlaceholder')"
|
||||
class="max-h-[50vh] min-h-40 overflow-y-auto max-w-full [&>*]:pr-10 flex flex-col"
|
||||
:placeholder="t('page.upload.text.uploadTextPlaceholder')"
|
||||
class="max-h-[50vh] min-h-40 overflow-y-auto max-w-full *:pr-10 flex flex-col"
|
||||
rules="required"
|
||||
/>
|
||||
<Button
|
||||
@@ -45,7 +44,7 @@ const handleTextShare = ({ type, config }: { type: string; config: any }) => {
|
||||
}
|
||||
"
|
||||
>
|
||||
<LucideX />
|
||||
<LucideX class="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div class="flex flex-row gap-3">
|
||||
@@ -68,5 +67,5 @@ const handleTextShare = ({ type, config }: { type: string; config: any }) => {
|
||||
</FormButton>
|
||||
<PickupShareBtn />
|
||||
</div>
|
||||
</div>
|
||||
</BaseCard>
|
||||
</template>
|
||||
|
||||
@@ -14,7 +14,7 @@ const renderHtml = computed(() => {
|
||||
<div
|
||||
:class="
|
||||
cx(
|
||||
'prose prose-sm [&>*]:outline-none prose-p:my-1 prose-headings:my-2 prose-pre:mb-0 prose-blockquote:border-black/50 selection:bg-primary/20',
|
||||
'prose prose-sm *:outline-none prose-p:my-1 prose-headings:my-2 prose-pre:mb-0 prose-blockquote:border-black/50 selection:bg-primary/20 break-all',
|
||||
props?.class
|
||||
)
|
||||
"
|
||||
|
||||
@@ -1,90 +1,81 @@
|
||||
<template>
|
||||
<div
|
||||
class="flex flex-row bg-white/50 backdrop-blur-xl p-2 rounded-full gap-1 sticky top-0 z-10"
|
||||
>
|
||||
<div
|
||||
v-for="item in routes"
|
||||
:key="item.key"
|
||||
:class="
|
||||
cx(
|
||||
'flex flex-row items-center text-sm px-4 py-2 font-bold rounded-full relative select-none cursor-pointer',
|
||||
!isActive(item) && 'hover:bg-black/5',
|
||||
item?.name && 'gap-2',
|
||||
item?.className,
|
||||
)
|
||||
"
|
||||
@click="handleClick(item)"
|
||||
>
|
||||
<motion.div
|
||||
v-if="isActive(item)"
|
||||
layoutId="navbar-active"
|
||||
class="absolute inset-0 rounded-full w-full h-full bg-black/10"
|
||||
/>
|
||||
<component :is="item.icon" />
|
||||
<div class="hidden sm:block">{{ item.name }}</div>
|
||||
<div class="flex flex-row bg-white/50 backdrop-blur-xl p-2 rounded-full gap-1 sticky top-0 z-10">
|
||||
<div
|
||||
v-for="item in routes"
|
||||
:key="item.key"
|
||||
:class="
|
||||
cx(
|
||||
'flex flex-row items-center text-sm px-4 py-2 font-bold rounded-full relative select-none cursor-pointer',
|
||||
!isActive(item) && 'hover:bg-black/5',
|
||||
item?.name && 'gap-2',
|
||||
item?.className
|
||||
)
|
||||
"
|
||||
@click="handleClick(item)"
|
||||
>
|
||||
<motion.div v-if="isActive(item)" layoutId="navbar-active" class="absolute inset-0 rounded-full w-full h-full bg-black/10" />
|
||||
<component :is="item.icon" />
|
||||
<div class="hidden sm:block">{{ item.name }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { cx } from "class-variance-authority";
|
||||
import { LucideClipboardType, LucidePaperclip } from "#components";
|
||||
import { motion } from "motion-v";
|
||||
import { LucideGlobe } from "lucide-vue-next";
|
||||
import showDrawer from "@/lib/showDrawer";
|
||||
import I18nSwitchDrawer from "./Drawer/I18nSwitchDrawer.vue";
|
||||
const { t } = useI18n();
|
||||
const routes = [
|
||||
{
|
||||
key: "about",
|
||||
icon: () =>
|
||||
h("img", {
|
||||
class: "size-10 rounded-full border-2 border-white/50",
|
||||
src: "/logo.png",
|
||||
}),
|
||||
onClick: () => {
|
||||
router.push("/about");
|
||||
import { cx } from 'class-variance-authority'
|
||||
import { LucideClipboardType, LucidePaperclip } from '#components'
|
||||
import { motion } from 'motion-v'
|
||||
import { LucideGlobe } from 'lucide-vue-next'
|
||||
import showDrawer from '@/lib/showDrawer'
|
||||
import I18nSwitchDrawer from './Drawer/I18nSwitchDrawer.vue'
|
||||
const { t } = useI18n()
|
||||
const routes = computed(() => [
|
||||
{
|
||||
key: 'about',
|
||||
icon: () =>
|
||||
h('img', {
|
||||
class: 'size-10 rounded-full border-2 border-white/50',
|
||||
src: '/logo.png',
|
||||
}),
|
||||
onClick: () => {
|
||||
router.push('/about')
|
||||
},
|
||||
isActive: (item: { key: string }) => route.path?.endsWith(item.key),
|
||||
className: '!p-1.5',
|
||||
},
|
||||
isActive: (item: { key: string }) => route.path?.endsWith(item.key),
|
||||
className: "!p-1.5",
|
||||
},
|
||||
{ name: t("navbar.file"), key: "file", icon: LucidePaperclip },
|
||||
{ name: t("navbar.text"), key: "text", icon: LucideClipboardType },
|
||||
{
|
||||
key: "i18n",
|
||||
icon: LucideGlobe,
|
||||
onClick: () => {
|
||||
showDrawer({
|
||||
render: () => h(I18nSwitchDrawer),
|
||||
});
|
||||
{ name: t('navbar.file'), key: 'file', icon: LucidePaperclip },
|
||||
{ name: t('navbar.text'), key: 'text', icon: LucideClipboardType },
|
||||
{
|
||||
key: 'i18n',
|
||||
icon: LucideGlobe,
|
||||
onClick: () => {
|
||||
showDrawer({
|
||||
render: (props) => h(I18nSwitchDrawer, { ...props }),
|
||||
})
|
||||
},
|
||||
className: 'size-12 !p-1.5 justify-center items-center',
|
||||
},
|
||||
className: "size-12 !p-1.5 justify-center items-center",
|
||||
},
|
||||
];
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const type = computed(() => route?.query?.type);
|
||||
])
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const type = computed(() => route?.query?.type)
|
||||
|
||||
const isActive = (item: {
|
||||
key: string;
|
||||
isActive?: (item: { key: string }) => boolean;
|
||||
}) => {
|
||||
const { key, isActive } = item || {};
|
||||
return isActive ? isActive(item) : type.value === key;
|
||||
};
|
||||
const isActive = (item: { key: string; isActive?: (item: { key: string }) => boolean }) => {
|
||||
const { key, isActive } = item || {}
|
||||
return isActive ? isActive(item) : type.value === key
|
||||
}
|
||||
|
||||
const handleClick = (item: { key: string; onClick?: () => void }) => {
|
||||
const { key, onClick } = item || {};
|
||||
if (onClick) {
|
||||
onClick();
|
||||
return;
|
||||
}
|
||||
router.push({
|
||||
path: "/",
|
||||
query: {
|
||||
...route.query,
|
||||
type: key,
|
||||
},
|
||||
});
|
||||
};
|
||||
const { key, onClick } = item || {}
|
||||
if (onClick) {
|
||||
onClick()
|
||||
return
|
||||
}
|
||||
router.push({
|
||||
path: '/',
|
||||
query: {
|
||||
...route.query,
|
||||
type: key,
|
||||
},
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user