更新
This commit is contained in:
@@ -0,0 +1,288 @@
|
|||||||
|
# ui-ux-pro-max
|
||||||
|
|
||||||
|
Comprehensive design guide for web and mobile applications. Contains 67 styles, 96 color palettes, 57 font pairings, 99 UX guidelines, and 25 chart types across 13 technology stacks. Searchable database with priority-based recommendations.
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
Check if Python is installed:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 --version || python --version
|
||||||
|
```
|
||||||
|
|
||||||
|
If Python is not installed, install it based on user's OS:
|
||||||
|
|
||||||
|
**macOS:**
|
||||||
|
```bash
|
||||||
|
brew install python3
|
||||||
|
```
|
||||||
|
|
||||||
|
**Ubuntu/Debian:**
|
||||||
|
```bash
|
||||||
|
sudo apt update && sudo apt install python3
|
||||||
|
```
|
||||||
|
|
||||||
|
**Windows:**
|
||||||
|
```powershell
|
||||||
|
winget install Python.Python.3.12
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## How to Use This Skill
|
||||||
|
|
||||||
|
When user requests UI/UX work (design, build, create, implement, review, fix, improve), follow this workflow:
|
||||||
|
|
||||||
|
### Step 1: Analyze User Requirements
|
||||||
|
|
||||||
|
Extract key information from user request:
|
||||||
|
- **Product type**: SaaS, e-commerce, portfolio, dashboard, landing page, etc.
|
||||||
|
- **Style keywords**: minimal, playful, professional, elegant, dark mode, etc.
|
||||||
|
- **Industry**: healthcare, fintech, gaming, education, etc.
|
||||||
|
- **Stack**: React, Vue, Next.js, or default to `html-tailwind`
|
||||||
|
|
||||||
|
### Step 2: Generate Design System (REQUIRED)
|
||||||
|
|
||||||
|
**Always start with `--design-system`** to get comprehensive recommendations with reasoning:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 skills/ui-ux-pro-max/scripts/search.py "<product_type> <industry> <keywords>" --design-system [-p "Project Name"]
|
||||||
|
```
|
||||||
|
|
||||||
|
This command:
|
||||||
|
1. Searches 5 domains in parallel (product, style, color, landing, typography)
|
||||||
|
2. Applies reasoning rules from `ui-reasoning.csv` to select best matches
|
||||||
|
3. Returns complete design system: pattern, style, colors, typography, effects
|
||||||
|
4. Includes anti-patterns to avoid
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```bash
|
||||||
|
python3 skills/ui-ux-pro-max/scripts/search.py "beauty spa wellness service" --design-system -p "Serenity Spa"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 2b: Persist Design System (Master + Overrides Pattern)
|
||||||
|
|
||||||
|
To save the design system for hierarchical retrieval across sessions, add `--persist`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 skills/ui-ux-pro-max/scripts/search.py "<query>" --design-system --persist -p "Project Name"
|
||||||
|
```
|
||||||
|
|
||||||
|
This creates:
|
||||||
|
- `design-system/MASTER.md` — Global Source of Truth with all design rules
|
||||||
|
- `design-system/pages/` — Folder for page-specific overrides
|
||||||
|
|
||||||
|
**With page-specific override:**
|
||||||
|
```bash
|
||||||
|
python3 skills/ui-ux-pro-max/scripts/search.py "<query>" --design-system --persist -p "Project Name" --page "dashboard"
|
||||||
|
```
|
||||||
|
|
||||||
|
This also creates:
|
||||||
|
- `design-system/pages/dashboard.md` — Page-specific deviations from Master
|
||||||
|
|
||||||
|
**How hierarchical retrieval works:**
|
||||||
|
1. When building a specific page (e.g., "Checkout"), first check `design-system/pages/checkout.md`
|
||||||
|
2. If the page file exists, its rules **override** the Master file
|
||||||
|
3. If not, use `design-system/MASTER.md` exclusively
|
||||||
|
|
||||||
|
### Step 3: Supplement with Detailed Searches (as needed)
|
||||||
|
|
||||||
|
After getting the design system, use domain searches to get additional details:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 skills/ui-ux-pro-max/scripts/search.py "<keyword>" --domain <domain> [-n <max_results>]
|
||||||
|
```
|
||||||
|
|
||||||
|
**When to use detailed searches:**
|
||||||
|
|
||||||
|
| Need | Domain | Example |
|
||||||
|
|------|--------|---------|
|
||||||
|
| More style options | `style` | `--domain style "glassmorphism dark"` |
|
||||||
|
| Chart recommendations | `chart` | `--domain chart "real-time dashboard"` |
|
||||||
|
| UX best practices | `ux` | `--domain ux "animation accessibility"` |
|
||||||
|
| Alternative fonts | `typography` | `--domain typography "elegant luxury"` |
|
||||||
|
| Landing structure | `landing` | `--domain landing "hero social-proof"` |
|
||||||
|
|
||||||
|
### Step 4: Stack Guidelines (Default: html-tailwind)
|
||||||
|
|
||||||
|
Get implementation-specific best practices. If user doesn't specify a stack, **default to `html-tailwind`**.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 skills/ui-ux-pro-max/scripts/search.py "<keyword>" --stack html-tailwind
|
||||||
|
```
|
||||||
|
|
||||||
|
Available stacks: `html-tailwind`, `react`, `nextjs`, `vue`, `svelte`, `swiftui`, `react-native`, `flutter`, `shadcn`, `jetpack-compose`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Search Reference
|
||||||
|
|
||||||
|
### Available Domains
|
||||||
|
|
||||||
|
| Domain | Use For | Example Keywords |
|
||||||
|
|--------|---------|------------------|
|
||||||
|
| `product` | Product type recommendations | SaaS, e-commerce, portfolio, healthcare, beauty, service |
|
||||||
|
| `style` | UI styles, colors, effects | glassmorphism, minimalism, dark mode, brutalism |
|
||||||
|
| `typography` | Font pairings, Google Fonts | elegant, playful, professional, modern |
|
||||||
|
| `color` | Color palettes by product type | saas, ecommerce, healthcare, beauty, fintech, service |
|
||||||
|
| `landing` | Page structure, CTA strategies | hero, hero-centric, testimonial, pricing, social-proof |
|
||||||
|
| `chart` | Chart types, library recommendations | trend, comparison, timeline, funnel, pie |
|
||||||
|
| `ux` | Best practices, anti-patterns | animation, accessibility, z-index, loading |
|
||||||
|
| `react` | React/Next.js performance | waterfall, bundle, suspense, memo, rerender, cache |
|
||||||
|
| `web` | Web interface guidelines | aria, focus, keyboard, semantic, virtualize |
|
||||||
|
| `prompt` | AI prompts, CSS keywords | (style name) |
|
||||||
|
|
||||||
|
### Available Stacks
|
||||||
|
|
||||||
|
| Stack | Focus |
|
||||||
|
|-------|-------|
|
||||||
|
| `html-tailwind` | Tailwind utilities, responsive, a11y (DEFAULT) |
|
||||||
|
| `react` | State, hooks, performance, patterns |
|
||||||
|
| `nextjs` | SSR, routing, images, API routes |
|
||||||
|
| `vue` | Composition API, Pinia, Vue Router |
|
||||||
|
| `svelte` | Runes, stores, SvelteKit |
|
||||||
|
| `swiftui` | Views, State, Navigation, Animation |
|
||||||
|
| `react-native` | Components, Navigation, Lists |
|
||||||
|
| `flutter` | Widgets, State, Layout, Theming |
|
||||||
|
| `shadcn` | shadcn/ui components, theming, forms, patterns |
|
||||||
|
| `jetpack-compose` | Composables, Modifiers, State Hoisting, Recomposition |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Example Workflow
|
||||||
|
|
||||||
|
**User request:** "Làm landing page cho dịch vụ chăm sóc da chuyên nghiệp"
|
||||||
|
|
||||||
|
### Step 1: Analyze Requirements
|
||||||
|
- Product type: Beauty/Spa service
|
||||||
|
- Style keywords: elegant, professional, soft
|
||||||
|
- Industry: Beauty/Wellness
|
||||||
|
- Stack: html-tailwind (default)
|
||||||
|
|
||||||
|
### Step 2: Generate Design System (REQUIRED)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 skills/ui-ux-pro-max/scripts/search.py "beauty spa wellness service elegant" --design-system -p "Serenity Spa"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output:** Complete design system with pattern, style, colors, typography, effects, and anti-patterns.
|
||||||
|
|
||||||
|
### Step 3: Supplement with Detailed Searches (as needed)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Get UX guidelines for animation and accessibility
|
||||||
|
python3 skills/ui-ux-pro-max/scripts/search.py "animation accessibility" --domain ux
|
||||||
|
|
||||||
|
# Get alternative typography options if needed
|
||||||
|
python3 skills/ui-ux-pro-max/scripts/search.py "elegant luxury serif" --domain typography
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 4: Stack Guidelines
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 skills/ui-ux-pro-max/scripts/search.py "layout responsive form" --stack html-tailwind
|
||||||
|
```
|
||||||
|
|
||||||
|
**Then:** Synthesize design system + detailed searches and implement the design.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Output Formats
|
||||||
|
|
||||||
|
The `--design-system` flag supports two output formats:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# ASCII box (default) - best for terminal display
|
||||||
|
python3 skills/ui-ux-pro-max/scripts/search.py "fintech crypto" --design-system
|
||||||
|
|
||||||
|
# Markdown - best for documentation
|
||||||
|
python3 skills/ui-ux-pro-max/scripts/search.py "fintech crypto" --design-system -f markdown
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tips for Better Results
|
||||||
|
|
||||||
|
1. **Be specific with keywords** - "healthcare SaaS dashboard" > "app"
|
||||||
|
2. **Search multiple times** - Different keywords reveal different insights
|
||||||
|
3. **Combine domains** - Style + Typography + Color = Complete design system
|
||||||
|
4. **Always check UX** - Search "animation", "z-index", "accessibility" for common issues
|
||||||
|
5. **Use stack flag** - Get implementation-specific best practices
|
||||||
|
6. **Iterate** - If first search doesn't match, try different keywords
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Common Rules for Professional UI
|
||||||
|
|
||||||
|
These are frequently overlooked issues that make UI look unprofessional:
|
||||||
|
|
||||||
|
### Icons & Visual Elements
|
||||||
|
|
||||||
|
| Rule | Do | Don't |
|
||||||
|
|------|----|----- |
|
||||||
|
| **No emoji icons** | Use SVG icons (Heroicons, Lucide, Simple Icons) | Use emojis like 🎨 🚀 ⚙️ as UI icons |
|
||||||
|
| **Stable hover states** | Use color/opacity transitions on hover | Use scale transforms that shift layout |
|
||||||
|
| **Correct brand logos** | Research official SVG from Simple Icons | Guess or use incorrect logo paths |
|
||||||
|
| **Consistent icon sizing** | Use fixed viewBox (24x24) with w-6 h-6 | Mix different icon sizes randomly |
|
||||||
|
|
||||||
|
### Interaction & Cursor
|
||||||
|
|
||||||
|
| Rule | Do | Don't |
|
||||||
|
|------|----|----- |
|
||||||
|
| **Cursor pointer** | Add `cursor-pointer` to all clickable/hoverable cards | Leave default cursor on interactive elements |
|
||||||
|
| **Hover feedback** | Provide visual feedback (color, shadow, border) | No indication element is interactive |
|
||||||
|
| **Smooth transitions** | Use `transition-colors duration-200` | Instant state changes or too slow (>500ms) |
|
||||||
|
|
||||||
|
### Light/Dark Mode Contrast
|
||||||
|
|
||||||
|
| Rule | Do | Don't |
|
||||||
|
|------|----|----- |
|
||||||
|
| **Glass card light mode** | Use `bg-white/80` or higher opacity | Use `bg-white/10` (too transparent) |
|
||||||
|
| **Text contrast light** | Use `#0F172A` (slate-900) for text | Use `#94A3B8` (slate-400) for body text |
|
||||||
|
| **Muted text light** | Use `#475569` (slate-600) minimum | Use gray-400 or lighter |
|
||||||
|
| **Border visibility** | Use `border-gray-200` in light mode | Use `border-white/10` (invisible) |
|
||||||
|
|
||||||
|
### Layout & Spacing
|
||||||
|
|
||||||
|
| Rule | Do | Don't |
|
||||||
|
|------|----|----- |
|
||||||
|
| **Floating navbar** | Add `top-4 left-4 right-4` spacing | Stick navbar to `top-0 left-0 right-0` |
|
||||||
|
| **Content padding** | Account for fixed navbar height | Let content hide behind fixed elements |
|
||||||
|
| **Consistent max-width** | Use same `max-w-6xl` or `max-w-7xl` | Mix different container widths |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Pre-Delivery Checklist
|
||||||
|
|
||||||
|
Before delivering UI code, verify these items:
|
||||||
|
|
||||||
|
### Visual Quality
|
||||||
|
- [ ] No emojis used as icons (use SVG instead)
|
||||||
|
- [ ] All icons from consistent icon set (Heroicons/Lucide)
|
||||||
|
- [ ] Brand logos are correct (verified from Simple Icons)
|
||||||
|
- [ ] Hover states don't cause layout shift
|
||||||
|
- [ ] Use theme colors directly (bg-primary) not var() wrapper
|
||||||
|
|
||||||
|
### Interaction
|
||||||
|
- [ ] All clickable elements have `cursor-pointer`
|
||||||
|
- [ ] Hover states provide clear visual feedback
|
||||||
|
- [ ] Transitions are smooth (150-300ms)
|
||||||
|
- [ ] Focus states visible for keyboard navigation
|
||||||
|
|
||||||
|
### Light/Dark Mode
|
||||||
|
- [ ] Light mode text has sufficient contrast (4.5:1 minimum)
|
||||||
|
- [ ] Glass/transparent elements visible in light mode
|
||||||
|
- [ ] Borders visible in both modes
|
||||||
|
- [ ] Test both modes before delivery
|
||||||
|
|
||||||
|
### Layout
|
||||||
|
- [ ] Floating elements have proper spacing from edges
|
||||||
|
- [ ] No content hidden behind fixed navbars
|
||||||
|
- [ ] Responsive at 375px, 768px, 1024px, 1440px
|
||||||
|
- [ ] No horizontal scroll on mobile
|
||||||
|
|
||||||
|
### Accessibility
|
||||||
|
- [ ] All images have alt text
|
||||||
|
- [ ] Form inputs have labels
|
||||||
|
- [ ] Color is not the only indicator
|
||||||
|
- [ ] `prefers-reduced-motion` respected
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
No,Data Type,Keywords,Best Chart Type,Secondary Options,Color Guidance,Performance Impact,Accessibility Notes,Library Recommendation,Interactive Level
|
||||||
|
1,Trend Over Time,"trend, time-series, line, growth, timeline, progress",Line Chart,"Area Chart, Smooth Area",Primary: #0080FF. Multiple series: use distinct colors. Fill: 20% opacity,⚡ Excellent (optimized),✓ Clear line patterns for colorblind users. Add pattern overlays.,"Chart.js, Recharts, ApexCharts",Hover + Zoom
|
||||||
|
2,Compare Categories,"compare, categories, bar, comparison, ranking",Bar Chart (Horizontal or Vertical),"Column Chart, Grouped Bar",Each bar: distinct color. Category: grouped same color. Sorted: descending order,⚡ Excellent,✓ Easy to compare. Add value labels on bars for clarity.,"Chart.js, Recharts, D3.js",Hover + Sort
|
||||||
|
3,Part-to-Whole,"part-to-whole, pie, donut, percentage, proportion, share",Pie Chart or Donut,"Stacked Bar, Treemap",Colors: 5-6 max. Contrasting palette. Large slices first. Use labels.,⚡ Good (limit 6 slices),⚠ Hard for accessibility. Better: Stacked bar with legend. Avoid pie if >5 items.,"Chart.js, Recharts, D3.js",Hover + Drill
|
||||||
|
4,Correlation/Distribution,"correlation, distribution, scatter, relationship, pattern",Scatter Plot or Bubble Chart,"Heat Map, Matrix",Color axis: gradient (blue-red). Size: relative. Opacity: 0.6-0.8 to show density,⚠ Moderate (many points),⚠ Provide data table alternative. Use pattern + color distinction.,"D3.js, Plotly, Recharts",Hover + Brush
|
||||||
|
5,Heatmap/Intensity,"heatmap, heat-map, intensity, density, matrix",Heat Map or Choropleth,"Grid Heat Map, Bubble Heat",Gradient: Cool (blue) to Hot (red). Scale: clear legend. Divergent for ±data,⚡ Excellent (color CSS),⚠ Colorblind: Use pattern overlay. Provide numerical legend.,"D3.js, Plotly, ApexCharts",Hover + Zoom
|
||||||
|
6,Geographic Data,"geographic, map, location, region, geo, spatial","Choropleth Map, Bubble Map",Geographic Heat Map,Regional: single color gradient or categorized colors. Legend: clear scale,⚠ Moderate (rendering),⚠ Include text labels for regions. Provide data table alternative.,"D3.js, Mapbox, Leaflet",Pan + Zoom + Drill
|
||||||
|
7,Funnel/Flow,funnel/flow,"Funnel Chart, Sankey",Waterfall (for flows),Stages: gradient (starting color → ending color). Show conversion %,⚡ Good,✓ Clear stage labels + percentages. Good for accessibility if labeled.,"D3.js, Recharts, Custom SVG",Hover + Drill
|
||||||
|
8,Performance vs Target,performance-vs-target,Gauge Chart or Bullet Chart,"Dial, Thermometer",Performance: Red→Yellow→Green gradient. Target: marker line. Threshold colors,⚡ Good,✓ Add numerical value + percentage label beside gauge.,"D3.js, ApexCharts, Custom SVG",Hover
|
||||||
|
9,Time-Series Forecast,time-series-forecast,Line with Confidence Band,Ribbon Chart,Actual: solid line #0080FF. Forecast: dashed #FF9500. Band: light shading,⚡ Good,✓ Clearly distinguish actual vs forecast. Add legend.,"Chart.js, ApexCharts, Plotly",Hover + Toggle
|
||||||
|
10,Anomaly Detection,anomaly-detection,Line Chart with Highlights,Scatter with Alert,Normal: blue #0080FF. Anomaly: red #FF0000 circle/square marker + alert,⚡ Good,✓ Circle/marker for anomalies. Add text alert annotation.,"D3.js, Plotly, ApexCharts",Hover + Alert
|
||||||
|
11,Hierarchical/Nested Data,hierarchical/nested-data,Treemap,"Sunburst, Nested Donut, Icicle",Parent: distinct hues. Children: lighter shades. White borders 2-3px.,⚠ Moderate,⚠ Poor - provide table alternative. Label large areas.,"D3.js, Recharts, ApexCharts",Hover + Drilldown
|
||||||
|
12,Flow/Process Data,flow/process-data,Sankey Diagram,"Alluvial, Chord Diagram",Gradient from source to target. Opacity 0.4-0.6 for flows.,⚠ Moderate,⚠ Poor - provide flow table alternative.,"D3.js (d3-sankey), Plotly",Hover + Drilldown
|
||||||
|
13,Cumulative Changes,cumulative-changes,Waterfall Chart,"Stacked Bar, Cascade",Increases: #4CAF50. Decreases: #F44336. Start: #2196F3. End: #0D47A1.,⚡ Good,✓ Good - clear directional colors with labels.,"ApexCharts, Highcharts, Plotly",Hover
|
||||||
|
14,Multi-Variable Comparison,multi-variable-comparison,Radar/Spider Chart,"Parallel Coordinates, Grouped Bar",Single: #0080FF 20% fill. Multiple: distinct colors per dataset.,⚡ Good,⚠ Moderate - limit 5-8 axes. Add data table.,"Chart.js, Recharts, ApexCharts",Hover + Toggle
|
||||||
|
15,Stock/Trading OHLC,stock/trading-ohlc,Candlestick Chart,"OHLC Bar, Heikin-Ashi",Bullish: #26A69A. Bearish: #EF5350. Volume: 40% opacity below.,⚡ Good,⚠ Moderate - provide OHLC data table.,"Lightweight Charts (TradingView), ApexCharts",Real-time + Hover + Zoom
|
||||||
|
16,Relationship/Connection Data,relationship/connection-data,Network Graph,"Hierarchical Tree, Adjacency Matrix",Node types: categorical colors. Edges: #90A4AE 60% opacity.,❌ Poor (500+ nodes struggles),❌ Very Poor - provide adjacency list alternative.,"D3.js (d3-force), Vis.js, Cytoscape.js",Drilldown + Hover + Drag
|
||||||
|
17,Distribution/Statistical,distribution/statistical,Box Plot,"Violin Plot, Beeswarm",Box: #BBDEFB. Border: #1976D2. Median: #D32F2F. Outliers: #F44336.,⚡ Excellent,"✓ Good - include stats table (min, Q1, median, Q3, max).","Plotly, D3.js, Chart.js (plugin)",Hover
|
||||||
|
18,Performance vs Target (Compact),performance-vs-target-(compact),Bullet Chart,"Gauge, Progress Bar","Ranges: #FFCDD2, #FFF9C4, #C8E6C9. Performance: #1976D2. Target: black 3px.",⚡ Excellent,✓ Excellent - compact with clear values.,"D3.js, Plotly, Custom SVG",Hover
|
||||||
|
19,Proportional/Percentage,proportional/percentage,Waffle Chart,"Pictogram, Stacked Bar 100%",10x10 grid. 3-5 categories max. 2-3px spacing between squares.,⚡ Good,✓ Good - better than pie for accessibility.,"D3.js, React-Waffle, Custom CSS Grid",Hover
|
||||||
|
20,Hierarchical Proportional,hierarchical-proportional,Sunburst Chart,"Treemap, Icicle, Circle Packing",Center to outer: darker to lighter. 15-20% lighter per level.,⚠ Moderate,⚠ Poor - provide hierarchy table alternative.,"D3.js (d3-hierarchy), Recharts, ApexCharts",Drilldown + Hover
|
||||||
|
21,Root Cause Analysis,"root cause, decomposition, tree, hierarchy, drill-down, ai-split",Decomposition Tree,"Decision Tree, Flow Chart",Nodes: #2563EB (Primary) vs #EF4444 (Negative impact). Connectors: Neutral grey.,⚠ Moderate (calculation heavy),✓ clear hierarchy. Allow keyboard navigation for nodes.,"Power BI (native), React-Flow, Custom D3.js",Drill + Expand
|
||||||
|
22,3D Spatial Data,"3d, spatial, immersive, terrain, molecular, volumetric",3D Scatter/Surface Plot,"Volumetric Rendering, Point Cloud",Depth cues: lighting/shading. Z-axis: color gradient (cool to warm).,❌ Heavy (WebGL required),❌ Poor - requires alternative 2D view or data table.,"Three.js, Deck.gl, Plotly 3D",Rotate + Zoom + VR
|
||||||
|
23,Real-Time Streaming,"streaming, real-time, ticker, live, velocity, pulse",Streaming Area Chart,"Ticker Tape, Moving Gauge",Current: Bright Pulse (#00FF00). History: Fading opacity. Grid: Dark.,⚡ Optimized (canvas/webgl),⚠ Flashing elements - provide pause button. High contrast.,Smoothed D3.js, CanvasJS
|
||||||
|
24,Sentiment/Emotion,"sentiment, emotion, nlp, opinion, feeling",Word Cloud with Sentiment,"Sentiment Arc, Radar Chart",Positive: #22C55E. Negative: #EF4444. Neutral: #94A3B8. Size = Frequency.,⚡ Good,⚠ Word clouds poor for screen readers. Use list view.,"D3-cloud, Highcharts, Nivo",Hover + Filter
|
||||||
|
25,Process Mining,"process, mining, variants, path, bottleneck, log",Process Map / Graph,"Directed Acyclic Graph (DAG), Petri Net",Happy path: #10B981 (Thick). Deviations: #F59E0B (Thin). Bottlenecks: #EF4444.,⚠ Moderate to Heavy,⚠ Complex graphs hard to navigate. Provide path summary.,"React-Flow, Cytoscape.js, Recharts",Drag + Node-Click
|
||||||
|
@@ -0,0 +1,97 @@
|
|||||||
|
No,Product Type,Primary (Hex),Secondary (Hex),CTA (Hex),Background (Hex),Text (Hex),Border (Hex),Notes
|
||||||
|
1,SaaS (General),#2563EB,#3B82F6,#F97316,#F8FAFC,#1E293B,#E2E8F0,Trust blue + orange CTA contrast
|
||||||
|
2,Micro SaaS,#6366F1,#818CF8,#10B981,#F5F3FF,#1E1B4B,#E0E7FF,Indigo primary + emerald CTA
|
||||||
|
3,E-commerce,#059669,#10B981,#F97316,#ECFDF5,#064E3B,#A7F3D0,Success green + urgency orange
|
||||||
|
4,E-commerce Luxury,#1C1917,#44403C,#CA8A04,#FAFAF9,#0C0A09,#D6D3D1,Premium dark + gold accent
|
||||||
|
5,Service Landing Page,#0EA5E9,#38BDF8,#F97316,#F0F9FF,#0C4A6E,#BAE6FD,Sky blue trust + warm CTA
|
||||||
|
6,B2B Service,#0F172A,#334155,#0369A1,#F8FAFC,#020617,#E2E8F0,Professional navy + blue CTA
|
||||||
|
7,Financial Dashboard,#0F172A,#1E293B,#22C55E,#020617,#F8FAFC,#334155,Dark bg + green positive indicators
|
||||||
|
8,Analytics Dashboard,#1E40AF,#3B82F6,#F59E0B,#F8FAFC,#1E3A8A,#DBEAFE,Blue data + amber highlights
|
||||||
|
9,Healthcare App,#0891B2,#22D3EE,#059669,#ECFEFF,#164E63,#A5F3FC,Calm cyan + health green
|
||||||
|
10,Educational App,#4F46E5,#818CF8,#F97316,#EEF2FF,#1E1B4B,#C7D2FE,Playful indigo + energetic orange
|
||||||
|
11,Creative Agency,#EC4899,#F472B6,#06B6D4,#FDF2F8,#831843,#FBCFE8,Bold pink + cyan accent
|
||||||
|
12,Portfolio/Personal,#18181B,#3F3F46,#2563EB,#FAFAFA,#09090B,#E4E4E7,Monochrome + blue accent
|
||||||
|
13,Gaming,#7C3AED,#A78BFA,#F43F5E,#0F0F23,#E2E8F0,#4C1D95,Neon purple + rose action
|
||||||
|
14,Government/Public Service,#0F172A,#334155,#0369A1,#F8FAFC,#020617,#E2E8F0,High contrast navy + blue
|
||||||
|
15,Fintech/Crypto,#F59E0B,#FBBF24,#8B5CF6,#0F172A,#F8FAFC,#334155,Gold trust + purple tech
|
||||||
|
16,Social Media App,#E11D48,#FB7185,#2563EB,#FFF1F2,#881337,#FECDD3,Vibrant rose + engagement blue
|
||||||
|
17,Productivity Tool,#0D9488,#14B8A6,#F97316,#F0FDFA,#134E4A,#99F6E4,Teal focus + action orange
|
||||||
|
18,Design System/Component Library,#4F46E5,#6366F1,#F97316,#EEF2FF,#312E81,#C7D2FE,Indigo brand + doc hierarchy
|
||||||
|
19,AI/Chatbot Platform,#7C3AED,#A78BFA,#06B6D4,#FAF5FF,#1E1B4B,#DDD6FE,AI purple + cyan interactions
|
||||||
|
20,NFT/Web3 Platform,#8B5CF6,#A78BFA,#FBBF24,#0F0F23,#F8FAFC,#4C1D95,Purple tech + gold value
|
||||||
|
21,Creator Economy Platform,#EC4899,#F472B6,#F97316,#FDF2F8,#831843,#FBCFE8,Creator pink + engagement orange
|
||||||
|
22,Sustainability/ESG Platform,#059669,#10B981,#0891B2,#ECFDF5,#064E3B,#A7F3D0,Nature green + ocean blue
|
||||||
|
23,Remote Work/Collaboration Tool,#6366F1,#818CF8,#10B981,#F5F3FF,#312E81,#E0E7FF,Calm indigo + success green
|
||||||
|
24,Mental Health App,#8B5CF6,#C4B5FD,#10B981,#FAF5FF,#4C1D95,#EDE9FE,Calming lavender + wellness green
|
||||||
|
25,Pet Tech App,#F97316,#FB923C,#2563EB,#FFF7ED,#9A3412,#FED7AA,Playful orange + trust blue
|
||||||
|
26,Smart Home/IoT Dashboard,#1E293B,#334155,#22C55E,#0F172A,#F8FAFC,#475569,Dark tech + status green
|
||||||
|
27,EV/Charging Ecosystem,#0891B2,#22D3EE,#22C55E,#ECFEFF,#164E63,#A5F3FC,Electric cyan + eco green
|
||||||
|
28,Subscription Box Service,#D946EF,#E879F9,#F97316,#FDF4FF,#86198F,#F5D0FE,Excitement purple + urgency orange
|
||||||
|
29,Podcast Platform,#1E1B4B,#312E81,#F97316,#0F0F23,#F8FAFC,#4338CA,Dark audio + warm accent
|
||||||
|
30,Dating App,#E11D48,#FB7185,#F97316,#FFF1F2,#881337,#FECDD3,Romantic rose + warm orange
|
||||||
|
31,Micro-Credentials/Badges Platform,#0369A1,#0EA5E9,#CA8A04,#F0F9FF,#0C4A6E,#BAE6FD,Trust blue + achievement gold
|
||||||
|
32,Knowledge Base/Documentation,#475569,#64748B,#2563EB,#F8FAFC,#1E293B,#E2E8F0,Neutral grey + link blue
|
||||||
|
33,Hyperlocal Services,#059669,#10B981,#F97316,#ECFDF5,#064E3B,#A7F3D0,Location green + action orange
|
||||||
|
34,Beauty/Spa/Wellness Service,#EC4899,#F9A8D4,#8B5CF6,#FDF2F8,#831843,#FBCFE8,Soft pink + lavender luxury
|
||||||
|
35,Luxury/Premium Brand,#1C1917,#44403C,#CA8A04,#FAFAF9,#0C0A09,#D6D3D1,Premium black + gold accent
|
||||||
|
36,Restaurant/Food Service,#DC2626,#F87171,#CA8A04,#FEF2F2,#450A0A,#FECACA,Appetizing red + warm gold
|
||||||
|
37,Fitness/Gym App,#F97316,#FB923C,#22C55E,#1F2937,#F8FAFC,#374151,Energy orange + success green
|
||||||
|
38,Real Estate/Property,#0F766E,#14B8A6,#0369A1,#F0FDFA,#134E4A,#99F6E4,Trust teal + professional blue
|
||||||
|
39,Travel/Tourism Agency,#0EA5E9,#38BDF8,#F97316,#F0F9FF,#0C4A6E,#BAE6FD,Sky blue + adventure orange
|
||||||
|
40,Hotel/Hospitality,#1E3A8A,#3B82F6,#CA8A04,#F8FAFC,#1E40AF,#BFDBFE,Luxury navy + gold service
|
||||||
|
41,Wedding/Event Planning,#DB2777,#F472B6,#CA8A04,#FDF2F8,#831843,#FBCFE8,Romantic pink + elegant gold
|
||||||
|
42,Legal Services,#1E3A8A,#1E40AF,#B45309,#F8FAFC,#0F172A,#CBD5E1,Authority navy + trust gold
|
||||||
|
43,Insurance Platform,#0369A1,#0EA5E9,#22C55E,#F0F9FF,#0C4A6E,#BAE6FD,Security blue + protected green
|
||||||
|
44,Banking/Traditional Finance,#0F172A,#1E3A8A,#CA8A04,#F8FAFC,#020617,#E2E8F0,Trust navy + premium gold
|
||||||
|
45,Online Course/E-learning,#0D9488,#2DD4BF,#F97316,#F0FDFA,#134E4A,#5EEAD4,Progress teal + achievement orange
|
||||||
|
46,Non-profit/Charity,#0891B2,#22D3EE,#F97316,#ECFEFF,#164E63,#A5F3FC,Compassion blue + action orange
|
||||||
|
47,Music Streaming,#1E1B4B,#4338CA,#22C55E,#0F0F23,#F8FAFC,#312E81,Dark audio + play green
|
||||||
|
48,Video Streaming/OTT,#0F0F23,#1E1B4B,#E11D48,#000000,#F8FAFC,#312E81,Cinema dark + play red
|
||||||
|
49,Job Board/Recruitment,#0369A1,#0EA5E9,#22C55E,#F0F9FF,#0C4A6E,#BAE6FD,Professional blue + success green
|
||||||
|
50,Marketplace (P2P),#7C3AED,#A78BFA,#22C55E,#FAF5FF,#4C1D95,#DDD6FE,Trust purple + transaction green
|
||||||
|
51,Logistics/Delivery,#2563EB,#3B82F6,#F97316,#EFF6FF,#1E40AF,#BFDBFE,Tracking blue + delivery orange
|
||||||
|
52,Agriculture/Farm Tech,#15803D,#22C55E,#CA8A04,#F0FDF4,#14532D,#BBF7D0,Earth green + harvest gold
|
||||||
|
53,Construction/Architecture,#64748B,#94A3B8,#F97316,#F8FAFC,#334155,#E2E8F0,Industrial grey + safety orange
|
||||||
|
54,Automotive/Car Dealership,#1E293B,#334155,#DC2626,#F8FAFC,#0F172A,#E2E8F0,Premium dark + action red
|
||||||
|
55,Photography Studio,#18181B,#27272A,#F8FAFC,#000000,#FAFAFA,#3F3F46,Pure black + white contrast
|
||||||
|
56,Coworking Space,#F59E0B,#FBBF24,#2563EB,#FFFBEB,#78350F,#FDE68A,Energetic amber + booking blue
|
||||||
|
57,Cleaning Service,#0891B2,#22D3EE,#22C55E,#ECFEFF,#164E63,#A5F3FC,Fresh cyan + clean green
|
||||||
|
58,Home Services (Plumber/Electrician),#1E40AF,#3B82F6,#F97316,#EFF6FF,#1E3A8A,#BFDBFE,Professional blue + urgent orange
|
||||||
|
59,Childcare/Daycare,#F472B6,#FBCFE8,#22C55E,#FDF2F8,#9D174D,#FCE7F3,Soft pink + safe green
|
||||||
|
60,Senior Care/Elderly,#0369A1,#38BDF8,#22C55E,#F0F9FF,#0C4A6E,#E0F2FE,Calm blue + reassuring green
|
||||||
|
61,Medical Clinic,#0891B2,#22D3EE,#22C55E,#F0FDFA,#134E4A,#CCFBF1,Medical teal + health green
|
||||||
|
62,Pharmacy/Drug Store,#15803D,#22C55E,#0369A1,#F0FDF4,#14532D,#BBF7D0,Pharmacy green + trust blue
|
||||||
|
63,Dental Practice,#0EA5E9,#38BDF8,#FBBF24,#F0F9FF,#0C4A6E,#BAE6FD,Fresh blue + smile yellow
|
||||||
|
64,Veterinary Clinic,#0D9488,#14B8A6,#F97316,#F0FDFA,#134E4A,#99F6E4,Caring teal + warm orange
|
||||||
|
65,Florist/Plant Shop,#15803D,#22C55E,#EC4899,#F0FDF4,#14532D,#BBF7D0,Natural green + floral pink
|
||||||
|
66,Bakery/Cafe,#92400E,#B45309,#F8FAFC,#FEF3C7,#78350F,#FDE68A,Warm brown + cream white
|
||||||
|
67,Coffee Shop,#78350F,#92400E,#FBBF24,#FEF3C7,#451A03,#FDE68A,Coffee brown + warm gold
|
||||||
|
68,Brewery/Winery,#7C2D12,#B91C1C,#CA8A04,#FEF2F2,#450A0A,#FECACA,Deep burgundy + craft gold
|
||||||
|
69,Airline,#1E3A8A,#3B82F6,#F97316,#EFF6FF,#1E40AF,#BFDBFE,Sky blue + booking orange
|
||||||
|
70,News/Media Platform,#DC2626,#EF4444,#1E40AF,#FEF2F2,#450A0A,#FECACA,Breaking red + link blue
|
||||||
|
71,Magazine/Blog,#18181B,#3F3F46,#EC4899,#FAFAFA,#09090B,#E4E4E7,Editorial black + accent pink
|
||||||
|
72,Freelancer Platform,#6366F1,#818CF8,#22C55E,#EEF2FF,#312E81,#C7D2FE,Creative indigo + hire green
|
||||||
|
73,Consulting Firm,#0F172A,#334155,#CA8A04,#F8FAFC,#020617,#E2E8F0,Authority navy + premium gold
|
||||||
|
74,Marketing Agency,#EC4899,#F472B6,#06B6D4,#FDF2F8,#831843,#FBCFE8,Bold pink + creative cyan
|
||||||
|
75,Event Management,#7C3AED,#A78BFA,#F97316,#FAF5FF,#4C1D95,#DDD6FE,Excitement purple + action orange
|
||||||
|
76,Conference/Webinar Platform,#1E40AF,#3B82F6,#22C55E,#EFF6FF,#1E3A8A,#BFDBFE,Professional blue + join green
|
||||||
|
77,Membership/Community,#7C3AED,#A78BFA,#22C55E,#FAF5FF,#4C1D95,#DDD6FE,Community purple + join green
|
||||||
|
78,Newsletter Platform,#0369A1,#0EA5E9,#F97316,#F0F9FF,#0C4A6E,#BAE6FD,Trust blue + subscribe orange
|
||||||
|
79,Digital Products/Downloads,#6366F1,#818CF8,#22C55E,#EEF2FF,#312E81,#C7D2FE,Digital indigo + buy green
|
||||||
|
80,Church/Religious Organization,#7C3AED,#A78BFA,#CA8A04,#FAF5FF,#4C1D95,#DDD6FE,Spiritual purple + warm gold
|
||||||
|
81,Sports Team/Club,#DC2626,#EF4444,#FBBF24,#FEF2F2,#7F1D1D,#FECACA,Team red + championship gold
|
||||||
|
82,Museum/Gallery,#18181B,#27272A,#F8FAFC,#FAFAFA,#09090B,#E4E4E7,Gallery black + white space
|
||||||
|
83,Theater/Cinema,#1E1B4B,#312E81,#CA8A04,#0F0F23,#F8FAFC,#4338CA,Dramatic dark + spotlight gold
|
||||||
|
84,Language Learning App,#4F46E5,#818CF8,#22C55E,#EEF2FF,#312E81,#C7D2FE,Learning indigo + progress green
|
||||||
|
85,Coding Bootcamp,#0F172A,#1E293B,#22C55E,#020617,#F8FAFC,#334155,Terminal dark + success green
|
||||||
|
86,Cybersecurity Platform,#00FF41,#0D0D0D,#FF3333,#000000,#E0E0E0,#1F1F1F,Matrix green + alert red
|
||||||
|
87,Developer Tool / IDE,#1E293B,#334155,#22C55E,#0F172A,#F8FAFC,#475569,Code dark + run green
|
||||||
|
88,Biotech / Life Sciences,#0EA5E9,#0284C7,#10B981,#F0F9FF,#0C4A6E,#BAE6FD,DNA blue + life green
|
||||||
|
89,Space Tech / Aerospace,#F8FAFC,#94A3B8,#3B82F6,#0B0B10,#F8FAFC,#1E293B,Star white + launch blue
|
||||||
|
90,Architecture / Interior,#171717,#404040,#D4AF37,#FFFFFF,#171717,#E5E5E5,Minimal black + accent gold
|
||||||
|
91,Quantum Computing,#00FFFF,#7B61FF,#FF00FF,#050510,#E0E0FF,#333344,Quantum cyan + interference purple
|
||||||
|
92,Biohacking / Longevity,#FF4D4D,#4D94FF,#00E676,#F5F5F7,#1C1C1E,#E5E5EA,Bio red/blue + vitality green
|
||||||
|
93,Autonomous Systems,#00FF41,#008F11,#FF3333,#0D1117,#E6EDF3,#30363D,Terminal green + alert red
|
||||||
|
94,Generative AI Art,#18181B,#3F3F46,#EC4899,#FAFAFA,#09090B,#E4E4E7,Canvas neutral + creative pink
|
||||||
|
95,Spatial / Vision OS,#FFFFFF,#E5E5E5,#007AFF,#888888,#000000,#CCCCCC,Glass white + system blue
|
||||||
|
96,Climate Tech,#059669,#10B981,#FBBF24,#ECFDF5,#064E3B,#A7F3D0,Nature green + solar gold
|
||||||
|
@@ -0,0 +1,101 @@
|
|||||||
|
No,Category,Icon Name,Keywords,Library,Import Code,Usage,Best For,Style
|
||||||
|
1,Navigation,menu,hamburger menu navigation toggle bars,Lucide,import { Menu } from 'lucide-react',<Menu />,Mobile navigation drawer toggle sidebar,Outline
|
||||||
|
2,Navigation,arrow-left,back previous return navigate,Lucide,import { ArrowLeft } from 'lucide-react',<ArrowLeft />,Back button breadcrumb navigation,Outline
|
||||||
|
3,Navigation,arrow-right,next forward continue navigate,Lucide,import { ArrowRight } from 'lucide-react',<ArrowRight />,Forward button next step CTA,Outline
|
||||||
|
4,Navigation,chevron-down,dropdown expand accordion select,Lucide,import { ChevronDown } from 'lucide-react',<ChevronDown />,Dropdown toggle accordion header,Outline
|
||||||
|
5,Navigation,chevron-up,collapse close accordion minimize,Lucide,import { ChevronUp } from 'lucide-react',<ChevronUp />,Accordion collapse minimize,Outline
|
||||||
|
6,Navigation,home,homepage main dashboard start,Lucide,import { Home } from 'lucide-react',<Home />,Home navigation main page,Outline
|
||||||
|
7,Navigation,x,close cancel dismiss remove exit,Lucide,import { X } from 'lucide-react',<X />,Modal close dismiss button,Outline
|
||||||
|
8,Navigation,external-link,open new tab external link,Lucide,import { ExternalLink } from 'lucide-react',<ExternalLink />,External link indicator,Outline
|
||||||
|
9,Action,plus,add create new insert,Lucide,import { Plus } from 'lucide-react',<Plus />,Add button create new item,Outline
|
||||||
|
10,Action,minus,remove subtract decrease delete,Lucide,import { Minus } from 'lucide-react',<Minus />,Remove item quantity decrease,Outline
|
||||||
|
11,Action,trash-2,delete remove discard bin,Lucide,import { Trash2 } from 'lucide-react',<Trash2 />,Delete action destructive,Outline
|
||||||
|
12,Action,edit,pencil modify change update,Lucide,import { Edit } from 'lucide-react',<Edit />,Edit button modify content,Outline
|
||||||
|
13,Action,save,disk store persist save,Lucide,import { Save } from 'lucide-react',<Save />,Save button persist changes,Outline
|
||||||
|
14,Action,download,export save file download,Lucide,import { Download } from 'lucide-react',<Download />,Download file export,Outline
|
||||||
|
15,Action,upload,import file attach upload,Lucide,import { Upload } from 'lucide-react',<Upload />,Upload file import,Outline
|
||||||
|
16,Action,copy,duplicate clipboard paste,Lucide,import { Copy } from 'lucide-react',<Copy />,Copy to clipboard,Outline
|
||||||
|
17,Action,share,social distribute send,Lucide,import { Share } from 'lucide-react',<Share />,Share button social,Outline
|
||||||
|
18,Action,search,find lookup filter query,Lucide,import { Search } from 'lucide-react',<Search />,Search input bar,Outline
|
||||||
|
19,Action,filter,sort refine narrow options,Lucide,import { Filter } from 'lucide-react',<Filter />,Filter dropdown sort,Outline
|
||||||
|
20,Action,settings,gear cog preferences config,Lucide,import { Settings } from 'lucide-react',<Settings />,Settings page configuration,Outline
|
||||||
|
21,Status,check,success done complete verified,Lucide,import { Check } from 'lucide-react',<Check />,Success state checkmark,Outline
|
||||||
|
22,Status,check-circle,success verified approved complete,Lucide,import { CheckCircle } from 'lucide-react',<CheckCircle />,Success badge verified,Outline
|
||||||
|
23,Status,x-circle,error failed cancel rejected,Lucide,import { XCircle } from 'lucide-react',<XCircle />,Error state failed,Outline
|
||||||
|
24,Status,alert-triangle,warning caution attention danger,Lucide,import { AlertTriangle } from 'lucide-react',<AlertTriangle />,Warning message caution,Outline
|
||||||
|
25,Status,alert-circle,info notice information help,Lucide,import { AlertCircle } from 'lucide-react',<AlertCircle />,Info notice alert,Outline
|
||||||
|
26,Status,info,information help tooltip details,Lucide,import { Info } from 'lucide-react',<Info />,Information tooltip help,Outline
|
||||||
|
27,Status,loader,loading spinner processing wait,Lucide,import { Loader } from 'lucide-react',<Loader className="animate-spin" />,Loading state spinner,Outline
|
||||||
|
28,Status,clock,time schedule pending wait,Lucide,import { Clock } from 'lucide-react',<Clock />,Pending time schedule,Outline
|
||||||
|
29,Communication,mail,email message inbox letter,Lucide,import { Mail } from 'lucide-react',<Mail />,Email contact inbox,Outline
|
||||||
|
30,Communication,message-circle,chat comment bubble conversation,Lucide,import { MessageCircle } from 'lucide-react',<MessageCircle />,Chat comment message,Outline
|
||||||
|
31,Communication,phone,call mobile telephone contact,Lucide,import { Phone } from 'lucide-react',<Phone />,Phone contact call,Outline
|
||||||
|
32,Communication,send,submit dispatch message airplane,Lucide,import { Send } from 'lucide-react',<Send />,Send message submit,Outline
|
||||||
|
33,Communication,bell,notification alert ring reminder,Lucide,import { Bell } from 'lucide-react',<Bell />,Notification bell alert,Outline
|
||||||
|
34,User,user,profile account person avatar,Lucide,import { User } from 'lucide-react',<User />,User profile account,Outline
|
||||||
|
35,User,users,team group people members,Lucide,import { Users } from 'lucide-react',<Users />,Team group members,Outline
|
||||||
|
36,User,user-plus,add invite new member,Lucide,import { UserPlus } from 'lucide-react',<UserPlus />,Add user invite,Outline
|
||||||
|
37,User,log-in,signin authenticate enter,Lucide,import { LogIn } from 'lucide-react',<LogIn />,Login signin,Outline
|
||||||
|
38,User,log-out,signout exit leave logout,Lucide,import { LogOut } from 'lucide-react',<LogOut />,Logout signout,Outline
|
||||||
|
39,Media,image,photo picture gallery thumbnail,Lucide,import { Image } from 'lucide-react',<Image />,Image photo gallery,Outline
|
||||||
|
40,Media,video,movie film play record,Lucide,import { Video } from 'lucide-react',<Video />,Video player media,Outline
|
||||||
|
41,Media,play,start video audio media,Lucide,import { Play } from 'lucide-react',<Play />,Play button video audio,Outline
|
||||||
|
42,Media,pause,stop halt video audio,Lucide,import { Pause } from 'lucide-react',<Pause />,Pause button media,Outline
|
||||||
|
43,Media,volume-2,sound audio speaker music,Lucide,import { Volume2 } from 'lucide-react',<Volume2 />,Volume audio sound,Outline
|
||||||
|
44,Media,mic,microphone record voice audio,Lucide,import { Mic } from 'lucide-react',<Mic />,Microphone voice record,Outline
|
||||||
|
45,Media,camera,photo capture snapshot picture,Lucide,import { Camera } from 'lucide-react',<Camera />,Camera photo capture,Outline
|
||||||
|
46,Commerce,shopping-cart,cart checkout basket buy,Lucide,import { ShoppingCart } from 'lucide-react',<ShoppingCart />,Shopping cart e-commerce,Outline
|
||||||
|
47,Commerce,shopping-bag,purchase buy store bag,Lucide,import { ShoppingBag } from 'lucide-react',<ShoppingBag />,Shopping bag purchase,Outline
|
||||||
|
48,Commerce,credit-card,payment card checkout stripe,Lucide,import { CreditCard } from 'lucide-react',<CreditCard />,Payment credit card,Outline
|
||||||
|
49,Commerce,dollar-sign,money price currency cost,Lucide,import { DollarSign } from 'lucide-react',<DollarSign />,Price money currency,Outline
|
||||||
|
50,Commerce,tag,label price discount sale,Lucide,import { Tag } from 'lucide-react',<Tag />,Price tag label,Outline
|
||||||
|
51,Commerce,gift,present reward bonus offer,Lucide,import { Gift } from 'lucide-react',<Gift />,Gift reward offer,Outline
|
||||||
|
52,Commerce,percent,discount sale offer promo,Lucide,import { Percent } from 'lucide-react',<Percent />,Discount percentage sale,Outline
|
||||||
|
53,Data,bar-chart,analytics statistics graph metrics,Lucide,import { BarChart } from 'lucide-react',<BarChart />,Bar chart analytics,Outline
|
||||||
|
54,Data,pie-chart,statistics distribution breakdown,Lucide,import { PieChart } from 'lucide-react',<PieChart />,Pie chart distribution,Outline
|
||||||
|
55,Data,trending-up,growth increase positive trend,Lucide,import { TrendingUp } from 'lucide-react',<TrendingUp />,Growth trend positive,Outline
|
||||||
|
56,Data,trending-down,decline decrease negative trend,Lucide,import { TrendingDown } from 'lucide-react',<TrendingDown />,Decline trend negative,Outline
|
||||||
|
57,Data,activity,pulse heartbeat monitor live,Lucide,import { Activity } from 'lucide-react',<Activity />,Activity monitor pulse,Outline
|
||||||
|
58,Data,database,storage server data backend,Lucide,import { Database } from 'lucide-react',<Database />,Database storage,Outline
|
||||||
|
59,Files,file,document page paper doc,Lucide,import { File } from 'lucide-react',<File />,File document,Outline
|
||||||
|
60,Files,file-text,document text page article,Lucide,import { FileText } from 'lucide-react',<FileText />,Text document article,Outline
|
||||||
|
61,Files,folder,directory organize group files,Lucide,import { Folder } from 'lucide-react',<Folder />,Folder directory,Outline
|
||||||
|
62,Files,folder-open,expanded browse files view,Lucide,import { FolderOpen } from 'lucide-react',<FolderOpen />,Open folder browse,Outline
|
||||||
|
63,Files,paperclip,attachment attach file link,Lucide,import { Paperclip } from 'lucide-react',<Paperclip />,Attachment paperclip,Outline
|
||||||
|
64,Files,link,url hyperlink chain connect,Lucide,import { Link } from 'lucide-react',<Link />,Link URL hyperlink,Outline
|
||||||
|
65,Files,clipboard,paste copy buffer notes,Lucide,import { Clipboard } from 'lucide-react',<Clipboard />,Clipboard paste,Outline
|
||||||
|
66,Layout,grid,tiles gallery layout dashboard,Lucide,import { Grid } from 'lucide-react',<Grid />,Grid layout gallery,Outline
|
||||||
|
67,Layout,list,rows table lines items,Lucide,import { List } from 'lucide-react',<List />,List view rows,Outline
|
||||||
|
68,Layout,columns,layout split dual sidebar,Lucide,import { Columns } from 'lucide-react',<Columns />,Column layout split,Outline
|
||||||
|
69,Layout,maximize,fullscreen expand enlarge zoom,Lucide,import { Maximize } from 'lucide-react',<Maximize />,Fullscreen maximize,Outline
|
||||||
|
70,Layout,minimize,reduce shrink collapse exit,Lucide,import { Minimize } from 'lucide-react',<Minimize />,Minimize reduce,Outline
|
||||||
|
71,Layout,sidebar,panel drawer navigation menu,Lucide,import { Sidebar } from 'lucide-react',<Sidebar />,Sidebar panel,Outline
|
||||||
|
72,Social,heart,like love favorite wishlist,Lucide,import { Heart } from 'lucide-react',<Heart />,Like favorite love,Outline
|
||||||
|
73,Social,star,rating review favorite bookmark,Lucide,import { Star } from 'lucide-react',<Star />,Star rating favorite,Outline
|
||||||
|
74,Social,thumbs-up,like approve agree positive,Lucide,import { ThumbsUp } from 'lucide-react',<ThumbsUp />,Like approve thumb,Outline
|
||||||
|
75,Social,thumbs-down,dislike disapprove disagree negative,Lucide,import { ThumbsDown } from 'lucide-react',<ThumbsDown />,Dislike disapprove,Outline
|
||||||
|
76,Social,bookmark,save later favorite mark,Lucide,import { Bookmark } from 'lucide-react',<Bookmark />,Bookmark save,Outline
|
||||||
|
77,Social,flag,report mark important highlight,Lucide,import { Flag } from 'lucide-react',<Flag />,Flag report,Outline
|
||||||
|
78,Device,smartphone,mobile phone device touch,Lucide,import { Smartphone } from 'lucide-react',<Smartphone />,Mobile smartphone,Outline
|
||||||
|
79,Device,tablet,ipad device touch screen,Lucide,import { Tablet } from 'lucide-react',<Tablet />,Tablet device,Outline
|
||||||
|
80,Device,monitor,desktop screen computer display,Lucide,import { Monitor } from 'lucide-react',<Monitor />,Desktop monitor,Outline
|
||||||
|
81,Device,laptop,notebook computer portable device,Lucide,import { Laptop } from 'lucide-react',<Laptop />,Laptop computer,Outline
|
||||||
|
82,Device,printer,print document output paper,Lucide,import { Printer } from 'lucide-react',<Printer />,Printer print,Outline
|
||||||
|
83,Security,lock,secure password protected private,Lucide,import { Lock } from 'lucide-react',<Lock />,Lock secure,Outline
|
||||||
|
84,Security,unlock,open access unsecure public,Lucide,import { Unlock } from 'lucide-react',<Unlock />,Unlock open,Outline
|
||||||
|
85,Security,shield,protection security safe guard,Lucide,import { Shield } from 'lucide-react',<Shield />,Shield protection,Outline
|
||||||
|
86,Security,key,password access unlock login,Lucide,import { Key } from 'lucide-react',<Key />,Key password,Outline
|
||||||
|
87,Security,eye,view show visible password,Lucide,import { Eye } from 'lucide-react',<Eye />,Show password view,Outline
|
||||||
|
88,Security,eye-off,hide invisible password hidden,Lucide,import { EyeOff } from 'lucide-react',<EyeOff />,Hide password,Outline
|
||||||
|
89,Location,map-pin,location marker place address,Lucide,import { MapPin } from 'lucide-react',<MapPin />,Location pin marker,Outline
|
||||||
|
90,Location,map,directions navigate geography location,Lucide,import { Map } from 'lucide-react',<Map />,Map directions,Outline
|
||||||
|
91,Location,navigation,compass direction pointer arrow,Lucide,import { Navigation } from 'lucide-react',<Navigation />,Navigation compass,Outline
|
||||||
|
92,Location,globe,world international global web,Lucide,import { Globe } from 'lucide-react',<Globe />,Globe world,Outline
|
||||||
|
93,Time,calendar,date schedule event appointment,Lucide,import { Calendar } from 'lucide-react',<Calendar />,Calendar date,Outline
|
||||||
|
94,Time,refresh-cw,reload sync update refresh,Lucide,import { RefreshCw } from 'lucide-react',<RefreshCw />,Refresh reload,Outline
|
||||||
|
95,Time,rotate-ccw,undo back revert history,Lucide,import { RotateCcw } from 'lucide-react',<RotateCcw />,Undo revert,Outline
|
||||||
|
96,Time,rotate-cw,redo forward repeat history,Lucide,import { RotateCw } from 'lucide-react',<RotateCw />,Redo forward,Outline
|
||||||
|
97,Development,code,develop programming syntax html,Lucide,import { Code } from 'lucide-react',<Code />,Code development,Outline
|
||||||
|
98,Development,terminal,console cli command shell,Lucide,import { Terminal } from 'lucide-react',<Terminal />,Terminal console,Outline
|
||||||
|
99,Development,git-branch,version control branch merge,Lucide,import { GitBranch } from 'lucide-react',<GitBranch />,Git branch,Outline
|
||||||
|
100,Development,github,repository code open source,Lucide,import { Github } from 'lucide-react',<Github />,GitHub repository,Outline
|
||||||
|
Can't render this file because it contains an unexpected character in line 28 and column 113.
|
@@ -0,0 +1,31 @@
|
|||||||
|
No,Pattern Name,Keywords,Section Order,Primary CTA Placement,Color Strategy,Recommended Effects,Conversion Optimization
|
||||||
|
1,Hero + Features + CTA,"hero, hero-centric, features, feature-rich, cta, call-to-action","1. Hero with headline/image, 2. Value prop, 3. Key features (3-5), 4. CTA section, 5. Footer",Hero (sticky) + Bottom,Hero: Brand primary or vibrant. Features: Card bg #FAFAFA. CTA: Contrasting accent color,"Hero parallax, feature card hover lift, CTA glow on hover",Deep CTA placement. Use contrasting color (at least 7:1 contrast ratio). Sticky navbar CTA.
|
||||||
|
2,Hero + Testimonials + CTA,"hero, testimonials, social-proof, trust, reviews, cta","1. Hero, 2. Problem statement, 3. Solution overview, 4. Testimonials carousel, 5. CTA",Hero (sticky) + Post-testimonials,"Hero: Brand color. Testimonials: Light bg #F5F5F5. Quotes: Italic, muted color #666. CTA: Vibrant","Testimonial carousel slide animations, quote marks animations, avatar fade-in",Social proof before CTA. Use 3-5 testimonials. Include photo + name + role. CTA after social proof.
|
||||||
|
3,Product Demo + Features,"demo, product-demo, features, showcase, interactive","1. Hero, 2. Product video/mockup (center), 3. Feature breakdown per section, 4. Comparison (optional), 5. CTA",Video center + CTA right/bottom,Video surround: Brand color overlay. Features: Icon color #0080FF. Text: Dark #222,"Video play button pulse, feature scroll reveals, demo interaction highlights",Embedded product demo increases engagement. Use interactive mockup if possible. Auto-play video muted.
|
||||||
|
4,Minimal Single Column,"minimal, simple, direct, single-column, clean","1. Hero headline, 2. Short description, 3. Benefit bullets (3 max), 4. CTA, 5. Footer","Center, large CTA button",Minimalist: Brand + white #FFFFFF + accent. Buttons: High contrast 7:1+. Text: Black/Dark grey,Minimal hover effects. Smooth scroll. CTA scale on hover (subtle),Single CTA focus. Large typography. Lots of whitespace. No nav clutter. Mobile-first.
|
||||||
|
5,Funnel (3-Step Conversion),"funnel, conversion, steps, wizard, onboarding","1. Hero, 2. Step 1 (problem), 3. Step 2 (solution), 4. Step 3 (action), 5. CTA progression",Each step: mini-CTA. Final: main CTA,"Step colors: 1 (Red/Problem), 2 (Orange/Process), 3 (Green/Solution). CTA: Brand color","Step number animations, progress bar fill, step transitions smooth scroll",Progressive disclosure. Show only essential info per step. Use progress indicators. Multiple CTAs.
|
||||||
|
6,Comparison Table + CTA,"comparison, table, compare, versus, cta","1. Hero, 2. Problem intro, 3. Comparison table (product vs competitors), 4. Pricing (optional), 5. CTA",Table: Right column. CTA: Below table,Table: Alternating rows (white/light grey). Your product: Highlight #FFFACD (light yellow) or green. Text: Dark,"Table row hover highlight, price toggle animations, feature checkmark animations",Use comparison to show unique value. Highlight your product row. Include 'free trial' in pricing row.
|
||||||
|
7,Lead Magnet + Form,"lead, form, signup, capture, email, magnet","1. Hero (benefit headline), 2. Lead magnet preview (ebook cover, checklist, etc), 3. Form (minimal fields), 4. CTA submit",Form CTA: Submit button,Lead magnet: Professional design. Form: Clean white bg. Inputs: Light border #CCCCCC. CTA: Brand color,"Form focus state animations, input validation animations, success confirmation animation",Form fields ≤ 3 for best conversion. Offer valuable lead magnet preview. Show form submission progress.
|
||||||
|
8,Pricing Page + CTA,"pricing, plans, tiers, comparison, cta","1. Hero (pricing headline), 2. Price comparison cards, 3. Feature comparison table, 4. FAQ section, 5. Final CTA",Each card: CTA button. Sticky CTA in nav,"Free: Grey, Starter: Blue, Pro: Green/Gold, Enterprise: Dark. Cards: 1px border, shadow","Price toggle animation (monthly/yearly), card comparison highlight, FAQ accordion open/close",Recommend starter plan (pre-select/highlight). Show annual discount (20-30%). Use FAQs to address concerns.
|
||||||
|
9,Video-First Hero,"video, hero, media, visual, engaging","1. Hero with video background, 2. Key features overlay, 3. Benefits section, 4. CTA",Overlay on video (center/bottom) + Bottom section,Dark overlay 60% on video. Brand accent for CTA. White text on dark.,"Video autoplay muted, parallax scroll, text fade-in on scroll",86% higher engagement with video. Add captions for accessibility. Compress video for performance.
|
||||||
|
10,Scroll-Triggered Storytelling,"storytelling, scroll, narrative, story, immersive","1. Intro hook, 2. Chapter 1 (problem), 3. Chapter 2 (journey), 4. Chapter 3 (solution), 5. Climax CTA",End of each chapter (mini) + Final climax CTA,Progressive reveal. Each chapter has distinct color. Building intensity.,"ScrollTrigger animations, parallax layers, progressive disclosure, chapter transitions",Narrative increases time-on-page 3x. Use progress indicator. Mobile: simplify animations.
|
||||||
|
11,AI Personalization Landing,"ai, personalization, smart, recommendation, dynamic","1. Dynamic hero (personalized), 2. Relevant features, 3. Tailored testimonials, 4. Smart CTA",Context-aware placement based on user segment,Adaptive based on user data. A/B test color variations per segment.,"Dynamic content swap, fade transitions, personalized product recommendations",20%+ conversion with personalization. Requires analytics integration. Fallback for new users.
|
||||||
|
12,Waitlist/Coming Soon,"waitlist, coming-soon, launch, early-access, notify","1. Hero with countdown, 2. Product teaser/preview, 3. Email capture form, 4. Social proof (waitlist count)",Email form prominent (above fold) + Sticky form on scroll,Anticipation: Dark + accent highlights. Countdown in brand color. Urgency indicators.,"Countdown timer animation, email validation feedback, success confetti, social share buttons",Scarcity + exclusivity. Show waitlist count. Early access benefits. Referral program.
|
||||||
|
13,Comparison Table Focus,"comparison, table, versus, compare, features","1. Hero (problem statement), 2. Comparison matrix (you vs competitors), 3. Feature deep-dive, 4. Winner CTA",After comparison table (highlighted row) + Bottom,Your product column highlighted (accent bg or green). Competitors neutral. Checkmarks green.,"Table row hover highlight, feature checkmark animations, sticky comparison header",Show value vs competitors. 35% higher conversion. Be factual. Include pricing if favorable.
|
||||||
|
14,Pricing-Focused Landing,"pricing, price, cost, plans, subscription","1. Hero (value proposition), 2. Pricing cards (3 tiers), 3. Feature comparison, 4. FAQ, 5. Final CTA",Each pricing card + Sticky CTA in nav + Bottom,Popular plan highlighted (brand color border/bg). Free: grey. Enterprise: dark/premium.,"Price toggle monthly/annual animation, card hover lift, FAQ accordion smooth open",Annual discount 20-30%. Recommend mid-tier (most popular badge). Address objections in FAQ.
|
||||||
|
15,App Store Style Landing,"app, mobile, download, store, install","1. Hero with device mockup, 2. Screenshots carousel, 3. Features with icons, 4. Reviews/ratings, 5. Download CTAs",Download buttons prominent (App Store + Play Store) throughout,Dark/light matching app store feel. Star ratings in gold. Screenshots with device frames.,"Device mockup rotations, screenshot slider, star rating animations, download button pulse",Show real screenshots. Include ratings (4.5+ stars). QR code for mobile. Platform-specific CTAs.
|
||||||
|
16,FAQ/Documentation Landing,"faq, documentation, help, support, questions","1. Hero with search bar, 2. Popular categories, 3. FAQ accordion, 4. Contact/support CTA",Search bar prominent + Contact CTA for unresolved questions,"Clean, high readability. Minimal color. Category icons in brand color. Success green for resolved.","Search autocomplete, smooth accordion open/close, category hover, helpful feedback buttons",Reduce support tickets. Track search analytics. Show related articles. Contact escalation path.
|
||||||
|
17,Immersive/Interactive Experience,"immersive, interactive, experience, 3d, animation","1. Full-screen interactive element, 2. Guided product tour, 3. Key benefits revealed, 4. CTA after completion",After interaction complete + Skip option for impatient users,Immersive experience colors. Dark background for focus. Highlight interactive elements.,"WebGL, 3D interactions, gamification elements, progress indicators, reward animations",40% higher engagement. Performance trade-off. Provide skip option. Mobile fallback essential.
|
||||||
|
18,Event/Conference Landing,"event, conference, meetup, registration, schedule","1. Hero (date/location/countdown), 2. Speakers grid, 3. Agenda/schedule, 4. Sponsors, 5. Register CTA",Register CTA sticky + After speakers + Bottom,Urgency colors (countdown). Event branding. Speaker cards professional. Sponsor logos neutral.,"Countdown timer, speaker hover cards with bio, agenda tabs, early bird countdown",Early bird pricing with deadline. Social proof (past attendees). Speaker credibility. Multi-ticket discounts.
|
||||||
|
19,Product Review/Ratings Focused,"reviews, ratings, testimonials, social-proof, stars","1. Hero (product + aggregate rating), 2. Rating breakdown, 3. Individual reviews, 4. Buy/CTA",After reviews summary + Buy button alongside reviews,Trust colors. Star ratings gold. Verified badge green. Review sentiment colors.,"Star fill animations, review filtering, helpful vote interactions, photo lightbox",User-generated content builds trust. Show verified purchases. Filter by rating. Respond to negative reviews.
|
||||||
|
20,Community/Forum Landing,"community, forum, social, members, discussion","1. Hero (community value prop), 2. Popular topics/categories, 3. Active members showcase, 4. Join CTA",Join button prominent + After member showcase,"Warm, welcoming. Member photos add humanity. Topic badges in brand colors. Activity indicators green.","Member avatars animation, activity feed live updates, topic hover previews, join success celebration","Show active community (member count, posts today). Highlight benefits. Preview content. Easy onboarding."
|
||||||
|
21,Before-After Transformation,"before-after, transformation, results, comparison","1. Hero (problem state), 2. Transformation slider/comparison, 3. How it works, 4. Results CTA",After transformation reveal + Bottom,Contrast: muted/grey (before) vs vibrant/colorful (after). Success green for results.,"Slider comparison interaction, before/after reveal animations, result counters, testimonial videos",Visual proof of value. 45% higher conversion. Real results. Specific metrics. Guarantee offer.
|
||||||
|
22,Marketplace / Directory,"marketplace, directory, search, listing","1. Hero (Search focused), 2. Categories, 3. Featured Listings, 4. Trust/Safety, 5. CTA (Become a host/seller)",Hero Search Bar + Navbar 'List your item',Search: High contrast. Categories: Visual icons. Trust: Blue/Green.,Search autocomplete animation," map hover pins, card carousel, Search bar is the CTA. Reduce friction to search. Popular searches suggestions."
|
||||||
|
23,Newsletter / Content First,"newsletter, content, writer, blog, subscribe","1. Hero (Value Prop + Form), 2. Recent Issues/Archives, 3. Social Proof (Subscriber count), 4. About Author",Hero inline form + Sticky header form,Minimalist. Paper-like background. Text focus. Accent color for Subscribe.,Text highlight animations," typewriter effect, subtle fade-in, Single field form (Email only). Show 'Join X, 000 readers'. Read sample link."
|
||||||
|
24,Webinar Registration,"webinar, registration, event, training, live","1. Hero (Topic + Timer + Form), 2. What you'll learn, 3. Speaker Bio, 4. Urgency/Bonuses, 5. Form (again)",Hero (Right side form) + Bottom anchor,Urgency: Red/Orange. Professional: Blue/Navy. Form: High contrast white.,Countdown timer," speaker avatar float, urgent ticker, Limited seats logic. 'Live' indicator. Auto-fill timezone."
|
||||||
|
25,Enterprise Gateway,"enterprise, corporate, gateway, solutions, portal","1. Hero (Video/Mission), 2. Solutions by Industry, 3. Solutions by Role, 4. Client Logos, 5. Contact Sales",Contact Sales (Primary) + Login (Secondary),Corporate: Navy/Grey. High integrity. Conservative accents.,Slow video background," logo carousel, tab switching for industries, Path selection (I am a...). Mega menu navigation. Trust signals prominent."
|
||||||
|
26,Portfolio Grid,"portfolio, grid, showcase, gallery, masonry","1. Hero (Name/Role), 2. Project Grid (Masonry), 3. About/Philosophy, 4. Contact",Project Card Hover + Footer Contact,Neutral background (let work shine). Text: Black/White. Accent: Minimal.,Image lazy load reveal," hover overlay info, lightbox view, Visuals first. Filter by category. Fast loading essential."
|
||||||
|
27,Horizontal Scroll Journey,"horizontal, scroll, journey, gallery, storytelling, panoramic","1. Intro (Vertical), 2. The Journey (Horizontal Track), 3. Detail Reveal, 4. Vertical Footer",Floating Sticky CTA or End of Horizontal Track,Continuous palette transition. Chapter colors. Progress bar #000000.,"Scroll-jacking (careful), parallax layers, horizontal slide, progress indicator","Immersive product discovery. High engagement. Keep navigation visible.
|
||||||
|
28,Bento Grid Showcase,bento, grid, features, modular, apple-style, showcase"", 1. Hero, 2. Bento Grid (Key Features), 3. Detail Cards, 4. Tech Specs, 5. CTA, Floating Action Button or Bottom of Grid, Card backgrounds: #F5F5F7 or Glass. Icons: Vibrant brand colors. Text: Dark., Hover card scale (1.02), video inside cards, tilt effect, staggered reveal, Scannable value props. High information density without clutter. Mobile stack.
|
||||||
|
29,Interactive 3D Configurator,3d, configurator, customizer, interactive, product"", 1. Hero (Configurator), 2. Feature Highlight (synced), 3. Price/Specs, 4. Purchase, Inside Configurator UI + Sticky Bottom Bar, Neutral studio background. Product: Realistic materials. UI: Minimal overlay., Real-time rendering, material swap animation, camera rotate/zoom, light reflection, Increases ownership feeling. 360 view reduces return rates. Direct add-to-cart.
|
||||||
|
30,AI-Driven Dynamic Landing,ai, dynamic, personalized, adaptive, generative"", 1. Prompt/Input Hero, 2. Generated Result Preview, 3. How it Works, 4. Value Prop, Input Field (Hero) + 'Try it' Buttons, Adaptive to user input. Dark mode for compute feel. Neon accents., Typing text effects, shimmering generation loaders, morphing layouts, Immediate value demonstration. 'Show, don't tell'. Low friction start."
|
||||||
|
@@ -0,0 +1,97 @@
|
|||||||
|
No,Product Type,Keywords,Primary Style Recommendation,Secondary Styles,Landing Page Pattern,Dashboard Style (if applicable),Color Palette Focus,Key Considerations
|
||||||
|
1,SaaS (General),"app, b2b, cloud, general, saas, software, subscription",Glassmorphism + Flat Design,"Soft UI Evolution, Minimalism",Hero + Features + CTA,Data-Dense + Real-Time Monitoring,Trust blue + accent contrast,Balance modern feel with clarity. Focus on CTAs.
|
||||||
|
2,Micro SaaS,"app, b2b, cloud, indie, micro, micro-saas, niche, saas, small, software, solo, subscription",Flat Design + Vibrant & Block,"Motion-Driven, Micro-interactions",Minimal & Direct + Demo,Executive Dashboard,Vibrant primary + white space,"Keep simple, show product quickly. Speed is key."
|
||||||
|
3,E-commerce,"buy, commerce, e, ecommerce, products, retail, sell, shop, store",Vibrant & Block-based,"Aurora UI, Motion-Driven",Feature-Rich Showcase,Sales Intelligence Dashboard,Brand primary + success green,Engagement & conversions. High visual hierarchy.
|
||||||
|
4,E-commerce Luxury,"buy, commerce, e, ecommerce, elegant, exclusive, high-end, luxury, premium, products, retail, sell, shop, store",Liquid Glass + Glassmorphism,"3D & Hyperrealism, Aurora UI",Feature-Rich Showcase,Sales Intelligence Dashboard,Premium colors + minimal accent,Elegance & sophistication. Premium materials.
|
||||||
|
5,Service Landing Page,"appointment, booking, consultation, conversion, landing, marketing, page, service",Hero-Centric + Trust & Authority,"Social Proof-Focused, Storytelling",Hero-Centric Design,N/A - Analytics for conversions,Brand primary + trust colors,Social proof essential. Show expertise.
|
||||||
|
6,B2B Service,"appointment, b, b2b, booking, business, consultation, corporate, enterprise, service",Trust & Authority + Minimal,"Feature-Rich, Conversion-Optimized",Feature-Rich Showcase,Sales Intelligence Dashboard,Professional blue + neutral grey,Credibility essential. Clear ROI messaging.
|
||||||
|
7,Financial Dashboard,"admin, analytics, dashboard, data, financial, panel",Dark Mode (OLED) + Data-Dense,"Minimalism, Accessible & Ethical",N/A - Dashboard focused,Financial Dashboard,Dark bg + red/green alerts + trust blue,"High contrast, real-time updates, accuracy paramount."
|
||||||
|
8,Analytics Dashboard,"admin, analytics, dashboard, data, panel",Data-Dense + Heat Map & Heatmap,"Minimalism, Dark Mode (OLED)",N/A - Analytics focused,Drill-Down Analytics + Comparative,Cool→Hot gradients + neutral grey,Clarity > aesthetics. Color-coded data priority.
|
||||||
|
9,Healthcare App,"app, clinic, health, healthcare, medical, patient",Neumorphism + Accessible & Ethical,"Soft UI Evolution, Claymorphism (for patients)",Social Proof-Focused,User Behavior Analytics,Calm blue + health green + trust,Accessibility mandatory. Calming aesthetic.
|
||||||
|
10,Educational App,"app, course, education, educational, learning, school, training",Claymorphism + Micro-interactions,"Vibrant & Block-based, Flat Design",Storytelling-Driven,User Behavior Analytics,Playful colors + clear hierarchy,Engagement & ease of use. Age-appropriate design.
|
||||||
|
11,Creative Agency,"agency, creative, design, marketing, studio",Brutalism + Motion-Driven,"Retro-Futurism, Storytelling-Driven",Storytelling-Driven,N/A - Portfolio focused,Bold primaries + artistic freedom,Differentiation key. Wow-factor necessary.
|
||||||
|
12,Portfolio/Personal,"creative, personal, portfolio, projects, showcase, work",Motion-Driven + Minimalism,"Brutalism, Aurora UI",Storytelling-Driven,N/A - Personal branding,Brand primary + artistic interpretation,Showcase work. Personality shine through.
|
||||||
|
13,Gaming,"entertainment, esports, game, gaming, play",3D & Hyperrealism + Retro-Futurism,"Motion-Driven, Vibrant & Block",Feature-Rich Showcase,N/A - Game focused,Vibrant + neon + immersive colors,Immersion priority. Performance critical.
|
||||||
|
14,Government/Public Service,"appointment, booking, consultation, government, public, service",Accessible & Ethical + Minimalism,"Flat Design, Inclusive Design",Minimal & Direct,Executive Dashboard,Professional blue + high contrast,WCAG AAA mandatory. Trust paramount.
|
||||||
|
15,Fintech/Crypto,"banking, blockchain, crypto, defi, finance, fintech, money, nft, payment, web3",Glassmorphism + Dark Mode (OLED),"Retro-Futurism, Motion-Driven",Conversion-Optimized,Real-Time Monitoring + Predictive,Dark tech colors + trust + vibrant accents,Security perception. Real-time data critical.
|
||||||
|
16,Social Media App,"app, community, content, entertainment, media, network, sharing, social, streaming, users, video",Vibrant & Block-based + Motion-Driven,"Aurora UI, Micro-interactions",Feature-Rich Showcase,User Behavior Analytics,Vibrant + engagement colors,Engagement & retention. Addictive design ethics.
|
||||||
|
17,Productivity Tool,"collaboration, productivity, project, task, tool, workflow",Flat Design + Micro-interactions,"Minimalism, Soft UI Evolution",Interactive Product Demo,Drill-Down Analytics,Clear hierarchy + functional colors,Ease of use. Speed & efficiency focus.
|
||||||
|
18,Design System/Component Library,"component, design, library, system",Minimalism + Accessible & Ethical,"Flat Design, Zero Interface",Feature-Rich Showcase,N/A - Dev focused,Clear hierarchy + code-like structure,Consistency. Developer-first approach.
|
||||||
|
19,AI/Chatbot Platform,"ai, artificial-intelligence, automation, chatbot, machine-learning, ml, platform",AI-Native UI + Minimalism,"Zero Interface, Glassmorphism",Interactive Product Demo,AI/ML Analytics Dashboard,Neutral + AI Purple (#6366F1),Conversational UI. Streaming text. Context awareness. Minimal chrome.
|
||||||
|
20,NFT/Web3 Platform,"nft, platform, web",Cyberpunk UI + Glassmorphism,"Aurora UI, 3D & Hyperrealism",Feature-Rich Showcase,Crypto/Blockchain Dashboard,Dark + Neon + Gold (#FFD700),Wallet integration. Transaction feedback. Gas fees display. Dark mode essential.
|
||||||
|
21,Creator Economy Platform,"creator, economy, platform",Vibrant & Block-based + Bento Box Grid,"Motion-Driven, Aurora UI",Social Proof-Focused,User Behavior Analytics,Vibrant + Brand colors,Creator profiles. Monetization display. Engagement metrics. Social proof.
|
||||||
|
22,Sustainability/ESG Platform,"ai, artificial-intelligence, automation, esg, machine-learning, ml, platform, sustainability",Organic Biophilic + Minimalism,"Accessible & Ethical, Flat Design",Trust & Authority,Energy/Utilities Dashboard,Green (#228B22) + Earth tones,Carbon footprint visuals. Progress indicators. Certification badges. Eco-friendly imagery.
|
||||||
|
23,Remote Work/Collaboration Tool,"collaboration, remote, tool, work",Soft UI Evolution + Minimalism,"Glassmorphism, Micro-interactions",Feature-Rich Showcase,Drill-Down Analytics,Calm Blue + Neutral grey,Real-time collaboration. Status indicators. Video integration. Notification management.
|
||||||
|
24,Mental Health App,"app, health, mental",Neumorphism + Accessible & Ethical,"Claymorphism, Soft UI Evolution",Social Proof-Focused,Healthcare Analytics,Calm Pastels + Trust colors,Calming aesthetics. Privacy-first. Crisis resources. Progress tracking. Accessibility mandatory.
|
||||||
|
25,Pet Tech App,"app, pet, tech",Claymorphism + Vibrant & Block-based,"Micro-interactions, Flat Design",Storytelling-Driven,User Behavior Analytics,Playful + Warm colors,Pet profiles. Health tracking. Playful UI. Photo galleries. Vet integration.
|
||||||
|
26,Smart Home/IoT Dashboard,"admin, analytics, dashboard, data, home, iot, panel, smart",Glassmorphism + Dark Mode (OLED),"Minimalism, AI-Native UI",Interactive Product Demo,Real-Time Monitoring,Dark + Status indicator colors,Device status. Real-time controls. Energy monitoring. Automation rules. Quick actions.
|
||||||
|
27,EV/Charging Ecosystem,"charging, ecosystem, ev",Minimalism + Aurora UI,"Glassmorphism, Organic Biophilic",Hero-Centric Design,Energy/Utilities Dashboard,Electric Blue (#009CD1) + Green,Charging station maps. Range estimation. Cost calculation. Environmental impact.
|
||||||
|
28,Subscription Box Service,"appointment, booking, box, consultation, membership, plan, recurring, service, subscription",Vibrant & Block-based + Motion-Driven,"Claymorphism, Aurora UI",Feature-Rich Showcase,E-commerce Analytics,Brand + Excitement colors,Unboxing experience. Personalization quiz. Subscription management. Product reveals.
|
||||||
|
29,Podcast Platform,"platform, podcast",Dark Mode (OLED) + Minimalism,"Motion-Driven, Vibrant & Block-based",Storytelling-Driven,Media/Entertainment Dashboard,Dark + Audio waveform accents,Audio player UX. Episode discovery. Creator tools. Analytics for podcasters.
|
||||||
|
30,Dating App,"app, dating",Vibrant & Block-based + Motion-Driven,"Aurora UI, Glassmorphism",Social Proof-Focused,User Behavior Analytics,Warm + Romantic (Pink/Red gradients),Profile cards. Swipe interactions. Match animations. Safety features. Video chat.
|
||||||
|
31,Micro-Credentials/Badges Platform,"badges, credentials, micro, platform",Minimalism + Flat Design,"Accessible & Ethical, Swiss Modernism 2.0",Trust & Authority,Education Dashboard,Trust Blue + Gold (#FFD700),Credential verification. Badge display. Progress tracking. Issuer trust. LinkedIn integration.
|
||||||
|
32,Knowledge Base/Documentation,"base, documentation, knowledge",Minimalism + Accessible & Ethical,"Swiss Modernism 2.0, Flat Design",FAQ/Documentation,N/A - Documentation focused,Clean hierarchy + minimal color,Search-first. Clear navigation. Code highlighting. Version switching. Feedback system.
|
||||||
|
33,Hyperlocal Services,"appointment, booking, consultation, hyperlocal, service, services",Minimalism + Vibrant & Block-based,"Micro-interactions, Flat Design",Conversion-Optimized,Drill-Down Analytics + Map,Location markers + Trust colors,Map integration. Service categories. Provider profiles. Booking system. Reviews.
|
||||||
|
34,Beauty/Spa/Wellness Service,"appointment, beauty, booking, consultation, service, spa, wellness",Soft UI Evolution + Neumorphism,"Glassmorphism, Minimalism",Hero-Centric Design + Social Proof,User Behavior Analytics,Soft pastels (Pink #FFB6C1 Sage #90EE90) + Cream + Gold accents,Calming aesthetic. Booking system. Service menu. Before/after gallery. Testimonials. Relaxing imagery.
|
||||||
|
35,Luxury/Premium Brand,"brand, elegant, exclusive, high-end, luxury, premium",Liquid Glass + Glassmorphism,"Minimalism, 3D & Hyperrealism",Storytelling-Driven + Feature-Rich,Sales Intelligence Dashboard,Black + Gold (#FFD700) + White + Minimal accent,Elegance paramount. Premium imagery. Storytelling. High-quality visuals. Exclusive feel.
|
||||||
|
36,Restaurant/Food Service,"appointment, booking, consultation, delivery, food, menu, order, restaurant, service",Vibrant & Block-based + Motion-Driven,"Claymorphism, Flat Design",Hero-Centric Design + Conversion,N/A - Booking focused,Warm colors (Orange Red Brown) + appetizing imagery,Menu display. Online ordering. Reservation system. Food photography. Location/hours prominent.
|
||||||
|
37,Fitness/Gym App,"app, exercise, fitness, gym, health, workout",Vibrant & Block-based + Dark Mode (OLED),"Motion-Driven, Neumorphism",Feature-Rich Showcase,User Behavior Analytics,Energetic (Orange #FF6B35 Electric Blue) + Dark bg,Progress tracking. Workout plans. Community features. Achievements. Motivational design.
|
||||||
|
38,Real Estate/Property,"buy, estate, housing, property, real, real-estate, rent",Glassmorphism + Minimalism,"Motion-Driven, 3D & Hyperrealism",Hero-Centric Design + Feature-Rich,Sales Intelligence Dashboard,Trust Blue (#0077B6) + Gold accents + White,Property listings. Virtual tours. Map integration. Agent profiles. Mortgage calculator. High-quality imagery.
|
||||||
|
39,Travel/Tourism Agency,"agency, booking, creative, design, flight, hotel, marketing, studio, tourism, travel, vacation",Aurora UI + Motion-Driven,"Vibrant & Block-based, Glassmorphism",Storytelling-Driven + Hero-Centric,Booking Analytics,Vibrant destination colors + Sky Blue + Warm accents,Destination showcase. Booking system. Itinerary builder. Reviews. Inspiration galleries. Mobile-first.
|
||||||
|
40,Hotel/Hospitality,"hospitality, hotel",Liquid Glass + Minimalism,"Glassmorphism, Soft UI Evolution",Hero-Centric Design + Social Proof,Revenue Management Dashboard,Warm neutrals + Gold (#D4AF37) + Brand accent,Room booking. Amenities showcase. Location maps. Guest reviews. Seasonal pricing. Luxury imagery.
|
||||||
|
41,Wedding/Event Planning,"conference, event, meetup, planning, registration, ticket, wedding",Soft UI Evolution + Aurora UI,"Glassmorphism, Motion-Driven",Storytelling-Driven + Social Proof,N/A - Planning focused,Soft Pink (#FFD6E0) + Gold + Cream + Sage,Portfolio gallery. Vendor directory. Planning tools. Timeline. Budget tracker. Romantic aesthetic.
|
||||||
|
42,Legal Services,"appointment, attorney, booking, compliance, consultation, contract, law, legal, service, services",Trust & Authority + Minimalism,"Accessible & Ethical, Swiss Modernism 2.0",Trust & Authority + Minimal,Case Management Dashboard,Navy Blue (#1E3A5F) + Gold + White,Credibility paramount. Practice areas. Attorney profiles. Case results. Contact forms. Professional imagery.
|
||||||
|
43,Insurance Platform,"insurance, platform",Trust & Authority + Flat Design,"Accessible & Ethical, Minimalism",Conversion-Optimized + Trust,Claims Analytics Dashboard,Trust Blue (#0066CC) + Green (security) + Neutral,Quote calculator. Policy comparison. Claims process. Trust signals. Clear pricing. Security badges.
|
||||||
|
44,Banking/Traditional Finance,"banking, finance, traditional",Minimalism + Accessible & Ethical,"Trust & Authority, Dark Mode (OLED)",Trust & Authority + Feature-Rich,Financial Dashboard,Navy (#0A1628) + Trust Blue + Gold accents,Security-first. Account overview. Transaction history. Mobile banking. Accessibility critical. Trust paramount.
|
||||||
|
45,Online Course/E-learning,"course, e, learning, online",Claymorphism + Vibrant & Block-based,"Motion-Driven, Flat Design",Feature-Rich Showcase + Social Proof,Education Dashboard,Vibrant learning colors + Progress green,Course catalog. Progress tracking. Video player. Quizzes. Certificates. Community forums. Gamification.
|
||||||
|
46,Non-profit/Charity,"charity, non, profit",Accessible & Ethical + Organic Biophilic,"Minimalism, Storytelling-Driven",Storytelling-Driven + Trust,Donation Analytics Dashboard,Cause-related colors + Trust + Warm,Impact stories. Donation flow. Transparency reports. Volunteer signup. Event calendar. Emotional connection.
|
||||||
|
47,Music Streaming,"music, streaming",Dark Mode (OLED) + Vibrant & Block-based,"Motion-Driven, Aurora UI",Feature-Rich Showcase,Media/Entertainment Dashboard,Dark (#121212) + Vibrant accents + Album art colors,Audio player. Playlist management. Artist pages. Personalization. Social features. Waveform visualizations.
|
||||||
|
48,Video Streaming/OTT,"ott, streaming, video",Dark Mode (OLED) + Motion-Driven,"Glassmorphism, Vibrant & Block-based",Hero-Centric Design + Feature-Rich,Media/Entertainment Dashboard,Dark bg + Content poster colors + Brand accent,Video player. Content discovery. Watchlist. Continue watching. Personalized recommendations. Thumbnail-heavy.
|
||||||
|
49,Job Board/Recruitment,"board, job, recruitment",Flat Design + Minimalism,"Vibrant & Block-based, Accessible & Ethical",Conversion-Optimized + Feature-Rich,HR Analytics Dashboard,Professional Blue + Success Green + Neutral,Job listings. Search/filter. Company profiles. Application tracking. Resume upload. Salary insights.
|
||||||
|
50,Marketplace (P2P),"buyers, listings, marketplace, p, platform, sellers",Vibrant & Block-based + Flat Design,"Micro-interactions, Trust & Authority",Feature-Rich Showcase + Social Proof,E-commerce Analytics,Trust colors + Category colors + Success green,Seller/buyer profiles. Listings. Reviews/ratings. Secure payment. Messaging. Search/filter. Trust badges.
|
||||||
|
51,Logistics/Delivery,"delivery, logistics",Minimalism + Flat Design,"Dark Mode (OLED), Micro-interactions",Feature-Rich Showcase + Conversion,Real-Time Monitoring + Route Analytics,Blue (#2563EB) + Orange (tracking) + Green (delivered),Real-time tracking. Delivery scheduling. Route optimization. Driver management. Status updates. Map integration.
|
||||||
|
52,Agriculture/Farm Tech,"agriculture, farm, tech",Organic Biophilic + Flat Design,"Minimalism, Accessible & Ethical",Feature-Rich Showcase + Trust,IoT Sensor Dashboard,Earth Green (#4A7C23) + Brown + Sky Blue,Crop monitoring. Weather data. IoT sensors. Yield tracking. Market prices. Sustainable imagery.
|
||||||
|
53,Construction/Architecture,"architecture, construction",Minimalism + 3D & Hyperrealism,"Brutalism, Swiss Modernism 2.0",Hero-Centric Design + Feature-Rich,Project Management Dashboard,Grey (#4A4A4A) + Orange (safety) + Blueprint Blue,Project portfolio. 3D renders. Timeline. Material specs. Team collaboration. Blueprint aesthetic.
|
||||||
|
54,Automotive/Car Dealership,"automotive, car, dealership",Motion-Driven + 3D & Hyperrealism,"Dark Mode (OLED), Glassmorphism",Hero-Centric Design + Feature-Rich,Sales Intelligence Dashboard,Brand colors + Metallic accents + Dark/Light,Vehicle showcase. 360° views. Comparison tools. Financing calculator. Test drive booking. High-quality imagery.
|
||||||
|
55,Photography Studio,"photography, studio",Motion-Driven + Minimalism,"Aurora UI, Glassmorphism",Storytelling-Driven + Hero-Centric,N/A - Portfolio focused,Black + White + Minimal accent,Portfolio gallery. Before/after. Service packages. Booking system. Client galleries. Full-bleed imagery.
|
||||||
|
56,Coworking Space,"coworking, space",Vibrant & Block-based + Glassmorphism,"Minimalism, Motion-Driven",Hero-Centric Design + Feature-Rich,Occupancy Dashboard,Energetic colors + Wood tones + Brand accent,Space tour. Membership plans. Booking system. Amenities. Community events. Virtual tour.
|
||||||
|
57,Cleaning Service,"appointment, booking, cleaning, consultation, service",Soft UI Evolution + Flat Design,"Minimalism, Micro-interactions",Conversion-Optimized + Trust,Service Analytics,Fresh Blue (#00B4D8) + Clean White + Green,Service packages. Booking system. Price calculator. Before/after gallery. Reviews. Trust badges.
|
||||||
|
58,Home Services (Plumber/Electrician),"appointment, booking, consultation, electrician, home, plumber, service, services",Flat Design + Trust & Authority,"Minimalism, Accessible & Ethical",Conversion-Optimized + Trust,Service Analytics,Trust Blue + Safety Orange + Professional grey,Service list. Emergency contact. Booking. Price transparency. Certifications. Local trust signals.
|
||||||
|
59,Childcare/Daycare,"childcare, daycare",Claymorphism + Vibrant & Block-based,"Soft UI Evolution, Accessible & Ethical",Social Proof-Focused + Trust,Parent Dashboard,Playful pastels + Safe colors + Warm accents,Programs. Staff profiles. Safety certifications. Parent portal. Activity updates. Cheerful imagery.
|
||||||
|
60,Senior Care/Elderly,"care, elderly, senior",Accessible & Ethical + Soft UI Evolution,"Minimalism, Neumorphism",Trust & Authority + Social Proof,Healthcare Analytics,Calm Blue + Warm neutrals + Large text,Care services. Staff qualifications. Facility tour. Family portal. Large touch targets. High contrast. Accessibility-first.
|
||||||
|
61,Medical Clinic,"clinic, medical",Accessible & Ethical + Minimalism,"Neumorphism, Trust & Authority",Trust & Authority + Conversion,Healthcare Analytics,Medical Blue (#0077B6) + Trust White + Calm Green,Services. Doctor profiles. Online booking. Patient portal. Insurance info. HIPAA compliant. Trust signals.
|
||||||
|
62,Pharmacy/Drug Store,"drug, pharmacy, store",Flat Design + Accessible & Ethical,"Minimalism, Trust & Authority",Conversion-Optimized + Trust,Inventory Dashboard,Pharmacy Green + Trust Blue + Clean White,Product catalog. Prescription upload. Refill reminders. Health info. Store locator. Safety certifications.
|
||||||
|
63,Dental Practice,"dental, practice",Soft UI Evolution + Minimalism,"Accessible & Ethical, Trust & Authority",Social Proof-Focused + Conversion,Patient Analytics,Fresh Blue + White + Smile Yellow accent,Services. Dentist profiles. Before/after. Online booking. Insurance. Patient testimonials. Friendly imagery.
|
||||||
|
64,Veterinary Clinic,"clinic, veterinary",Claymorphism + Accessible & Ethical,"Soft UI Evolution, Flat Design",Social Proof-Focused + Trust,Pet Health Dashboard,Caring Blue + Pet-friendly colors + Warm accents,Pet services. Vet profiles. Online booking. Pet portal. Emergency info. Friendly animal imagery.
|
||||||
|
65,Florist/Plant Shop,"florist, plant, shop",Organic Biophilic + Vibrant & Block-based,"Aurora UI, Motion-Driven",Hero-Centric Design + Conversion,E-commerce Analytics,Natural Green + Floral pinks/purples + Earth tones,Product catalog. Occasion categories. Delivery scheduling. Care guides. Seasonal collections. Beautiful imagery.
|
||||||
|
66,Bakery/Cafe,"bakery, cafe",Vibrant & Block-based + Soft UI Evolution,"Claymorphism, Motion-Driven",Hero-Centric Design + Conversion,N/A - Order focused,Warm Brown + Cream + Appetizing accents,Menu display. Online ordering. Location/hours. Catering. Seasonal specials. Appetizing photography.
|
||||||
|
67,Coffee Shop,"coffee, shop",Minimalism + Organic Biophilic,"Soft UI Evolution, Flat Design",Hero-Centric Design + Conversion,N/A - Order focused,Coffee Brown (#6F4E37) + Cream + Warm accents,Menu. Online ordering. Loyalty program. Location. Story/origin. Cozy aesthetic.
|
||||||
|
68,Brewery/Winery,"brewery, winery",Motion-Driven + Storytelling-Driven,"Dark Mode (OLED), Organic Biophilic",Storytelling-Driven + Hero-Centric,N/A - E-commerce focused,Deep amber/burgundy + Gold + Craft aesthetic,Product showcase. Story/heritage. Tasting notes. Events. Club membership. Artisanal imagery.
|
||||||
|
69,Airline,"ai, airline, artificial-intelligence, automation, machine-learning, ml",Minimalism + Glassmorphism,"Motion-Driven, Accessible & Ethical",Conversion-Optimized + Feature-Rich,Operations Dashboard,Sky Blue + Brand colors + Trust accents,Flight search. Booking. Check-in. Boarding pass. Loyalty program. Route maps. Mobile-first.
|
||||||
|
70,News/Media Platform,"content, entertainment, media, news, platform, streaming, video",Minimalism + Flat Design,"Dark Mode (OLED), Accessible & Ethical",Hero-Centric Design + Feature-Rich,Media Analytics Dashboard,Brand colors + High contrast + Category colors,Article layout. Breaking news. Categories. Search. Subscription. Mobile reading. Fast loading.
|
||||||
|
71,Magazine/Blog,"articles, blog, content, magazine, posts, writing",Swiss Modernism 2.0 + Motion-Driven,"Minimalism, Aurora UI",Storytelling-Driven + Hero-Centric,Content Analytics,Editorial colors + Brand primary + Clean white,Article showcase. Category navigation. Author profiles. Newsletter signup. Related content. Typography-focused.
|
||||||
|
72,Freelancer Platform,"freelancer, platform",Flat Design + Minimalism,"Vibrant & Block-based, Micro-interactions",Feature-Rich Showcase + Conversion,Marketplace Analytics,Professional Blue + Success Green + Neutral,Profile creation. Portfolio. Skill matching. Messaging. Payment. Reviews. Project management.
|
||||||
|
73,Consulting Firm,"consulting, firm",Trust & Authority + Minimalism,"Swiss Modernism 2.0, Accessible & Ethical",Trust & Authority + Feature-Rich,N/A - Lead generation,Navy + Gold + Professional grey,Service areas. Case studies. Team profiles. Thought leadership. Contact. Professional credibility.
|
||||||
|
74,Marketing Agency,"agency, creative, design, marketing, studio",Brutalism + Motion-Driven,"Vibrant & Block-based, Aurora UI",Storytelling-Driven + Feature-Rich,Campaign Analytics,Bold brand colors + Creative freedom,Portfolio. Case studies. Services. Team. Creative showcase. Results-focused. Bold aesthetic.
|
||||||
|
75,Event Management,"conference, event, management, meetup, registration, ticket",Vibrant & Block-based + Motion-Driven,"Glassmorphism, Aurora UI",Hero-Centric Design + Feature-Rich,Event Analytics,Event theme colors + Excitement accents,Event showcase. Registration. Agenda. Speakers. Sponsors. Ticket sales. Countdown timer.
|
||||||
|
76,Conference/Webinar Platform,"conference, platform, webinar",Glassmorphism + Minimalism,"Motion-Driven, Flat Design",Feature-Rich Showcase + Conversion,Attendee Analytics,Professional Blue + Video accent + Brand,Registration. Agenda. Speaker profiles. Live stream. Networking. Recording access. Virtual event features.
|
||||||
|
77,Membership/Community,"community, membership",Vibrant & Block-based + Soft UI Evolution,"Bento Box Grid, Micro-interactions",Social Proof-Focused + Conversion,Community Analytics,Community brand colors + Engagement accents,Member benefits. Pricing tiers. Community showcase. Events. Member directory. Exclusive content.
|
||||||
|
78,Newsletter Platform,"newsletter, platform",Minimalism + Flat Design,"Swiss Modernism 2.0, Accessible & Ethical",Minimal & Direct + Conversion,Email Analytics,Brand primary + Clean white + CTA accent,Subscribe form. Archive. About. Social proof. Sample content. Simple conversion.
|
||||||
|
79,Digital Products/Downloads,"digital, downloads, products",Vibrant & Block-based + Motion-Driven,"Glassmorphism, Bento Box Grid",Feature-Rich Showcase + Conversion,E-commerce Analytics,Product category colors + Brand + Success green,Product showcase. Preview. Pricing. Instant delivery. License management. Customer reviews.
|
||||||
|
80,Church/Religious Organization,"church, organization, religious",Accessible & Ethical + Soft UI Evolution,"Minimalism, Trust & Authority",Hero-Centric Design + Social Proof,N/A - Community focused,Warm Gold + Deep Purple/Blue + White,Service times. Events. Sermons. Community. Giving. Location. Welcoming imagery.
|
||||||
|
81,Sports Team/Club,"club, sports, team",Vibrant & Block-based + Motion-Driven,"Dark Mode (OLED), 3D & Hyperrealism",Hero-Centric Design + Feature-Rich,Performance Analytics,Team colors + Energetic accents,Schedule. Roster. News. Tickets. Merchandise. Fan engagement. Action imagery.
|
||||||
|
82,Museum/Gallery,"gallery, museum",Minimalism + Motion-Driven,"Swiss Modernism 2.0, 3D & Hyperrealism",Storytelling-Driven + Feature-Rich,Visitor Analytics,Art-appropriate neutrals + Exhibition accents,Exhibitions. Collections. Tickets. Events. Virtual tours. Educational content. Art-focused design.
|
||||||
|
83,Theater/Cinema,"cinema, theater",Dark Mode (OLED) + Motion-Driven,"Vibrant & Block-based, Glassmorphism",Hero-Centric Design + Conversion,Booking Analytics,Dark + Spotlight accents + Gold,Showtimes. Seat selection. Trailers. Coming soon. Membership. Dramatic imagery.
|
||||||
|
84,Language Learning App,"app, language, learning",Claymorphism + Vibrant & Block-based,"Micro-interactions, Flat Design",Feature-Rich Showcase + Social Proof,Learning Analytics,Playful colors + Progress indicators + Country flags,Lesson structure. Progress tracking. Gamification. Speaking practice. Community. Achievement badges.
|
||||||
|
85,Coding Bootcamp,"bootcamp, coding",Dark Mode (OLED) + Minimalism,"Cyberpunk UI, Flat Design",Feature-Rich Showcase + Social Proof,Student Analytics,Code editor colors + Brand + Success green,Curriculum. Projects. Career outcomes. Alumni. Pricing. Application. Terminal aesthetic.
|
||||||
|
86,Cybersecurity Platform,"cyber, security, platform",Cyberpunk UI + Dark Mode (OLED),"Neubrutalism, Minimal & Direct",Trust & Authority + Real-Time,Real-Time Monitoring + Heat Map,Matrix Green + Deep Black + Terminal feel,Data density. Threat visualization. Dark mode default.
|
||||||
|
87,Developer Tool / IDE,"dev, developer, tool, ide",Dark Mode (OLED) + Minimalism,"Flat Design, Bento Box Grid",Minimal & Direct + Documentation,Real-Time Monitor + Terminal,Dark syntax theme colors + Blue focus,Keyboard shortcuts. Syntax highlighting. Fast performance.
|
||||||
|
88,Biotech / Life Sciences,"biotech, biology, science",Glassmorphism + Clean Science,"Minimalism, Organic Biophilic",Storytelling-Driven + Research,Data-Dense + Predictive,Sterile White + DNA Blue + Life Green,Data accuracy. Cleanliness. Complex data viz.
|
||||||
|
89,Space Tech / Aerospace,"aerospace, space, tech",Holographic / HUD + Dark Mode,"Glassmorphism, 3D & Hyperrealism",Immersive Experience + Hero,Real-Time Monitoring + 3D,Deep Space Black + Star White + Metallic,High-tech feel. Precision. Telemetry data.
|
||||||
|
90,Architecture / Interior,"architecture, design, interior",Exaggerated Minimalism + High Imagery,"Swiss Modernism 2.0, Parallax",Portfolio Grid + Visuals,Project Management + Gallery,Monochrome + Gold Accent + High Imagery,High-res images. Typography. Space.
|
||||||
|
91,Quantum Computing Interface,"quantum, computing, physics, qubit, future, science",Holographic / HUD + Dark Mode,"Glassmorphism, Spatial UI",Immersive/Interactive Experience,3D Spatial Data + Real-Time Monitor,Quantum Blue #00FFFF + Deep Black + Interference patterns,Visualize complexity. Qubit states. Probability clouds. High-tech trust.
|
||||||
|
92,Biohacking / Longevity App,"biohacking, health, longevity, tracking, wellness, science",Biomimetic / Organic 2.0,"Minimalism, Dark Mode (OLED)",Data-Dense + Storytelling,Real-Time Monitor + Biological Data,Cellular Pink/Red + DNA Blue + Clean White,Personal data privacy. Scientific credibility. Biological visualizations.
|
||||||
|
93,Autonomous Drone Fleet Manager,"drone, autonomous, fleet, aerial, logistics, robotics",HUD / Sci-Fi FUI,"Real-Time Monitor, Spatial UI",Real-Time Monitor,Geographic + Real-Time,Tactical Green #00FF00 + Alert Red + Map Dark,Real-time telemetry. 3D spatial awareness. Latency indicators. Safety alerts.
|
||||||
|
94,Generative Art Platform,"art, generative, ai, creative, platform, gallery",Minimalism (Frame) + Gen Z Chaos,"Masonry Grid, Dark Mode",Bento Grid Showcase,Gallery / Portfolio,Neutral #F5F5F5 (Canvas) + User Content,Content is king. Fast loading. Creator attribution. Minting flow.
|
||||||
|
95,Spatial Computing OS / App,"spatial, vr, ar, vision, os, immersive, mixed-reality",Spatial UI (VisionOS),"Glassmorphism, 3D & Hyperrealism",Immersive/Interactive Experience,Spatial Dashboard,Frosted Glass + System Colors + Depth,Gaze/Pinch interaction. Depth hierarchy. Environment awareness.
|
||||||
|
96,Sustainable Energy / Climate Tech,"climate, energy, sustainable, green, tech, carbon",Organic Biophilic + E-Ink / Paper,"Data-Dense, Swiss Modernism",Interactive Demo + Data,Energy/Utilities Dashboard,Earth Green + Sky Blue + Solar Yellow,Data transparency. Impact visualization. Low-carbon web design.
|
||||||
|
@@ -0,0 +1,45 @@
|
|||||||
|
No,Category,Issue,Keywords,Platform,Description,Do,Don't,Code Example Good,Code Example Bad,Severity
|
||||||
|
1,Async Waterfall,Defer Await,async await defer branch,React/Next.js,Move await into branches where actually used to avoid blocking unused code paths,Move await operations into branches where they're needed,Await at top of function blocking all branches,"if (skip) return { skipped: true }; const data = await fetch()","const data = await fetch(); if (skip) return { skipped: true }",Critical
|
||||||
|
2,Async Waterfall,Promise.all Parallel,promise all parallel concurrent,React/Next.js,Execute independent async operations concurrently using Promise.all(),Use Promise.all() for independent operations,Sequential await for independent operations,"const [user, posts] = await Promise.all([fetchUser(), fetchPosts()])","const user = await fetchUser(); const posts = await fetchPosts()",Critical
|
||||||
|
3,Async Waterfall,Dependency Parallelization,better-all dependency parallel,React/Next.js,Use better-all for operations with partial dependencies to maximize parallelism,Use better-all to start each task at earliest possible moment,Wait for unrelated data before starting dependent fetch,"await all({ user() {}, config() {}, profile() { return fetch((await this.$.user).id) } })","const [user, config] = await Promise.all([...]); const profile = await fetchProfile(user.id)",Critical
|
||||||
|
4,Async Waterfall,API Route Optimization,api route waterfall promise,React/Next.js,In API routes start independent operations immediately even if not awaited yet,Start promises early and await late,Sequential awaits in API handlers,"const sessionP = auth(); const configP = fetchConfig(); const session = await sessionP","const session = await auth(); const config = await fetchConfig()",Critical
|
||||||
|
5,Async Waterfall,Suspense Boundaries,suspense streaming boundary,React/Next.js,Use Suspense to show wrapper UI faster while data loads,Wrap async components in Suspense boundaries,Await data blocking entire page render,"<Suspense fallback={<Skeleton />}><DataDisplay /></Suspense>","const data = await fetchData(); return <DataDisplay data={data} />",High
|
||||||
|
6,Bundle Size,Barrel Imports,barrel import direct path,React/Next.js,Import directly from source files instead of barrel files to avoid loading unused modules,Import directly from source path,Import from barrel/index files,"import Check from 'lucide-react/dist/esm/icons/check'","import { Check } from 'lucide-react'",Critical
|
||||||
|
7,Bundle Size,Dynamic Imports,dynamic import lazy next,React/Next.js,Use next/dynamic to lazy-load large components not needed on initial render,Use dynamic() for heavy components,Import heavy components at top level,"const Monaco = dynamic(() => import('./monaco'), { ssr: false })","import { MonacoEditor } from './monaco-editor'",Critical
|
||||||
|
8,Bundle Size,Defer Third Party,analytics defer third-party,React/Next.js,Load analytics and logging after hydration since they don't block interaction,Load non-critical scripts after hydration,Include analytics in main bundle,"const Analytics = dynamic(() => import('@vercel/analytics'), { ssr: false })","import { Analytics } from '@vercel/analytics/react'",Medium
|
||||||
|
9,Bundle Size,Conditional Loading,conditional module lazy,React/Next.js,Load large data or modules only when a feature is activated,Dynamic import when feature enabled,Import large modules unconditionally,"useEffect(() => { if (enabled) import('./heavy.js') }, [enabled])","import { heavyData } from './heavy.js'",High
|
||||||
|
10,Bundle Size,Preload Intent,preload hover focus intent,React/Next.js,Preload heavy bundles on hover/focus before they're needed,Preload on user intent signals,Load only on click,"onMouseEnter={() => import('./editor')}","onClick={() => import('./editor')}",Medium
|
||||||
|
11,Server,React.cache Dedup,react cache deduplicate request,React/Next.js,Use React.cache() for server-side request deduplication within single request,Wrap data fetchers with cache(),Fetch same data multiple times in tree,"export const getUser = cache(async () => await db.user.find())","export async function getUser() { return await db.user.find() }",Medium
|
||||||
|
12,Server,LRU Cache Cross-Request,lru cache cross request,React/Next.js,Use LRU cache for data shared across sequential requests,Use LRU for cross-request caching,Refetch same data on every request,"const cache = new LRUCache({ max: 1000, ttl: 5*60*1000 })","Always fetch from database",High
|
||||||
|
13,Server,Minimize Serialization,serialization rsc boundary,React/Next.js,Only pass fields that client actually uses across RSC boundaries,Pass only needed fields to client components,Pass entire objects to client,"<Profile name={user.name} />","<Profile user={user} /> // 50 fields serialized",High
|
||||||
|
14,Server,Parallel Fetching,parallel fetch component composition,React/Next.js,Restructure components to parallelize data fetching in RSC,Use component composition for parallel fetches,Sequential fetches in parent component,"<Header /><Sidebar /> // both fetch in parallel","const header = await fetchHeader(); return <><div>{header}</div><Sidebar /></>",Critical
|
||||||
|
15,Server,After Non-blocking,after non-blocking logging,React/Next.js,Use Next.js after() to schedule work after response is sent,Use after() for logging/analytics,Block response for non-critical operations,"after(async () => { await logAction() }); return Response.json(data)","await logAction(); return Response.json(data)",Medium
|
||||||
|
16,Client,SWR Deduplication,swr dedup cache revalidate,React/Next.js,Use SWR for automatic request deduplication and caching,Use useSWR for client data fetching,Manual fetch in useEffect,"const { data } = useSWR('/api/users', fetcher)","useEffect(() => { fetch('/api/users').then(setUsers) }, [])",Medium-High
|
||||||
|
17,Client,Event Listener Dedup,event listener deduplicate global,React/Next.js,Share global event listeners across component instances,Use useSWRSubscription for shared listeners,Register listener per component instance,"useSWRSubscription('global-keydown', () => { window.addEventListener... })","useEffect(() => { window.addEventListener('keydown', handler) }, [])",Low
|
||||||
|
18,Rerender,Defer State Reads,state read callback subscription,React/Next.js,Don't subscribe to state only used in callbacks,Read state on-demand in callbacks,Subscribe to state used only in handlers,"const handleClick = () => { const params = new URLSearchParams(location.search) }","const params = useSearchParams(); const handleClick = () => { params.get('ref') }",Medium
|
||||||
|
19,Rerender,Memoized Components,memo extract expensive,React/Next.js,Extract expensive work into memoized components for early returns,Extract to memo() components,Compute expensive values before early return,"const UserAvatar = memo(({ user }) => ...); if (loading) return <Skeleton />","const avatar = useMemo(() => compute(user)); if (loading) return <Skeleton />",Medium
|
||||||
|
20,Rerender,Narrow Dependencies,effect dependency primitive,React/Next.js,Specify primitive dependencies instead of objects in effects,Use primitive values in dependency arrays,Use object references as dependencies,"useEffect(() => { console.log(user.id) }, [user.id])","useEffect(() => { console.log(user.id) }, [user])",Low
|
||||||
|
21,Rerender,Derived State,derived boolean subscription,React/Next.js,Subscribe to derived booleans instead of continuous values,Use derived boolean state,Subscribe to continuous values,"const isMobile = useMediaQuery('(max-width: 767px)')","const width = useWindowWidth(); const isMobile = width < 768",Medium
|
||||||
|
22,Rerender,Functional setState,functional setstate callback,React/Next.js,Use functional setState updates for stable callbacks and no stale closures,Use functional form: setState(curr => ...),Reference state directly in setState,"setItems(curr => [...curr, newItem])","setItems([...items, newItem]) // items in deps",Medium
|
||||||
|
23,Rerender,Lazy State Init,usestate lazy initialization,React/Next.js,Pass function to useState for expensive initial values,Use function form for expensive init,Compute expensive value directly,"useState(() => buildSearchIndex(items))","useState(buildSearchIndex(items)) // runs every render",Medium
|
||||||
|
24,Rerender,Transitions,starttransition non-urgent,React/Next.js,Mark frequent non-urgent state updates as transitions,Use startTransition for non-urgent updates,Block UI on every state change,"startTransition(() => setScrollY(window.scrollY))","setScrollY(window.scrollY) // blocks on every scroll",Medium
|
||||||
|
25,Rendering,SVG Animation Wrapper,svg animation wrapper div,React/Next.js,Wrap SVG in div and animate wrapper for hardware acceleration,Animate div wrapper around SVG,Animate SVG element directly,"<div class='animate-spin'><svg>...</svg></div>","<svg class='animate-spin'>...</svg>",Low
|
||||||
|
26,Rendering,Content Visibility,content-visibility auto,React/Next.js,Apply content-visibility: auto to defer off-screen rendering,Use content-visibility for long lists,Render all list items immediately,".item { content-visibility: auto; contain-intrinsic-size: 0 80px }","Render 1000 items without optimization",High
|
||||||
|
27,Rendering,Hoist Static JSX,hoist static jsx element,React/Next.js,Extract static JSX outside components to avoid re-creation,Hoist static elements to module scope,Create static elements inside components,"const skeleton = <div class='animate-pulse' />; function C() { return skeleton }","function C() { return <div class='animate-pulse' /> }",Low
|
||||||
|
28,Rendering,Hydration No Flicker,hydration mismatch flicker,React/Next.js,Use inline script to set client-only data before hydration,Inject sync script for client-only values,Use useEffect causing flash,"<script dangerouslySetInnerHTML={{ __html: 'el.className = localStorage.theme' }} />","useEffect(() => setTheme(localStorage.theme), []) // flickers",Medium
|
||||||
|
29,Rendering,Conditional Render,conditional render ternary,React/Next.js,Use ternary instead of && when condition can be 0 or NaN,Use explicit ternary for conditionals,Use && with potentially falsy numbers,"{count > 0 ? <Badge>{count}</Badge> : null}","{count && <Badge>{count}</Badge>} // renders '0'",Low
|
||||||
|
30,Rendering,Activity Component,activity show hide preserve,React/Next.js,Use Activity component to preserve state/DOM for toggled components,Use Activity for expensive toggle components,Unmount/remount on visibility toggle,"<Activity mode={isOpen ? 'visible' : 'hidden'}><Menu /></Activity>","{isOpen && <Menu />} // loses state",Medium
|
||||||
|
31,JS Perf,Batch DOM CSS,batch dom css reflow,React/Next.js,Group CSS changes via classes or cssText to minimize reflows,Use class toggle or cssText,Change styles one property at a time,"element.classList.add('highlighted')","el.style.width='100px'; el.style.height='200px'",Medium
|
||||||
|
32,JS Perf,Index Map Lookup,map index lookup find,React/Next.js,Build Map for repeated lookups instead of multiple .find() calls,Build index Map for O(1) lookups,Use .find() in loops,"const byId = new Map(users.map(u => [u.id, u])); byId.get(id)","users.find(u => u.id === order.userId) // O(n) each time",Low-Medium
|
||||||
|
33,JS Perf,Cache Property Access,cache property loop,React/Next.js,Cache object property lookups in hot paths,Cache values before loops,Access nested properties in loops,"const val = obj.config.settings.value; for (...) process(val)","for (...) process(obj.config.settings.value)",Low-Medium
|
||||||
|
34,JS Perf,Cache Function Results,memoize cache function,React/Next.js,Use module-level Map to cache repeated function results,Use Map cache for repeated calls,Recompute same values repeatedly,"const cache = new Map(); if (cache.has(x)) return cache.get(x)","slugify(name) // called 100 times same input",Medium
|
||||||
|
35,JS Perf,Cache Storage API,localstorage cache read,React/Next.js,Cache localStorage/sessionStorage reads in memory,Cache storage reads in Map,Read storage on every call,"if (!cache.has(key)) cache.set(key, localStorage.getItem(key))","localStorage.getItem('theme') // every call",Low-Medium
|
||||||
|
36,JS Perf,Combine Iterations,combine filter map loop,React/Next.js,Combine multiple filter/map into single loop,Single loop for multiple categorizations,Chain multiple filter() calls,"for (u of users) { if (u.isAdmin) admins.push(u); if (u.isTester) testers.push(u) }","users.filter(admin); users.filter(tester); users.filter(inactive)",Low-Medium
|
||||||
|
37,JS Perf,Length Check First,length check array compare,React/Next.js,Check array lengths before expensive comparisons,Early return if lengths differ,Always run expensive comparison,"if (a.length !== b.length) return true; // then compare","a.sort().join() !== b.sort().join() // even when lengths differ",Medium-High
|
||||||
|
38,JS Perf,Early Return,early return exit function,React/Next.js,Return early when result is determined to skip processing,Return immediately on first error,Process all items then check errors,"for (u of users) { if (!u.email) return { error: 'Email required' } }","let hasError; for (...) { if (!email) hasError=true }; if (hasError)...",Low-Medium
|
||||||
|
39,JS Perf,Hoist RegExp,regexp hoist module,React/Next.js,Don't create RegExp inside render - hoist or memoize,Hoist RegExp to module scope,Create RegExp every render,"const EMAIL_RE = /^[^@]+@[^@]+$/; function validate() { EMAIL_RE.test(x) }","function C() { const re = new RegExp(pattern); re.test(x) }",Low-Medium
|
||||||
|
40,JS Perf,Loop Min Max,loop min max sort,React/Next.js,Use loop for min/max instead of sort - O(n) vs O(n log n),Single pass loop for min/max,Sort array to find min/max,"let max = arr[0]; for (x of arr) if (x > max) max = x","arr.sort((a,b) => b-a)[0] // O(n log n)",Low
|
||||||
|
41,JS Perf,Set Map Lookups,set map includes has,React/Next.js,Use Set/Map for O(1) lookups instead of array.includes(),Convert to Set for membership checks,Use .includes() for repeated checks,"const allowed = new Set(['a','b']); allowed.has(id)","const allowed = ['a','b']; allowed.includes(id)",Low-Medium
|
||||||
|
42,JS Perf,toSorted Immutable,tosorted sort immutable,React/Next.js,Use toSorted() instead of sort() to avoid mutating arrays,Use toSorted() for immutability,Mutate arrays with sort(),"users.toSorted((a,b) => a.name.localeCompare(b.name))","users.sort((a,b) => a.name.localeCompare(b.name)) // mutates",Medium-High
|
||||||
|
43,Advanced,Event Handler Refs,useeffectevent ref handler,React/Next.js,Store callbacks in refs for stable effect subscriptions,Use useEffectEvent for stable handlers,Re-subscribe on every callback change,"const onEvent = useEffectEvent(handler); useEffect(() => { listen(onEvent) }, [])","useEffect(() => { listen(handler) }, [handler]) // re-subscribes",Low
|
||||||
|
44,Advanced,useLatest Hook,uselatest ref callback,React/Next.js,Access latest values in callbacks without adding to dependency arrays,Use useLatest for fresh values in stable callbacks,Add callback to effect dependencies,"const cbRef = useLatest(cb); useEffect(() => { setTimeout(() => cbRef.current()) }, [])","useEffect(() => { setTimeout(() => cb()) }, [cb]) // re-runs",Low
|
||||||
|
@@ -0,0 +1,54 @@
|
|||||||
|
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
|
||||||
|
1,Architecture,Use Islands Architecture,Astro's partial hydration only loads JS for interactive components,Interactive components with client directives,Hydrate entire page like traditional SPA,<Counter client:load />,Everything as client component,High,https://docs.astro.build/en/concepts/islands/
|
||||||
|
2,Architecture,Default to zero JS,Astro ships zero JS by default - add only when needed,Static components without client directive,Add client:load to everything,<Header /> (static),<Header client:load /> (unnecessary),High,https://docs.astro.build/en/basics/astro-components/
|
||||||
|
3,Architecture,Choose right client directive,Different directives for different hydration timing,client:visible for below-fold client:idle for non-critical,client:load for everything,<Comments client:visible />,<Comments client:load />,Medium,https://docs.astro.build/en/reference/directives-reference/#client-directives
|
||||||
|
4,Architecture,Use content collections,Type-safe content management for blogs docs,Content collections for structured content,Loose markdown files without schema,const posts = await getCollection('blog'),import.meta.glob('./posts/*.md'),High,https://docs.astro.build/en/guides/content-collections/
|
||||||
|
5,Architecture,Define collection schemas,Zod schemas for content validation,Schema with required fields and types,No schema validation,"defineCollection({ schema: z.object({...}) })",defineCollection({}),High,https://docs.astro.build/en/guides/content-collections/#defining-a-collection-schema
|
||||||
|
6,Routing,Use file-based routing,Create routes by adding .astro files in pages/,pages/ directory for routes,Manual route configuration,src/pages/about.astro,Custom router setup,Medium,https://docs.astro.build/en/basics/astro-pages/
|
||||||
|
7,Routing,Dynamic routes with brackets,Use [param] for dynamic routes,Bracket notation for params,Query strings for dynamic content,pages/blog/[slug].astro,pages/blog.astro?slug=x,Medium,https://docs.astro.build/en/guides/routing/#dynamic-routes
|
||||||
|
8,Routing,Use getStaticPaths for SSG,Generate static pages at build time,getStaticPaths for known dynamic routes,Fetch at runtime for static content,"export async function getStaticPaths() { return [...] }",No getStaticPaths with dynamic route,High,https://docs.astro.build/en/reference/api-reference/#getstaticpaths
|
||||||
|
9,Routing,Enable SSR when needed,Server-side rendering for dynamic content,output: 'server' or 'hybrid' for dynamic,SSR for purely static sites,"export const prerender = false;",SSR for static blog,Medium,https://docs.astro.build/en/guides/server-side-rendering/
|
||||||
|
10,Components,Keep .astro for static,Use .astro components for static content,Astro components for layout structure,React/Vue for static markup,<Layout><slot /></Layout>,<ReactLayout>{children}</ReactLayout>,High,
|
||||||
|
11,Components,Use framework components for interactivity,React Vue Svelte for complex interactivity,Framework component with client directive,Astro component with inline scripts,<ReactCounter client:load />,<script> in .astro for complex state,Medium,https://docs.astro.build/en/guides/framework-components/
|
||||||
|
12,Components,Pass data via props,Astro components receive props in frontmatter,Astro.props for component data,Global state for simple data,"const { title } = Astro.props;",Import global store,Low,https://docs.astro.build/en/basics/astro-components/#component-props
|
||||||
|
13,Components,Use slots for composition,Named and default slots for flexible layouts,<slot /> for child content,Props for HTML content,<slot name="header" />,<Component header={<div>...</div>} />,Medium,https://docs.astro.build/en/basics/astro-components/#slots
|
||||||
|
14,Components,Colocate component styles,Scoped styles in component file,<style> in same .astro file,Separate CSS files for component styles,<style> .card { } </style>,import './Card.css',Low,
|
||||||
|
15,Styling,Use scoped styles by default,Astro scopes styles to component automatically,<style> for component-specific styles,Global styles for everything,<style> h1 { } </style> (scoped),<style is:global> for everything,Medium,https://docs.astro.build/en/guides/styling/#scoped-styles
|
||||||
|
16,Styling,Use is:global sparingly,Global styles only when truly needed,is:global for base styles or overrides,is:global for component styles,<style is:global> body { } </style>,<style is:global> .card { } </style>,Medium,
|
||||||
|
17,Styling,Integrate Tailwind properly,Use @astrojs/tailwind integration,Official Tailwind integration,Manual Tailwind setup,npx astro add tailwind,Manual PostCSS config,Low,https://docs.astro.build/en/guides/integrations-guide/tailwind/
|
||||||
|
18,Styling,Use CSS variables for theming,Define tokens in :root,CSS custom properties for themes,Hardcoded colors everywhere,:root { --primary: #3b82f6; },color: #3b82f6; everywhere,Medium,
|
||||||
|
19,Data,Fetch in frontmatter,Data fetching in component frontmatter,Top-level await in frontmatter,useEffect for initial data,const data = await fetch(url),client-side fetch on mount,High,https://docs.astro.build/en/guides/data-fetching/
|
||||||
|
20,Data,Use Astro.glob for local files,Import multiple local files,Astro.glob for markdown/data files,Manual imports for each file,const posts = await Astro.glob('./posts/*.md'),"import post1; import post2;",Medium,
|
||||||
|
21,Data,Prefer content collections over glob,Type-safe collections for structured content,getCollection() for blog/docs,Astro.glob for structured content,await getCollection('blog'),await Astro.glob('./blog/*.md'),High,
|
||||||
|
22,Data,Use environment variables correctly,Import.meta.env for env vars,PUBLIC_ prefix for client vars,Expose secrets to client,import.meta.env.PUBLIC_API_URL,import.meta.env.SECRET in client,High,https://docs.astro.build/en/guides/environment-variables/
|
||||||
|
23,Performance,Preload critical assets,Use link preload for important resources,Preload fonts above-fold images,No preload hints,"<link rel=""preload"" href=""font.woff2"" as=""font"">",No preload for critical assets,Medium,
|
||||||
|
24,Performance,Optimize images with astro:assets,Built-in image optimization,<Image /> component for optimization,<img> for local images,"import { Image } from 'astro:assets';","<img src=""./image.jpg"">",High,https://docs.astro.build/en/guides/images/
|
||||||
|
25,Performance,Use picture for responsive images,Multiple formats and sizes,<Picture /> for art direction,Single image size for all screens,<Picture /> with multiple sources,<Image /> with single size,Medium,
|
||||||
|
26,Performance,Lazy load below-fold content,Defer loading non-critical content,loading=lazy for images client:visible for components,Load everything immediately,"<img loading=""lazy"">",No lazy loading,Medium,
|
||||||
|
27,Performance,Minimize client directives,Each directive adds JS bundle,Audit client: usage regularly,Sprinkle client:load everywhere,Only interactive components hydrated,Every component with client:load,High,
|
||||||
|
28,ViewTransitions,Enable View Transitions,Smooth page transitions,<ViewTransitions /> in head,Full page reloads,"import { ViewTransitions } from 'astro:transitions';",No transition API,Medium,https://docs.astro.build/en/guides/view-transitions/
|
||||||
|
29,ViewTransitions,Use transition:name,Named elements for morphing,transition:name for persistent elements,Unnamed transitions,"<header transition:name=""header"">",<header> without name,Low,
|
||||||
|
30,ViewTransitions,Handle transition:persist,Keep state across navigations,transition:persist for media players,Re-initialize on every navigation,"<video transition:persist id=""player"">",Video restarts on navigation,Medium,
|
||||||
|
31,ViewTransitions,Add fallback for no-JS,Graceful degradation,Content works without JS,Require JS for basic navigation,Static content accessible,Broken without ViewTransitions JS,High,
|
||||||
|
32,SEO,Use built-in SEO component,Head management for meta tags,Astro SEO integration or manual head,No meta tags,"<title>{title}</title><meta name=""description"">",No SEO tags,High,
|
||||||
|
33,SEO,Generate sitemap,Automatic sitemap generation,@astrojs/sitemap integration,Manual sitemap maintenance,npx astro add sitemap,Hand-written sitemap.xml,Medium,https://docs.astro.build/en/guides/integrations-guide/sitemap/
|
||||||
|
34,SEO,Add RSS feed for content,RSS for blogs and content sites,@astrojs/rss for feed generation,No RSS feed,rss() helper in pages/rss.xml.js,No feed for blog,Low,https://docs.astro.build/en/guides/rss/
|
||||||
|
35,SEO,Use canonical URLs,Prevent duplicate content issues,Astro.url for canonical generation,"<link rel=""canonical"" href={Astro.url}>",No canonical tags,Medium,
|
||||||
|
36,Integrations,Use official integrations,Astro's integration system,npx astro add for integrations,Manual configuration,npx astro add react,Manual React setup,Medium,https://docs.astro.build/en/guides/integrations-guide/
|
||||||
|
37,Integrations,Configure integrations in astro.config,Centralized configuration,integrations array in config,Scattered configuration,"integrations: [react(), tailwind()]",Multiple config files,Low,
|
||||||
|
38,Integrations,Use adapter for deployment,Platform-specific adapters,Correct adapter for host,Wrong or no adapter,@astrojs/vercel for Vercel,No adapter for SSR,High,https://docs.astro.build/en/guides/deploy/
|
||||||
|
39,TypeScript,Enable TypeScript,Type safety for Astro projects,tsconfig.json with astro types,No TypeScript,Astro TypeScript template,JavaScript only,Medium,https://docs.astro.build/en/guides/typescript/
|
||||||
|
40,TypeScript,Type component props,Define prop interfaces,Props interface in frontmatter,Untyped props,"interface Props { title: string }",No props typing,Medium,
|
||||||
|
41,TypeScript,Use strict mode,Catch errors early,strict: true in tsconfig,Loose TypeScript config,strictest template,base template,Low,
|
||||||
|
42,Markdown,Use MDX for components,Components in markdown content,@astrojs/mdx for interactive docs,Plain markdown with workarounds,<Component /> in .mdx,HTML in .md files,Medium,https://docs.astro.build/en/guides/integrations-guide/mdx/
|
||||||
|
43,Markdown,Configure markdown plugins,Extend markdown capabilities,remarkPlugins rehypePlugins in config,Manual HTML for features,remarkPlugins: [remarkToc],Manual TOC in every post,Low,
|
||||||
|
44,Markdown,Use frontmatter for metadata,Structured post metadata,Frontmatter with typed schema,Inline metadata,title date in frontmatter,# Title as first line,Medium,
|
||||||
|
45,API,Use API routes for endpoints,Server endpoints in pages/api,pages/api/[endpoint].ts for APIs,External API for simple endpoints,pages/api/posts.json.ts,Separate Express server,Medium,https://docs.astro.build/en/guides/endpoints/
|
||||||
|
46,API,Return proper responses,Use Response object,new Response() with headers,Plain objects,return new Response(JSON.stringify(data)),return data,Medium,
|
||||||
|
47,API,Handle methods correctly,Export named method handlers,export GET POST handlers,Single default export,export const GET = async () => {},export default async () => {},Low,
|
||||||
|
48,Security,Sanitize user content,Prevent XSS in dynamic content,set:html only for trusted content,set:html with user input,"<Fragment set:html={sanitized} />","<div set:html={userInput} />",High,
|
||||||
|
49,Security,Use HTTPS in production,Secure connections,HTTPS for all production sites,HTTP in production,https://example.com,http://example.com,High,
|
||||||
|
50,Security,Validate API input,Check and sanitize all input,Zod validation for API routes,Trust all input,const body = schema.parse(data),const body = await request.json(),High,
|
||||||
|
51,Build,Use hybrid rendering,Mix static and dynamic pages,output: 'hybrid' for flexibility,All SSR or all static,prerender per-page basis,Single rendering mode,Medium,https://docs.astro.build/en/guides/server-side-rendering/#hybrid-rendering
|
||||||
|
52,Build,Analyze bundle size,Monitor JS bundle impact,Build output shows bundle sizes,Ignore bundle growth,Check astro build output,No size monitoring,Medium,
|
||||||
|
53,Build,Use prefetch,Preload linked pages,prefetch integration,No prefetch for navigation,npx astro add prefetch,Manual prefetch,Low,https://docs.astro.build/en/guides/prefetch/
|
||||||
|
Can't render this file because it contains an unexpected character in line 14 and column 147.
|
@@ -0,0 +1,53 @@
|
|||||||
|
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
|
||||||
|
1,Widgets,Use StatelessWidget when possible,Immutable widgets are simpler,StatelessWidget for static UI,StatefulWidget for everything,class MyWidget extends StatelessWidget,class MyWidget extends StatefulWidget (static),Medium,https://api.flutter.dev/flutter/widgets/StatelessWidget-class.html
|
||||||
|
2,Widgets,Keep widgets small,Single responsibility principle,Extract widgets into smaller pieces,Large build methods,Column(children: [Header() Content()]),500+ line build method,Medium,
|
||||||
|
3,Widgets,Use const constructors,Compile-time constants for performance,const MyWidget() when possible,Non-const for static widgets,const Text('Hello'),Text('Hello') for literals,High,https://dart.dev/guides/language/language-tour#constant-constructors
|
||||||
|
4,Widgets,Prefer composition over inheritance,Combine widgets using children,Compose widgets,Extend widget classes,Container(child: MyContent()),class MyContainer extends Container,Medium,
|
||||||
|
5,State,Use setState correctly,Minimal state in StatefulWidget,setState for UI state changes,setState for business logic,setState(() { _counter++; }),Complex logic in setState,Medium,https://api.flutter.dev/flutter/widgets/State/setState.html
|
||||||
|
6,State,Avoid setState in build,Never call setState during build,setState in callbacks only,setState in build method,onPressed: () => setState(() {}),build() { setState(); },High,
|
||||||
|
7,State,Use state management for complex apps,Provider Riverpod BLoC,State management for shared state,setState for global state,Provider.of<MyState>(context),Global setState calls,Medium,
|
||||||
|
8,State,Prefer Riverpod or Provider,Recommended state solutions,Riverpod for new projects,InheritedWidget manually,ref.watch(myProvider),Custom InheritedWidget,Medium,https://riverpod.dev/
|
||||||
|
9,State,Dispose resources,Clean up controllers and subscriptions,dispose() for cleanup,Memory leaks from subscriptions,@override void dispose() { controller.dispose(); },No dispose implementation,High,
|
||||||
|
10,Layout,Use Column and Row,Basic layout widgets,Column Row for linear layouts,Stack for simple layouts,"Column(children: [Text(), Button()])",Stack for vertical list,Medium,https://api.flutter.dev/flutter/widgets/Column-class.html
|
||||||
|
11,Layout,Use Expanded and Flexible,Control flex behavior,Expanded to fill space,Fixed sizes in flex containers,Expanded(child: Container()),Container(width: 200) in Row,Medium,
|
||||||
|
12,Layout,Use SizedBox for spacing,Consistent spacing,SizedBox for gaps,Container for spacing only,SizedBox(height: 16),Container(height: 16),Low,
|
||||||
|
13,Layout,Use LayoutBuilder for responsive,Respond to constraints,LayoutBuilder for adaptive layouts,Fixed sizes for responsive,LayoutBuilder(builder: (context constraints) {}),Container(width: 375),Medium,https://api.flutter.dev/flutter/widgets/LayoutBuilder-class.html
|
||||||
|
14,Layout,Avoid deep nesting,Keep widget tree shallow,Extract deeply nested widgets,10+ levels of nesting,Extract widget to method or class,Column(Row(Column(Row(...)))),Medium,
|
||||||
|
15,Lists,Use ListView.builder,Lazy list building,ListView.builder for long lists,ListView with children for large lists,"ListView.builder(itemCount: 100, itemBuilder: ...)",ListView(children: items.map(...).toList()),High,https://api.flutter.dev/flutter/widgets/ListView-class.html
|
||||||
|
16,Lists,Provide itemExtent when known,Skip measurement,itemExtent for fixed height items,No itemExtent for uniform lists,ListView.builder(itemExtent: 50),ListView.builder without itemExtent,Medium,
|
||||||
|
17,Lists,Use keys for stateful items,Preserve widget state,Key for stateful list items,No key for dynamic lists,ListTile(key: ValueKey(item.id)),ListTile without key,High,
|
||||||
|
18,Lists,Use SliverList for custom scroll,Custom scroll effects,CustomScrollView with Slivers,Nested ListViews,CustomScrollView(slivers: [SliverList()]),ListView inside ListView,Medium,https://api.flutter.dev/flutter/widgets/SliverList-class.html
|
||||||
|
19,Navigation,Use Navigator 2.0 or GoRouter,Declarative routing,go_router for navigation,Navigator.push for complex apps,GoRouter(routes: [...]),Navigator.push everywhere,Medium,https://pub.dev/packages/go_router
|
||||||
|
20,Navigation,Use named routes,Organized navigation,Named routes for clarity,Anonymous routes,Navigator.pushNamed(context '/home'),Navigator.push(context MaterialPageRoute()),Low,
|
||||||
|
21,Navigation,Handle back button (PopScope),Android back behavior and predictive back (Android 14+),Use PopScope widget (WillPopScope is deprecated),Use WillPopScope,"PopScope(canPop: false, onPopInvoked: (didPop) => ...)",WillPopScope(onWillPop: ...),High,https://api.flutter.dev/flutter/widgets/PopScope-class.html
|
||||||
|
22,Navigation,Pass typed arguments,Type-safe route arguments,Typed route arguments,Dynamic arguments,MyRoute(id: '123'),arguments: {'id': '123'},Medium,
|
||||||
|
23,Async,Use FutureBuilder,Async UI building,FutureBuilder for async data,setState for async,FutureBuilder(future: fetchData()),fetchData().then((d) => setState()),Medium,https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html
|
||||||
|
24,Async,Use StreamBuilder,Stream UI building,StreamBuilder for streams,Manual stream subscription,StreamBuilder(stream: myStream),stream.listen in initState,Medium,https://api.flutter.dev/flutter/widgets/StreamBuilder-class.html
|
||||||
|
25,Async,Handle loading and error states,Complete async UI states,ConnectionState checks,Only success state,if (snapshot.connectionState == ConnectionState.waiting),No loading indicator,High,
|
||||||
|
26,Async,Cancel subscriptions,Clean up stream subscriptions,Cancel in dispose,Memory leaks,subscription.cancel() in dispose,No subscription cleanup,High,
|
||||||
|
27,Theming,Use ThemeData,Consistent theming,ThemeData for app theme,Hardcoded colors,Theme.of(context).primaryColor,Color(0xFF123456) everywhere,Medium,https://api.flutter.dev/flutter/material/ThemeData-class.html
|
||||||
|
28,Theming,Use ColorScheme,Material 3 color system,ColorScheme for colors,Individual color properties,colorScheme: ColorScheme.fromSeed(),primaryColor: Colors.blue,Medium,
|
||||||
|
29,Theming,Access theme via context,Dynamic theme access,Theme.of(context),Static theme reference,Theme.of(context).textTheme.bodyLarge,TextStyle(fontSize: 16),Medium,
|
||||||
|
30,Theming,Support dark mode,Respect system theme,darkTheme in MaterialApp,Light theme only,"MaterialApp(theme: light, darkTheme: dark)",MaterialApp(theme: light),Medium,
|
||||||
|
31,Animation,Use implicit animations,Simple animations,AnimatedContainer AnimatedOpacity,Explicit for simple transitions,AnimatedContainer(duration: Duration()),AnimationController for fade,Low,https://api.flutter.dev/flutter/widgets/AnimatedContainer-class.html
|
||||||
|
32,Animation,Use AnimationController for complex,Fine-grained control,AnimationController with Ticker,Implicit for complex sequences,AnimationController(vsync: this),AnimatedContainer for staggered,Medium,
|
||||||
|
33,Animation,Dispose AnimationControllers,Clean up animation resources,dispose() for controllers,Memory leaks,controller.dispose() in dispose,No controller disposal,High,
|
||||||
|
34,Animation,Use Hero for transitions,Shared element transitions,Hero for navigation animations,Manual shared element,Hero(tag: 'image' child: Image()),Custom shared element animation,Low,https://api.flutter.dev/flutter/widgets/Hero-class.html
|
||||||
|
35,Forms,Use Form widget,Form validation,Form with GlobalKey,Individual validation,Form(key: _formKey child: ...),TextField without Form,Medium,https://api.flutter.dev/flutter/widgets/Form-class.html
|
||||||
|
36,Forms,Use TextEditingController,Control text input,Controller for text fields,onChanged for all text,final controller = TextEditingController(),onChanged: (v) => setState(),Medium,
|
||||||
|
37,Forms,Validate on submit,Form validation flow,_formKey.currentState!.validate(),Skip validation,if (_formKey.currentState!.validate()),Submit without validation,High,
|
||||||
|
38,Forms,Dispose controllers,Clean up text controllers,dispose() for controllers,Memory leaks,controller.dispose() in dispose,No controller disposal,High,
|
||||||
|
39,Performance,Use const widgets,Reduce rebuilds,const for static widgets,No const for literals,const Icon(Icons.add),Icon(Icons.add),High,
|
||||||
|
40,Performance,Avoid rebuilding entire tree,Minimal rebuild scope,Isolate changing widgets,setState on parent,Consumer only around changing widget,setState on root widget,High,
|
||||||
|
41,Performance,Use RepaintBoundary,Isolate repaints,RepaintBoundary for animations,Full screen repaints,RepaintBoundary(child: AnimatedWidget()),Animation without boundary,Medium,https://api.flutter.dev/flutter/widgets/RepaintBoundary-class.html
|
||||||
|
42,Performance,Profile with DevTools,Measure before optimizing,Flutter DevTools profiling,Guess at performance,DevTools performance tab,Optimize without measuring,Medium,https://docs.flutter.dev/tools/devtools
|
||||||
|
43,Accessibility,Use Semantics widget,Screen reader support,Semantics for accessibility,Missing accessibility info,Semantics(label: 'Submit button'),GestureDetector without semantics,High,https://api.flutter.dev/flutter/widgets/Semantics-class.html
|
||||||
|
44,Accessibility,Support large fonts,MediaQuery text scaling,MediaQuery.textScaleFactor,Fixed font sizes,style: Theme.of(context).textTheme,TextStyle(fontSize: 14),High,
|
||||||
|
45,Accessibility,Test with screen readers,TalkBack and VoiceOver,Test accessibility regularly,Skip accessibility testing,Regular TalkBack testing,No screen reader testing,High,
|
||||||
|
46,Testing,Use widget tests,Test widget behavior,WidgetTester for UI tests,Unit tests only,testWidgets('...' (tester) async {}),Only test() for UI,Medium,https://docs.flutter.dev/testing
|
||||||
|
47,Testing,Use integration tests,Full app testing,integration_test package,Manual testing only,IntegrationTestWidgetsFlutterBinding,Manual E2E testing,Medium,
|
||||||
|
48,Testing,Mock dependencies,Isolate tests,Mockito or mocktail,Real dependencies in tests,when(mock.method()).thenReturn(),Real API calls in tests,Medium,
|
||||||
|
49,Platform,Use Platform checks,Platform-specific code,Platform.isIOS Platform.isAndroid,Same code for all platforms,if (Platform.isIOS) {},Hardcoded iOS behavior,Medium,
|
||||||
|
50,Platform,Use kIsWeb for web,Web platform detection,kIsWeb for web checks,Platform for web,if (kIsWeb) {},Platform.isWeb (doesn't exist),Medium,
|
||||||
|
51,Packages,Use pub.dev packages,Community packages,Popular maintained packages,Custom implementations,cached_network_image,Custom image cache,Medium,https://pub.dev/
|
||||||
|
52,Packages,Check package quality,Quality before adding,Pub points and popularity,Any package without review,100+ pub points,Unmaintained packages,Medium,
|
||||||
|
@@ -0,0 +1,56 @@
|
|||||||
|
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
|
||||||
|
1,Animation,Use Tailwind animate utilities,Built-in animations are optimized and respect reduced-motion,Use animate-pulse animate-spin animate-ping,Custom @keyframes for simple effects,animate-pulse,@keyframes pulse {...},Medium,https://tailwindcss.com/docs/animation
|
||||||
|
2,Animation,Limit bounce animations,Continuous bounce is distracting and causes motion sickness,Use animate-bounce sparingly on CTAs only,Multiple bounce animations on page,Single CTA with animate-bounce,5+ elements with animate-bounce,High,
|
||||||
|
3,Animation,Transition duration,Use appropriate transition speeds for UI feedback,duration-150 to duration-300 for UI,duration-1000 or longer for UI elements,transition-all duration-200,transition-all duration-1000,Medium,https://tailwindcss.com/docs/transition-duration
|
||||||
|
4,Animation,Hover transitions,Add smooth transitions on hover state changes,Add transition class with hover states,Instant hover changes without transition,hover:bg-gray-100 transition-colors,hover:bg-gray-100 (no transition),Low,
|
||||||
|
5,Z-Index,Use Tailwind z-* scale,Consistent stacking context with predefined scale,z-0 z-10 z-20 z-30 z-40 z-50,Arbitrary z-index values,z-50 for modals,z-[9999],Medium,https://tailwindcss.com/docs/z-index
|
||||||
|
6,Z-Index,Fixed elements z-index,Fixed navigation and modals need explicit z-index,z-50 for nav z-40 for dropdowns,Relying on DOM order for stacking,fixed top-0 z-50,fixed top-0 (no z-index),High,
|
||||||
|
7,Z-Index,Negative z-index for backgrounds,Use negative z-index for decorative backgrounds,z-[-1] for background elements,Positive z-index for backgrounds,-z-10 for decorative,z-10 for background,Low,
|
||||||
|
8,Layout,Container max-width,Limit content width for readability,max-w-7xl mx-auto for main content,Full-width content on large screens,max-w-7xl mx-auto px-4,w-full (no max-width),Medium,https://tailwindcss.com/docs/container
|
||||||
|
9,Layout,Responsive padding,Adjust padding for different screen sizes,px-4 md:px-6 lg:px-8,Same padding all sizes,px-4 sm:px-6 lg:px-8,px-8 (same all sizes),Medium,
|
||||||
|
10,Layout,Grid gaps,Use consistent gap utilities for spacing,gap-4 gap-6 gap-8,Margins on individual items,grid gap-6,grid with mb-4 on each item,Medium,https://tailwindcss.com/docs/gap
|
||||||
|
11,Layout,Flexbox alignment,Use flex utilities for alignment,items-center justify-between,Multiple nested wrappers,flex items-center justify-between,Nested divs for alignment,Low,
|
||||||
|
12,Images,Aspect ratio,Maintain consistent image aspect ratios,aspect-video aspect-square,No aspect ratio on containers,aspect-video rounded-lg,No aspect control,Medium,https://tailwindcss.com/docs/aspect-ratio
|
||||||
|
13,Images,Object fit,Control image scaling within containers,object-cover object-contain,Stretched distorted images,object-cover w-full h-full,No object-fit,Medium,https://tailwindcss.com/docs/object-fit
|
||||||
|
14,Images,Lazy loading,Defer loading of off-screen images,loading='lazy' on images,All images eager load,<img loading='lazy'>,<img> without lazy,High,
|
||||||
|
15,Images,Responsive images,Serve appropriate image sizes,srcset and sizes attributes,Same large image all devices,srcset with multiple sizes,4000px image everywhere,High,
|
||||||
|
16,Typography,Prose plugin,Use @tailwindcss/typography for rich text,prose prose-lg for article content,Custom styles for markdown,prose prose-lg max-w-none,Custom text styling,Medium,https://tailwindcss.com/docs/typography-plugin
|
||||||
|
17,Typography,Line height,Use appropriate line height for readability,leading-relaxed for body text,Default tight line height,leading-relaxed (1.625),leading-none or leading-tight,Medium,https://tailwindcss.com/docs/line-height
|
||||||
|
18,Typography,Font size scale,Use consistent text size scale,text-sm text-base text-lg text-xl,Arbitrary font sizes,text-lg,text-[17px],Low,https://tailwindcss.com/docs/font-size
|
||||||
|
19,Typography,Text truncation,Handle long text gracefully,truncate or line-clamp-*,Overflow breaking layout,line-clamp-2,No overflow handling,Medium,https://tailwindcss.com/docs/text-overflow
|
||||||
|
20,Colors,Opacity utilities,Use color opacity utilities,bg-black/50 text-white/80,Separate opacity class,bg-black/50,bg-black opacity-50,Low,https://tailwindcss.com/docs/background-color
|
||||||
|
21,Colors,Dark mode,Support dark mode with dark: prefix,dark:bg-gray-900 dark:text-white,No dark mode support,dark:bg-gray-900,Only light theme,Medium,https://tailwindcss.com/docs/dark-mode
|
||||||
|
22,Colors,Semantic colors,Use semantic color naming in config,primary secondary danger success,Generic color names in components,bg-primary,bg-blue-500 everywhere,Medium,
|
||||||
|
23,Spacing,Consistent spacing scale,Use Tailwind spacing scale consistently,p-4 m-6 gap-8,Arbitrary pixel values,p-4 (1rem),p-[15px],Low,https://tailwindcss.com/docs/customizing-spacing
|
||||||
|
24,Spacing,Negative margins,Use sparingly for overlapping effects,-mt-4 for overlapping elements,Negative margins for layout fixing,-mt-8 for card overlap,-m-2 to fix spacing issues,Medium,
|
||||||
|
25,Spacing,Space between,Use space-y-* for vertical lists,space-y-4 on flex/grid column,Margin on each child,space-y-4,Each child has mb-4,Low,https://tailwindcss.com/docs/space
|
||||||
|
26,Forms,Focus states,Always show focus indicators,focus:ring-2 focus:ring-blue-500,Remove focus outline,focus:ring-2 focus:ring-offset-2,focus:outline-none (no replacement),High,
|
||||||
|
27,Forms,Input sizing,Consistent input dimensions,h-10 px-3 for inputs,Inconsistent input heights,h-10 w-full px-3,Various heights per input,Medium,
|
||||||
|
28,Forms,Disabled states,Clear disabled styling,disabled:opacity-50 disabled:cursor-not-allowed,No disabled indication,disabled:opacity-50,Same style as enabled,Medium,
|
||||||
|
29,Forms,Placeholder styling,Style placeholder text appropriately,placeholder:text-gray-400,Dark placeholder text,placeholder:text-gray-400,Default dark placeholder,Low,
|
||||||
|
30,Responsive,Mobile-first approach,Start with mobile styles and add breakpoints,Default mobile + md: lg: xl:,Desktop-first approach,text-sm md:text-base,text-base max-md:text-sm,Medium,https://tailwindcss.com/docs/responsive-design
|
||||||
|
31,Responsive,Breakpoint testing,Test at standard breakpoints,320 375 768 1024 1280 1536,Only test on development device,Test all breakpoints,Single device testing,High,
|
||||||
|
32,Responsive,Hidden/shown utilities,Control visibility per breakpoint,hidden md:block,Different content per breakpoint,hidden md:flex,Separate mobile/desktop components,Low,https://tailwindcss.com/docs/display
|
||||||
|
33,Buttons,Button sizing,Consistent button dimensions,px-4 py-2 or px-6 py-3,Inconsistent button sizes,px-4 py-2 text-sm,Various padding per button,Medium,
|
||||||
|
34,Buttons,Touch targets,Minimum 44px touch target on mobile,min-h-[44px] on mobile,Small buttons on mobile,min-h-[44px] min-w-[44px],h-8 w-8 on mobile,High,
|
||||||
|
35,Buttons,Loading states,Show loading feedback,disabled + spinner icon,Clickable during loading,<Button disabled><Spinner/></Button>,Button without loading state,High,
|
||||||
|
36,Buttons,Icon buttons,Accessible icon-only buttons,aria-label on icon buttons,Icon button without label,<button aria-label='Close'><XIcon/></button>,<button><XIcon/></button>,High,
|
||||||
|
37,Cards,Card structure,Consistent card styling,rounded-lg shadow-md p-6,Inconsistent card styles,rounded-2xl shadow-lg p-6,Mixed card styling,Low,
|
||||||
|
38,Cards,Card hover states,Interactive cards should have hover feedback,hover:shadow-lg transition-shadow,No hover on clickable cards,hover:shadow-xl transition-shadow,Static cards that are clickable,Medium,
|
||||||
|
39,Cards,Card spacing,Consistent internal card spacing,space-y-4 for card content,Inconsistent internal spacing,space-y-4 or p-6,Mixed mb-2 mb-4 mb-6,Low,
|
||||||
|
40,Accessibility,Screen reader text,Provide context for screen readers,sr-only for hidden labels,Missing context for icons,<span class='sr-only'>Close menu</span>,No label for icon button,High,https://tailwindcss.com/docs/screen-readers
|
||||||
|
41,Accessibility,Focus visible,Show focus only for keyboard users,focus-visible:ring-2,Focus on all interactions,focus-visible:ring-2,focus:ring-2 (shows on click too),Medium,
|
||||||
|
42,Accessibility,Reduced motion,Respect user motion preferences,motion-reduce:animate-none,Ignore motion preferences,motion-reduce:transition-none,No reduced motion support,High,https://tailwindcss.com/docs/hover-focus-and-other-states#prefers-reduced-motion
|
||||||
|
43,Performance,Configure content paths,Tailwind needs to know where classes are used,Use 'content' array in config,Use deprecated 'purge' option (v2),"content: ['./src/**/*.{js,ts,jsx,tsx}']",purge: [...],High,https://tailwindcss.com/docs/content-configuration
|
||||||
|
44,Performance,JIT mode,Use JIT for faster builds and smaller bundles,JIT enabled (default in v3),Full CSS in development,Tailwind v3 defaults,Tailwind v2 without JIT,Medium,
|
||||||
|
45,Performance,Avoid @apply bloat,Use @apply sparingly,Direct utilities in HTML,Heavy @apply usage,class='px-4 py-2 rounded',@apply px-4 py-2 rounded;,Low,https://tailwindcss.com/docs/reusing-styles
|
||||||
|
46,Plugins,Official plugins,Use official Tailwind plugins,@tailwindcss/forms typography aspect-ratio,Custom implementations,@tailwindcss/forms,Custom form reset CSS,Medium,https://tailwindcss.com/docs/plugins
|
||||||
|
47,Plugins,Custom utilities,Create utilities for repeated patterns,Custom utility in config,Repeated arbitrary values,Custom shadow utility,"shadow-[0_4px_20px_rgba(0,0,0,0.1)] everywhere",Medium,
|
||||||
|
48,Layout,Container Queries,Use @container for component-based responsiveness,Use @container and @lg: etc.,Media queries for component internals,@container @lg:grid-cols-2,@media (min-width: ...) inside component,Medium,https://github.com/tailwindlabs/tailwindcss-container-queries
|
||||||
|
49,Interactivity,Group and Peer,Style based on parent/sibling state,group-hover peer-checked,JS for simple state interactions,group-hover:text-blue-500,onMouseEnter={() => setHover(true)},Low,https://tailwindcss.com/docs/hover-focus-and-other-states#styling-based-on-parent-state
|
||||||
|
50,Customization,Arbitrary Values,Use [] for one-off values,w-[350px] for specific needs,Creating config for single use,top-[117px] (if strictly needed),style={{ top: '117px' }},Low,https://tailwindcss.com/docs/adding-custom-styles#using-arbitrary-values
|
||||||
|
51,Colors,Theme color variables,Define colors in Tailwind theme and use directly,bg-primary text-success border-cta,bg-[var(--color-primary)] text-[var(--color-success)],bg-primary,bg-[var(--color-primary)],Medium,https://tailwindcss.com/docs/customizing-colors
|
||||||
|
52,Colors,Use bg-linear-to-* for gradients,Tailwind v4 uses bg-linear-to-* syntax for gradients,bg-linear-to-r bg-linear-to-b,bg-gradient-to-* (deprecated in v4),bg-linear-to-r from-blue-500 to-purple-500,bg-gradient-to-r from-blue-500 to-purple-500,Medium,https://tailwindcss.com/docs/background-image
|
||||||
|
53,Layout,Use shrink-0 shorthand,Shorter class name for flex-shrink-0,shrink-0 shrink,flex-shrink-0 flex-shrink,shrink-0,flex-shrink-0,Low,https://tailwindcss.com/docs/flex-shrink
|
||||||
|
54,Layout,Use size-* for square dimensions,Single utility for equal width and height,size-4 size-8 size-12,Separate h-* w-* for squares,size-6,h-6 w-6,Low,https://tailwindcss.com/docs/size
|
||||||
|
55,Images,SVG explicit dimensions,Add width/height attributes to SVGs to prevent layout shift before CSS loads,<svg class='size-6' width='24' height='24'>,SVG without explicit dimensions,<svg class='size-6' width='24' height='24'>,<svg class='size-6'>,High,
|
||||||
|
@@ -0,0 +1,53 @@
|
|||||||
|
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
|
||||||
|
1,Composable,Pure UI composables,Composable functions should only render UI,Accept state and callbacks,Calling usecase/repo,Pure UI composable,Business logic in UI,High,https://developer.android.com/jetpack/compose/mental-model
|
||||||
|
2,Composable,Small composables,Each composable has single responsibility,Split into components,Huge composable,Reusable UI,Monolithic UI,Medium,
|
||||||
|
3,Composable,Stateless by default,Prefer stateless composables,Hoist state,Local mutable state,Stateless UI,Hidden state,High,https://developer.android.com/jetpack/compose/state#state-hoisting
|
||||||
|
4,State,Single source of truth,UI state comes from one source,StateFlow from VM,Multiple states,Unified UiState,Scattered state,High,https://developer.android.com/topic/architecture/ui-layer
|
||||||
|
5,State,Model UI State,Use sealed interface/data class,UiState.Loading,Boolean flags,Explicit state,Flag hell,High,
|
||||||
|
6,State,remember only UI state,remember for UI-only state,"Scroll, animation",Business state,Correct remember,Misuse remember,High,https://developer.android.com/jetpack/compose/state
|
||||||
|
7,State,rememberSaveable,Persist state across config,rememberSaveable,remember,State survives,State lost,High,https://developer.android.com/jetpack/compose/state#restore-ui-state
|
||||||
|
8,State,derivedStateOf,Optimize recomposition,derivedStateOf,Recompute always,Optimized,Jank,Medium,https://developer.android.com/jetpack/compose/performance
|
||||||
|
9,SideEffect,LaunchedEffect keys,Use correct keys,LaunchedEffect(id),LaunchedEffect(Unit),Scoped effect,Infinite loop,High,https://developer.android.com/jetpack/compose/side-effects
|
||||||
|
10,SideEffect,rememberUpdatedState,Avoid stale lambdas,rememberUpdatedState,Capture directly,Safe callback,Stale state,Medium,https://developer.android.com/jetpack/compose/side-effects
|
||||||
|
11,SideEffect,DisposableEffect,Clean up resources,onDispose,No cleanup,No leak,Memory leak,High,
|
||||||
|
12,Architecture,Unidirectional data flow,UI → VM → State,onEvent,Two-way binding,Predictable flow,Hard debug,High,https://developer.android.com/topic/architecture
|
||||||
|
13,Architecture,No business logic in UI,Logic belongs to VM,Collect state,Call repo,Clean UI,Fat UI,High,
|
||||||
|
14,Architecture,Expose immutable state,Expose StateFlow,asStateFlow,Mutable exposed,Safe API,State mutation,High,
|
||||||
|
15,Lifecycle,Lifecycle-aware collect,Use collectAsStateWithLifecycle,Lifecycle aware,collectAsState,No leak,Leak,High,https://developer.android.com/jetpack/compose/lifecycle
|
||||||
|
16,Navigation,Event-based navigation,VM emits navigation event,"VM: Channel + receiveAsFlow(), V: Collect with Dispatchers.Main.immediate",Nav in UI,Decoupled nav,Using State / SharedFlow for navigation -> event is replayed and navigation fires again (StateFlow),High,https://developer.android.com/jetpack/compose/navigation
|
||||||
|
17,Navigation,Typed routes,Use sealed routes,sealed class Route,String routes,Type-safe,Runtime crash,Medium,
|
||||||
|
18,Performance,Stable parameters,Prefer immutable/stable params,@Immutable,Mutable params,Stable recomposition,Extra recomposition,High,https://developer.android.com/jetpack/compose/performance
|
||||||
|
19,Performance,Use key in Lazy,Provide stable keys,key=id,No key,Stable list,Item jump,High,
|
||||||
|
20,Performance,Avoid heavy work,No heavy computation in UI,Precompute in VM,Compute in UI,Smooth UI,Jank,High,
|
||||||
|
21,Performance,Remember expensive objects,remember heavy objects,remember,Recreate each recomposition,Efficient,Wasteful,Medium,
|
||||||
|
22,Theming,Design system,Centralized theme,Material3 tokens,Hardcoded values,Consistent UI,Inconsistent,High,https://developer.android.com/jetpack/compose/themes
|
||||||
|
23,Theming,Dark mode support,Theme-based colors,colorScheme,Fixed color,Adaptive UI,Broken dark,Medium,
|
||||||
|
24,Layout,Prefer Modifier over extra layouts,Use Modifier to adjust layout instead of adding wrapper composables,Use Modifier.padding(),Wrap content with extra Box,Padding via modifier,Box just for padding,High,https://developer.android.com/jetpack/compose/modifiers
|
||||||
|
25,Layout,Avoid deep layout nesting,Deep layout trees increase measure & layout cost,Keep layout flat,Box ? Column ? Box ? Row,Flat hierarchy,Deep nested tree,High,
|
||||||
|
26,Layout,Use Row/Column for linear layout,Linear layouts are simpler and more performant,Use Row / Column,Custom layout for simple cases,Row/Column usage,Over-engineered layout,High,
|
||||||
|
27,Layout,Use Box only for overlapping content,Box should be used only when children overlap,Stack elements,Use Box as Column,Proper overlay,Misused Box,Medium,
|
||||||
|
28,Layout,Prefer LazyColumn over Column scroll,Lazy layouts are virtualized and efficient,LazyColumn,Column.verticalScroll(),Lazy list,Scrollable Column,High,https://developer.android.com/jetpack/compose/lists
|
||||||
|
29,Layout,Avoid nested scroll containers,Nested scrolling causes UX & performance issues,Single scroll container,Scroll inside scroll,One scroll per screen,Nested scroll,High,
|
||||||
|
30,Layout,Avoid fillMaxSize by default,fillMaxSize may break parent constraints,Use exact size,Fill max everywhere,Constraint-aware size,Overfilled layout,Medium,
|
||||||
|
31,Layout,Avoid intrinsic size unless necessary,Intrinsic measurement is expensive,Explicit sizing,IntrinsicSize.Min,Predictable layout,Expensive measure,High,https://developer.android.com/jetpack/compose/layout/intrinsics
|
||||||
|
32,Layout,Use Arrangement and Alignment APIs,Declare layout intent explicitly,Use Arrangement / Alignment,Manual spacing hacks,Declarative spacing,Magic spacing,High,
|
||||||
|
33,Layout,Extract reusable layout patterns,Repeated layouts should be shared,Create layout composable,Copy-paste layouts,Reusable scaffold,Duplicated layout,High,
|
||||||
|
34,Theming,No hardcoded text style,Use typography,MaterialTheme.typography,Hardcode sp,Scalable,Inconsistent,Medium,
|
||||||
|
35,Testing,Stateless UI testing,Composable easy to test,Pass state,Hidden state,Testable,Hard test,High,https://developer.android.com/jetpack/compose/testing
|
||||||
|
36,Testing,Use testTag,Stable UI selectors,Modifier.testTag,Find by text,Stable tests,Flaky tests,Medium,
|
||||||
|
37,Preview,Multiple previews,Preview multiple states,@Preview,Single preview,Better dev UX,Misleading,Low,https://developer.android.com/jetpack/compose/tooling/preview
|
||||||
|
38,DI,Inject VM via Hilt,Use hiltViewModel,@HiltViewModel,Manual VM,Clean DI,Coupling,High,https://developer.android.com/training/dependency-injection/hilt-jetpack
|
||||||
|
39,DI,No DI in UI,Inject in VM,Constructor inject,Inject composable,Proper scope,Wrong scope,High,
|
||||||
|
40,Accessibility,Content description,Accessible UI,contentDescription,Ignore a11y,Inclusive,A11y fail,Medium,https://developer.android.com/jetpack/compose/accessibility
|
||||||
|
41,Accessibility,Semantics,Use semantics API,Modifier.semantics,None,Testable a11y,Invisible,Medium,
|
||||||
|
42,Animation,Compose animation APIs,Use animate*AsState,AnimatedVisibility,Manual anim,Smooth,Jank,Medium,https://developer.android.com/jetpack/compose/animation
|
||||||
|
43,Animation,Avoid animation logic in VM,Animation is UI concern,Animate in UI,Animate in VM,Correct layering,Mixed concern,Low,
|
||||||
|
44,Modularization,Feature-based UI modules,UI per feature,:feature:ui,God module,Scalable,Tight coupling,High,https://developer.android.com/topic/modularization
|
||||||
|
45,Modularization,Public UI contracts,Expose minimal UI API,Interface/Route,Expose impl,Encapsulated,Leaky module,Medium,
|
||||||
|
46,State,Snapshot state only,Use Compose state,mutableStateOf,Custom observable,Compose aware,Buggy UI,Medium,
|
||||||
|
47,State,Avoid mutable collections,Immutable list/map,PersistentList,MutableList,Stable UI,Silent bug,High,
|
||||||
|
48,Lifecycle,RememberCoroutineScope usage,Only for UI jobs,UI coroutine,Long jobs,Scoped job,Leak,Medium,https://developer.android.com/jetpack/compose/side-effects#remembercoroutinescope
|
||||||
|
49,Interop,Interop View carefully,Use AndroidView,Isolated usage,Mix everywhere,Safe interop,Messy UI,Low,https://developer.android.com/jetpack/compose/interop
|
||||||
|
50,Interop,Avoid legacy patterns,No LiveData in UI,StateFlow,LiveData,Modern stack,Legacy debt,Medium,
|
||||||
|
51,Debug,Use layout inspector,Inspect recomposition,Tools,Blind debug,Fast debug,Guessing,Low,https://developer.android.com/studio/debug/layout-inspector
|
||||||
|
52,Debug,Enable recomposition counts,Track recomposition,Debug flags,Ignore,Performance aware,Hidden jank,Low,
|
||||||
|
@@ -0,0 +1,53 @@
|
|||||||
|
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
|
||||||
|
1,Routing,Use App Router for new projects,App Router is the recommended approach in Next.js 14+,app/ directory with page.tsx,pages/ for new projects,app/dashboard/page.tsx,pages/dashboard.tsx,Medium,https://nextjs.org/docs/app
|
||||||
|
2,Routing,Use file-based routing,Create routes by adding files in app directory,page.tsx for routes layout.tsx for layouts,Manual route configuration,app/blog/[slug]/page.tsx,Custom router setup,Medium,https://nextjs.org/docs/app/building-your-application/routing
|
||||||
|
3,Routing,Colocate related files,Keep components styles tests with their routes,Component files alongside page.tsx,Separate components folder,app/dashboard/_components/,components/dashboard/,Low,
|
||||||
|
4,Routing,Use route groups for organization,Group routes without affecting URL,Parentheses for route groups,Nested folders affecting URL,(marketing)/about/page.tsx,marketing/about/page.tsx,Low,https://nextjs.org/docs/app/building-your-application/routing/route-groups
|
||||||
|
5,Routing,Handle loading states,Use loading.tsx for route loading UI,loading.tsx alongside page.tsx,Manual loading state management,app/dashboard/loading.tsx,useState for loading in page,Medium,https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming
|
||||||
|
6,Routing,Handle errors with error.tsx,Catch errors at route level,error.tsx with reset function,try/catch in every component,app/dashboard/error.tsx,try/catch in page component,High,https://nextjs.org/docs/app/building-your-application/routing/error-handling
|
||||||
|
7,Rendering,Use Server Components by default,Server Components reduce client JS bundle,Keep components server by default,Add 'use client' unnecessarily,export default function Page(),('use client') for static content,High,https://nextjs.org/docs/app/building-your-application/rendering/server-components
|
||||||
|
8,Rendering,Mark Client Components explicitly,'use client' for interactive components,Add 'use client' only when needed,Server Component with hooks/events,('use client') for onClick useState,No directive with useState,High,https://nextjs.org/docs/app/building-your-application/rendering/client-components
|
||||||
|
9,Rendering,Push Client Components down,Keep Client Components as leaf nodes,Client wrapper for interactive parts only,Mark page as Client Component,<InteractiveButton/> in Server Page,('use client') on page.tsx,High,
|
||||||
|
10,Rendering,Use streaming for better UX,Stream content with Suspense boundaries,Suspense for slow data fetches,Wait for all data before render,<Suspense><SlowComponent/></Suspense>,await allData then render,Medium,https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming
|
||||||
|
11,Rendering,Choose correct rendering strategy,SSG for static SSR for dynamic ISR for semi-static,generateStaticParams for known paths,SSR for static content,export const revalidate = 3600,fetch without cache config,Medium,
|
||||||
|
12,DataFetching,Fetch data in Server Components,Fetch directly in async Server Components,async function Page() { const data = await fetch() },useEffect for initial data,const data = await fetch(url),useEffect(() => fetch(url)),High,https://nextjs.org/docs/app/building-your-application/data-fetching
|
||||||
|
13,DataFetching,Configure caching explicitly (Next.js 15+),Next.js 15 changed defaults to uncached for fetch,Explicitly set cache: 'force-cache' for static data,Assume default is cached (it's not in Next.js 15),fetch(url { cache: 'force-cache' }),fetch(url) // Uncached in v15,High,https://nextjs.org/docs/app/building-your-application/upgrading/version-15
|
||||||
|
14,DataFetching,Deduplicate fetch requests,React and Next.js dedupe same requests,Same fetch call in multiple components,Manual request deduplication,Multiple components fetch same URL,Custom cache layer,Low,
|
||||||
|
15,DataFetching,Use Server Actions for mutations,Server Actions for form submissions,action={serverAction} in forms,API route for every mutation,<form action={createPost}>,<form onSubmit={callApiRoute}>,Medium,https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations
|
||||||
|
16,DataFetching,Revalidate data appropriately,Use revalidatePath/revalidateTag after mutations,Revalidate after Server Action,'use client' with manual refetch,revalidatePath('/posts'),router.refresh() everywhere,Medium,https://nextjs.org/docs/app/building-your-application/caching#revalidating
|
||||||
|
17,Images,Use next/image for optimization,Automatic image optimization and lazy loading,<Image> component for all images,<img> tags directly,<Image src={} alt={} width={} height={}>,<img src={}/>,High,https://nextjs.org/docs/app/building-your-application/optimizing/images
|
||||||
|
18,Images,Provide width and height,Prevent layout shift with dimensions,width and height props or fill,Missing dimensions,<Image width={400} height={300}/>,<Image src={url}/>,High,
|
||||||
|
19,Images,Use fill for responsive images,Fill container with object-fit,fill prop with relative parent,Fixed dimensions for responsive,"<Image fill className=""object-cover""/>",<Image width={window.width}/>,Medium,
|
||||||
|
20,Images,Configure remote image domains,Whitelist external image sources,remotePatterns in next.config.js,Allow all domains,remotePatterns: [{ hostname: 'cdn.example.com' }],domains: ['*'],High,https://nextjs.org/docs/app/api-reference/components/image#remotepatterns
|
||||||
|
21,Images,Use priority for LCP images,Mark above-fold images as priority,priority prop on hero images,All images with priority,<Image priority src={hero}/>,<Image priority/> on every image,Medium,
|
||||||
|
22,Fonts,Use next/font for fonts,Self-hosted fonts with zero layout shift,next/font/google or next/font/local,External font links,import { Inter } from 'next/font/google',"<link href=""fonts.googleapis.com""/>",Medium,https://nextjs.org/docs/app/building-your-application/optimizing/fonts
|
||||||
|
23,Fonts,Apply font to layout,Set font in root layout for consistency,className on body in layout.tsx,Font in individual pages,<body className={inter.className}>,Each page imports font,Low,
|
||||||
|
24,Fonts,Use variable fonts,Variable fonts reduce bundle size,Single variable font file,Multiple font weights as files,Inter({ subsets: ['latin'] }),Inter_400 Inter_500 Inter_700,Low,
|
||||||
|
25,Metadata,Use generateMetadata for dynamic,Generate metadata based on params,export async function generateMetadata(),Hardcoded metadata everywhere,generateMetadata({ params }),export const metadata = {},Medium,https://nextjs.org/docs/app/building-your-application/optimizing/metadata
|
||||||
|
26,Metadata,Include OpenGraph images,Add OG images for social sharing,opengraph-image.tsx or og property,Missing social preview images,opengraph: { images: ['/og.png'] },No OG configuration,Medium,
|
||||||
|
27,Metadata,Use metadata API,Export metadata object for static metadata,export const metadata = {},Manual head tags,export const metadata = { title: 'Page' },<head><title>Page</title></head>,Medium,
|
||||||
|
28,API,Use Route Handlers for APIs,app/api routes for API endpoints,app/api/users/route.ts,pages/api for new projects,export async function GET(request),export default function handler,Medium,https://nextjs.org/docs/app/building-your-application/routing/route-handlers
|
||||||
|
29,API,Return proper Response objects,Use NextResponse for API responses,NextResponse.json() for JSON,Plain objects or res.json(),return NextResponse.json({ data }),return { data },Medium,
|
||||||
|
30,API,Handle HTTP methods explicitly,Export named functions for methods,Export GET POST PUT DELETE,Single handler for all methods,export async function POST(),switch(req.method),Low,
|
||||||
|
31,API,Validate request body,Validate input before processing,Zod or similar for validation,Trust client input,const body = schema.parse(await req.json()),const body = await req.json(),High,
|
||||||
|
32,Middleware,Use middleware for auth,Protect routes with middleware.ts,middleware.ts at root,Auth check in every page,export function middleware(request),if (!session) redirect in page,Medium,https://nextjs.org/docs/app/building-your-application/routing/middleware
|
||||||
|
33,Middleware,Match specific paths,Configure middleware matcher,config.matcher for specific routes,Run middleware on all routes,matcher: ['/dashboard/:path*'],No matcher config,Medium,
|
||||||
|
34,Middleware,Keep middleware edge-compatible,Middleware runs on Edge runtime,Edge-compatible code only,Node.js APIs in middleware,Edge-compatible auth check,fs.readFile in middleware,High,
|
||||||
|
35,Environment,Use NEXT_PUBLIC prefix,Client-accessible env vars need prefix,NEXT_PUBLIC_ for client vars,Server vars exposed to client,NEXT_PUBLIC_API_URL,API_SECRET in client code,High,https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
|
||||||
|
36,Environment,Validate env vars,Check required env vars exist,Validate on startup,Undefined env at runtime,if (!process.env.DATABASE_URL) throw,process.env.DATABASE_URL (might be undefined),High,
|
||||||
|
37,Environment,Use .env.local for secrets,Local env file for development secrets,.env.local gitignored,Secrets in .env committed,.env.local with secrets,.env with DATABASE_PASSWORD,High,
|
||||||
|
38,Performance,Analyze bundle size,Use @next/bundle-analyzer,Bundle analyzer in dev,Ship large bundles blindly,ANALYZE=true npm run build,No bundle analysis,Medium,https://nextjs.org/docs/app/building-your-application/optimizing/bundle-analyzer
|
||||||
|
39,Performance,Use dynamic imports,Code split with next/dynamic,dynamic() for heavy components,Import everything statically,const Chart = dynamic(() => import('./Chart')),import Chart from './Chart',Medium,https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading
|
||||||
|
40,Performance,Avoid layout shifts,Reserve space for dynamic content,Skeleton loaders aspect ratios,Content popping in,"<Skeleton className=""h-48""/>",No placeholder for async content,High,
|
||||||
|
41,Performance,Use Partial Prerendering,Combine static and dynamic in one route,Static shell with Suspense holes,Full dynamic or static pages,Static header + dynamic content,Entire page SSR,Low,https://nextjs.org/docs/app/building-your-application/rendering/partial-prerendering
|
||||||
|
42,Link,Use next/link for navigation,Client-side navigation with prefetching,"<Link href=""""> for internal links",<a> for internal navigation,"<Link href=""/about"">About</Link>","<a href=""/about"">About</a>",High,https://nextjs.org/docs/app/api-reference/components/link
|
||||||
|
43,Link,Prefetch strategically,Control prefetching behavior,prefetch={false} for low-priority,Prefetch all links,<Link prefetch={false}>,Default prefetch on every link,Low,
|
||||||
|
44,Link,Use scroll option appropriately,Control scroll behavior on navigation,scroll={false} for tabs pagination,Always scroll to top,<Link scroll={false}>,Manual scroll management,Low,
|
||||||
|
45,Config,Use next.config.js correctly,Configure Next.js behavior,Proper config options,Deprecated or wrong options,images: { remotePatterns: [] },images: { domains: [] },Medium,https://nextjs.org/docs/app/api-reference/next-config-js
|
||||||
|
46,Config,Enable strict mode,Catch potential issues early,reactStrictMode: true,Strict mode disabled,reactStrictMode: true,reactStrictMode: false,Medium,
|
||||||
|
47,Config,Configure redirects and rewrites,Use config for URL management,redirects() rewrites() in config,Manual redirect handling,redirects: async () => [...],res.redirect in pages,Medium,https://nextjs.org/docs/app/api-reference/next-config-js/redirects
|
||||||
|
48,Deployment,Use Vercel for easiest deploy,Vercel optimized for Next.js,Deploy to Vercel,Self-host without knowledge,vercel deploy,Complex Docker setup for simple app,Low,https://nextjs.org/docs/app/building-your-application/deploying
|
||||||
|
49,Deployment,Configure output for self-hosting,Set output option for deployment target,output: 'standalone' for Docker,Default output for containers,output: 'standalone',No output config for Docker,Medium,https://nextjs.org/docs/app/building-your-application/deploying#self-hosting
|
||||||
|
50,Security,Sanitize user input,Never trust user input,Escape sanitize validate all input,Direct interpolation of user data,DOMPurify.sanitize(userInput),dangerouslySetInnerHTML={{ __html: userInput }},High,
|
||||||
|
51,Security,Use CSP headers,Content Security Policy for XSS protection,Configure CSP in next.config.js,No security headers,headers() with CSP,No CSP configuration,High,https://nextjs.org/docs/app/building-your-application/configuring/content-security-policy
|
||||||
|
52,Security,Validate Server Action input,Server Actions are public endpoints,Validate and authorize in Server Action,Trust Server Action input,Auth check + validation in action,Direct database call without check,High,
|
||||||
|
@@ -0,0 +1,51 @@
|
|||||||
|
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
|
||||||
|
1,Installation,Add Nuxt UI module,Install and configure Nuxt UI in your Nuxt project,pnpm add @nuxt/ui and add to modules,Manual component imports,"modules: ['@nuxt/ui']","import { UButton } from '@nuxt/ui'",High,https://ui.nuxt.com/docs/getting-started/installation/nuxt
|
||||||
|
2,Installation,Import Tailwind and Nuxt UI CSS,Required CSS imports in main.css file,@import tailwindcss and @import @nuxt/ui,Skip CSS imports,"@import ""tailwindcss""; @import ""@nuxt/ui"";",No CSS imports,High,https://ui.nuxt.com/docs/getting-started/installation/nuxt
|
||||||
|
3,Installation,Wrap app with UApp component,UApp provides global configs for Toast Tooltip and overlays,<UApp> wrapper in app.vue,Skip UApp wrapper,<UApp><NuxtPage/></UApp>,<NuxtPage/> without wrapper,High,https://ui.nuxt.com/docs/components/app
|
||||||
|
4,Components,Use U prefix for components,All Nuxt UI components use U prefix by default,UButton UInput UModal,Button Input Modal,<UButton>Click</UButton>,<Button>Click</Button>,Medium,https://ui.nuxt.com/docs/getting-started/installation/nuxt
|
||||||
|
5,Components,Use semantic color props,Use semantic colors like primary secondary error,color="primary" color="error",Hardcoded colors,"<UButton color=""primary"">","<UButton class=""bg-green-500"">",Medium,https://ui.nuxt.com/docs/getting-started/theme/design-system
|
||||||
|
6,Components,Use variant prop for styling,Nuxt UI provides solid outline soft subtle ghost link variants,variant="soft" variant="outline",Custom button classes,"<UButton variant=""soft"">","<UButton class=""border bg-transparent"">",Medium,https://ui.nuxt.com/docs/components/button
|
||||||
|
7,Components,Use size prop consistently,Components support xs sm md lg xl sizes,size="sm" size="lg",Arbitrary sizing classes,"<UButton size=""lg"">","<UButton class=""text-xl px-6"">",Low,https://ui.nuxt.com/docs/components/button
|
||||||
|
8,Icons,Use icon prop with Iconify format,Nuxt UI supports Iconify icons via icon prop,icon="lucide:home" icon="heroicons:user",i-lucide-home format,"<UButton icon=""lucide:home"">","<UButton icon=""i-lucide-home"">",Medium,https://ui.nuxt.com/docs/getting-started/integrations/icons/nuxt
|
||||||
|
9,Icons,Use leadingIcon and trailingIcon,Position icons with dedicated props for clarity,leadingIcon="lucide:plus" trailingIcon="lucide:arrow-right",Manual icon positioning,"<UButton leadingIcon=""lucide:plus"">","<UButton><Icon name=""lucide:plus""/>Add</UButton>",Low,https://ui.nuxt.com/docs/components/button
|
||||||
|
10,Theming,Configure colors in app.config.ts,Runtime color configuration without restart,ui.colors.primary in app.config.ts,Hardcoded colors in components,"defineAppConfig({ ui: { colors: { primary: 'blue' } } })","<UButton class=""bg-blue-500"">",High,https://ui.nuxt.com/docs/getting-started/theme/design-system
|
||||||
|
11,Theming,Use @theme directive for custom colors,Define design tokens in CSS with Tailwind @theme,@theme { --color-brand-500: #xxx },Inline color definitions,@theme { --color-brand-500: #ef4444; },:style="{ color: '#ef4444' }",Medium,https://ui.nuxt.com/docs/getting-started/theme/design-system
|
||||||
|
12,Theming,Extend semantic colors in nuxt.config,Register new colors like tertiary in theme.colors,theme.colors array in ui config,Use undefined colors,"ui: { theme: { colors: ['primary', 'tertiary'] } }","<UButton color=""tertiary""> without config",Medium,https://ui.nuxt.com/docs/getting-started/theme/design-system
|
||||||
|
13,Forms,Use UForm with schema validation,UForm supports Zod Yup Joi Valibot schemas,:schema prop with validation schema,Manual form validation,"<UForm :schema=""schema"" :state=""state"">",Manual @blur validation,High,https://ui.nuxt.com/docs/components/form
|
||||||
|
14,Forms,Use UFormField for field wrapper,Provides label error message and validation display,UFormField with name prop,Manual error handling,"<UFormField name=""email"" label=""Email"">",<div><label>Email</label><UInput/><span>error</span></div>,Medium,https://ui.nuxt.com/docs/components/form-field
|
||||||
|
15,Forms,Handle form submit with @submit,UForm emits submit event with validated data,@submit handler on UForm,@click on submit button,"<UForm @submit=""onSubmit"">","<UButton @click=""onSubmit"">",Medium,https://ui.nuxt.com/docs/components/form
|
||||||
|
16,Forms,Use validateOn prop for validation timing,Control when validation triggers (blur change input),validateOn="['blur']" for performance,Always validate on input,"<UForm :validateOn=""['blur', 'change']"">","<UForm> (validates on every keystroke)",Low,https://ui.nuxt.com/docs/components/form
|
||||||
|
17,Overlays,Use v-model:open for overlay control,Modal Slideover Drawer use v-model:open,v-model:open for controlled state,Manual show/hide logic,"<UModal v-model:open=""isOpen"">",<UModal v-if="isOpen">,Medium,https://ui.nuxt.com/docs/components/modal
|
||||||
|
18,Overlays,Use useOverlay composable for programmatic overlays,Open overlays programmatically without template refs,useOverlay().open(MyModal),Template ref and manual control,"const overlay = useOverlay(); overlay.open(MyModal, { props })","const modal = ref(); modal.value.open()",Medium,https://ui.nuxt.com/docs/components/modal
|
||||||
|
19,Overlays,Use title and description props,Built-in header support for overlays,title="Confirm" description="Are you sure?",Manual header content,"<UModal title=""Confirm"" description=""Are you sure?"">","<UModal><template #header><h2>Confirm</h2></template>",Low,https://ui.nuxt.com/docs/components/modal
|
||||||
|
20,Dashboard,Use UDashboardSidebar for navigation,Provides collapsible resizable sidebar with mobile support,UDashboardSidebar with header default footer slots,Custom sidebar implementation,<UDashboardSidebar><template #header>...</template></UDashboardSidebar>,<aside class="w-64 border-r">,Medium,https://ui.nuxt.com/docs/components/dashboard-sidebar
|
||||||
|
21,Dashboard,Use UDashboardGroup for layout,Wraps dashboard components with sidebar state management,UDashboardGroup > UDashboardSidebar + UDashboardPanel,Manual layout flex containers,<UDashboardGroup><UDashboardSidebar/><UDashboardPanel/></UDashboardGroup>,"<div class=""flex""><aside/><main/></div>",Medium,https://ui.nuxt.com/docs/components/dashboard-group
|
||||||
|
22,Dashboard,Use UDashboardNavbar for top navigation,Responsive navbar with mobile menu support,UDashboardNavbar in dashboard layout,Custom navbar implementation,<UDashboardNavbar :links="navLinks"/>,<nav class="border-b">,Low,https://ui.nuxt.com/docs/components/dashboard-navbar
|
||||||
|
23,Tables,Use UTable with data and columns props,Powered by TanStack Table with built-in features,:data and :columns props,Manual table markup,"<UTable :data=""users"" :columns=""columns""/>","<table><tr v-for=""user in users"">",High,https://ui.nuxt.com/docs/components/table
|
||||||
|
24,Tables,Define columns with accessorKey,Column definitions use accessorKey for data binding,accessorKey: 'email' in column def,String column names only,"{ accessorKey: 'email', header: 'Email' }","['name', 'email']",Medium,https://ui.nuxt.com/docs/components/table
|
||||||
|
25,Tables,Use cell slot for custom rendering,Customize cell content with scoped slots,#cell-columnName slot,Override entire table,<template #cell-status="{ row }">,Manual column render function,Medium,https://ui.nuxt.com/docs/components/table
|
||||||
|
26,Tables,Enable sorting with sortable column option,Add sortable: true to column definition,sortable: true in column,Manual sort implementation,"{ accessorKey: 'name', sortable: true }",@click="sortBy('name')",Low,https://ui.nuxt.com/docs/components/table
|
||||||
|
27,Navigation,Use UNavigationMenu for nav links,Horizontal or vertical navigation with dropdown support,UNavigationMenu with items array,Manual nav with v-for,"<UNavigationMenu :items=""navItems""/>","<nav><a v-for=""item in items"">",Medium,https://ui.nuxt.com/docs/components/navigation-menu
|
||||||
|
28,Navigation,Use UBreadcrumb for page hierarchy,Automatic breadcrumb with NuxtLink support,:items array with label and to,Manual breadcrumb links,"<UBreadcrumb :items=""breadcrumbs""/>","<nav><span v-for=""crumb in crumbs"">",Low,https://ui.nuxt.com/docs/components/breadcrumb
|
||||||
|
29,Navigation,Use UTabs for tabbed content,Tab navigation with content panels,UTabs with items containing slot content,Manual tab state,"<UTabs :items=""tabs""/>","<div><button @click=""tab=1"">",Medium,https://ui.nuxt.com/docs/components/tabs
|
||||||
|
30,Feedback,Use useToast for notifications,Composable for toast notifications,useToast().add({ title description }),Alert components for toasts,"const toast = useToast(); toast.add({ title: 'Saved' })",<UAlert v-if="showSuccess">,High,https://ui.nuxt.com/docs/components/toast
|
||||||
|
31,Feedback,Use UAlert for inline messages,Static alert messages with icon and actions,UAlert with title description color,Toast for static messages,"<UAlert title=""Warning"" color=""warning""/>",useToast for inline alerts,Medium,https://ui.nuxt.com/docs/components/alert
|
||||||
|
32,Feedback,Use USkeleton for loading states,Placeholder content during data loading,USkeleton with appropriate size,Spinner for content loading,<USkeleton class="h-4 w-32"/>,<UIcon name="lucide:loader" class="animate-spin"/>,Low,https://ui.nuxt.com/docs/components/skeleton
|
||||||
|
33,Color Mode,Use UColorModeButton for theme toggle,Built-in light/dark mode toggle button,UColorModeButton component,Manual color mode logic,<UColorModeButton/>,"<button @click=""toggleColorMode"">",Low,https://ui.nuxt.com/docs/components/color-mode-button
|
||||||
|
34,Color Mode,Use UColorModeSelect for theme picker,Dropdown to select system light or dark mode,UColorModeSelect component,Custom select for theme,<UColorModeSelect/>,"<USelect v-model=""colorMode"" :items=""modes""/>",Low,https://ui.nuxt.com/docs/components/color-mode-select
|
||||||
|
35,Customization,Use ui prop for component styling,Override component styles via ui prop,ui prop with slot class overrides,Global CSS overrides,"<UButton :ui=""{ base: 'rounded-full' }""/>",<UButton class="!rounded-full"/>,Medium,https://ui.nuxt.com/docs/getting-started/theme/components
|
||||||
|
36,Customization,Configure default variants in nuxt.config,Set default color and size for all components,theme.defaultVariants in ui config,Repeat props on every component,"ui: { theme: { defaultVariants: { color: 'neutral' } } }","<UButton color=""neutral""> everywhere",Medium,https://ui.nuxt.com/docs/getting-started/installation/nuxt
|
||||||
|
37,Customization,Use app.config.ts for theme overrides,Runtime theme customization,defineAppConfig with ui key,nuxt.config for runtime values,"defineAppConfig({ ui: { button: { defaultVariants: { size: 'sm' } } } })","nuxt.config ui.button.size: 'sm'",Medium,https://ui.nuxt.com/docs/getting-started/theme/components
|
||||||
|
38,Performance,Enable component detection,Tree-shake unused component CSS,experimental.componentDetection: true,Include all component CSS,"ui: { experimental: { componentDetection: true } }","ui: {} (includes all CSS)",Low,https://ui.nuxt.com/docs/getting-started/installation/nuxt
|
||||||
|
39,Performance,Use UTable virtualize for large data,Enable virtualization for 1000+ rows,:virtualize prop on UTable,Render all rows,"<UTable :data=""largeData"" virtualize/>","<UTable :data=""largeData""/>",Medium,https://ui.nuxt.com/docs/components/table
|
||||||
|
40,Accessibility,Use semantic component props,Components have built-in ARIA support,Use title description label props,Skip accessibility props,"<UModal title=""Settings"">","<UModal><h2>Settings</h2>",Medium,https://ui.nuxt.com/docs/components/modal
|
||||||
|
41,Accessibility,Use UFormField for form accessibility,Automatic label-input association,UFormField wraps inputs,Manual id and for attributes,"<UFormField label=""Email""><UInput/></UFormField>","<label for=""email"">Email</label><UInput id=""email""/>",High,https://ui.nuxt.com/docs/components/form-field
|
||||||
|
42,Content,Use UContentToc for table of contents,Automatic TOC with active heading highlight,UContentToc with :links,Manual TOC implementation,"<UContentToc :links=""toc""/>","<nav><a v-for=""heading in headings"">",Low,https://ui.nuxt.com/docs/components/content-toc
|
||||||
|
43,Content,Use UContentSearch for docs search,Command palette for documentation search,UContentSearch with Nuxt Content,Custom search implementation,<UContentSearch/>,<UCommandPalette :groups="searchResults"/>,Low,https://ui.nuxt.com/docs/components/content-search
|
||||||
|
44,AI/Chat,Use UChatMessages for chat UI,Designed for Vercel AI SDK integration,UChatMessages with messages array,Custom chat message list,"<UChatMessages :messages=""messages""/>","<div v-for=""msg in messages"">",Medium,https://ui.nuxt.com/docs/components/chat-messages
|
||||||
|
45,AI/Chat,Use UChatPrompt for input,Enhanced textarea for AI prompts,UChatPrompt with v-model,Basic textarea,<UChatPrompt v-model="prompt"/>,<UTextarea v-model="prompt"/>,Medium,https://ui.nuxt.com/docs/components/chat-prompt
|
||||||
|
46,Editor,Use UEditor for rich text,TipTap-based editor with toolbar support,UEditor with v-model:content,Custom TipTap setup,"<UEditor v-model:content=""content""/>",Manual TipTap initialization,Medium,https://ui.nuxt.com/docs/components/editor
|
||||||
|
47,Links,Use to prop for navigation,UButton and ULink support NuxtLink to prop,to="/dashboard" for internal links,href for internal navigation,"<UButton to=""/dashboard"">","<UButton href=""/dashboard"">",Medium,https://ui.nuxt.com/docs/components/button
|
||||||
|
48,Links,Use external prop for outside links,Explicitly mark external links,target="_blank" with external URLs,Forget rel="noopener","<UButton to=""https://example.com"" target=""_blank"">","<UButton href=""https://..."">",Low,https://ui.nuxt.com/docs/components/link
|
||||||
|
49,Loading,Use loadingAuto on buttons,Automatic loading state from @click promise,loadingAuto prop on UButton,Manual loading state,"<UButton loadingAuto @click=""async () => await save()"">","<UButton :loading=""isLoading"" @click=""save"">",Low,https://ui.nuxt.com/docs/components/button
|
||||||
|
50,Loading,Use UForm loadingAuto,Auto-disable form during submit,loadingAuto on UForm (default true),Manual form disabled state,"<UForm @submit=""handleSubmit"">","<UForm :disabled=""isSubmitting"">",Low,https://ui.nuxt.com/docs/components/form
|
||||||
|
Can't render this file because it contains an unexpected character in line 6 and column 94.
|
@@ -0,0 +1,59 @@
|
|||||||
|
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
|
||||||
|
1,Routing,Use file-based routing,Create routes by adding files in pages directory,pages/ directory with index.vue,Manual route configuration,pages/dashboard/index.vue,Custom router setup,Medium,https://nuxt.com/docs/getting-started/routing
|
||||||
|
2,Routing,Use dynamic route parameters,Create dynamic routes with bracket syntax,[id].vue for dynamic params,Hardcoded routes for dynamic content,pages/posts/[id].vue,pages/posts/post1.vue,Medium,https://nuxt.com/docs/getting-started/routing
|
||||||
|
3,Routing,Use catch-all routes,Handle multiple path segments with [...slug],[...slug].vue for catch-all,Multiple nested dynamic routes,pages/[...slug].vue,pages/[a]/[b]/[c].vue,Low,https://nuxt.com/docs/getting-started/routing
|
||||||
|
4,Routing,Define page metadata with definePageMeta,Set page-level configuration and middleware,definePageMeta for layout middleware title,Manual route meta configuration,"definePageMeta({ layout: 'admin', middleware: 'auth' })",router.beforeEach for page config,High,https://nuxt.com/docs/api/utils/define-page-meta
|
||||||
|
5,Routing,Use validate for route params,Validate dynamic route parameters before rendering,validate function in definePageMeta,Manual validation in setup,"definePageMeta({ validate: (route) => /^\d+$/.test(route.params.id) })",if (!valid) navigateTo('/404'),Medium,https://nuxt.com/docs/api/utils/define-page-meta
|
||||||
|
6,Rendering,Use SSR by default,Server-side rendering is enabled by default,Keep ssr: true (default),Disable SSR unnecessarily,ssr: true (default),ssr: false for all pages,High,https://nuxt.com/docs/guide/concepts/rendering
|
||||||
|
7,Rendering,Use .client suffix for client-only components,Mark components to render only on client,ComponentName.client.vue suffix,v-if with process.client check,Comments.client.vue,<div v-if="process.client"><Comments/></div>,Medium,https://nuxt.com/docs/guide/directory-structure/components
|
||||||
|
8,Rendering,Use .server suffix for server-only components,Mark components to render only on server,ComponentName.server.vue suffix,Manual server check,HeavyMarkdown.server.vue,v-if="process.server",Low,https://nuxt.com/docs/guide/directory-structure/components
|
||||||
|
9,DataFetching,Use useFetch for simple data fetching,Wrapper around useAsyncData for URL fetching,useFetch for API calls,$fetch in onMounted,"const { data } = await useFetch('/api/posts')","onMounted(async () => { data.value = await $fetch('/api/posts') })",High,https://nuxt.com/docs/api/composables/use-fetch
|
||||||
|
10,DataFetching,Use useAsyncData for complex fetching,Fine-grained control over async data,useAsyncData for CMS or custom fetching,useFetch for non-URL data sources,"const { data } = await useAsyncData('posts', () => cms.getPosts())","const { data } = await useFetch(() => cms.getPosts())",Medium,https://nuxt.com/docs/api/composables/use-async-data
|
||||||
|
11,DataFetching,Use $fetch for non-reactive requests,$fetch for event handlers and non-component code,$fetch in event handlers or server routes,useFetch in click handlers,"async function submit() { await $fetch('/api/submit', { method: 'POST' }) }","async function submit() { await useFetch('/api/submit') }",High,https://nuxt.com/docs/api/utils/dollarfetch
|
||||||
|
12,DataFetching,Use lazy option for non-blocking fetch,Defer data fetching for better initial load,lazy: true for below-fold content,Blocking fetch for non-critical data,"useFetch('/api/comments', { lazy: true })",await useFetch('/api/comments') for footer,Medium,https://nuxt.com/docs/api/composables/use-fetch
|
||||||
|
13,DataFetching,Use server option to control fetch location,Choose where data is fetched,server: false for client-only data,Server fetch for user-specific client data,"useFetch('/api/user-preferences', { server: false })",useFetch for localStorage-dependent data,Medium,https://nuxt.com/docs/api/composables/use-fetch
|
||||||
|
14,DataFetching,Use pick to reduce payload size,Select only needed fields from response,pick option for large responses,Fetching entire objects when few fields needed,"useFetch('/api/user', { pick: ['id', 'name'] })",useFetch('/api/user') then destructure,Low,https://nuxt.com/docs/api/composables/use-fetch
|
||||||
|
15,DataFetching,Use transform for data manipulation,Transform data before storing in state,transform option for data shaping,Manual transformation after fetch,"useFetch('/api/posts', { transform: (posts) => posts.map(p => p.title) })",const titles = data.value.map(p => p.title),Low,https://nuxt.com/docs/api/composables/use-fetch
|
||||||
|
16,DataFetching,Handle loading and error states,Always handle pending and error states,Check status pending error refs,Ignoring loading states,"<div v-if=""status === 'pending'"">Loading...</div>",No loading indicator,High,https://nuxt.com/docs/getting-started/data-fetching
|
||||||
|
17,Lifecycle,Avoid side effects in script setup root,Move side effects to lifecycle hooks,Side effects in onMounted,setInterval in root script setup,"onMounted(() => { interval = setInterval(...) })","<script setup>setInterval(...)</script>",High,https://nuxt.com/docs/guide/concepts/nuxt-lifecycle
|
||||||
|
18,Lifecycle,Use onMounted for DOM access,Access DOM only after component is mounted,onMounted for DOM manipulation,Direct DOM access in setup,"onMounted(() => { document.getElementById('el') })","<script setup>document.getElementById('el')</script>",High,https://nuxt.com/docs/api/composables/on-mounted
|
||||||
|
19,Lifecycle,Use nextTick for post-render access,Wait for DOM updates before accessing elements,await nextTick() after state changes,Immediate DOM access after state change,"count.value++; await nextTick(); el.value.focus()","count.value++; el.value.focus()",Medium,https://nuxt.com/docs/api/utils/next-tick
|
||||||
|
20,Lifecycle,Use onPrehydrate for pre-hydration logic,Run code before Nuxt hydrates the page,onPrehydrate for client setup,onMounted for hydration-critical code,"onPrehydrate(() => { console.log(window) })",onMounted for pre-hydration needs,Low,https://nuxt.com/docs/api/composables/on-prehydrate
|
||||||
|
21,Server,Use server/api for API routes,Create API endpoints in server/api directory,server/api/users.ts for /api/users,Manual Express setup,server/api/hello.ts -> /api/hello,app.get('/api/hello'),High,https://nuxt.com/docs/guide/directory-structure/server
|
||||||
|
22,Server,Use defineEventHandler for handlers,Define server route handlers,defineEventHandler for all handlers,export default function,"export default defineEventHandler((event) => { return { hello: 'world' } })","export default function(req, res) {}",High,https://nuxt.com/docs/guide/directory-structure/server
|
||||||
|
23,Server,Use server/routes for non-api routes,Routes without /api prefix,server/routes for custom paths,server/api for non-api routes,server/routes/sitemap.xml.ts,server/api/sitemap.xml.ts,Medium,https://nuxt.com/docs/guide/directory-structure/server
|
||||||
|
24,Server,Use getQuery and readBody for input,Access query params and request body,getQuery(event) readBody(event),Direct event access,"const { id } = getQuery(event)",event.node.req.query,Medium,https://nuxt.com/docs/guide/directory-structure/server
|
||||||
|
25,Server,Validate server input,Always validate input in server handlers,Zod or similar for validation,Trust client input,"const body = await readBody(event); schema.parse(body)",const body = await readBody(event),High,https://nuxt.com/docs/guide/directory-structure/server
|
||||||
|
26,State,Use useState for shared reactive state,SSR-friendly shared state across components,useState for cross-component state,ref for shared state,"const count = useState('count', () => 0)",const count = ref(0) in composable,High,https://nuxt.com/docs/api/composables/use-state
|
||||||
|
27,State,Use unique keys for useState,Prevent state conflicts with unique keys,Descriptive unique keys for each state,Generic or duplicate keys,"useState('user-preferences', () => ({}))",useState('data') in multiple places,Medium,https://nuxt.com/docs/api/composables/use-state
|
||||||
|
28,State,Use Pinia for complex state,Pinia for advanced state management,@pinia/nuxt for complex apps,Custom state management,useMainStore() with Pinia,Custom reactive store implementation,Medium,https://nuxt.com/docs/getting-started/state-management
|
||||||
|
29,State,Use callOnce for one-time async operations,Ensure async operations run only once,callOnce for store initialization,Direct await in component,"await callOnce(store.fetch)",await store.fetch() on every render,Medium,https://nuxt.com/docs/api/utils/call-once
|
||||||
|
30,SEO,Use useSeoMeta for SEO tags,Type-safe SEO meta tag management,useSeoMeta for meta tags,useHead for simple meta,"useSeoMeta({ title: 'Home', ogTitle: 'Home', description: '...' })","useHead({ meta: [{ name: 'description', content: '...' }] })",High,https://nuxt.com/docs/api/composables/use-seo-meta
|
||||||
|
31,SEO,Use reactive values in useSeoMeta,Dynamic SEO tags with refs or getters,Computed getters for dynamic values,Static values for dynamic content,"useSeoMeta({ title: () => post.value.title })","useSeoMeta({ title: post.value.title })",Medium,https://nuxt.com/docs/api/composables/use-seo-meta
|
||||||
|
32,SEO,Use useHead for non-meta head elements,Scripts styles links in head,useHead for scripts and links,useSeoMeta for scripts,"useHead({ script: [{ src: '/analytics.js' }] })","useSeoMeta({ script: '...' })",Medium,https://nuxt.com/docs/api/composables/use-head
|
||||||
|
33,SEO,Include OpenGraph tags,Add OG tags for social sharing,ogTitle ogDescription ogImage,Missing social preview,"useSeoMeta({ ogImage: '/og.png', twitterCard: 'summary_large_image' })",No OG configuration,Medium,https://nuxt.com/docs/api/composables/use-seo-meta
|
||||||
|
34,Middleware,Use defineNuxtRouteMiddleware,Define route middleware properly,defineNuxtRouteMiddleware wrapper,export default function,"export default defineNuxtRouteMiddleware((to, from) => {})","export default function(to, from) {}",High,https://nuxt.com/docs/guide/directory-structure/middleware
|
||||||
|
35,Middleware,Use navigateTo for redirects,Redirect in middleware with navigateTo,return navigateTo('/login'),router.push in middleware,"if (!auth) return navigateTo('/login')","if (!auth) router.push('/login')",High,https://nuxt.com/docs/api/utils/navigate-to
|
||||||
|
36,Middleware,Reference middleware in definePageMeta,Apply middleware to specific pages,middleware array in definePageMeta,Global middleware for page-specific,definePageMeta({ middleware: ['auth'] }),Global auth check for one page,Medium,https://nuxt.com/docs/guide/directory-structure/middleware
|
||||||
|
37,Middleware,Use .global suffix for global middleware,Apply middleware to all routes,auth.global.ts for app-wide auth,Manual middleware on every page,middleware/auth.global.ts,middleware: ['auth'] on every page,Medium,https://nuxt.com/docs/guide/directory-structure/middleware
|
||||||
|
38,ErrorHandling,Use createError for errors,Create errors with proper status codes,createError with statusCode,throw new Error,"throw createError({ statusCode: 404, statusMessage: 'Not Found' })",throw new Error('Not Found'),High,https://nuxt.com/docs/api/utils/create-error
|
||||||
|
39,ErrorHandling,Use NuxtErrorBoundary for local errors,Handle errors within component subtree,NuxtErrorBoundary for component errors,Global error page for local errors,"<NuxtErrorBoundary @error=""log""><template #error=""{ error }"">",error.vue for component errors,Medium,https://nuxt.com/docs/getting-started/error-handling
|
||||||
|
40,ErrorHandling,Use clearError to recover from errors,Clear error state and optionally redirect,clearError({ redirect: '/' }),Manual error state reset,clearError({ redirect: '/home' }),error.value = null,Medium,https://nuxt.com/docs/api/utils/clear-error
|
||||||
|
41,ErrorHandling,Use short statusMessage,Keep statusMessage brief for security,Short generic messages,Detailed error info in statusMessage,"createError({ statusCode: 400, statusMessage: 'Bad Request' })","createError({ statusMessage: 'Invalid user ID: 123' })",High,https://nuxt.com/docs/getting-started/error-handling
|
||||||
|
42,Link,Use NuxtLink for internal navigation,Client-side navigation with prefetching,<NuxtLink to> for internal links,<a href> for internal links,<NuxtLink to="/about">About</NuxtLink>,<a href="/about">About</a>,High,https://nuxt.com/docs/api/components/nuxt-link
|
||||||
|
43,Link,Configure prefetch behavior,Control when prefetching occurs,prefetchOn for interaction-based,Default prefetch for low-priority,"<NuxtLink prefetch-on=""interaction"">",Always default prefetch,Low,https://nuxt.com/docs/api/components/nuxt-link
|
||||||
|
44,Link,Use useRouter for programmatic navigation,Navigate programmatically,useRouter().push() for navigation,Direct window.location,"const router = useRouter(); router.push('/dashboard')",window.location.href = '/dashboard',Medium,https://nuxt.com/docs/api/composables/use-router
|
||||||
|
45,Link,Use navigateTo in composables,Navigate outside components,navigateTo() in middleware or plugins,useRouter in non-component code,return navigateTo('/login'),router.push in middleware,Medium,https://nuxt.com/docs/api/utils/navigate-to
|
||||||
|
46,AutoImports,Leverage auto-imports,Use auto-imported composables directly,Direct use of ref computed useFetch,Manual imports for Nuxt composables,"const count = ref(0)","import { ref } from 'vue'; const count = ref(0)",Medium,https://nuxt.com/docs/guide/concepts/auto-imports
|
||||||
|
47,AutoImports,Use #imports for explicit imports,Explicit imports when needed,#imports for clarity or disabled auto-imports,"import from 'vue' when auto-import enabled","import { ref } from '#imports'","import { ref } from 'vue'",Low,https://nuxt.com/docs/guide/concepts/auto-imports
|
||||||
|
48,AutoImports,Configure third-party auto-imports,Add external package auto-imports,imports.presets in nuxt.config,Manual imports everywhere,"imports: { presets: [{ from: 'vue-i18n', imports: ['useI18n'] }] }",import { useI18n } everywhere,Low,https://nuxt.com/docs/guide/concepts/auto-imports
|
||||||
|
49,Plugins,Use defineNuxtPlugin,Define plugins properly,defineNuxtPlugin wrapper,export default function,"export default defineNuxtPlugin((nuxtApp) => {})","export default function(ctx) {}",High,https://nuxt.com/docs/guide/directory-structure/plugins
|
||||||
|
50,Plugins,Use provide for injection,Provide helpers across app,return { provide: {} } for type safety,nuxtApp.provide without types,"return { provide: { hello: (name) => `Hello ${name}!` } }","nuxtApp.provide('hello', fn)",Medium,https://nuxt.com/docs/guide/directory-structure/plugins
|
||||||
|
51,Plugins,Use .client or .server suffix,Control plugin execution environment,plugin.client.ts for client-only,if (process.client) checks,analytics.client.ts,"if (process.client) { // analytics }",Medium,https://nuxt.com/docs/guide/directory-structure/plugins
|
||||||
|
52,Environment,Use runtimeConfig for env vars,Access environment variables safely,runtimeConfig in nuxt.config,process.env directly,"runtimeConfig: { apiSecret: '', public: { apiBase: '' } }",process.env.API_SECRET in components,High,https://nuxt.com/docs/guide/going-further/runtime-config
|
||||||
|
53,Environment,Use NUXT_ prefix for env override,Override config with environment variables,NUXT_API_SECRET NUXT_PUBLIC_API_BASE,Custom env var names,NUXT_PUBLIC_API_BASE=https://api.example.com,API_BASE=https://api.example.com,High,https://nuxt.com/docs/guide/going-further/runtime-config
|
||||||
|
54,Environment,Access public config with useRuntimeConfig,Get public config in components,useRuntimeConfig().public,Direct process.env access,const config = useRuntimeConfig(); config.public.apiBase,process.env.NUXT_PUBLIC_API_BASE,High,https://nuxt.com/docs/api/composables/use-runtime-config
|
||||||
|
55,Environment,Keep secrets in private config,Server-only secrets in runtimeConfig root,runtimeConfig.apiSecret (server only),Secrets in public config,runtimeConfig: { dbPassword: '' },runtimeConfig: { public: { dbPassword: '' } },High,https://nuxt.com/docs/guide/going-further/runtime-config
|
||||||
|
56,Performance,Use Lazy prefix for code splitting,Lazy load components with Lazy prefix,<LazyComponent> for below-fold,Eager load all components,<LazyMountainsList v-if="show"/>,<MountainsList/> for hidden content,Medium,https://nuxt.com/docs/guide/directory-structure/components
|
||||||
|
57,Performance,Use useLazyFetch for non-blocking data,Alias for useFetch with lazy: true,useLazyFetch for secondary data,useFetch for all requests,"const { data } = useLazyFetch('/api/comments')",await useFetch for comments section,Medium,https://nuxt.com/docs/api/composables/use-lazy-fetch
|
||||||
|
58,Performance,Use lazy hydration for interactivity,Delay component hydration until needed,LazyComponent with hydration strategy,Immediate hydration for all,<LazyModal hydrate-on-visible/>,<Modal/> in footer,Low,https://nuxt.com/docs/guide/going-further/experimental-features
|
||||||
|
Can't render this file because it contains an unexpected character in line 8 and column 193.
|
@@ -0,0 +1,52 @@
|
|||||||
|
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
|
||||||
|
1,Components,Use functional components,Hooks-based components are standard,Functional components with hooks,Class components,const App = () => { },class App extends Component,Medium,https://reactnative.dev/docs/intro-react
|
||||||
|
2,Components,Keep components small,Single responsibility principle,Split into smaller components,Large monolithic components,<Header /><Content /><Footer />,500+ line component,Medium,
|
||||||
|
3,Components,Use TypeScript,Type safety for props and state,TypeScript for new projects,JavaScript without types,const Button: FC<Props> = () => { },const Button = (props) => { },Medium,
|
||||||
|
4,Components,Colocate component files,Keep related files together,Component folder with styles,Flat structure,components/Button/index.tsx styles.ts,components/Button.tsx styles/button.ts,Low,
|
||||||
|
5,Styling,Use StyleSheet.create,Optimized style objects,StyleSheet for all styles,Inline style objects,StyleSheet.create({ container: {} }),style={{ margin: 10 }},High,https://reactnative.dev/docs/stylesheet
|
||||||
|
6,Styling,Avoid inline styles,Prevent object recreation,Styles in StyleSheet,Inline style objects in render,style={styles.container},"style={{ margin: 10, padding: 5 }}",Medium,
|
||||||
|
7,Styling,Use flexbox for layout,React Native uses flexbox,flexDirection alignItems justifyContent,Absolute positioning everywhere,flexDirection: 'row',position: 'absolute' everywhere,Medium,https://reactnative.dev/docs/flexbox
|
||||||
|
8,Styling,Handle platform differences,Platform-specific styles,Platform.select or .ios/.android files,Same styles for both platforms,"Platform.select({ ios: {}, android: {} })",Hardcoded iOS values,Medium,https://reactnative.dev/docs/platform-specific-code
|
||||||
|
9,Styling,Use responsive dimensions,Scale for different screens,Dimensions or useWindowDimensions,Fixed pixel values,useWindowDimensions(),width: 375,Medium,
|
||||||
|
10,Navigation,Use React Navigation,Standard navigation library,React Navigation for routing,Manual navigation management,createStackNavigator(),Custom navigation state,Medium,https://reactnavigation.org/
|
||||||
|
11,Navigation,Type navigation params,Type-safe navigation,Typed navigation props,Untyped navigation,"navigation.navigate<RootStackParamList>('Home', { id })","navigation.navigate('Home', { id })",Medium,
|
||||||
|
12,Navigation,Use deep linking,Support URL-based navigation,Configure linking prop,No deep link support,linking: { prefixes: [] },No linking configuration,Medium,https://reactnavigation.org/docs/deep-linking/
|
||||||
|
13,Navigation,Handle back button,Android back button handling,useFocusEffect with BackHandler,Ignore back button,BackHandler.addEventListener,No back handler,High,
|
||||||
|
14,State,Use useState for local state,Simple component state,useState for UI state,Class component state,"const [count, setCount] = useState(0)",this.state = { count: 0 },Medium,
|
||||||
|
15,State,Use useReducer for complex state,Complex state logic,useReducer for related state,Multiple useState for related values,useReducer(reducer initialState),5+ useState calls,Medium,
|
||||||
|
16,State,Use context sparingly,Context for global state,Context for theme auth locale,Context for frequently changing data,ThemeContext for app theme,Context for list item data,Medium,
|
||||||
|
17,State,Consider Zustand or Redux,External state management,Zustand for simple Redux for complex,useState for global state,create((set) => ({ })),Prop drilling global state,Medium,
|
||||||
|
18,Lists,Use FlatList for long lists,Virtualized list rendering,FlatList for 50+ items,ScrollView with map,<FlatList data={items} />,<ScrollView>{items.map()}</ScrollView>,High,https://reactnative.dev/docs/flatlist
|
||||||
|
19,Lists,Provide keyExtractor,Unique keys for list items,keyExtractor with stable ID,Index as key,keyExtractor={(item) => item.id},"keyExtractor={(_, index) => index}",High,
|
||||||
|
20,Lists,Optimize renderItem,Memoize list item components,React.memo for list items,Inline render function,renderItem={({ item }) => <MemoizedItem item={item} />},renderItem={({ item }) => <View>...</View>},High,
|
||||||
|
21,Lists,Use getItemLayout for fixed height,Skip measurement for performance,getItemLayout when height known,Dynamic measurement for fixed items,"getItemLayout={(_, index) => ({ length: 50, offset: 50 * index, index })}",No getItemLayout for fixed height,Medium,
|
||||||
|
22,Lists,Implement windowSize,Control render window,Smaller windowSize for memory,Default windowSize for large lists,windowSize={5},windowSize={21} for huge lists,Medium,
|
||||||
|
23,Performance,Use React.memo,Prevent unnecessary re-renders,memo for pure components,No memoization,export default memo(MyComponent),export default MyComponent,Medium,
|
||||||
|
24,Performance,Use useCallback for handlers,Stable function references,useCallback for props,New function on every render,"useCallback(() => {}, [deps])",() => handlePress(),Medium,
|
||||||
|
25,Performance,Use useMemo for expensive ops,Cache expensive calculations,useMemo for heavy computations,Recalculate every render,"useMemo(() => expensive(), [deps])",const result = expensive(),Medium,
|
||||||
|
26,Performance,Avoid anonymous functions in JSX,Prevent re-renders,Named handlers or useCallback,Inline arrow functions,onPress={handlePress},onPress={() => doSomething()},Medium,
|
||||||
|
27,Performance,Use Hermes engine,Improved startup and memory,Enable Hermes in build,JavaScriptCore for new projects,hermes_enabled: true,hermes_enabled: false,Medium,https://reactnative.dev/docs/hermes
|
||||||
|
28,Images,Use expo-image,Modern performant image component for React Native,"Use expo-image for caching, blurring, and performance",Use default Image for heavy lists or unmaintained libraries,<Image source={url} cachePolicy='memory-disk' /> (expo-image),<FastImage source={url} />,Medium,https://docs.expo.dev/versions/latest/sdk/image/
|
||||||
|
29,Images,Specify image dimensions,Prevent layout shifts,width and height for remote images,No dimensions for network images,<Image style={{ width: 100 height: 100 }} />,<Image source={{ uri }} /> no size,High,
|
||||||
|
30,Images,Use resizeMode,Control image scaling,resizeMode cover contain,Stretch images,"resizeMode=""cover""",No resizeMode,Low,
|
||||||
|
31,Forms,Use controlled inputs,State-controlled form fields,value + onChangeText,Uncontrolled inputs,<TextInput value={text} onChangeText={setText} />,<TextInput defaultValue={text} />,Medium,
|
||||||
|
32,Forms,Handle keyboard,Manage keyboard visibility,KeyboardAvoidingView,Content hidden by keyboard,"<KeyboardAvoidingView behavior=""padding"">",No keyboard handling,High,https://reactnative.dev/docs/keyboardavoidingview
|
||||||
|
33,Forms,Use proper keyboard types,Appropriate keyboard for input,keyboardType for input type,Default keyboard for all,"keyboardType=""email-address""","keyboardType=""default"" for email",Low,
|
||||||
|
34,Touch,Use Pressable,Modern touch handling,Pressable for touch interactions,TouchableOpacity for new code,<Pressable onPress={} />,<TouchableOpacity onPress={} />,Low,https://reactnative.dev/docs/pressable
|
||||||
|
35,Touch,Provide touch feedback,Visual feedback on press,Ripple or opacity change,No feedback on press,android_ripple={{ color: 'gray' }},No press feedback,Medium,
|
||||||
|
36,Touch,Set hitSlop for small targets,Increase touch area,hitSlop for icons and small buttons,Tiny touch targets,hitSlop={{ top: 10 bottom: 10 }},44x44 with no hitSlop,Medium,
|
||||||
|
37,Animation,Use Reanimated,High-performance animations,react-native-reanimated,Animated API for complex,useSharedValue useAnimatedStyle,Animated.timing for gesture,Medium,https://docs.swmansion.com/react-native-reanimated/
|
||||||
|
38,Animation,Run on UI thread,worklets for smooth animation,Run animations on UI thread,JS thread animations,runOnUI(() => {}),Animated on JS thread,High,
|
||||||
|
39,Animation,Use gesture handler,Native gesture recognition,react-native-gesture-handler,JS-based gesture handling,<GestureDetector>,<View onTouchMove={} />,Medium,https://docs.swmansion.com/react-native-gesture-handler/
|
||||||
|
40,Async,Handle loading states,Show loading indicators,ActivityIndicator during load,Empty screen during load,{isLoading ? <ActivityIndicator /> : <Content />},No loading state,Medium,
|
||||||
|
41,Async,Handle errors gracefully,Error boundaries and fallbacks,Error UI for failed requests,Crash on error,{error ? <ErrorView /> : <Content />},No error handling,High,
|
||||||
|
42,Async,Cancel async operations,Cleanup on unmount,AbortController or cleanup,Memory leaks from async,useEffect cleanup,No cleanup for subscriptions,High,
|
||||||
|
43,Accessibility,Add accessibility labels,Describe UI elements,accessibilityLabel for all interactive,Missing labels,"accessibilityLabel=""Submit form""",<Pressable> without label,High,https://reactnative.dev/docs/accessibility
|
||||||
|
44,Accessibility,Use accessibility roles,Semantic meaning,accessibilityRole for elements,Wrong roles,"accessibilityRole=""button""",No role for button,Medium,
|
||||||
|
45,Accessibility,Support screen readers,Test with TalkBack/VoiceOver,Test with screen readers,Skip accessibility testing,Regular TalkBack testing,No screen reader testing,High,
|
||||||
|
46,Testing,Use React Native Testing Library,Component testing,render and fireEvent,Enzyme or manual testing,render(<Component />),shallow(<Component />),Medium,https://callstack.github.io/react-native-testing-library/
|
||||||
|
47,Testing,Test on real devices,Real device behavior,Test on iOS and Android devices,Simulator only,Device testing in CI,Simulator only testing,High,
|
||||||
|
48,Testing,Use Detox for E2E,End-to-end testing,Detox for critical flows,Manual E2E testing,detox test,Manual testing only,Medium,https://wix.github.io/Detox/
|
||||||
|
49,Native,Use native modules carefully,Bridge has overhead,Batch native calls,Frequent bridge crossing,Batch updates,Call native on every keystroke,High,
|
||||||
|
50,Native,Use Expo when possible,Simplified development,Expo for standard features,Bare RN for simple apps,expo install package,react-native link package,Low,https://docs.expo.dev/
|
||||||
|
51,Native,Handle permissions,Request permissions properly,Check and request permissions,Assume permissions granted,PermissionsAndroid.request(),Access without permission check,High,https://reactnative.dev/docs/permissionsandroid
|
||||||
|
@@ -0,0 +1,54 @@
|
|||||||
|
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
|
||||||
|
1,State,Use useState for local state,Simple component state should use useState hook,useState for form inputs toggles counters,Class components this.state,"const [count, setCount] = useState(0)",this.state = { count: 0 },Medium,https://react.dev/reference/react/useState
|
||||||
|
2,State,Lift state up when needed,Share state between siblings by lifting to parent,Lift shared state to common ancestor,Prop drilling through many levels,Parent holds state passes down,Deep prop chains,Medium,https://react.dev/learn/sharing-state-between-components
|
||||||
|
3,State,Use useReducer for complex state,Complex state logic benefits from reducer pattern,useReducer for state with multiple sub-values,Multiple useState for related values,useReducer with action types,5+ useState calls that update together,Medium,https://react.dev/reference/react/useReducer
|
||||||
|
4,State,Avoid unnecessary state,Derive values from existing state when possible,Compute derived values in render,Store derivable values in state,const total = items.reduce(...),"const [total, setTotal] = useState(0)",High,https://react.dev/learn/choosing-the-state-structure
|
||||||
|
5,State,Initialize state lazily,Use function form for expensive initial state,useState(() => computeExpensive()),useState(computeExpensive()),useState(() => JSON.parse(data)),useState(JSON.parse(data)),Medium,https://react.dev/reference/react/useState#avoiding-recreating-the-initial-state
|
||||||
|
6,Effects,Clean up effects,Return cleanup function for subscriptions timers,Return cleanup function in useEffect,No cleanup for subscriptions,useEffect(() => { sub(); return unsub; }),useEffect(() => { subscribe(); }),High,https://react.dev/reference/react/useEffect#connecting-to-an-external-system
|
||||||
|
7,Effects,Specify dependencies correctly,Include all values used inside effect in deps array,All referenced values in dependency array,Empty deps with external references,[value] when using value in effect,[] when using props/state in effect,High,https://react.dev/reference/react/useEffect#specifying-reactive-dependencies
|
||||||
|
8,Effects,Avoid unnecessary effects,Don't use effects for transforming data or events,Transform data during render handle events directly,useEffect for derived state or event handling,const filtered = items.filter(...),useEffect(() => setFiltered(items.filter(...))),High,https://react.dev/learn/you-might-not-need-an-effect
|
||||||
|
9,Effects,Use refs for non-reactive values,Store values that don't trigger re-renders in refs,useRef for interval IDs DOM elements,useState for values that don't need render,const intervalRef = useRef(null),"const [intervalId, setIntervalId] = useState()",Medium,https://react.dev/reference/react/useRef
|
||||||
|
10,Rendering,Use keys properly,Stable unique keys for list items,Use stable IDs as keys,Array index as key for dynamic lists,key={item.id},key={index},High,https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key
|
||||||
|
11,Rendering,Memoize expensive calculations,Use useMemo for costly computations,useMemo for expensive filtering/sorting,Recalculate every render,"useMemo(() => expensive(), [deps])",const result = expensiveCalc(),Medium,https://react.dev/reference/react/useMemo
|
||||||
|
12,Rendering,Memoize callbacks passed to children,Use useCallback for functions passed as props,useCallback for handlers passed to memoized children,New function reference every render,"useCallback(() => {}, [deps])",const handler = () => {},Medium,https://react.dev/reference/react/useCallback
|
||||||
|
13,Rendering,Use React.memo wisely,Wrap components that render often with same props,memo for pure components with stable props,memo everything or nothing,memo(ExpensiveList),memo(SimpleButton),Low,https://react.dev/reference/react/memo
|
||||||
|
14,Rendering,Avoid inline object/array creation in JSX,Create objects outside render or memoize,Define style objects outside component,Inline objects in props,<div style={styles.container}>,<div style={{ margin: 10 }}>,Medium,
|
||||||
|
15,Components,Keep components small and focused,Single responsibility for each component,One concern per component,Large multi-purpose components,<UserAvatar /><UserName />,<UserCard /> with 500 lines,Medium,
|
||||||
|
16,Components,Use composition over inheritance,Compose components using children and props,Use children prop for flexibility,Inheritance hierarchies,<Card>{content}</Card>,class SpecialCard extends Card,Medium,https://react.dev/learn/thinking-in-react
|
||||||
|
17,Components,Colocate related code,Keep related components and hooks together,Related files in same directory,Flat structure with many files,components/User/UserCard.tsx,components/UserCard.tsx + hooks/useUser.ts,Low,
|
||||||
|
18,Components,Use fragments to avoid extra DOM,Fragment or <> for multiple elements without wrapper,<> for grouping without DOM node,Extra div wrappers,<>{items.map(...)}</>,<div>{items.map(...)}</div>,Low,https://react.dev/reference/react/Fragment
|
||||||
|
19,Props,Destructure props,Destructure props for cleaner component code,Destructure in function signature,props.name props.value throughout,"function User({ name, age })",function User(props),Low,
|
||||||
|
20,Props,Provide default props values,Use default parameters or defaultProps,Default values in destructuring,Undefined checks throughout,function Button({ size = 'md' }),if (size === undefined) size = 'md',Low,
|
||||||
|
21,Props,Avoid prop drilling,Use context or composition for deeply nested data,Context for global data composition for UI,Passing props through 5+ levels,<UserContext.Provider>,<A user={u}><B user={u}><C user={u}>,Medium,https://react.dev/learn/passing-data-deeply-with-context
|
||||||
|
22,Props,Validate props with TypeScript,Use TypeScript interfaces for prop types,interface Props { name: string },PropTypes or no validation,interface ButtonProps { onClick: () => void },Button.propTypes = {},Medium,
|
||||||
|
23,Events,Use synthetic events correctly,React normalizes events across browsers,e.preventDefault() e.stopPropagation(),Access native event unnecessarily,onClick={(e) => e.preventDefault()},onClick={(e) => e.nativeEvent.preventDefault()},Low,https://react.dev/reference/react-dom/components/common#react-event-object
|
||||||
|
24,Events,Avoid binding in render,Use arrow functions in class or hooks,Arrow functions in functional components,bind in render or constructor,const handleClick = () => {},this.handleClick.bind(this),Medium,
|
||||||
|
25,Events,Pass event handlers not call results,Pass function reference not invocation,onClick={handleClick},onClick={handleClick()} causing immediate call,onClick={handleClick},onClick={handleClick()},High,
|
||||||
|
26,Forms,Controlled components for forms,Use state to control form inputs,value + onChange for inputs,Uncontrolled inputs with refs,<input value={val} onChange={setVal}>,<input ref={inputRef}>,Medium,https://react.dev/reference/react-dom/components/input#controlling-an-input-with-a-state-variable
|
||||||
|
27,Forms,Handle form submission properly,Prevent default and handle in submit handler,onSubmit with preventDefault,onClick on submit button only,<form onSubmit={handleSubmit}>,<button onClick={handleSubmit}>,Medium,
|
||||||
|
28,Forms,Debounce rapid input changes,Debounce search/filter inputs,useDeferredValue or debounce for search,Filter on every keystroke,useDeferredValue(searchTerm),useEffect filtering on every change,Medium,https://react.dev/reference/react/useDeferredValue
|
||||||
|
29,Hooks,Follow rules of hooks,Only call hooks at top level and in React functions,Hooks at component top level,Hooks in conditions loops or callbacks,"const [x, setX] = useState()","if (cond) { const [x, setX] = useState() }",High,https://react.dev/reference/rules/rules-of-hooks
|
||||||
|
30,Hooks,Custom hooks for reusable logic,Extract shared stateful logic to custom hooks,useCustomHook for reusable patterns,Duplicate hook logic across components,const { data } = useFetch(url),Duplicate useEffect/useState in components,Medium,https://react.dev/learn/reusing-logic-with-custom-hooks
|
||||||
|
31,Hooks,Name custom hooks with use prefix,Custom hooks must start with use,useFetch useForm useAuth,fetchData or getData for hook,function useFetch(url),function fetchData(url),High,
|
||||||
|
32,Context,Use context for global data,Context for theme auth locale,Context for app-wide state,Context for frequently changing data,<ThemeContext.Provider>,Context for form field values,Medium,https://react.dev/learn/passing-data-deeply-with-context
|
||||||
|
33,Context,Split contexts by concern,Separate contexts for different domains,ThemeContext + AuthContext,One giant AppContext,<ThemeProvider><AuthProvider>,<AppProvider value={{theme user...}}>,Medium,
|
||||||
|
34,Context,Memoize context values,Prevent unnecessary re-renders with useMemo,useMemo for context value object,New object reference every render,"value={useMemo(() => ({...}), [])}","value={{ user, theme }}",High,
|
||||||
|
35,Performance,Use React DevTools Profiler,Profile to identify performance bottlenecks,Profile before optimizing,Optimize without measuring,React DevTools Profiler,Guessing at bottlenecks,Medium,https://react.dev/learn/react-developer-tools
|
||||||
|
36,Performance,Lazy load components,Use React.lazy for code splitting,lazy() for routes and heavy components,Import everything upfront,const Page = lazy(() => import('./Page')),import Page from './Page',Medium,https://react.dev/reference/react/lazy
|
||||||
|
37,Performance,Virtualize long lists,Use windowing for lists over 100 items,react-window or react-virtual,Render thousands of DOM nodes,<VirtualizedList items={items}/>,{items.map(i => <Item />)},High,
|
||||||
|
38,Performance,Batch state updates,React 18 auto-batches but be aware,Let React batch related updates,Manual batching with flushSync,setA(1); setB(2); // batched,flushSync(() => setA(1)),Low,https://react.dev/learn/queueing-a-series-of-state-updates
|
||||||
|
39,ErrorHandling,Use error boundaries,Catch JavaScript errors in component tree,ErrorBoundary wrapping sections,Let errors crash entire app,<ErrorBoundary><App/></ErrorBoundary>,No error handling,High,https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary
|
||||||
|
40,ErrorHandling,Handle async errors,Catch errors in async operations,try/catch in async handlers,Unhandled promise rejections,try { await fetch() } catch(e) {},await fetch() // no catch,High,
|
||||||
|
41,Testing,Test behavior not implementation,Test what user sees and does,Test renders and interactions,Test internal state or methods,expect(screen.getByText('Hello')),expect(component.state.name),Medium,https://testing-library.com/docs/react-testing-library/intro/
|
||||||
|
42,Testing,Use testing-library queries,Use accessible queries,getByRole getByLabelText,getByTestId for everything,getByRole('button'),getByTestId('submit-btn'),Medium,https://testing-library.com/docs/queries/about#priority
|
||||||
|
43,Accessibility,Use semantic HTML,Proper HTML elements for their purpose,button for clicks nav for navigation,div with onClick for buttons,<button onClick={...}>,<div onClick={...}>,High,https://react.dev/reference/react-dom/components#all-html-components
|
||||||
|
44,Accessibility,Manage focus properly,Handle focus for modals dialogs,Focus trap in modals return focus on close,No focus management,useEffect to focus input,Modal without focus trap,High,
|
||||||
|
45,Accessibility,Announce dynamic content,Use ARIA live regions for updates,aria-live for dynamic updates,Silent updates to screen readers,"<div aria-live=""polite"">{msg}</div>",<div>{msg}</div>,Medium,
|
||||||
|
46,Accessibility,Label form controls,Associate labels with inputs,htmlFor matching input id,Placeholder as only label,"<label htmlFor=""email"">Email</label>","<input placeholder=""Email""/>",High,
|
||||||
|
47,TypeScript,Type component props,Define interfaces for all props,interface Props with all prop types,any or missing types,interface Props { name: string },function Component(props: any),High,
|
||||||
|
48,TypeScript,Type state properly,Provide types for useState,useState<Type>() for complex state,Inferred any types,useState<User | null>(null),useState(null),Medium,
|
||||||
|
49,TypeScript,Type event handlers,Use React event types,React.ChangeEvent<HTMLInputElement>,Generic Event type,onChange: React.ChangeEvent<HTMLInputElement>,onChange: Event,Medium,
|
||||||
|
50,TypeScript,Use generics for reusable components,Generic components for flexible typing,Generic props for list components,Union types for flexibility,<List<T> items={T[]}>,<List items={any[]}>,Medium,
|
||||||
|
51,Patterns,Container/Presentational split,Separate data logic from UI,Container fetches presentational renders,Mixed data and UI in one,<UserContainer><UserView/></UserContainer>,<User /> with fetch and render,Low,
|
||||||
|
52,Patterns,Render props for flexibility,Share code via render prop pattern,Render prop for customizable rendering,Duplicate logic across components,<DataFetcher render={data => ...}/>,Copy paste fetch logic,Low,https://react.dev/reference/react/cloneElement#passing-data-with-a-render-prop
|
||||||
|
53,Patterns,Compound components,Related components sharing state,Tab + TabPanel sharing context,Prop drilling between related,<Tabs><Tab/><TabPanel/></Tabs>,<Tabs tabs={[]} panels={[...]}/>,Low,
|
||||||
|
@@ -0,0 +1,61 @@
|
|||||||
|
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
|
||||||
|
1,Setup,Use CLI for installation,Install components via shadcn CLI for proper setup,npx shadcn@latest add component-name,Manual copy-paste from docs,npx shadcn@latest add button,Copy component code manually,High,https://ui.shadcn.com/docs/cli
|
||||||
|
2,Setup,Initialize project properly,Run init command to set up components.json and globals.css,npx shadcn@latest init before adding components,Skip init and add components directly,npx shadcn@latest init,npx shadcn@latest add button (without init),High,https://ui.shadcn.com/docs/installation
|
||||||
|
3,Setup,Configure path aliases,Set up proper import aliases in tsconfig and components.json,Use @/components/ui path aliases,Relative imports like ../../components,import { Button } from "@/components/ui/button",import { Button } from "../../components/ui/button",Medium,https://ui.shadcn.com/docs/installation
|
||||||
|
4,Theming,Use CSS variables for colors,Define colors as CSS variables in globals.css for theming,CSS variables in :root and .dark,Hardcoded color values in components,bg-primary text-primary-foreground,bg-blue-500 text-white,High,https://ui.shadcn.com/docs/theming
|
||||||
|
5,Theming,Follow naming convention,Use semantic color names with foreground pattern,primary/primary-foreground secondary/secondary-foreground,Generic color names,--primary --primary-foreground,--blue --light-blue,Medium,https://ui.shadcn.com/docs/theming
|
||||||
|
6,Theming,Support dark mode,Include .dark class styles for all custom CSS,Define both :root and .dark color schemes,Only light mode colors,.dark { --background: 240 10% 3.9%; },No .dark class styles,High,https://ui.shadcn.com/docs/dark-mode
|
||||||
|
7,Components,Use component variants,Leverage cva variants for consistent styling,Use variant prop for different styles,Inline conditional classes,<Button variant="destructive">,<Button className={isError ? "bg-red-500" : "bg-blue-500"}>,Medium,https://ui.shadcn.com/docs/components/button
|
||||||
|
8,Components,Compose with className,Add custom classes via className prop for overrides,Extend with className for one-off customizations,Modify component source directly,<Button className="w-full">,Edit button.tsx to add w-full,Medium,https://ui.shadcn.com/docs/components/button
|
||||||
|
9,Components,Use size variants consistently,Apply size prop for consistent sizing across components,size="sm" size="lg" for sizing,Mix size classes inconsistently,<Button size="lg">,<Button className="text-lg px-8 py-4">,Medium,https://ui.shadcn.com/docs/components/button
|
||||||
|
10,Components,Prefer compound components,Use provided sub-components for complex UI,Card + CardHeader + CardContent pattern,Single component with many props,<Card><CardHeader><CardTitle>,<Card title="x" content="y" footer="z">,Medium,https://ui.shadcn.com/docs/components/card
|
||||||
|
11,Dialog,Use Dialog for modal content,Dialog component for overlay modal windows,Dialog for confirmations forms details,Alert for modal content,<Dialog><DialogContent>,<Alert> styled as modal,High,https://ui.shadcn.com/docs/components/dialog
|
||||||
|
12,Dialog,Handle dialog state properly,Use open and onOpenChange for controlled dialogs,Controlled state with useState,Uncontrolled with default open only,"<Dialog open={open} onOpenChange={setOpen}>","<Dialog defaultOpen={true}>",Medium,https://ui.shadcn.com/docs/components/dialog
|
||||||
|
13,Dialog,Include proper dialog structure,Use DialogHeader DialogTitle DialogDescription,Complete semantic structure,Missing title or description,<DialogHeader><DialogTitle><DialogDescription>,<DialogContent><p>Content</p></DialogContent>,High,https://ui.shadcn.com/docs/components/dialog
|
||||||
|
14,Sheet,Use Sheet for side panels,Sheet component for slide-out panels and drawers,Sheet for navigation filters settings,Dialog for side content,<Sheet side="right">,<Dialog> with slide animation,Medium,https://ui.shadcn.com/docs/components/sheet
|
||||||
|
15,Sheet,Specify sheet side,Set side prop for sheet slide direction,Explicit side="left" or side="right",Default side without consideration,<Sheet><SheetContent side="left">,<Sheet><SheetContent>,Low,https://ui.shadcn.com/docs/components/sheet
|
||||||
|
16,Form,Use Form with react-hook-form,Integrate Form component with react-hook-form for validation,useForm + Form + FormField pattern,Custom form handling without Form,<Form {...form}><FormField control={form.control}>,<form onSubmit={handleSubmit}>,High,https://ui.shadcn.com/docs/components/form
|
||||||
|
17,Form,Use FormField for inputs,Wrap inputs in FormField for proper labeling and errors,FormField + FormItem + FormLabel + FormControl,Input without FormField wrapper,<FormField><FormItem><FormLabel><FormControl><Input>,<Input onChange={...}>,High,https://ui.shadcn.com/docs/components/form
|
||||||
|
18,Form,Display form messages,Use FormMessage for validation error display,FormMessage after FormControl,Custom error text without FormMessage,<FormControl><Input/></FormControl><FormMessage/>,<Input/>{error && <span>{error}</span>},Medium,https://ui.shadcn.com/docs/components/form
|
||||||
|
19,Form,Use Zod for validation,Define form schema with Zod for type-safe validation,zodResolver with form schema,Manual validation logic,zodResolver(formSchema),validate: (values) => { if (!values.email) },Medium,https://ui.shadcn.com/docs/components/form
|
||||||
|
20,Select,Use Select for dropdowns,Select component for option selection,Select for choosing from list,Native select element,<Select><SelectTrigger><SelectContent>,<select><option>,Medium,https://ui.shadcn.com/docs/components/select
|
||||||
|
21,Select,Structure Select properly,Include Trigger Value Content and Items,Complete Select structure,Missing SelectValue or SelectContent,<SelectTrigger><SelectValue/></SelectTrigger><SelectContent><SelectItem>,<Select><option>,High,https://ui.shadcn.com/docs/components/select
|
||||||
|
22,Command,Use Command for search,Command component for searchable lists and palettes,Command for command palette search,Input with custom dropdown,<Command><CommandInput><CommandList>,<Input><div className="dropdown">,Medium,https://ui.shadcn.com/docs/components/command
|
||||||
|
23,Command,Group command items,Use CommandGroup for categorized items,CommandGroup with heading for sections,Flat list without grouping,<CommandGroup heading="Suggestions"><CommandItem>,<CommandItem> without groups,Low,https://ui.shadcn.com/docs/components/command
|
||||||
|
24,Table,Use Table for data display,Table component for structured data,Table for tabular data display,Div grid for table-like layouts,<Table><TableHeader><TableBody><TableRow>,<div className="grid">,Medium,https://ui.shadcn.com/docs/components/table
|
||||||
|
25,Table,Include proper table structure,Use TableHeader TableBody TableRow TableCell,Semantic table structure,Missing thead or tbody,<TableHeader><TableRow><TableHead>,<Table><TableRow> without header,High,https://ui.shadcn.com/docs/components/table
|
||||||
|
26,DataTable,Use DataTable for complex tables,Combine Table with TanStack Table for features,DataTable pattern for sorting filtering pagination,Custom table implementation,useReactTable + Table components,Custom sort filter pagination logic,Medium,https://ui.shadcn.com/docs/components/data-table
|
||||||
|
27,Tabs,Use Tabs for content switching,Tabs component for tabbed interfaces,Tabs for related content sections,Custom tab implementation,<Tabs><TabsList><TabsTrigger><TabsContent>,<div onClick={() => setTab(...)},Medium,https://ui.shadcn.com/docs/components/tabs
|
||||||
|
28,Tabs,Set default tab value,Specify defaultValue for initial tab,defaultValue on Tabs component,No default leaving first tab,<Tabs defaultValue="account">,<Tabs> without defaultValue,Low,https://ui.shadcn.com/docs/components/tabs
|
||||||
|
29,Accordion,Use Accordion for collapsible,Accordion for expandable content sections,Accordion for FAQ settings panels,Custom collapse implementation,<Accordion><AccordionItem><AccordionTrigger>,<div onClick={() => setOpen(!open)}>,Medium,https://ui.shadcn.com/docs/components/accordion
|
||||||
|
30,Accordion,Choose accordion type,Use type="single" or type="multiple" appropriately,type="single" for one open type="multiple" for many,Default type without consideration,<Accordion type="single" collapsible>,<Accordion> without type,Low,https://ui.shadcn.com/docs/components/accordion
|
||||||
|
31,Toast,Use Sonner for toasts,Sonner integration for toast notifications,toast() from sonner for notifications,Custom toast implementation,toast("Event created"),setShowToast(true),Medium,https://ui.shadcn.com/docs/components/sonner
|
||||||
|
32,Toast,Add Toaster to layout,Include Toaster component in root layout,<Toaster /> in app layout,Toaster in individual pages,app/layout.tsx: <Toaster />,page.tsx: <Toaster />,High,https://ui.shadcn.com/docs/components/sonner
|
||||||
|
33,Toast,Use toast variants,Apply toast.success toast.error for context,Semantic toast methods,Generic toast for all messages,toast.success("Saved!") toast.error("Failed"),toast("Saved!") toast("Failed"),Medium,https://ui.shadcn.com/docs/components/sonner
|
||||||
|
34,Popover,Use Popover for floating content,Popover for dropdown menus and floating panels,Popover for contextual actions,Absolute positioned divs,<Popover><PopoverTrigger><PopoverContent>,<div className="relative"><div className="absolute">,Medium,https://ui.shadcn.com/docs/components/popover
|
||||||
|
35,Popover,Handle popover alignment,Use align and side props for positioning,Explicit alignment configuration,Default alignment for all,<PopoverContent align="start" side="bottom">,<PopoverContent>,Low,https://ui.shadcn.com/docs/components/popover
|
||||||
|
36,DropdownMenu,Use DropdownMenu for actions,DropdownMenu for action lists and context menus,DropdownMenu for user menu actions,Popover for action lists,<DropdownMenu><DropdownMenuTrigger><DropdownMenuContent>,<Popover> for menu actions,Medium,https://ui.shadcn.com/docs/components/dropdown-menu
|
||||||
|
37,DropdownMenu,Group menu items,Use DropdownMenuGroup and DropdownMenuSeparator,Organized menu with separators,Flat list of items,<DropdownMenuGroup><DropdownMenuItem><DropdownMenuSeparator>,<DropdownMenuItem> without organization,Low,https://ui.shadcn.com/docs/components/dropdown-menu
|
||||||
|
38,Tooltip,Use Tooltip for hints,Tooltip for icon buttons and truncated text,Tooltip for additional context,Title attribute for tooltips,<Tooltip><TooltipTrigger><TooltipContent>,<button title="Delete">,Medium,https://ui.shadcn.com/docs/components/tooltip
|
||||||
|
39,Tooltip,Add TooltipProvider,Wrap app or section in TooltipProvider,TooltipProvider at app level,TooltipProvider per tooltip,<TooltipProvider><App/></TooltipProvider>,<Tooltip><TooltipProvider>,High,https://ui.shadcn.com/docs/components/tooltip
|
||||||
|
40,Skeleton,Use Skeleton for loading,Skeleton component for loading placeholders,Skeleton matching content layout,Spinner for content loading,<Skeleton className="h-4 w-[200px]"/>,<Spinner/> for card loading,Medium,https://ui.shadcn.com/docs/components/skeleton
|
||||||
|
41,Skeleton,Match skeleton dimensions,Size skeleton to match loaded content,Skeleton same size as expected content,Generic skeleton size,<Skeleton className="h-12 w-12 rounded-full"/>,<Skeleton/> without sizing,Medium,https://ui.shadcn.com/docs/components/skeleton
|
||||||
|
42,AlertDialog,Use AlertDialog for confirms,AlertDialog for destructive action confirmation,AlertDialog for delete confirmations,Dialog for confirmations,<AlertDialog><AlertDialogTrigger><AlertDialogContent>,<Dialog> for delete confirmation,High,https://ui.shadcn.com/docs/components/alert-dialog
|
||||||
|
43,AlertDialog,Include action buttons,Use AlertDialogAction and AlertDialogCancel,Standard confirm/cancel pattern,Custom buttons in AlertDialog,<AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction>,<Button>Cancel</Button><Button>Confirm</Button>,Medium,https://ui.shadcn.com/docs/components/alert-dialog
|
||||||
|
44,Sidebar,Use Sidebar for navigation,Sidebar component for app navigation,Sidebar for main app navigation,Custom sidebar implementation,<SidebarProvider><Sidebar><SidebarContent>,<div className="w-64 fixed">,Medium,https://ui.shadcn.com/docs/components/sidebar
|
||||||
|
45,Sidebar,Wrap in SidebarProvider,Use SidebarProvider for sidebar state management,SidebarProvider at layout level,Sidebar without provider,<SidebarProvider><Sidebar></SidebarProvider>,<Sidebar> without provider,High,https://ui.shadcn.com/docs/components/sidebar
|
||||||
|
46,Sidebar,Use SidebarTrigger,Include SidebarTrigger for mobile toggle,SidebarTrigger for responsive toggle,Custom toggle button,<SidebarTrigger/>,<Button onClick={() => toggleSidebar()}>,Medium,https://ui.shadcn.com/docs/components/sidebar
|
||||||
|
47,Chart,Use Chart for data viz,Chart component with Recharts integration,Chart component for dashboards,Direct Recharts without wrapper,<ChartContainer config={chartConfig}>,<ResponsiveContainer><BarChart>,Medium,https://ui.shadcn.com/docs/components/chart
|
||||||
|
48,Chart,Define chart config,Create chartConfig for consistent theming,chartConfig with color definitions,Inline colors in charts,"{ desktop: { label: ""Desktop"", color: ""#2563eb"" } }",<Bar fill="#2563eb"/>,Medium,https://ui.shadcn.com/docs/components/chart
|
||||||
|
49,Chart,Use ChartTooltip,Apply ChartTooltip for interactive charts,ChartTooltip with ChartTooltipContent,Recharts Tooltip directly,<ChartTooltip content={<ChartTooltipContent/>}/>,<Tooltip/> from recharts,Low,https://ui.shadcn.com/docs/components/chart
|
||||||
|
50,Blocks,Use blocks for scaffolding,Start from shadcn blocks for common layouts,npx shadcn@latest add dashboard-01,Build dashboard from scratch,npx shadcn@latest add login-01,Custom login page from scratch,Medium,https://ui.shadcn.com/blocks
|
||||||
|
51,Blocks,Customize block components,Modify copied block code to fit needs,Edit block files after installation,Use blocks without modification,Customize dashboard-01 layout,Use dashboard-01 as-is,Low,https://ui.shadcn.com/blocks
|
||||||
|
52,A11y,Use semantic components,Shadcn components have built-in ARIA,Rely on component accessibility,Override ARIA attributes,<Button> has button role,<div role="button">,High,https://ui.shadcn.com/docs/components/button
|
||||||
|
53,A11y,Maintain focus management,Dialog Sheet handle focus automatically,Let components manage focus,Custom focus handling,<Dialog> traps focus,document.querySelector().focus(),High,https://ui.shadcn.com/docs/components/dialog
|
||||||
|
54,A11y,Provide labels,Use FormLabel and aria-label appropriately,FormLabel for form inputs,Placeholder as only label,<FormLabel>Email</FormLabel><Input/>,<Input placeholder="Email"/>,High,https://ui.shadcn.com/docs/components/form
|
||||||
|
55,Performance,Import components individually,Import only needed components,Named imports from component files,Import all from index,import { Button } from "@/components/ui/button",import { Button Card Dialog } from "@/components/ui",Medium,
|
||||||
|
56,Performance,Lazy load dialogs,Dynamic import for heavy dialog content,React.lazy for dialog content,Import all dialogs upfront,const HeavyContent = lazy(() => import('./Heavy')),import HeavyContent from './Heavy',Medium,
|
||||||
|
57,Customization,Extend variants with cva,Add new variants using class-variance-authority,Extend buttonVariants for new styles,Inline classes for variants,"variants: { size: { xl: ""h-14 px-8"" } }",className="h-14 px-8",Medium,https://ui.shadcn.com/docs/components/button
|
||||||
|
58,Customization,Create custom components,Build new components following shadcn patterns,Use cn() and cva for custom components,Different patterns for custom,const Custom = ({ className }) => <div className={cn("base" className)}>,const Custom = ({ style }) => <div style={style}>,Medium,
|
||||||
|
59,Patterns,Use asChild for composition,asChild prop for component composition,Slot pattern with asChild,Wrapper divs for composition,<Button asChild><Link href="/">,<Button><Link href="/"></Link></Button>,Medium,https://ui.shadcn.com/docs/components/button
|
||||||
|
60,Patterns,Combine with React Hook Form,Form + useForm for complete forms,RHF Controller with shadcn inputs,Custom form state management,<FormField control={form.control} name="email">,<Input value={email} onChange={(e) => setEmail(e.target.value)},High,https://ui.shadcn.com/docs/components/form
|
||||||
|
Can't render this file because it contains an unexpected character in line 4 and column 188.
|
@@ -0,0 +1,54 @@
|
|||||||
|
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
|
||||||
|
1,Reactivity,Use $: for reactive statements,Automatic dependency tracking,$: for derived values,Manual recalculation,$: doubled = count * 2,let doubled; count && (doubled = count * 2),Medium,https://svelte.dev/docs/svelte-components#script-3-$-marks-a-statement-as-reactive
|
||||||
|
2,Reactivity,Trigger reactivity with assignment,Svelte tracks assignments not mutations,Reassign arrays/objects to trigger update,Mutate without reassignment,"items = [...items, newItem]",items.push(newItem),High,https://svelte.dev/docs/svelte-components#script-2-assignments-are-reactive
|
||||||
|
3,Reactivity,Use $state in Svelte 5,Runes for explicit reactivity,let count = $state(0),Implicit reactivity in Svelte 5,let count = $state(0),let count = 0 (Svelte 5),Medium,https://svelte.dev/blog/runes
|
||||||
|
4,Reactivity,Use $derived for computed values,$derived replaces $: in Svelte 5,let doubled = $derived(count * 2),$: in Svelte 5,let doubled = $derived(count * 2),$: doubled = count * 2 (Svelte 5),Medium,
|
||||||
|
5,Reactivity,Use $effect for side effects,$effect replaces $: side effects,Use $effect for subscriptions,$: for side effects in Svelte 5,$effect(() => console.log(count)),$: console.log(count) (Svelte 5),Medium,
|
||||||
|
6,Props,Export let for props,Declare props with export let,export let propName,Props without export,export let count = 0,let count = 0,High,https://svelte.dev/docs/svelte-components#script-1-export-creates-a-component-prop
|
||||||
|
7,Props,Use $props in Svelte 5,$props rune for prop access,let { name } = $props(),export let in Svelte 5,"let { name, age = 0 } = $props()",export let name; export let age = 0,Medium,
|
||||||
|
8,Props,Provide default values,Default props with assignment,export let count = 0,Required props without defaults,export let count = 0,export let count,Low,
|
||||||
|
9,Props,Use spread props,Pass through unknown props,{...$$restProps} on elements,Manual prop forwarding,<button {...$$restProps}>,<button class={$$props.class}>,Low,https://svelte.dev/docs/basic-markup#attributes-and-props
|
||||||
|
10,Bindings,Use bind: for two-way binding,Simplified input handling,bind:value for inputs,on:input with manual update,<input bind:value={name}>,<input value={name} on:input={e => name = e.target.value}>,Low,https://svelte.dev/docs/element-directives#bind-property
|
||||||
|
11,Bindings,Bind to DOM elements,Reference DOM nodes,bind:this for element reference,querySelector in onMount,<div bind:this={el}>,onMount(() => el = document.querySelector()),Medium,
|
||||||
|
12,Bindings,Use bind:group for radios/checkboxes,Simplified group handling,bind:group for radio/checkbox groups,Manual checked handling,"<input type=""radio"" bind:group={selected}>","<input type=""radio"" checked={selected === value}>",Low,
|
||||||
|
13,Events,Use on: for event handlers,Event directive syntax,on:click={handler},addEventListener in onMount,<button on:click={handleClick}>,onMount(() => btn.addEventListener()),Medium,https://svelte.dev/docs/element-directives#on-eventname
|
||||||
|
14,Events,Forward events with on:event,Pass events to parent,on:click without handler,createEventDispatcher for DOM events,<button on:click>,"dispatch('click', event)",Low,
|
||||||
|
15,Events,Use createEventDispatcher,Custom component events,dispatch for custom events,on:event for custom events,"dispatch('save', { data })",on:save without dispatch,Medium,https://svelte.dev/docs/svelte#createeventdispatcher
|
||||||
|
16,Lifecycle,Use onMount for initialization,Run code after component mounts,onMount for setup and data fetching,Code in script body for side effects,onMount(() => fetchData()),fetchData() in script body,High,https://svelte.dev/docs/svelte#onmount
|
||||||
|
17,Lifecycle,Return cleanup from onMount,Automatic cleanup on destroy,Return function from onMount,Separate onDestroy for paired cleanup,onMount(() => { sub(); return unsub }),onMount(sub); onDestroy(unsub),Medium,
|
||||||
|
18,Lifecycle,Use onDestroy sparingly,Only when onMount cleanup not possible,onDestroy for non-mount cleanup,onDestroy for mount-related cleanup,onDestroy for store unsubscribe,onDestroy(() => clearInterval(id)),Low,
|
||||||
|
19,Lifecycle,Avoid beforeUpdate/afterUpdate,Usually not needed,Reactive statements instead,beforeUpdate for derived state,$: if (x) doSomething(),beforeUpdate(() => doSomething()),Low,
|
||||||
|
20,Stores,Use writable for mutable state,Basic reactive store,writable for shared mutable state,Local variables for shared state,const count = writable(0),let count = 0 in module,Medium,https://svelte.dev/docs/svelte-store#writable
|
||||||
|
21,Stores,Use readable for read-only state,External data sources,readable for derived/external data,writable for read-only data,"readable(0, set => interval(set))",writable(0) for timer,Low,https://svelte.dev/docs/svelte-store#readable
|
||||||
|
22,Stores,Use derived for computed stores,Combine or transform stores,derived for computed values,Manual subscription for derived,"derived(count, $c => $c * 2)",count.subscribe(c => doubled = c * 2),Medium,https://svelte.dev/docs/svelte-store#derived
|
||||||
|
23,Stores,Use $ prefix for auto-subscription,Automatic subscribe/unsubscribe,$storeName in components,Manual subscription,{$count},count.subscribe(c => value = c),High,
|
||||||
|
24,Stores,Clean up custom subscriptions,Unsubscribe when component destroys,Return unsubscribe from onMount,Leave subscriptions open,onMount(() => store.subscribe(fn)),store.subscribe(fn) in script,High,
|
||||||
|
25,Slots,Use slots for composition,Content projection,<slot> for flexible content,Props for all content,<slot>Default</slot>,"<Component content=""text""/>",Medium,https://svelte.dev/docs/special-elements#slot
|
||||||
|
26,Slots,Name slots for multiple areas,Multiple content areas,"<slot name=""header"">",Single slot for complex layouts,"<slot name=""header""><slot name=""footer"">",<slot> with complex conditionals,Low,
|
||||||
|
27,Slots,Check slot content with $$slots,Conditional slot rendering,$$slots.name for conditional rendering,Always render slot wrapper,"{#if $$slots.footer}<slot name=""footer""/>{/if}","<div><slot name=""footer""/></div>",Low,
|
||||||
|
28,Styling,Use scoped styles by default,Styles scoped to component,<style> for component styles,Global styles for component,:global() only when needed,<style> all global,Medium,https://svelte.dev/docs/svelte-components#style
|
||||||
|
29,Styling,Use :global() sparingly,Escape scoping when needed,:global for third-party styling,Global for all styles,:global(.external-lib),<style> without scoping,Medium,
|
||||||
|
30,Styling,Use CSS variables for theming,Dynamic styling,CSS custom properties,Inline styles for themes,"style=""--color: {color}""","style=""color: {color}""",Low,
|
||||||
|
31,Transitions,Use built-in transitions,Svelte transition directives,transition:fade for simple effects,Manual CSS transitions,<div transition:fade>,<div class:fade={visible}>,Low,https://svelte.dev/docs/element-directives#transition-fn
|
||||||
|
32,Transitions,Use in: and out: separately,Different enter/exit animations,in:fly out:fade for asymmetric,Same transition for both,<div in:fly out:fade>,<div transition:fly>,Low,
|
||||||
|
33,Transitions,Add local modifier,Prevent ancestor trigger,transition:fade|local,Global transitions for lists,<div transition:slide|local>,<div transition:slide>,Medium,
|
||||||
|
34,Actions,Use actions for DOM behavior,Reusable DOM logic,use:action for DOM enhancements,onMount for each usage,<div use:clickOutside>,onMount(() => setupClickOutside(el)),Medium,https://svelte.dev/docs/element-directives#use-action
|
||||||
|
35,Actions,Return update and destroy,Lifecycle methods for actions,"Return { update, destroy }",Only initial setup,"return { update(params) {}, destroy() {} }",return destroy only,Medium,
|
||||||
|
36,Actions,Pass parameters to actions,Configure action behavior,use:action={params},Hardcoded action behavior,<div use:tooltip={options}>,<div use:tooltip>,Low,
|
||||||
|
37,Logic,Use {#if} for conditionals,Template conditionals,{#if} {:else if} {:else},Ternary in expressions,{#if cond}...{:else}...{/if},{cond ? a : b} for complex,Low,https://svelte.dev/docs/logic-blocks#if
|
||||||
|
38,Logic,Use {#each} for lists,List rendering,{#each} with key,Map in expression,{#each items as item (item.id)},{items.map(i => `<div>${i}</div>`)},Medium,
|
||||||
|
39,Logic,Always use keys in {#each},Proper list reconciliation,(item.id) for unique key,Index as key or no key,{#each items as item (item.id)},"{#each items as item, i (i)}",High,
|
||||||
|
40,Logic,Use {#await} for promises,Handle async states,{#await} for loading/error states,Manual promise handling,{#await promise}...{:then}...{:catch},{#if loading}...{#if error},Medium,https://svelte.dev/docs/logic-blocks#await
|
||||||
|
41,SvelteKit,Use +page.svelte for routes,File-based routing,+page.svelte for route components,Custom routing setup,routes/about/+page.svelte,routes/About.svelte,Medium,https://kit.svelte.dev/docs/routing
|
||||||
|
42,SvelteKit,Use +page.js for data loading,Load data before render,load function in +page.js,onMount for data fetching,export function load() {},onMount(() => fetchData()),High,https://kit.svelte.dev/docs/load
|
||||||
|
43,SvelteKit,Use +page.server.js for server-only,Server-side data loading,+page.server.js for sensitive data,+page.js for API keys,+page.server.js with DB access,+page.js with DB access,High,
|
||||||
|
44,SvelteKit,Use form actions,Server-side form handling,+page.server.js actions,API routes for forms,export const actions = { default },fetch('/api/submit'),Medium,https://kit.svelte.dev/docs/form-actions
|
||||||
|
45,SvelteKit,Use $app/stores for app state,$page $navigating $updated,$page for current page data,Manual URL parsing,import { page } from '$app/stores',window.location.pathname,Medium,https://kit.svelte.dev/docs/modules#$app-stores
|
||||||
|
46,Performance,Use {#key} for forced re-render,Reset component state,{#key id} for fresh instance,Manual destroy/create,{#key item.id}<Component/>{/key},on:change={() => component = null},Low,https://svelte.dev/docs/logic-blocks#key
|
||||||
|
47,Performance,Avoid unnecessary reactivity,Not everything needs $:,$: only for side effects,$: for simple assignments,$: if (x) console.log(x),$: y = x (when y = x works),Low,
|
||||||
|
48,Performance,Use immutable compiler option,Skip equality checks,immutable: true for large lists,Default for all components,<svelte:options immutable/>,Default without immutable,Low,
|
||||||
|
49,TypeScript,"Use lang=""ts"" in script",TypeScript support,"<script lang=""ts"">",JavaScript for typed projects,"<script lang=""ts"">",<script> with JSDoc,Medium,https://svelte.dev/docs/typescript
|
||||||
|
50,TypeScript,Type props with interface,Explicit prop types,interface $$Props for types,Untyped props,interface $$Props { name: string },export let name,Medium,
|
||||||
|
51,TypeScript,Type events with createEventDispatcher,Type-safe events,createEventDispatcher<Events>(),Untyped dispatch,createEventDispatcher<{ save: Data }>(),createEventDispatcher(),Medium,
|
||||||
|
52,Accessibility,Use semantic elements,Proper HTML in templates,button nav main appropriately,div for everything,<button on:click>,<div on:click>,High,
|
||||||
|
53,Accessibility,Add aria to dynamic content,Accessible state changes,aria-live for updates,Silent dynamic updates,"<div aria-live=""polite"">{message}</div>",<div>{message}</div>,Medium,
|
||||||
|
@@ -0,0 +1,51 @@
|
|||||||
|
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
|
||||||
|
1,Views,Use struct for views,SwiftUI views are value types,struct MyView: View,class MyView: View,struct ContentView: View { var body: some View },class ContentView: View,High,https://developer.apple.com/documentation/swiftui/view
|
||||||
|
2,Views,Keep views small and focused,Single responsibility for each view,Extract subviews for complex layouts,Large monolithic views,Extract HeaderView FooterView,500+ line View struct,Medium,
|
||||||
|
3,Views,Use body computed property,body returns the view hierarchy,var body: some View { },func body() -> some View,"var body: some View { Text(""Hello"") }",func body() -> Text,High,
|
||||||
|
4,Views,Prefer composition over inheritance,Compose views using ViewBuilder,Combine smaller views,Inheritance hierarchies,VStack { Header() Content() },class SpecialView extends BaseView,Medium,
|
||||||
|
5,State,Use @State for local state,Simple value types owned by view,@State for view-local primitives,@State for shared data,@State private var count = 0,@State var sharedData: Model,High,https://developer.apple.com/documentation/swiftui/state
|
||||||
|
6,State,Use @Binding for two-way data,Pass mutable state to child views,@Binding for child input,@State in child for parent data,@Binding var isOn: Bool,$isOn to pass binding,Medium,https://developer.apple.com/documentation/swiftui/binding
|
||||||
|
7,State,Use @StateObject for reference types,ObservableObject owned by view,@StateObject for view-created objects,@ObservedObject for owned objects,@StateObject private var vm = ViewModel(),@ObservedObject var vm = ViewModel(),High,https://developer.apple.com/documentation/swiftui/stateobject
|
||||||
|
8,State,Use @ObservedObject for injected objects,Reference types passed from parent,@ObservedObject for injected dependencies,@StateObject for injected objects,@ObservedObject var vm: ViewModel,@StateObject var vm: ViewModel (injected),High,https://developer.apple.com/documentation/swiftui/observedobject
|
||||||
|
9,State,Use @EnvironmentObject for shared state,App-wide state injection,@EnvironmentObject for global state,Prop drilling through views,@EnvironmentObject var settings: Settings,Pass settings through 5 views,Medium,https://developer.apple.com/documentation/swiftui/environmentobject
|
||||||
|
10,State,Use @Published in ObservableObject,Automatically publish property changes,@Published for observed properties,Manual objectWillChange calls,@Published var items: [Item] = [],var items: [Item] { didSet { objectWillChange.send() } },Medium,
|
||||||
|
11,Observable,Use @Observable macro (iOS 17+),Modern observation without Combine,@Observable class for view models,ObservableObject for new projects,@Observable class ViewModel { },class ViewModel: ObservableObject,Medium,https://developer.apple.com/documentation/observation
|
||||||
|
12,Observable,Use @Bindable for @Observable,Create bindings from @Observable,@Bindable var vm for bindings,@Binding with @Observable,@Bindable var viewModel,$viewModel.name with @Observable,Medium,
|
||||||
|
13,Layout,Use VStack HStack ZStack,Standard stack-based layouts,Stacks for linear arrangements,GeometryReader for simple layouts,VStack { Text() Image() },GeometryReader for vertical list,Medium,https://developer.apple.com/documentation/swiftui/vstack
|
||||||
|
14,Layout,Use LazyVStack LazyHStack for lists,Lazy loading for performance,Lazy stacks for long lists,Regular stacks for 100+ items,LazyVStack { ForEach(items) },VStack { ForEach(largeArray) },High,https://developer.apple.com/documentation/swiftui/lazyvstack
|
||||||
|
15,Layout,Use GeometryReader sparingly,Only when needed for sizing,GeometryReader for responsive layouts,GeometryReader everywhere,GeometryReader for aspect ratio,GeometryReader wrapping everything,Medium,
|
||||||
|
16,Layout,Use spacing and padding consistently,Consistent spacing throughout app,Design system spacing values,Magic numbers for spacing,.padding(16) or .padding(),".padding(13), .padding(17)",Low,
|
||||||
|
17,Layout,Use frame modifiers correctly,Set explicit sizes when needed,.frame(maxWidth: .infinity),Fixed sizes for responsive content,.frame(maxWidth: .infinity),.frame(width: 375),Medium,
|
||||||
|
18,Modifiers,Order modifiers correctly,Modifier order affects rendering,Background before padding for full coverage,Wrong modifier order,.padding().background(Color.red),.background(Color.red).padding(),High,
|
||||||
|
19,Modifiers,Create custom ViewModifiers,Reusable modifier combinations,ViewModifier for repeated styling,Duplicate modifier chains,struct CardStyle: ViewModifier,.shadow().cornerRadius() everywhere,Medium,https://developer.apple.com/documentation/swiftui/viewmodifier
|
||||||
|
20,Modifiers,Use conditional modifiers carefully,Avoid changing view identity,if-else with same view type,Conditional that changes view identity,Text(title).foregroundColor(isActive ? .blue : .gray),if isActive { Text().bold() } else { Text() },Medium,
|
||||||
|
21,Navigation,Use NavigationStack (iOS 16+),Modern navigation with type-safe paths,NavigationStack with navigationDestination,NavigationView for new projects,NavigationStack { },NavigationView { } (deprecated),Medium,https://developer.apple.com/documentation/swiftui/navigationstack
|
||||||
|
22,Navigation,Use navigationDestination,Type-safe navigation destinations,.navigationDestination(for:),NavigationLink(destination:),.navigationDestination(for: Item.self),NavigationLink(destination: DetailView()),Medium,
|
||||||
|
23,Navigation,Use @Environment for dismiss,Programmatic navigation dismissal,@Environment(\.dismiss) var dismiss,presentationMode (deprecated),@Environment(\.dismiss) var dismiss,@Environment(\.presentationMode),Low,
|
||||||
|
24,Lists,Use List for scrollable content,Built-in scrolling and styling,List for standard scrollable content,ScrollView + VStack for simple lists,List { ForEach(items) { } },ScrollView { VStack { ForEach } },Low,https://developer.apple.com/documentation/swiftui/list
|
||||||
|
25,Lists,Provide stable identifiers,Use Identifiable or explicit id,Identifiable protocol or id parameter,Index as identifier,ForEach(items) where Item: Identifiable,"ForEach(items.indices, id: \.self)",High,
|
||||||
|
26,Lists,Use onDelete and onMove,Standard list editing,onDelete for swipe to delete,Custom delete implementation,.onDelete(perform: delete),.onTapGesture for delete,Low,
|
||||||
|
27,Forms,Use Form for settings,Grouped input controls,Form for settings screens,Manual grouping for forms,Form { Section { Toggle() } },VStack { Toggle() },Low,https://developer.apple.com/documentation/swiftui/form
|
||||||
|
28,Forms,Use @FocusState for keyboard,Manage keyboard focus,@FocusState for text field focus,Manual first responder handling,@FocusState private var isFocused: Bool,UIKit first responder,Medium,https://developer.apple.com/documentation/swiftui/focusstate
|
||||||
|
29,Forms,Validate input properly,Show validation feedback,Real-time validation feedback,Submit without validation,TextField with validation state,TextField without error handling,Medium,
|
||||||
|
30,Async,Use .task for async work,Automatic cancellation on view disappear,.task for view lifecycle async,onAppear with Task,.task { await loadData() },onAppear { Task { await loadData() } },Medium,https://developer.apple.com/documentation/swiftui/view/task(priority:_:)
|
||||||
|
31,Async,Handle loading states,Show progress during async operations,ProgressView during loading,Empty view during load,if isLoading { ProgressView() },No loading indicator,Medium,
|
||||||
|
32,Async,Use @MainActor for UI updates,Ensure UI updates on main thread,@MainActor on view models,Manual DispatchQueue.main,@MainActor class ViewModel,DispatchQueue.main.async,Medium,
|
||||||
|
33,Animation,Use withAnimation,Animate state changes,withAnimation for state transitions,No animation for state changes,withAnimation { isExpanded.toggle() },isExpanded.toggle(),Low,https://developer.apple.com/documentation/swiftui/withanimation(_:_:)
|
||||||
|
34,Animation,Use .animation modifier,Apply animations to views,.animation(.spring()) on view,Manual animation timing,.animation(.easeInOut),CABasicAnimation equivalent,Low,
|
||||||
|
35,Animation,Respect reduced motion,Check accessibility settings,Check accessibilityReduceMotion,Ignore motion preferences,@Environment(\.accessibilityReduceMotion),Always animate regardless,High,
|
||||||
|
36,Preview,Use #Preview macro (Xcode 15+),Modern preview syntax,#Preview for view previews,PreviewProvider protocol,#Preview { ContentView() },struct ContentView_Previews: PreviewProvider,Low,
|
||||||
|
37,Preview,Create multiple previews,Test different states and devices,Multiple previews for states,Single preview only,"#Preview(""Light"") { } #Preview(""Dark"") { }",Single preview configuration,Low,
|
||||||
|
38,Preview,Use preview data,Dedicated preview mock data,Static preview data,Production data in previews,Item.preview for preview,Fetch real data in preview,Low,
|
||||||
|
39,Performance,Avoid expensive body computations,Body should be fast to compute,Precompute in view model,Heavy computation in body,vm.computedValue in body,Complex calculation in body,High,
|
||||||
|
40,Performance,Use Equatable views,Skip unnecessary view updates,Equatable for complex views,Default equality for all views,struct MyView: View Equatable,No Equatable conformance,Medium,
|
||||||
|
41,Performance,Profile with Instruments,Measure before optimizing,Use SwiftUI Instruments,Guess at performance issues,Profile with Instruments,Optimize without measuring,Medium,
|
||||||
|
42,Accessibility,Add accessibility labels,Describe UI elements,.accessibilityLabel for context,Missing labels,".accessibilityLabel(""Close button"")",Button without label,High,https://developer.apple.com/documentation/swiftui/view/accessibilitylabel(_:)-1d7jv
|
||||||
|
43,Accessibility,Support Dynamic Type,Respect text size preferences,Scalable fonts and layouts,Fixed font sizes,.font(.body) with Dynamic Type,.font(.system(size: 16)),High,
|
||||||
|
44,Accessibility,Use semantic views,Proper accessibility traits,Correct accessibilityTraits,Wrong semantic meaning,Button for actions Image for display,Image that acts like button,Medium,
|
||||||
|
45,Testing,Use ViewInspector for testing,Third-party view testing,ViewInspector for unit tests,UI tests only,ViewInspector assertions,Only XCUITest,Medium,
|
||||||
|
46,Testing,Test view models,Unit test business logic,XCTest for view model,Skip view model testing,Test ViewModel methods,No unit tests,Medium,
|
||||||
|
47,Testing,Use preview as visual test,Previews catch visual regressions,Multiple preview configurations,No visual verification,Preview different states,Single preview only,Low,
|
||||||
|
48,Architecture,Use MVVM pattern,Separate view and logic,ViewModel for business logic,Logic in View,ObservableObject ViewModel,@State for complex logic,Medium,
|
||||||
|
49,Architecture,Keep views dumb,Views display view model state,View reads from ViewModel,Business logic in View,view.items from vm.items,Complex filtering in View,Medium,
|
||||||
|
50,Architecture,Use dependency injection,Inject dependencies for testing,Initialize with dependencies,Hard-coded dependencies,init(service: ServiceProtocol),let service = RealService(),Medium,
|
||||||
|
@@ -0,0 +1,50 @@
|
|||||||
|
No,Category,Guideline,Description,Do,Don't,Code Good,Code Bad,Severity,Docs URL
|
||||||
|
1,Composition,Use Composition API for new projects,Composition API offers better TypeScript support and logic reuse,<script setup> for components,Options API for new projects,<script setup>,export default { data() },Medium,https://vuejs.org/guide/extras/composition-api-faq.html
|
||||||
|
2,Composition,Use script setup syntax,Cleaner syntax with automatic exports,<script setup> with defineProps,setup() function manually,<script setup>,<script> setup() { return {} },Low,https://vuejs.org/api/sfc-script-setup.html
|
||||||
|
3,Reactivity,Use ref for primitives,ref() for primitive values that need reactivity,ref() for strings numbers booleans,reactive() for primitives,const count = ref(0),const count = reactive(0),Medium,https://vuejs.org/guide/essentials/reactivity-fundamentals.html
|
||||||
|
4,Reactivity,Use reactive for objects,reactive() for complex objects and arrays,reactive() for objects with multiple properties,ref() for complex objects,const state = reactive({ user: null }),const state = ref({ user: null }),Medium,
|
||||||
|
5,Reactivity,Access ref values with .value,Remember .value in script unwrap in template,Use .value in script,Forget .value in script,count.value++,count++ (in script),High,
|
||||||
|
6,Reactivity,Use computed for derived state,Computed properties cache and update automatically,computed() for derived values,Methods for derived values,const doubled = computed(() => count.value * 2),const doubled = () => count.value * 2,Medium,https://vuejs.org/guide/essentials/computed.html
|
||||||
|
7,Reactivity,Use shallowRef for large objects,Avoid deep reactivity for performance,shallowRef for large data structures,ref for large nested objects,const bigData = shallowRef(largeObject),const bigData = ref(largeObject),Medium,https://vuejs.org/api/reactivity-advanced.html#shallowref
|
||||||
|
8,Watchers,Use watchEffect for simple cases,Auto-tracks dependencies,watchEffect for simple reactive effects,watch with explicit deps when not needed,watchEffect(() => console.log(count.value)),"watch(count, (val) => console.log(val))",Low,https://vuejs.org/guide/essentials/watchers.html
|
||||||
|
9,Watchers,Use watch for specific sources,Explicit control over what to watch,watch with specific refs,watchEffect for complex conditional logic,"watch(userId, fetchUser)",watchEffect with conditionals,Medium,
|
||||||
|
10,Watchers,Clean up side effects,Return cleanup function in watchers,Return cleanup in watchEffect,Leave subscriptions open,watchEffect((onCleanup) => { onCleanup(unsub) }),watchEffect without cleanup,High,
|
||||||
|
11,Props,Define props with defineProps,Type-safe prop definitions,defineProps with TypeScript,Props without types,defineProps<{ msg: string }>(),defineProps(['msg']),Medium,https://vuejs.org/guide/typescript/composition-api.html#typing-component-props
|
||||||
|
12,Props,Use withDefaults for default values,Provide defaults for optional props,withDefaults with defineProps,Defaults in destructuring,"withDefaults(defineProps<Props>(), { count: 0 })",const { count = 0 } = defineProps(),Medium,
|
||||||
|
13,Props,Avoid mutating props,Props should be read-only,Emit events to parent for changes,Direct prop mutation,"emit('update:modelValue', newVal)",props.modelValue = newVal,High,
|
||||||
|
14,Emits,Define emits with defineEmits,Type-safe event emissions,defineEmits with types,Emit without definition,defineEmits<{ change: [id: number] }>(),"emit('change', id) without define",Medium,https://vuejs.org/guide/typescript/composition-api.html#typing-component-emits
|
||||||
|
15,Emits,Use v-model for two-way binding,Simplified parent-child data flow,v-model with modelValue prop,:value + @input manually,"<Child v-model=""value""/>","<Child :value=""value"" @input=""value = $event""/>",Low,https://vuejs.org/guide/components/v-model.html
|
||||||
|
16,Lifecycle,Use onMounted for DOM access,DOM is ready in onMounted,onMounted for DOM operations,Access DOM in setup directly,onMounted(() => el.value.focus()),el.value.focus() in setup,High,https://vuejs.org/api/composition-api-lifecycle.html
|
||||||
|
17,Lifecycle,Clean up in onUnmounted,Remove listeners and subscriptions,onUnmounted for cleanup,Leave listeners attached,onUnmounted(() => window.removeEventListener()),No cleanup on unmount,High,
|
||||||
|
18,Lifecycle,Avoid onBeforeMount for data,Use onMounted or setup for data fetching,Fetch in onMounted or setup,Fetch in onBeforeMount,onMounted(async () => await fetchData()),onBeforeMount(async () => await fetchData()),Low,
|
||||||
|
19,Components,Use single-file components,Keep template script style together,.vue files for components,Separate template/script files,Component.vue with all parts,Component.js + Component.html,Low,
|
||||||
|
20,Components,Use PascalCase for components,Consistent component naming,PascalCase in imports and templates,kebab-case in script,<MyComponent/>,<my-component/>,Low,https://vuejs.org/style-guide/rules-strongly-recommended.html
|
||||||
|
21,Components,Prefer composition over mixins,Composables replace mixins,Composables for shared logic,Mixins for code reuse,const { data } = useApi(),mixins: [apiMixin],Medium,
|
||||||
|
22,Composables,Name composables with use prefix,Convention for composable functions,useFetch useAuth useForm,getData or fetchApi,export function useFetch(),export function fetchData(),Medium,https://vuejs.org/guide/reusability/composables.html
|
||||||
|
23,Composables,Return refs from composables,Maintain reactivity when destructuring,Return ref values,Return reactive objects that lose reactivity,return { data: ref(null) },return reactive({ data: null }),Medium,
|
||||||
|
24,Composables,Accept ref or value params,Use toValue for flexible inputs,toValue() or unref() for params,Only accept ref or only value,const val = toValue(maybeRef),const val = maybeRef.value,Low,https://vuejs.org/api/reactivity-utilities.html#tovalue
|
||||||
|
25,Templates,Use v-bind shorthand,Cleaner template syntax,:prop instead of v-bind:prop,Full v-bind syntax,"<div :class=""cls"">","<div v-bind:class=""cls"">",Low,
|
||||||
|
26,Templates,Use v-on shorthand,Cleaner event binding,@event instead of v-on:event,Full v-on syntax,"<button @click=""handler"">","<button v-on:click=""handler"">",Low,
|
||||||
|
27,Templates,Avoid v-if with v-for,v-if has higher priority causes issues,Wrap in template or computed filter,v-if on same element as v-for,<template v-for><div v-if>,<div v-for v-if>,High,https://vuejs.org/style-guide/rules-essential.html#avoid-v-if-with-v-for
|
||||||
|
28,Templates,Use key with v-for,Proper list rendering and updates,Unique key for each item,Index as key for dynamic lists,"v-for=""item in items"" :key=""item.id""","v-for=""(item, i) in items"" :key=""i""",High,
|
||||||
|
29,State,Use Pinia for global state,Official state management for Vue 3,Pinia stores for shared state,Vuex for new projects,const store = useCounterStore(),Vuex with mutations,Medium,https://pinia.vuejs.org/
|
||||||
|
30,State,Define stores with defineStore,Composition API style stores,Setup stores with defineStore,Options stores for complex state,"defineStore('counter', () => {})","defineStore('counter', { state })",Low,
|
||||||
|
31,State,Use storeToRefs for destructuring,Maintain reactivity when destructuring,storeToRefs(store),Direct destructuring,const { count } = storeToRefs(store),const { count } = store,High,https://pinia.vuejs.org/core-concepts/#destructuring-from-a-store
|
||||||
|
32,Routing,Use useRouter and useRoute,Composition API router access,useRouter() useRoute() in setup,this.$router this.$route,const router = useRouter(),this.$router.push(),Medium,https://router.vuejs.org/guide/advanced/composition-api.html
|
||||||
|
33,Routing,Lazy load route components,Code splitting for routes,() => import() for components,Static imports for all routes,component: () => import('./Page.vue'),component: Page,Medium,https://router.vuejs.org/guide/advanced/lazy-loading.html
|
||||||
|
34,Routing,Use navigation guards,Protect routes and handle redirects,beforeEach for auth checks,Check auth in each component,router.beforeEach((to) => {}),Check auth in onMounted,Medium,
|
||||||
|
35,Performance,Use v-once for static content,Skip re-renders for static elements,v-once on never-changing content,v-once on dynamic content,<div v-once>{{ staticText }}</div>,<div v-once>{{ dynamicText }}</div>,Low,https://vuejs.org/api/built-in-directives.html#v-once
|
||||||
|
36,Performance,Use v-memo for expensive lists,Memoize list items,v-memo with dependency array,Re-render entire list always,"<div v-for v-memo=""[item.id]"">",<div v-for> without memo,Medium,https://vuejs.org/api/built-in-directives.html#v-memo
|
||||||
|
37,Performance,Use shallowReactive for flat objects,Avoid deep reactivity overhead,shallowReactive for flat state,reactive for simple objects,shallowReactive({ count: 0 }),reactive({ count: 0 }),Low,
|
||||||
|
38,Performance,Use defineAsyncComponent,Lazy load heavy components,defineAsyncComponent for modals dialogs,Import all components eagerly,defineAsyncComponent(() => import()),import HeavyComponent from,Medium,https://vuejs.org/guide/components/async.html
|
||||||
|
39,TypeScript,Use generic components,Type-safe reusable components,Generic with defineComponent,Any types in components,"<script setup lang=""ts"" generic=""T"">",<script setup> without types,Medium,https://vuejs.org/guide/typescript/composition-api.html
|
||||||
|
40,TypeScript,Type template refs,Proper typing for DOM refs,ref<HTMLInputElement>(null),ref(null) without type,const input = ref<HTMLInputElement>(null),const input = ref(null),Medium,
|
||||||
|
41,TypeScript,Use PropType for complex props,Type complex prop types,PropType<User> for object props,Object without type,type: Object as PropType<User>,type: Object,Medium,
|
||||||
|
42,Testing,Use Vue Test Utils,Official testing library,mount shallowMount for components,Manual DOM testing,import { mount } from '@vue/test-utils',document.createElement,Medium,https://test-utils.vuejs.org/
|
||||||
|
43,Testing,Test component behavior,Focus on inputs and outputs,Test props emit and rendered output,Test internal implementation,expect(wrapper.text()).toContain(),expect(wrapper.vm.internalState),Medium,
|
||||||
|
44,Forms,Use v-model modifiers,Built-in input handling,.lazy .number .trim modifiers,Manual input parsing,"<input v-model.number=""age"">","<input v-model=""age""> then parse",Low,https://vuejs.org/guide/essentials/forms.html#modifiers
|
||||||
|
45,Forms,Use VeeValidate or FormKit,Form validation libraries,VeeValidate for complex forms,Manual validation logic,useField useForm from vee-validate,Custom validation in each input,Medium,
|
||||||
|
46,Accessibility,Use semantic elements,Proper HTML elements in templates,button nav main for purpose,div for everything,<button @click>,<div @click>,High,
|
||||||
|
47,Accessibility,Bind aria attributes dynamically,Keep ARIA in sync with state,":aria-expanded=""isOpen""",Static ARIA values,":aria-expanded=""menuOpen""","aria-expanded=""true""",Medium,
|
||||||
|
48,SSR,Use Nuxt for SSR,Full-featured SSR framework,Nuxt 3 for SSR apps,Manual SSR setup,npx nuxi init my-app,Custom SSR configuration,Medium,https://nuxt.com/
|
||||||
|
49,SSR,Handle hydration mismatches,Client/server content must match,ClientOnly for browser-only content,Different content server/client,<ClientOnly><BrowserWidget/></ClientOnly>,<div>{{ Date.now() }}</div>,High,
|
||||||
|
@@ -0,0 +1,68 @@
|
|||||||
|
No,Style Category,Type,Keywords,Primary Colors,Secondary Colors,Effects & Animation,Best For,Do Not Use For,Light Mode ✓,Dark Mode ✓,Performance,Accessibility,Mobile-Friendly,Conversion-Focused,Framework Compatibility,Era/Origin,Complexity,AI Prompt Keywords,CSS/Technical Keywords,Implementation Checklist,Design System Variables
|
||||||
|
1,Minimalism & Swiss Style,General,"Clean, simple, spacious, functional, white space, high contrast, geometric, sans-serif, grid-based, essential","Monochromatic, Black #000000, White #FFFFFF","Neutral (Beige #F5F1E8, Grey #808080, Taupe #B38B6D), Primary accent","Subtle hover (200-250ms), smooth transitions, sharp shadows if any, clear type hierarchy, fast loading","Enterprise apps, dashboards, documentation sites, SaaS platforms, professional tools","Creative portfolios, entertainment, playful brands, artistic experiments",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AAA,✓ High,◐ Medium,"Tailwind 10/10, Bootstrap 9/10, MUI 9/10",1950s Swiss,Low,"Design a minimalist landing page. Use: white space, geometric layouts, sans-serif fonts, high contrast, grid-based structure, essential elements only. Avoid shadows and gradients. Focus on clarity and functionality.","display: grid, gap: 2rem, font-family: sans-serif, color: #000 or #FFF, max-width: 1200px, clean borders, no box-shadow unless necessary","☐ Grid-based layout 12-16 columns, ☐ Typography hierarchy clear, ☐ No unnecessary decorations, ☐ WCAG AAA contrast verified, ☐ Mobile responsive grid","--spacing: 2rem, --border-radius: 0px, --font-weight: 400-700, --shadow: none, --accent-color: single primary only"
|
||||||
|
2,Neumorphism,General,"Soft UI, embossed, debossed, convex, concave, light source, subtle depth, rounded (12-16px), monochromatic","Light pastels: Soft Blue #C8E0F4, Soft Pink #F5E0E8, Soft Grey #E8E8E8","Tints/shades (±30%), gradient subtlety, color harmony","Soft box-shadow (multiple: -5px -5px 15px, 5px 5px 15px), smooth press (150ms), inner subtle shadow","Health/wellness apps, meditation platforms, fitness trackers, minimal interaction UIs","Complex apps, critical accessibility, data-heavy dashboards, high-contrast required",✓ Full,◐ Partial,⚡ Good,⚠ Low contrast,✓ Good,◐ Medium,"Tailwind 8/10, CSS-in-JS 9/10",2020s Modern,Medium,"Create a neumorphic UI with soft 3D effects. Use light pastels, rounded corners (12-16px), subtle soft shadows (multiple layers), no hard lines, monochromatic color scheme with light/dark variations. Embossed/debossed effect on interactive elements.","border-radius: 12-16px, box-shadow: -5px -5px 15px rgba(0,0,0,0.1), 5px 5px 15px rgba(255,255,255,0.8), background: linear-gradient(145deg, color1, color2), transform: scale on press","☐ Rounded corners 12-16px consistent, ☐ Multiple shadow layers (2-3), ☐ Pastel color verified, ☐ Monochromatic palette checked, ☐ Press animation smooth 150ms","--border-radius: 14px, --shadow-soft-1: -5px -5px 15px, --shadow-soft-2: 5px 5px 15px, --color-light: #F5F5F5, --color-primary: single pastel"
|
||||||
|
3,Glassmorphism,General,"Frosted glass, transparent, blurred background, layered, vibrant background, light source, depth, multi-layer","Translucent white: rgba(255,255,255,0.1-0.3)","Vibrant: Electric Blue #0080FF, Neon Purple #8B00FF, Vivid Pink #FF1493, Teal #20B2AA","Backdrop blur (10-20px), subtle border (1px solid rgba white 0.2), light reflection, Z-depth","Modern SaaS, financial dashboards, high-end corporate, lifestyle apps, modal overlays, navigation","Low-contrast backgrounds, critical accessibility, performance-limited, dark text on dark",✓ Full,✓ Full,⚠ Good,⚠ Ensure 4.5:1,✓ Good,✓ High,"Tailwind 9/10, MUI 8/10, Chakra 8/10",2020s Modern,Medium,"Design a glassmorphic interface with frosted glass effect. Use backdrop blur (10-20px), translucent overlays (rgba 10-30% opacity), vibrant background colors, subtle borders, light source reflection, layered depth. Perfect for modern overlays and cards.","backdrop-filter: blur(15px), background: rgba(255, 255, 255, 0.15), border: 1px solid rgba(255,255,255,0.2), -webkit-backdrop-filter: blur(15px), z-index layering for depth","☐ Backdrop-filter blur 10-20px, ☐ Translucent white 15-30% opacity, ☐ Subtle border 1px light, ☐ Vibrant background verified, ☐ Text contrast 4.5:1 checked","--blur-amount: 15px, --glass-opacity: 0.15, --border-color: rgba(255,255,255,0.2), --background: vibrant color, --text-color: light/dark based on BG"
|
||||||
|
4,Brutalism,General,"Raw, unpolished, stark, high contrast, plain text, default fonts, visible borders, asymmetric, anti-design","Primary: Red #FF0000, Blue #0000FF, Yellow #FFFF00, Black #000000, White #FFFFFF","Limited: Neon Green #00FF00, Hot Pink #FF00FF, minimal secondary","No smooth transitions (instant), sharp corners (0px), bold typography (700+), visible grid, large blocks","Design portfolios, artistic projects, counter-culture brands, editorial/media sites, tech blogs","Corporate environments, conservative industries, critical accessibility, customer-facing professional",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AAA,◐ Medium,✗ Low,"Tailwind 10/10, Bootstrap 7/10",1950s Brutalist,Low,"Create a brutalist design with raw, unpolished, stark aesthetic. Use pure primary colors (red, blue, yellow), black & white, no smooth transitions (instant), sharp corners, bold large typography, visible grid lines, default system fonts, intentional 'broken' design elements.","border-radius: 0px, transition: none or 0s, font-family: system-ui or monospace, font-weight: 700+, border: visible 2-4px, colors: #FF0000, #0000FF, #FFFF00, #000000, #FFFFFF","☐ No border-radius (0px), ☐ No transitions (instant), ☐ Bold typography (700+), ☐ Pure primary colors used, ☐ Visible grid/borders, ☐ Asymmetric layout intentional","--border-radius: 0px, --transition-duration: 0s, --font-weight: 700-900, --colors: primary only, --border-style: visible, --grid-visible: true"
|
||||||
|
5,3D & Hyperrealism,General,"Depth, realistic textures, 3D models, spatial navigation, tactile, skeuomorphic elements, rich detail, immersive","Deep Navy #001F3F, Forest Green #228B22, Burgundy #800020, Gold #FFD700, Silver #C0C0C0","Complex gradients (5-10 stops), realistic lighting, shadow variations (20-40% darker)","WebGL/Three.js 3D, realistic shadows (layers), physics lighting, parallax (3-5 layers), smooth 3D (300-400ms)","Gaming, product showcase, immersive experiences, high-end e-commerce, architectural viz, VR/AR","Low-end mobile, performance-limited, critical accessibility, data tables/forms",◐ Partial,◐ Partial,❌ Poor,⚠ Not accessible,✗ Low,◐ Medium,"Three.js 10/10, R3F 10/10, Babylon.js 10/10",2020s Modern,High,"Build an immersive 3D interface using realistic textures, 3D models (Three.js/Babylon.js), complex shadows, realistic lighting, parallax scrolling (3-5 layers), physics-based motion. Include skeuomorphic elements with tactile detail.","transform: translate3d, perspective: 1000px, WebGL canvas, Three.js/Babylon.js library, box-shadow: complex multi-layer, background: complex gradients, filter: drop-shadow()","☐ WebGL/Three.js integrated, ☐ 3D models loaded, ☐ Parallax 3-5 layers, ☐ Realistic lighting verified, ☐ Complex shadows rendered, ☐ Physics animation smooth 300-400ms","--perspective: 1000px, --parallax-layers: 5, --lighting-intensity: realistic, --shadow-depth: 20-40%, --animation-duration: 300-400ms"
|
||||||
|
6,Vibrant & Block-based,General,"Bold, energetic, playful, block layout, geometric shapes, high color contrast, duotone, modern, energetic","Neon Green #39FF14, Electric Purple #BF00FF, Vivid Pink #FF1493, Bright Cyan #00FFFF, Sunburst #FFAA00","Complementary: Orange #FF7F00, Shocking Pink #FF006E, Lime #CCFF00, triadic schemes","Large sections (48px+ gaps), animated patterns, bold hover (color shift), scroll-snap, large type (32px+), 200-300ms","Startups, creative agencies, gaming, social media, youth-focused, entertainment, consumer","Financial institutions, healthcare, formal business, government, conservative, elderly",✓ Full,✓ Full,⚡ Good,◐ Ensure WCAG,✓ High,✓ High,"Tailwind 10/10, Chakra 9/10, Styled 9/10",2020s Modern,Medium,"Design an energetic, vibrant interface with bold block layouts, geometric shapes, high color contrast, large typography (32px+), animated background patterns, duotone effects. Perfect for startups and youth-focused apps. Use 4-6 contrasting colors from complementary/triadic schemes.","display: flex/grid with large gaps (48px+), font-size: 32px+, background: animated patterns (CSS), color: neon/vibrant colors, animation: continuous pattern movement","☐ Block layout with 48px+ gaps, ☐ Large typography 32px+, ☐ 4-6 vibrant colors max, ☐ Animated patterns active, ☐ Scroll-snap enabled, ☐ High contrast verified (7:1+)","--block-gap: 48px, --typography-size: 32px+, --color-palette: 4-6 vibrant colors, --animation: continuous pattern, --contrast-ratio: 7:1+"
|
||||||
|
7,Dark Mode (OLED),General,"Dark theme, low light, high contrast, deep black, midnight blue, eye-friendly, OLED, night mode, power efficient","Deep Black #000000, Dark Grey #121212, Midnight Blue #0A0E27","Vibrant accents: Neon Green #39FF14, Electric Blue #0080FF, Gold #FFD700, Plasma Purple #BF00FF","Minimal glow (text-shadow: 0 0 10px), dark-to-light transitions, low white emission, high readability, visible focus","Night-mode apps, coding platforms, entertainment, eye-strain prevention, OLED devices, low-light","Print-first content, high-brightness outdoor, color-accuracy-critical",✗ No,✓ Only,⚡ Excellent,✓ WCAG AAA,✓ High,◐ Low,"Tailwind 10/10, MUI 10/10, Chakra 10/10",2020s Modern,Low,"Create an OLED-optimized dark interface with deep black (#000000), dark grey (#121212), midnight blue accents. Use minimal glow effects, vibrant neon accents (green, blue, gold, purple), high contrast text. Optimize for eye comfort and OLED power saving.","background: #000000 or #121212, color: #FFFFFF or #E0E0E0, text-shadow: 0 0 10px neon-color (sparingly), filter: brightness(0.8) if needed, color-scheme: dark","☐ Deep black #000000 or #121212, ☐ Vibrant neon accents used, ☐ Text contrast 7:1+, ☐ Minimal glow effects, ☐ OLED power optimization, ☐ No white (#FFFFFF) background","--bg-black: #000000, --bg-dark-grey: #121212, --text-primary: #FFFFFF, --accent-neon: neon colors, --glow-effect: minimal, --oled-optimized: true"
|
||||||
|
8,Accessible & Ethical,General,"High contrast, large text (16px+), keyboard navigation, screen reader friendly, WCAG compliant, focus state, semantic","WCAG AA/AAA (4.5:1 min), simple primary, clear secondary, high luminosity (7:1+)","Symbol-based colors (not color-only), supporting patterns, inclusive combinations","Clear focus rings (3-4px), ARIA labels, skip links, responsive design, reduced motion, 44x44px touch targets","Government, healthcare, education, inclusive products, large audience, legal compliance, public",None - accessibility universal,✓ Full,✓ Full,⚡ Excellent,✓ WCAG AAA,✓ High,✓ High,All frameworks 10/10,Universal,Low,"Design with WCAG AAA compliance. Include: high contrast (7:1+), large text (16px+), keyboard navigation, screen reader compatibility, focus states visible (3-4px ring), semantic HTML, ARIA labels, skip links, reduced motion support (prefers-reduced-motion), 44x44px touch targets.","color-contrast: 7:1+, font-size: 16px+, outline: 3-4px on :focus-visible, aria-label, role attributes, @media (prefers-reduced-motion), touch-target: 44x44px, cursor: pointer","☐ WCAG AAA verified, ☐ 7:1+ contrast checked, ☐ Keyboard navigation tested, ☐ Screen reader tested, ☐ Focus visible 3-4px, ☐ Semantic HTML used, ☐ Touch targets 44x44px","--contrast-ratio: 7:1, --font-size-min: 16px, --focus-ring: 3-4px, --touch-target: 44x44px, --wcag-level: AAA, --keyboard-accessible: true, --sr-tested: true"
|
||||||
|
9,Claymorphism,General,"Soft 3D, chunky, playful, toy-like, bubbly, thick borders (3-4px), double shadows, rounded (16-24px)","Pastel: Soft Peach #FDBCB4, Baby Blue #ADD8E6, Mint #98FF98, Lilac #E6E6FA, light BG","Soft gradients (pastel-to-pastel), light/dark variations (20-30%), gradient subtle","Inner+outer shadows (subtle, no hard lines), soft press (200ms ease-out), fluffy elements, smooth transitions","Educational apps, children's apps, SaaS platforms, creative tools, fun-focused, onboarding, casual games","Formal corporate, professional services, data-critical, serious/medical, legal apps, finance",✓ Full,◐ Partial,⚡ Good,⚠ Ensure 4.5:1,✓ High,✓ High,"Tailwind 9/10, CSS-in-JS 9/10",2020s Modern,Medium,"Design a playful, toy-like interface with soft 3D, chunky elements, bubbly aesthetic, rounded edges (16-24px), thick borders (3-4px), double shadows (inner + outer), pastel colors, smooth animations. Perfect for children's apps and creative tools.","border-radius: 16-24px, border: 3-4px solid, box-shadow: inset -2px -2px 8px, 4px 4px 8px, background: pastel-gradient, animation: soft bounce (cubic-bezier 0.34, 1.56)","☐ Border-radius 16-24px, ☐ Thick borders 3-4px, ☐ Double shadows (inner+outer), ☐ Pastel colors used, ☐ Soft bounce animations, ☐ Playful interactions","--border-radius: 20px, --border-width: 3-4px, --shadow-inner: inset -2px -2px 8px, --shadow-outer: 4px 4px 8px, --color-palette: pastels, --animation: bounce"
|
||||||
|
10,Aurora UI,General,"Vibrant gradients, smooth blend, Northern Lights effect, mesh gradient, luminous, atmospheric, abstract","Complementary: Blue-Orange, Purple-Yellow, Electric Blue #0080FF, Magenta #FF1493, Cyan #00FFFF","Smooth transitions (Blue→Purple→Pink→Teal), iridescent effects, blend modes (screen, multiply)","Large flowing CSS/SVG gradients, subtle 8-12s animations, depth via color layering, smooth morph","Modern SaaS, creative agencies, branding, music platforms, lifestyle, premium products, hero sections","Data-heavy dashboards, critical accessibility, content-heavy where distraction issues",✓ Full,✓ Full,⚠ Good,⚠ Text contrast,✓ Good,✓ High,"Tailwind 9/10, CSS-in-JS 10/10",2020s Modern,Medium,"Create a vibrant gradient interface inspired by Northern Lights with mesh gradients, smooth color blends, flowing animations. Use complementary color pairs (blue-orange, purple-yellow), flowing background gradients, subtle continuous animations (8-12s loops), iridescent effects.","background: conic-gradient or radial-gradient with multiple stops, animation: @keyframes gradient (8-12s), background-size: 200% 200%, filter: saturate(1.2), blend-mode: screen or multiply","☐ Mesh/flowing gradients applied, ☐ 8-12s animation loop, ☐ Complementary colors used, ☐ Smooth color transitions, ☐ Iridescent effect subtle, ☐ Text contrast verified","--gradient-colors: complementary pairs, --animation-duration: 8-12s, --blend-mode: screen, --color-saturation: 1.2, --effect: iridescent, --loop-smooth: true"
|
||||||
|
11,Retro-Futurism,General,"Vintage sci-fi, 80s aesthetic, neon glow, geometric patterns, CRT scanlines, pixel art, cyberpunk, synthwave","Neon Blue #0080FF, Hot Pink #FF006E, Cyan #00FFFF, Deep Black #1A1A2E, Purple #5D34D0","Metallic Silver #C0C0C0, Gold #FFD700, duotone, 80s Pink #FF10F0, neon accents","CRT scanlines (::before overlay), neon glow (text-shadow+box-shadow), glitch effects (skew/offset keyframes)","Gaming, entertainment, music platforms, tech brands, artistic projects, nostalgic, cyberpunk","Conservative industries, critical accessibility, professional/corporate, elderly, legal/finance",✓ Full,✓ Dark focused,⚠ Moderate,⚠ High contrast/strain,◐ Medium,◐ Medium,"Tailwind 8/10, CSS-in-JS 9/10",1980s Retro,Medium,"Build a retro-futuristic (cyberpunk/vaporwave) interface with neon colors (blue, pink, cyan), deep black background, 80s aesthetic, CRT scanlines, glitch effects, neon glow text/borders, monospace fonts, geometric patterns. Use neon text-shadow and animated glitch effects.","color: neon colors (#0080FF, #FF006E, #00FFFF), text-shadow: 0 0 10px neon, background: #000 or #1A1A2E, font-family: monospace, animation: glitch (skew+offset), filter: hue-rotate","☐ Neon colors used, ☐ CRT scanlines effect, ☐ Glitch animations active, ☐ Monospace font, ☐ Deep black background, ☐ Glow effects applied, ☐ 80s patterns present","--neon-colors: #0080FF #FF006E #00FFFF, --background: #000000, --font-family: monospace, --effect: glitch+glow, --scanline-opacity: 0.3, --crt-effect: true"
|
||||||
|
12,Flat Design,General,"2D, minimalist, bold colors, no shadows, clean lines, simple shapes, typography-focused, modern, icon-heavy","Solid bright: Red, Orange, Blue, Green, limited palette (4-6 max)","Complementary colors, muted secondaries, high saturation, clean accents","No gradients/shadows, simple hover (color/opacity shift), fast loading, clean transitions (150-200ms ease), minimal icons","Web apps, mobile apps, cross-platform, startup MVPs, user-friendly, SaaS, dashboards, corporate","Complex 3D, premium/luxury, artistic portfolios, immersive experiences, high-detail",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AAA,✓ High,✓ High,"Tailwind 10/10, Bootstrap 10/10, MUI 9/10",2010s Modern,Low,"Create a flat, 2D interface with bold colors, no shadows/gradients, clean lines, simple geometric shapes, icon-heavy, typography-focused, minimal ornamentation. Use 4-6 solid, bright colors in a limited palette with high saturation.","box-shadow: none, background: solid color, border-radius: 0-4px, color: solid (no gradients), fill: solid, stroke: 1-2px, font: bold sans-serif, icons: simplified SVG","☐ No shadows/gradients, ☐ 4-6 solid colors max, ☐ Clean lines consistent, ☐ Simple shapes used, ☐ Icon-heavy layout, ☐ High saturation colors, ☐ Fast loading verified","--shadow: none, --color-palette: 4-6 solid, --border-radius: 2px, --gradient: none, --icons: simplified SVG, --animation: minimal 150-200ms"
|
||||||
|
13,Skeuomorphism,General,"Realistic, texture, depth, 3D appearance, real-world metaphors, shadows, gradients, tactile, detailed, material","Rich realistic: wood, leather, metal colors, detailed gradients (8-12 stops), metallic effects","Realistic lighting gradients, shadow variations (30-50% darker), texture overlays, material colors","Realistic shadows (layers), depth (perspective), texture details (noise, grain), realistic animations (300-500ms)","Legacy apps, gaming, immersive storytelling, premium products, luxury, realistic simulations, education","Modern enterprise, critical accessibility, low-performance, web (use Flat/Modern)",◐ Partial,◐ Partial,❌ Poor,⚠ Textures reduce readability,✗ Low,◐ Medium,"CSS-in-JS 7/10, Custom 8/10",2007-2012 iOS,High,"Design a realistic, textured interface with 3D depth, real-world metaphors (leather, wood, metal), complex gradients (8-12 stops), realistic shadows, grain/texture overlays, tactile press animations. Perfect for premium/luxury products.","background: complex gradient (8-12 stops), box-shadow: realistic multi-layer, background-image: texture overlay (noise, grain), filter: drop-shadow, transform: scale on press (300-500ms)","☐ Realistic textures applied, ☐ Complex gradients 8-12 stops, ☐ Multi-layer shadows, ☐ Texture overlays present, ☐ Tactile animations smooth, ☐ Depth effect pronounced","--gradient-stops: 8-12, --texture-overlay: noise+grain, --shadow-layers: 3+, --animation-duration: 300-500ms, --depth-effect: pronounced, --tactile: true"
|
||||||
|
14,Liquid Glass,General,"Flowing glass, morphing, smooth transitions, fluid effects, translucent, animated blur, iridescent, chromatic aberration","Vibrant iridescent (rainbow spectrum), translucent base with opacity shifts, gradient fluidity","Chromatic aberration (Red-Cyan), iridescent oil-spill, fluid gradient blends, holographic effects","Morphing elements (SVG/CSS), fluid animations (400-600ms curves), dynamic blur (backdrop-filter), color transitions","Premium SaaS, high-end e-commerce, creative platforms, branding experiences, luxury portfolios","Performance-limited, critical accessibility, complex data, budget projects",✓ Full,✓ Full,⚠ Moderate-Poor,⚠ Text contrast,◐ Medium,✓ High,"Framer Motion 10/10, GSAP 10/10",2020s Modern,High,"Create a premium liquid glass effect with morphing shapes, flowing animations, chromatic aberration, iridescent gradients, smooth 400-600ms transitions. Use SVG morphing for shape changes, dynamic blur, smooth color transitions creating a fluid, premium feel.","animation: morphing SVG paths (400-600ms), backdrop-filter: blur + saturate, filter: hue-rotate + brightness, blend-mode: screen, background: iridescent gradient","☐ Morphing animations 400-600ms, ☐ Chromatic aberration applied, ☐ Dynamic blur active, ☐ Iridescent gradients, ☐ Smooth color transitions, ☐ Premium feel achieved","--morph-duration: 400-600ms, --blur-amount: 15px, --chromatic-aberration: true, --iridescent: true, --blend-mode: screen, --smooth-transitions: true"
|
||||||
|
15,Motion-Driven,General,"Animation-heavy, microinteractions, smooth transitions, scroll effects, parallax, entrance anim, page transitions","Bold colors emphasize movement, high contrast animated, dynamic gradients, accent action colors","Transitional states, success (Green #22C55E), error (Red #EF4444), neutral feedback","Scroll anim (Intersection Observer), hover (300-400ms), entrance, parallax (3-5 layers), page transitions","Portfolio sites, storytelling platforms, interactive experiences, entertainment apps, creative, SaaS","Data dashboards, critical accessibility, low-power devices, content-heavy, motion-sensitive",✓ Full,✓ Full,⚠ Good,⚠ Prefers-reduced-motion,✓ Good,✓ High,"GSAP 10/10, Framer Motion 10/10",2020s Modern,High,"Build an animation-heavy interface with scroll-triggered animations, microinteractions, parallax scrolling (3-5 layers), smooth transitions (300-400ms), entrance animations, page transitions. Use Intersection Observer for scroll effects, transform for performance, GPU acceleration.","animation: @keyframes scroll-reveal, transform: translateY/X, Intersection Observer API, will-change: transform, scroll-behavior: smooth, animation-duration: 300-400ms","☐ Scroll animations active, ☐ Parallax 3-5 layers, ☐ Entrance animations smooth, ☐ Page transitions fluid, ☐ GPU accelerated, ☐ Prefers-reduced-motion respected","--animation-duration: 300-400ms, --parallax-layers: 5, --scroll-behavior: smooth, --gpu-accelerated: true, --entrance-animation: true, --page-transition: smooth"
|
||||||
|
16,Micro-interactions,General,"Small animations, gesture-based, tactile feedback, subtle animations, contextual interactions, responsive","Subtle color shifts (10-20%), feedback: Green #22C55E, Red #EF4444, Amber #F59E0B","Accent feedback, neutral supporting, clear action indicators","Small hover (50-100ms), loading spinners, success/error state anim, gesture-triggered (swipe/pinch), haptic","Mobile apps, touchscreen UIs, productivity tools, user-friendly, consumer apps, interactive components","Desktop-only, critical performance, accessibility-first (alternatives needed)",✓ Full,✓ Full,⚡ Excellent,✓ Good,✓ High,✓ High,"Framer Motion 10/10, React Spring 9/10",2020s Modern,Medium,"Design with delightful micro-interactions: small 50-100ms animations, gesture-based responses, tactile feedback, loading spinners, success/error states, subtle hover effects, haptic feedback triggers for mobile. Focus on responsive, contextual interactions.","animation: short 50-100ms, transition: hover states, @media (hover: hover) for desktop, :active for press, haptic-feedback CSS/API, loading animation smooth loop","☐ Micro-animations 50-100ms, ☐ Gesture-responsive, ☐ Tactile feedback visual/haptic, ☐ Loading spinners smooth, ☐ Success/error states clear, ☐ Hover effects subtle","--micro-animation-duration: 50-100ms, --gesture-responsive: true, --haptic-feedback: true, --loading-animation: smooth, --state-feedback: success+error"
|
||||||
|
17,Inclusive Design,General,"Accessible, color-blind friendly, high contrast, haptic feedback, voice interaction, screen reader, WCAG AAA, universal","WCAG AAA (7:1+ contrast), avoid red-green only, symbol-based indicators, high contrast primary","Supporting patterns (stripes, dots, hatch), symbols, combinations, clear non-color indicators","Haptic feedback (vibration), voice guidance, focus indicators (4px+ ring), motion options, alt content, semantic","Public services, education, healthcare, finance, government, accessible consumer, inclusive",None - accessibility universal,✓ Full,✓ Full,⚡ Excellent,✓ WCAG AAA,✓ High,✓ High,All frameworks 10/10,Universal,Low,"Design for universal accessibility: high contrast (7:1+), large text (16px+), keyboard-only navigation, screen reader optimization, WCAG AAA compliance, symbol-based color indicators (not color-only), haptic feedback, voice interaction support, reduced motion options.","aria-* attributes complete, role attributes semantic, focus-visible: 3-4px ring, color-contrast: 7:1+, @media (prefers-reduced-motion), alt text on all images, form labels properly associated","☐ WCAG AAA verified, ☐ 7:1+ contrast all text, ☐ Keyboard accessible (Tab/Enter), ☐ Screen reader tested, ☐ Focus visible 3-4px, ☐ No color-only indicators, ☐ Haptic fallback","--contrast-ratio: 7:1, --font-size: 16px+, --keyboard-accessible: true, --sr-compatible: true, --wcag-level: AAA, --color-symbols: true, --haptic: enabled"
|
||||||
|
18,Zero Interface,General,"Minimal visible UI, voice-first, gesture-based, AI-driven, invisible controls, predictive, context-aware, ambient","Neutral backgrounds: Soft white #FAFAFA, light grey #F0F0F0, warm off-white #F5F1E8","Subtle feedback: light green, light red, minimal UI elements, soft accents","Voice recognition UI, gesture detection, AI predictions (smooth reveal), progressive disclosure, smart suggestions","Voice assistants, AI platforms, future-forward UX, smart home, contextual computing, ambient experiences","Complex workflows, data-entry heavy, traditional systems, legacy support, explicit control",✓ Full,✓ Full,⚡ Excellent,✓ Excellent,✓ High,✓ High,"Tailwind 10/10, Custom 10/10",2020s AI-Era,Low,"Create a voice-first, gesture-based, AI-driven interface with minimal visible UI, progressive disclosure, voice recognition UI, gesture detection, AI predictions, smart suggestions, context-aware actions. Hide controls until needed.","voice-commands: Web Speech API, gesture-detection: touch events, AI-predictions: hidden by default (reveal on hover), progressive-disclosure: show on demand, minimal UI visible","☐ Voice commands responsive, ☐ Gesture detection active, ☐ AI predictions hidden/revealed, ☐ Progressive disclosure working, ☐ Minimal visible UI, ☐ Smart suggestions contextual","--voice-ui: enabled, --gesture-detection: active, --ai-predictions: smart, --progressive-disclosure: true, --visible-ui: minimal, --context-aware: true"
|
||||||
|
19,Soft UI Evolution,General,"Evolved soft UI, better contrast, modern aesthetics, subtle depth, accessibility-focused, improved shadows, hybrid","Improved contrast pastels: Soft Blue #87CEEB, Soft Pink #FFB6C1, Soft Green #90EE90, better hierarchy","Better combinations, accessible secondary, supporting with improved contrast, modern accents","Improved shadows (softer than flat, clearer than neumorphism), modern (200-300ms), focus visible, WCAG AA/AAA","Modern enterprise apps, SaaS platforms, health/wellness, modern business tools, professional, hybrid","Extreme minimalism, critical performance, systems without modern OS",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AA+,✓ High,✓ High,"Tailwind 9/10, MUI 9/10, Chakra 9/10",2020s Modern,Medium,"Design evolved neumorphism with improved contrast (WCAG AA+), modern aesthetics, subtle depth, accessibility focus. Use soft shadows (softer than flat but clearer than pure neumorphism), better color hierarchy, improved focus states, modern 200-300ms animations.","box-shadow: softer multi-layer (0 2px 4px), background: improved contrast pastels, border-radius: 8-12px, animation: 200-300ms smooth, outline: 2-3px on focus, contrast: 4.5:1+","☐ Improved contrast AA/AAA, ☐ Soft shadows modern, ☐ Border-radius 8-12px, ☐ Animations 200-300ms, ☐ Focus states visible, ☐ Color hierarchy clear","--shadow-soft: modern blend, --border-radius: 10px, --animation-duration: 200-300ms, --contrast-ratio: 4.5:1+, --color-hierarchy: improved, --wcag-level: AA+"
|
||||||
|
20,Hero-Centric Design,Landing Page,"Large hero section, compelling headline, high-contrast CTA, product showcase, value proposition, hero image/video, dramatic visual","Brand primary color, white/light backgrounds for contrast, accent color for CTA","Supporting colors for secondary CTAs, accent highlights, trust elements (testimonials, logos)","Smooth scroll reveal, fade-in animations on hero, subtle background parallax, CTA glow/pulse effect","SaaS landing pages, product launches, service landing pages, B2B platforms, tech companies","Complex navigation, multi-page experiences, data-heavy applications",✓ Full,✓ Full,⚡ Good,✓ WCAG AA,✓ Full,✓ Very High,"Tailwind 10/10, Bootstrap 9/10",2020s Modern,Medium,"Design a hero-centric landing page. Use: full-width hero section, compelling headline (60-80 chars), high-contrast CTA button, product screenshot or video, value proposition above fold, gradient or image background, clear visual hierarchy.","min-height: 100vh, display: flex, align-items: center, background: linear-gradient or image, text-shadow for readability, max-width: 800px for text, button with hover scale (1.05)","☐ Hero section full viewport height, ☐ Headline visible above fold, ☐ CTA button high contrast, ☐ Background image optimized (WebP), ☐ Text readable on background, ☐ Mobile responsive layout","--hero-min-height: 100vh, --headline-size: clamp(2rem, 5vw, 4rem), --cta-padding: 1rem 2rem, --overlay-opacity: 0.5, --text-shadow: 0 2px 4px rgba(0,0,0,0.3)"
|
||||||
|
21,Conversion-Optimized,Landing Page,"Form-focused, minimalist design, single CTA focus, high contrast, urgency elements, trust signals, social proof, clear value","Primary brand color, high-contrast white/light backgrounds, warning/urgency colors for time-limited offers","Secondary CTA color (muted), trust element colors (testimonial highlights), accent for key benefits","Hover states on CTA (color shift, slight scale), form field focus animations, loading spinner, success feedback","E-commerce product pages, free trial signups, lead generation, SaaS pricing pages, limited-time offers","Complex feature explanations, multi-product showcases, technical documentation",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AA,✓ Full (mobile-optimized),✓ Very High,"Tailwind 10/10, Bootstrap 9/10",2020s Modern,Medium,"Design a conversion-optimized landing page. Use: single primary CTA, minimal distractions, trust badges, urgency elements (limited time), social proof (testimonials), clear value proposition, form above fold, progress indicators.","form with focus states, input:focus ring, button: primary color high contrast, position: sticky for CTA, max-width: 600px for form, loading spinner, success/error states","☐ Single primary CTA visible, ☐ Form fields minimal (3-5), ☐ Trust badges present, ☐ Social proof above fold, ☐ Mobile form optimized, ☐ Loading states implemented, ☐ A/B test ready","--cta-color: high contrast primary, --form-max-width: 600px, --input-height: 48px, --focus-ring: 3px solid accent, --success-color: #22C55E, --error-color: #EF4444"
|
||||||
|
22,Feature-Rich Showcase,Landing Page,"Multiple feature sections, grid layout, benefit cards, visual feature demonstrations, interactive elements, problem-solution pairs","Primary brand, bright secondary colors for feature cards, contrasting accent for CTAs","Supporting colors for: benefits (green), problems (red/orange), features (blue/purple), social proof (neutral)","Card hover effects (lift/scale), icon animations on scroll, feature toggle animations, smooth section transitions","Enterprise SaaS, software tools landing pages, platform services, complex product explanations, B2B products","Simple product pages, early-stage startups with few features, entertainment landing pages",✓ Full,✓ Full,⚡ Good,✓ WCAG AA,✓ Good,✓ High,"Tailwind 10/10, Bootstrap 9/10",2020s Modern,Medium,"Design a feature showcase landing page. Use: grid layout for features (3-4 columns), feature cards with icons, benefit-focused copy, alternating sections, comparison tables, interactive demos, problem-solution pairs.","display: grid, grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)), gap: 2rem, card hover effects (translateY -4px), icon containers, alternating background colors","☐ Feature grid responsive, ☐ Icons consistent style, ☐ Card hover effects smooth, ☐ Alternating sections contrast, ☐ Benefits clearly stated, ☐ Mobile stacks properly","--card-padding: 2rem, --card-radius: 12px, --icon-size: 48px, --grid-gap: 2rem, --section-padding: 4rem 0, --hover-transform: translateY(-4px)"
|
||||||
|
23,Minimal & Direct,Landing Page,"Minimal text, white space heavy, single column layout, direct messaging, clean typography, visual-centric, fast-loading","Monochromatic primary, white background, single accent color for CTA, black/dark grey text","Minimal secondary colors, reserved for critical CTAs only, neutral supporting elements","Very subtle hover effects, minimal animations, fast page load (no heavy animations), smooth scroll","Simple service landing pages, indie products, consulting services, micro SaaS, freelancer portfolios","Feature-heavy products, complex explanations, multi-product showcases",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AAA,✓ Full,✓ High,"Tailwind 10/10, Bootstrap 9/10",2020s Modern,Medium,"Design a minimal direct landing page. Use: single column layout, maximum white space, essential content only, one CTA, clean typography, no decorative elements, fast loading, direct messaging.","max-width: 680px, margin: 0 auto, padding: 4rem 2rem, font-size: 18-20px, line-height: 1.6, minimal animations, no box-shadow, clean borders only","☐ Single column centered, ☐ White space generous, ☐ One primary CTA only, ☐ No decorative images, ☐ Page weight < 500KB, ☐ Load time < 2s","--content-max-width: 680px, --spacing-large: 4rem, --font-size-body: 18px, --line-height: 1.6, --color-text: #1a1a1a, --color-bg: #ffffff"
|
||||||
|
24,Social Proof-Focused,Landing Page,"Testimonials prominent, client logos displayed, case studies sections, reviews/ratings, user avatars, success metrics, credibility markers","Primary brand, trust colors (blue), success/growth colors (green), neutral backgrounds","Testimonial highlight colors, logo grid backgrounds (light grey), badge/achievement colors","Testimonial carousel animations, logo grid fade-in, stat counter animations (number count-up), review star ratings","B2B SaaS, professional services, premium products, e-commerce conversion pages, established brands","Startup MVPs, products without users, niche/experimental products",✓ Full,✓ Full,⚡ Good,✓ WCAG AA,✓ Full,✓ High,"Tailwind 10/10, Bootstrap 9/10",2020s Modern,Medium,"Design a social proof landing page. Use: testimonials with photos, client logos grid, case study cards, review ratings (stars), user count metrics, success stories, trust indicators, before/after comparisons.","testimonial cards with avatar, logo grid (grayscale filter), star rating SVGs, counter animations (count-up), blockquote styling, carousel for testimonials, metric cards","☐ Testimonials with real photos, ☐ Logo grid 6-12 logos, ☐ Star ratings accessible, ☐ Metrics animated on scroll, ☐ Case studies linked, ☐ Mobile carousel works","--avatar-size: 64px, --logo-height: 40px, --star-color: #FBBF24, --metric-font-size: 3rem, --testimonial-bg: #F9FAFB, --blockquote-border: 4px solid accent"
|
||||||
|
25,Interactive Product Demo,Landing Page,"Embedded product mockup/video, interactive elements, product walkthrough, step-by-step guides, hover-to-reveal features, embedded demos","Primary brand, interface colors matching product, demo highlight colors for interactive elements","Product UI colors, tutorial step colors (numbered progression), hover state indicators","Product animation playback, step progression animations, hover reveal effects, smooth zoom on interaction","SaaS platforms, tool/software products, productivity apps landing pages, developer tools, productivity software","Simple services, consulting, non-digital products, complexity-averse audiences",✓ Full,✓ Full,⚠ Good (video/interactive),✓ WCAG AA,✓ Good,✓ Very High,"Tailwind 10/10, Bootstrap 9/10",2020s Modern,Medium,"Design an interactive demo landing page. Use: embedded product mockup, video walkthrough, step-by-step guide, hover-to-reveal features, live demo button, screenshot carousel, feature highlights on interaction.","video element with controls, position: relative for overlays, hover reveal (opacity transition), step indicators, modal for full demo, screenshot lightbox, play button overlay","☐ Demo video loads fast, ☐ Fallback for no-JS, ☐ Step indicators clear, ☐ Hover states obvious, ☐ Mobile touch friendly, ☐ Demo CTA prominent","--video-aspect-ratio: 16/9, --overlay-bg: rgba(0,0,0,0.7), --step-indicator-size: 32px, --play-button-size: 80px, --transition-duration: 300ms"
|
||||||
|
26,Trust & Authority,Landing Page,"Certificates/badges displayed, expert credentials, case studies with metrics, before/after comparisons, industry recognition, security badges","Professional colors (blue/grey), trust colors, certification badge colors (gold/silver accents)","Certificate highlight colors, metric showcase colors, comparison highlight (success green)","Badge hover effects, metric pulse animations, certificate carousel, smooth stat reveal","Healthcare/medical landing pages, financial services, enterprise software, premium/luxury products, legal services","Casual products, entertainment, viral/social-first products",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AAA,✓ Full,✓ High,"Tailwind 10/10, Bootstrap 9/10",2020s Modern,Medium,"Design a trust-focused landing page. Use: certification badges, security indicators, expert credentials, industry awards, case study metrics, compliance logos (GDPR, SOC2), guarantee badges, professional photography.","badge grid layout, shield icons, lock icons for security, certificate styling, metric cards with icons, professional color scheme (blue/grey), subtle shadows for depth","☐ Security badges visible, ☐ Certifications verified, ☐ Metrics with sources, ☐ Professional imagery, ☐ Guarantee clearly stated, ☐ Contact info accessible","--badge-height: 48px, --trust-color: #1E40AF, --security-green: #059669, --card-shadow: 0 4px 6px rgba(0,0,0,0.1), --metric-highlight: #F59E0B"
|
||||||
|
27,Storytelling-Driven,Landing Page,"Narrative flow, visual story progression, section transitions, consistent character/brand voice, emotional messaging, journey visualization","Brand primary, warm/emotional colors, varied accent colors per story section, high visual variety","Story section color coding, emotional state colors (calm, excitement, success), transitional gradients","Section-to-section animations, scroll-triggered reveals, character/icon animations, morphing transitions, parallax narrative","Brand/startup stories, mission-driven products, premium/lifestyle brands, documentary-style products, educational","Technical/complex products (unless narrative-driven), traditional enterprise software",✓ Full,✓ Full,⚠ Moderate (animations),✓ WCAG AA,✓ Good,✓ High,"Tailwind 10/10, Bootstrap 9/10",2020s Modern,Medium,"Design a storytelling landing page. Use: narrative flow sections, scroll-triggered reveals, chapter-like structure, emotional imagery, brand journey visualization, founder story, mission statement, timeline progression.","scroll-snap sections, Intersection Observer for reveals, parallax backgrounds, section transitions, timeline CSS, narrative typography (varied sizes), image-text alternating","☐ Story flows naturally, ☐ Scroll reveals smooth, ☐ Sections timed well, ☐ Emotional hooks present, ☐ Mobile story readable, ☐ Skip option available","--section-min-height: 100vh, --reveal-duration: 600ms, --narrative-font: serif, --chapter-spacing: 8rem, --timeline-color: accent, --parallax-speed: 0.5"
|
||||||
|
28,Data-Dense Dashboard,BI/Analytics,"Multiple charts/widgets, data tables, KPI cards, minimal padding, grid layout, space-efficient, maximum data visibility","Neutral primary (light grey/white #F5F5F5), data colors (blue/green/red), dark text #333333","Chart colors: success (green #22C55E), warning (amber #F59E0B), alert (red #EF4444), neutral (grey)","Hover tooltips, chart zoom on click, row highlighting on hover, smooth filter animations, data loading spinners","Business intelligence dashboards, financial analytics, enterprise reporting, operational dashboards, data warehousing","Marketing dashboards, consumer-facing analytics, simple reporting",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AA,◐ Medium,✗ Not applicable,"Recharts 9/10, Chart.js 9/10, D3.js 10/10",2020s Modern,Medium,"Design a data-dense dashboard. Use: multiple chart widgets, KPI cards row, data tables with sorting, minimal padding (8-12px), efficient grid layout, filter sidebar, dense but readable typography, maximum information density.","display: grid, grid-template-columns: repeat(12, 1fr), gap: 8px, padding: 12px, font-size: 12-14px, overflow: auto for tables, compact card design, sticky headers","☐ Grid layout 12 columns, ☐ KPI cards responsive, ☐ Tables sortable, ☐ Filters functional, ☐ Loading states for data, ☐ Export functionality","--grid-gap: 8px, --card-padding: 12px, --font-size-small: 12px, --table-row-height: 36px, --sidebar-width: 240px, --header-height: 56px"
|
||||||
|
29,Heat Map & Heatmap Style,BI/Analytics,"Color-coded grid/matrix, data intensity visualization, geographical heat maps, correlation matrices, cell-based representation, gradient coloring","Gradient scale: Cool (blue #0080FF) to hot (red #FF0000), neutral middle (white/yellow)","Support gradients: Light (cool blue) to dark (warm red), divergent for positive/negative data, monochromatic options","Color gradient transitions on data change, cell highlighting on hover, tooltip reveal on click, smooth color animation","Geographical analysis, performance matrices, correlation analysis, user behavior heatmaps, temperature/intensity data","Linear data representation, categorical comparisons (use bar charts), small datasets",✓ Full,✓ Full (with adjustments),⚡ Excellent,⚠ Colorblind considerations,◐ Medium,✗ Not applicable,"Recharts 9/10, Chart.js 9/10, D3.js 10/10",2020s Modern,Medium,"Design a heatmap visualization. Use: color gradient scale (cool to hot), cell-based grid, intensity legend, hover tooltips, geographic or matrix layout, divergent color scheme for +/- values, accessible color alternatives.","display: grid, background: linear-gradient for legend, cell hover states, tooltip positioning, color scale (blue→white→red), SVG for geographic, canvas for large datasets","☐ Color scale clear, ☐ Legend visible, ☐ Tooltips informative, ☐ Colorblind alternatives, ☐ Zoom/pan for geo, ☐ Performance for large data","--heatmap-cool: #0080FF, --heatmap-neutral: #FFFFFF, --heatmap-hot: #FF0000, --cell-size: 24px, --legend-width: 200px, --tooltip-bg: rgba(0,0,0,0.9)"
|
||||||
|
30,Executive Dashboard,BI/Analytics,"High-level KPIs, large key metrics, minimal detail, summary view, trend indicators, at-a-glance insights, executive summary","Brand colors, professional palette (blue/grey/white), accent for KPIs, red for alerts/concerns","KPI highlight colors: positive (green), negative (red), neutral (grey), trend arrow colors","KPI value animations (count-up), trend arrow direction animations, metric card hover lift, alert pulse effect","C-suite dashboards, business summary reports, decision-maker dashboards, strategic planning views","Detailed analyst dashboards, technical deep-dives, operational monitoring",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AA,✗ Low (not mobile-optimized),✗ Not applicable,"Recharts 9/10, Chart.js 9/10, D3.js 10/10",2020s Modern,Medium,"Design an executive dashboard. Use: large KPI cards (4-6 max), trend sparklines, high-level summary only, clean layout with white space, traffic light indicators (red/yellow/green), at-a-glance insights, minimal detail.","display: flex for KPI row, large font-size (24-48px) for metrics, sparkline SVG inline, status indicators (border-left color), card shadows for hierarchy, responsive breakpoints","☐ KPIs 4-6 maximum, ☐ Trends visible, ☐ Status colors clear, ☐ One-page view, ☐ Mobile simplified, ☐ Print-friendly layout","--kpi-font-size: 48px, --sparkline-height: 32px, --status-green: #22C55E, --status-yellow: #F59E0B, --status-red: #EF4444, --card-min-width: 280px"
|
||||||
|
31,Real-Time Monitoring,BI/Analytics,"Live data updates, status indicators, alert notifications, streaming data visualization, active monitoring, streaming charts","Alert colors: critical (red #FF0000), warning (orange #FFA500), normal (green #22C55E), updating (blue animation)","Status indicator colors, chart line colors varying by metric, streaming data highlight colors","Real-time chart animations, alert pulse/glow, status indicator blink animation, smooth data stream updates, loading effect","System monitoring dashboards, DevOps dashboards, real-time analytics, stock market dashboards, live event tracking","Historical analysis, long-term trend reports, archived data dashboards",✓ Full,✓ Full,⚡ Good (real-time load),✓ WCAG AA,◐ Medium,✗ Not applicable,"Recharts 9/10, Chart.js 9/10, D3.js 10/10",2020s Modern,Medium,"Design a real-time monitoring dashboard. Use: live status indicators (pulsing), streaming charts, alert notifications, connection status, auto-refresh indicators, critical alerts prominent, system health overview.","animation: pulse for live, WebSocket for streaming, position: fixed for alerts, status-dot with animation, chart real-time updates, notification toast, connection indicator","☐ Live updates working, ☐ Alert sounds optional, ☐ Connection status shown, ☐ Auto-refresh indicated, ☐ Critical alerts prominent, ☐ Offline fallback","--pulse-animation: pulse 2s infinite, --alert-z-index: 1000, --live-indicator: #22C55E, --critical-color: #DC2626, --update-interval: 5s, --toast-duration: 5s"
|
||||||
|
32,Drill-Down Analytics,BI/Analytics,"Hierarchical data exploration, expandable sections, interactive drill-down paths, summary-to-detail flow, context preservation","Primary brand, breadcrumb colors, drill-level indicator colors, hierarchy depth colors","Drill-down path indicator colors, level-specific colors, highlight colors for selected level, transition colors","Drill-down expand animations, breadcrumb click transitions, smooth detail reveal, level change smooth, data reload animation","Sales analytics, product analytics, funnel analysis, multi-dimensional data exploration, business intelligence","Simple linear data, single-metric dashboards, streaming real-time dashboards",✓ Full,✓ Full,⚡ Good,✓ WCAG AA,◐ Medium,✗ Not applicable,"Recharts 9/10, Chart.js 9/10, D3.js 10/10",2020s Modern,Medium,"Design a drill-down analytics dashboard. Use: breadcrumb navigation, expandable sections, summary-to-detail flow, back button prominent, level indicators, context preservation, hierarchical data display.","breadcrumb nav with separators, details/summary for expand, transition for drill animation, position: sticky breadcrumb, nested grid layouts, smooth scroll to detail","☐ Breadcrumbs clear, ☐ Back navigation easy, ☐ Expand animation smooth, ☐ Context preserved, ☐ Mobile drill works, ☐ Deep links supported","--breadcrumb-separator: /, --expand-duration: 300ms, --level-indent: 24px, --back-button-size: 40px, --context-bar-height: 48px, --drill-transition: 300ms ease"
|
||||||
|
33,Comparative Analysis Dashboard,BI/Analytics,"Side-by-side comparisons, period-over-period metrics, A/B test results, regional comparisons, performance benchmarks","Comparison colors: primary (blue), comparison (orange/purple), delta indicator (green/red)","Winning metric color (green), losing metric color (red), neutral comparison (grey), benchmark colors","Comparison bar animations (grow to value), delta indicator animations (direction arrows), highlight on compare","Period-over-period reporting, A/B test dashboards, market comparison, competitive analysis, regional performance","Single metric dashboards, future projections (use forecasting), real-time only (no historical)",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AA,◐ Medium,✗ Not applicable,"Recharts 9/10, Chart.js 9/10, D3.js 10/10",2020s Modern,Medium,"Design a comparison dashboard. Use: side-by-side metrics, period selectors (vs last month), delta indicators (+/-), benchmark lines, A/B comparison tables, winning/losing highlights, percentage change badges.","display: flex for side-by-side, gap for comparison spacing, color coding (green up, red down), arrow indicators, diff highlighting, comparison table zebra striping","☐ Period selector works, ☐ Deltas calculated, ☐ Colors meaningful, ☐ Benchmarks shown, ☐ Mobile stacks properly, ☐ Export comparison","--positive-color: #22C55E, --negative-color: #EF4444, --neutral-color: #6B7280, --comparison-gap: 2rem, --arrow-size: 16px, --badge-padding: 4px 8px"
|
||||||
|
34,Predictive Analytics,BI/Analytics,"Forecast lines, confidence intervals, trend projections, scenario modeling, AI-driven insights, anomaly detection visualization","Forecast line color (distinct from actual), confidence interval shading, anomaly highlight (red alert), trend colors","High confidence (dark color), low confidence (light color), anomaly colors (red/orange), normal trend (green/blue)","Forecast line animation on draw, confidence band fade-in, anomaly pulse alert, smoothing function animations","Forecasting dashboards, anomaly detection systems, trend prediction dashboards, AI-powered analytics, budget planning","Historical-only dashboards, simple reporting, real-time operational dashboards",✓ Full,✓ Full,⚠ Good (computation),✓ WCAG AA,◐ Medium,✗ Not applicable,"Recharts 9/10, Chart.js 9/10, D3.js 10/10",2020s Modern,Medium,"Design a predictive analytics dashboard. Use: forecast lines (dashed), confidence intervals (shaded bands), trend projections, anomaly highlights, scenario toggles, AI insight cards, probability indicators.","stroke-dasharray for forecast lines, fill-opacity for confidence bands, anomaly markers (circles), tooltip for predictions, toggle switches for scenarios, gradient for probability","☐ Forecast line distinct, ☐ Confidence bands visible, ☐ Anomalies highlighted, ☐ Scenarios switchable, ☐ Predictions dated, ☐ Accuracy shown","--forecast-dash: 5 5, --confidence-opacity: 0.2, --anomaly-color: #F59E0B, --prediction-color: #8B5CF6, --scenario-toggle-width: 48px, --ai-accent: #6366F1"
|
||||||
|
35,User Behavior Analytics,BI/Analytics,"Funnel visualization, user flow diagrams, conversion tracking, engagement metrics, user journey mapping, cohort analysis","Funnel stage colors: high engagement (green), drop-off (red), conversion (blue), user flow arrows (grey)","Stage completion colors (success), abandonment colors (warning), engagement levels (gradient), cohort colors","Funnel animation (fill-down), flow diagram animations (connection draw), conversion pulse, engagement bar fill","Conversion funnel analysis, user journey tracking, engagement analytics, cohort analysis, retention tracking","Real-time operational metrics, technical system monitoring, financial transactions",✓ Full,✓ Full,⚡ Good,✓ WCAG AA,✓ Good,✗ Not applicable,"Recharts 9/10, Chart.js 9/10, D3.js 10/10",2020s Modern,Medium,"Design a user behavior analytics dashboard. Use: funnel visualization, user flow diagrams (Sankey), conversion metrics, engagement heatmaps, cohort tables, retention curves, session replay indicators.","SVG funnel with gradients, Sankey diagram library, percentage labels, cohort grid cells, retention chart (line/area), click heatmap overlay, session timeline","☐ Funnel stages clear, ☐ Flow diagram readable, ☐ Conversions calculated, ☐ Cohorts comparable, ☐ Retention trends visible, ☐ Privacy compliant","--funnel-width: 100%, --stage-colors: gradient, --flow-opacity: 0.6, --cohort-cell-size: 40px, --retention-line-color: #3B82F6, --engagement-scale: 5 levels"
|
||||||
|
36,Financial Dashboard,BI/Analytics,"Revenue metrics, profit/loss visualization, budget tracking, financial ratios, portfolio performance, cash flow, audit trail","Financial colors: profit (green #22C55E), loss (red #EF4444), neutral (grey), trust (dark blue #003366)","Revenue highlight (green), expenses (red), budget variance (orange/red), balance (grey), accuracy (blue)","Number animations (count-up), trend direction indicators, percentage change animations, profit/loss color transitions","Financial reporting, accounting dashboards, portfolio tracking, budget monitoring, banking analytics","Simple business dashboards, entertainment/social metrics, non-financial data",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AAA,✗ Low,✗ Not applicable,"Recharts 9/10, Chart.js 9/10, D3.js 10/10",2020s Modern,Medium,"Design a financial dashboard. Use: revenue/expense charts, profit margins, budget vs actual, cash flow waterfall, financial ratios, audit trail table, currency formatting, period comparisons.","number formatting (Intl.NumberFormat), waterfall chart (positive/negative bars), variance coloring, table with totals row, sparkline for trends, sticky column headers","☐ Currency formatted, ☐ Decimals consistent, ☐ P&L clear, ☐ Budget variance shown, ☐ Audit trail complete, ☐ Export to Excel","--currency-symbol: $, --decimal-places: 2, --profit-color: #22C55E, --loss-color: #EF4444, --variance-threshold: 10%, --table-header-bg: #F3F4F6"
|
||||||
|
37,Sales Intelligence Dashboard,BI/Analytics,"Deal pipeline, sales metrics, territory performance, sales rep leaderboard, win-loss analysis, quota tracking, forecast accuracy","Sales colors: won (green), lost (red), in-progress (blue), blocked (orange), quota met (gold), quota missed (grey)","Pipeline stage colors, rep performance colors, quota achievement colors, forecast accuracy colors","Deal movement animations, metric updates, leaderboard ranking changes, gauge needle movements, status change highlights","CRM dashboards, sales management, opportunity tracking, performance management, quota planning","Marketing analytics, customer support metrics, HR dashboards",✓ Full,✓ Full,⚡ Good,✓ WCAG AA,◐ Medium,✗ Not applicable,"Recharts 9/10, Chart.js 9/10",2020s Modern,Medium,"Design a sales intelligence dashboard. Use: pipeline funnel, deal cards (kanban), quota gauges, leaderboard table, territory map, win/loss ratios, forecast accuracy, activity timeline.","kanban columns (flex), gauge chart (SVG arc), leaderboard ranking styles, map integration (Mapbox/Google), timeline vertical, deal card with status border","☐ Pipeline stages shown, ☐ Deals draggable, ☐ Quotas visualized, ☐ Rankings updated, ☐ Territory clickable, ☐ CRM integration","--pipeline-colors: stage gradient, --gauge-track: #E5E7EB, --gauge-fill: primary, --rank-1-color: #FFD700, --rank-2-color: #C0C0C0, --rank-3-color: #CD7F32"
|
||||||
|
38,Neubrutalism,General,"Bold borders, black outlines, primary colors, thick shadows, no gradients, flat colors, 45° shadows, playful, Gen Z","#FFEB3B (Yellow), #FF5252 (Red), #2196F3 (Blue), #000000 (Black borders)","Limited accent colors, high contrast combinations, no gradients allowed","box-shadow: 4px 4px 0 #000, border: 3px solid #000, no gradients, sharp corners (0px), bold typography","Gen Z brands, startups, creative agencies, Figma-style apps, Notion-style interfaces, tech blogs","Luxury brands, finance, healthcare, conservative industries (too playful)",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AAA,✓ High,✓ High,"Tailwind 10/10, Bootstrap 8/10",2020s Modern,Low,"Design a neubrutalist interface. Use: high contrast, hard black borders (3px+), bright pop colors, no blur, sharp or slightly rounded corners, bold typography, hard shadows (offset 4px 4px), raw aesthetic but functional.","border: 3px solid black, box-shadow: 5px 5px 0px black, colors: #FFDB58 #FF6B6B #4ECDC4, font-weight: 700, no gradients","☐ Hard borders (2-4px), ☐ Hard offset shadows, ☐ High saturation colors, ☐ Bold typography, ☐ No blurs/gradients, ☐ Distinctive 'ugly-cute' look","--border-width: 3px, --shadow-offset: 4px, --shadow-color: #000, --colors: high saturation, --font: bold sans"
|
||||||
|
39,Bento Box Grid,General,"Modular cards, asymmetric grid, varied sizes, Apple-style, dashboard tiles, negative space, clean hierarchy, cards","Neutral base + brand accent, #FFFFFF, #F5F5F5, brand primary","Subtle gradients, shadow variations, accent highlights for interactive cards","grid-template with varied spans, rounded-xl (16px), subtle shadows, hover scale (1.02), smooth transitions","Dashboards, product pages, portfolios, Apple-style marketing, feature showcases, SaaS","Dense data tables, text-heavy content, real-time monitoring",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AA,✓ High,✓ High,"Tailwind 10/10, CSS Grid 10/10",2020s Apple,Low,"Design a Bento Box grid layout. Use: modular cards with varied sizes (1x1, 2x1, 2x2), Apple-style aesthetic, rounded corners (16-24px), soft shadows, clean hierarchy, asymmetric grid, neutral backgrounds (#F5F5F7), hover effects.","display: grid, grid-template-columns: repeat(4, 1fr), grid-auto-rows: 200px, gap: 16px, border-radius: 24px, background: #FFFFFF, box-shadow: 0 4px 6px rgba(0,0,0,0.05)","☐ Grid responsive (4→2→1 cols), ☐ Card spans varied, ☐ Rounded corners consistent, ☐ Shadows subtle, ☐ Content fits cards, ☐ Hover scale (1.02)","--grid-gap: 16px, --card-radius: 24px, --card-bg: #FFFFFF, --page-bg: #F5F5F7, --shadow: 0 4px 6px rgba(0,0,0,0.05), --hover-scale: 1.02"
|
||||||
|
40,Y2K Aesthetic,General,"Neon pink, chrome, metallic, bubblegum, iridescent, glossy, retro-futurism, 2000s, futuristic nostalgia","#FF69B4 (Hot Pink), #00FFFF (Cyan), #C0C0C0 (Silver), #9400D3 (Purple)","Metallic gradients, glossy overlays, iridescent effects, chrome textures","linear-gradient metallic, glossy buttons, 3D chrome effects, glow animations, bubble shapes","Fashion brands, music platforms, Gen Z brands, nostalgia marketing, entertainment, youth-focused","B2B enterprise, healthcare, finance, conservative industries, elderly users",✓ Full,◐ Partial,⚠ Good,⚠ Check contrast,✓ Good,✓ High,"Tailwind 8/10, CSS-in-JS 9/10",Y2K 2000s,Medium,"Design a Y2K aesthetic interface. Use: neon pink/cyan colors, chrome/metallic textures, bubblegum gradients, glossy buttons, iridescent effects, 2000s futurism, star/sparkle decorations, bubble shapes, tech-optimistic vibe.","background: linear-gradient(135deg, #FF69B4, #00FFFF), filter: drop-shadow for glow, border-radius: 50% for bubbles, metallic gradients (silver/chrome), text-shadow: neon glow, ::before for sparkles","☐ Neon colors balanced, ☐ Chrome effects visible, ☐ Glossy buttons styled, ☐ Bubble shapes decorative, ☐ Sparkle animations, ☐ Retro fonts loaded","--neon-pink: #FF69B4, --neon-cyan: #00FFFF, --chrome-silver: #C0C0C0, --glossy-gradient: linear-gradient(180deg, white 0%, transparent 50%), --glow-blur: 10px"
|
||||||
|
41,Cyberpunk UI,General,"Neon, dark mode, terminal, HUD, sci-fi, glitch, dystopian, futuristic, matrix, tech noir","#00FF00 (Matrix Green), #FF00FF (Magenta), #00FFFF (Cyan), #0D0D0D (Dark)","Neon gradients, scanline overlays, glitch colors, terminal green accents","Neon glow (text-shadow), glitch animations (skew/offset), scanlines (::before overlay), terminal fonts","Gaming platforms, tech products, crypto apps, sci-fi applications, developer tools, entertainment","Corporate enterprise, healthcare, family apps, conservative brands, elderly users",✗ No,✓ Only,⚠ Moderate,⚠ Limited (dark+neon),◐ Medium,◐ Medium,"Tailwind 8/10, Custom CSS 10/10",2020s Cyberpunk,Medium,"Design a cyberpunk interface. Use: neon colors on dark (#0D0D0D), terminal/HUD aesthetic, glitch effects, scanlines overlay, matrix green accents, monospace fonts, angular shapes, dystopian tech feel.","background: #0D0D0D, color: #00FF00 or #FF00FF, font-family: monospace, text-shadow: 0 0 10px neon, animation: glitch (transform skew), ::before scanlines (repeating-linear-gradient)","☐ Dark background only, ☐ Neon accents visible, ☐ Glitch effect subtle, ☐ Scanlines optional, ☐ Monospace font, ☐ Terminal aesthetic","--bg-dark: #0D0D0D, --neon-green: #00FF00, --neon-magenta: #FF00FF, --neon-cyan: #00FFFF, --scanline-opacity: 0.1, --glitch-duration: 0.3s"
|
||||||
|
42,Organic Biophilic,General,"Nature, organic shapes, green, sustainable, rounded, flowing, wellness, earthy, natural textures","#228B22 (Forest Green), #8B4513 (Earth Brown), #87CEEB (Sky Blue), #F5F5DC (Beige)","Natural gradients, earth tones, sky blues, organic textures, wood/stone colors","Rounded corners (16-24px), organic curves (border-radius variations), natural shadows, flowing SVG shapes","Wellness apps, sustainability brands, eco products, health apps, meditation, organic food brands","Tech-focused products, gaming, industrial, urban brands",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AA,✓ High,✓ High,"Tailwind 10/10, CSS 10/10",2020s Sustainable,Low,"Design a biophilic organic interface. Use: nature-inspired colors (greens, browns), organic curved shapes, rounded corners (16-24px), natural textures (wood, stone), flowing SVG elements, wellness aesthetic, earthy palette.","border-radius: 16-24px (varied), background: earth tones, SVG organic shapes (blob), box-shadow: natural soft, color: #228B22 #8B4513 #87CEEB, texture overlays (subtle)","☐ Earth tones dominant, ☐ Organic curves present, ☐ Natural textures subtle, ☐ Green accents, ☐ Rounded everywhere, ☐ Calming feel","--forest-green: #228B22, --earth-brown: #8B4513, --sky-blue: #87CEEB, --cream-bg: #F5F5DC, --organic-radius: 24px, --shadow-soft: 0 8px 32px rgba(0,0,0,0.08)"
|
||||||
|
43,AI-Native UI,General,"Chatbot, conversational, voice, assistant, agentic, ambient, minimal chrome, streaming text, AI interactions","Neutral + single accent, #6366F1 (AI Purple), #10B981 (Success), #F5F5F5 (Background)","Status indicators, streaming highlights, context card colors, subtle accent variations","Typing indicators (3-dot pulse), streaming text animations, pulse animations, context cards, smooth reveals","AI products, chatbots, voice assistants, copilots, AI-powered tools, conversational interfaces","Traditional forms, data-heavy dashboards, print-first content",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AA,✓ High,✓ High,"Tailwind 10/10, React 10/10",2020s AI-Era,Low,"Design an AI-native interface. Use: minimal chrome, conversational layout, streaming text area, typing indicators (3-dot pulse), context cards, subtle AI accent color (#6366F1), clean input field, response bubbles.","chat bubble layout (flex-direction: column), typing animation (3 dots pulse), streaming text (overflow: hidden + animation), input: sticky bottom, context cards (border-left accent), minimal borders","☐ Chat layout responsive, ☐ Typing indicator smooth, ☐ Input always visible, ☐ Context cards styled, ☐ AI responses distinct, ☐ User messages aligned right","--ai-accent: #6366F1, --user-bubble-bg: #E0E7FF, --ai-bubble-bg: #F9FAFB, --input-height: 48px, --typing-dot-size: 8px, --message-gap: 16px"
|
||||||
|
44,Memphis Design,General,"80s, geometric, playful, postmodern, shapes, patterns, squiggles, triangles, neon, abstract, bold","#FF71CE (Hot Pink), #FFCE5C (Yellow), #86CCCA (Teal), #6A7BB4 (Blue Purple)","Complementary geometric colors, pattern fills, contrasting accent shapes","transform: rotate(), clip-path: polygon(), mix-blend-mode, repeating patterns, bold shapes","Creative agencies, music sites, youth brands, event promotion, artistic portfolios, entertainment","Corporate finance, healthcare, legal, elderly users, conservative brands",✓ Full,✓ Full,⚡ Excellent,⚠ Check contrast,✓ Good,◐ Medium,"Tailwind 9/10, CSS 10/10",1980s Postmodern,Medium,"Design a Memphis style interface. Use: bold geometric shapes (triangles, squiggles, circles), bright clashing colors, 80s postmodern aesthetic, playful patterns, dotted textures, asymmetric layouts, decorative elements.","clip-path: polygon() for shapes, background: repeating patterns, transform: rotate() for tilted elements, mix-blend-mode for overlays, border: dashed/dotted patterns, bold sans-serif","☐ Geometric shapes visible, ☐ Colors bold/clashing, ☐ Patterns present, ☐ Layout asymmetric, ☐ Playful decorations, ☐ 80s vibe achieved","--memphis-pink: #FF71CE, --memphis-yellow: #FFCE5C, --memphis-teal: #86CCCA, --memphis-purple: #6A7BB4, --pattern-size: 20px, --shape-rotation: 15deg"
|
||||||
|
45,Vaporwave,General,"Synthwave, retro-futuristic, 80s-90s, neon, glitch, nostalgic, sunset gradient, dreamy, aesthetic","#FF71CE (Pink), #01CDFE (Cyan), #05FFA1 (Mint), #B967FF (Purple)","Sunset gradients, glitch overlays, VHS effects, neon accents, pastel variations","text-shadow glow, linear-gradient, filter: hue-rotate(), glitch animations, retro scan lines","Music platforms, gaming, creative portfolios, tech startups, entertainment, artistic projects","Business apps, e-commerce, education, healthcare, enterprise software",✓ Full,✓ Dark focused,⚠ Moderate,⚠ Poor (motion),◐ Medium,◐ Medium,"Tailwind 8/10, CSS-in-JS 9/10",1980s-90s Retro,Medium,"Design a vaporwave aesthetic interface. Use: sunset gradients (pink/cyan/purple), 80s-90s nostalgia, glitch effects, Greek statue imagery, palm trees, grid patterns, neon glow, retro-futuristic feel, dreamy atmosphere.","background: linear-gradient(180deg, #FF71CE, #01CDFE, #B967FF), filter: hue-rotate(), text-shadow: neon glow, retro grid (perspective + linear-gradient), VHS scanlines","☐ Sunset gradient present, ☐ Neon glow applied, ☐ Retro grid visible, ☐ Glitch effects subtle, ☐ Dreamy atmosphere, ☐ 80s-90s aesthetic","--vapor-pink: #FF71CE, --vapor-cyan: #01CDFE, --vapor-mint: #05FFA1, --vapor-purple: #B967FF, --grid-color: rgba(255,255,255,0.1), --glow-intensity: 15px"
|
||||||
|
46,Dimensional Layering,General,"Depth, overlapping, z-index, layers, 3D, shadows, elevation, floating, cards, spatial hierarchy","Neutral base (#FFFFFF, #F5F5F5, #E0E0E0) + brand accent for elevated elements","Shadow variations (sm/md/lg/xl), elevation colors, highlight colors for top layers","z-index stacking, box-shadow elevation (4 levels), transform: translateZ(), backdrop-filter, parallax","Dashboards, card layouts, modals, navigation, product showcases, SaaS interfaces","Print-style layouts, simple blogs, low-end devices, flat design requirements",✓ Full,✓ Full,⚠ Good,⚠ Moderate (SR issues),✓ Good,✓ High,"Tailwind 10/10, MUI 10/10, Chakra 10/10",2020s Modern,Medium,"Design with dimensional layering. Use: z-index depth (multiple layers), overlapping cards, elevation shadows (4 levels), floating elements, parallax depth, backdrop blur for hierarchy, spatial UI feel.","z-index: 1-4 levels, box-shadow: elevation scale (sm/md/lg/xl), transform: translateZ(), backdrop-filter: blur(), position: relative for stacking, parallax on scroll","☐ Layers clearly defined, ☐ Shadows show depth, ☐ Overlaps intentional, ☐ Hierarchy clear, ☐ Performance optimized, ☐ Mobile depth maintained","--elevation-1: 0 1px 3px rgba(0,0,0,0.1), --elevation-2: 0 4px 6px rgba(0,0,0,0.1), --elevation-3: 0 10px 20px rgba(0,0,0,0.1), --elevation-4: 0 20px 40px rgba(0,0,0,0.15), --blur-amount: 8px"
|
||||||
|
47,Exaggerated Minimalism,General,"Bold minimalism, oversized typography, high contrast, negative space, loud minimal, statement design","#000000 (Black), #FFFFFF (White), single vibrant accent only","Minimal - single accent color, no secondary colors, extreme restraint","font-size: clamp(3rem 10vw 12rem), font-weight: 900, letter-spacing: -0.05em, massive whitespace","Fashion, architecture, portfolios, agency landing pages, luxury brands, editorial","E-commerce catalogs, dashboards, forms, data-heavy, elderly users, complex apps",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AA,✓ High,✓ High,"Tailwind 10/10, Typography.js 10/10",2020s Modern,Low,"Design with exaggerated minimalism. Use: oversized typography (clamp 3rem-12rem), extreme negative space, black/white primary, single accent color only, bold statements, minimal elements, dramatic contrast.","font-size: clamp(3rem, 10vw, 12rem), font-weight: 900, letter-spacing: -0.05em, color: #000 or #FFF, padding: 8rem+, single accent, no decorations","☐ Typography oversized, ☐ White space extreme, ☐ Black/white dominant, ☐ Single accent only, ☐ Elements minimal, ☐ Statement clear","--type-giant: clamp(3rem, 10vw, 12rem), --type-weight: 900, --spacing-huge: 8rem, --color-primary: #000000, --color-bg: #FFFFFF, --accent: single color only"
|
||||||
|
48,Kinetic Typography,General,"Motion text, animated type, moving letters, dynamic, typing effect, morphing, scroll-triggered text","Flexible - high contrast recommended, bold colors for emphasis, animation-friendly palette","Accent colors for emphasis, transition colors, gradient text fills","@keyframes text animation, typing effect, background-clip: text, GSAP ScrollTrigger, split text","Hero sections, marketing sites, video platforms, storytelling, creative portfolios, landing pages","Long-form content, accessibility-critical, data interfaces, forms, elderly users",✓ Full,✓ Full,⚠ Moderate,❌ Poor (motion),✓ Good,✓ Very High,"GSAP 10/10, Framer Motion 10/10",2020s Modern,High,"Design with kinetic typography. Use: animated text, scroll-triggered reveals, typing effects, letter-by-letter animations, morphing text, gradient text fills, oversized hero text, text as the main visual element.","@keyframes for text animation, background-clip: text, GSAP SplitText, typing effect (steps()), transform on letters, scroll-triggered (Intersection Observer), variable fonts for morphing","☐ Text animations smooth, ☐ Prefers-reduced-motion respected, ☐ Fallback for no-JS, ☐ Mobile performance ok, ☐ Typing effect timed, ☐ Scroll triggers work","--text-animation-duration: 1s, --letter-delay: 0.05s, --typing-speed: 100ms, --gradient-text: linear-gradient(90deg, #color1, #color2), --morph-duration: 0.5s"
|
||||||
|
49,Parallax Storytelling,General,"Scroll-driven, narrative, layered scrolling, immersive, progressive disclosure, cinematic, scroll-triggered","Story-dependent, often gradients and natural colors, section-specific palettes","Section transition colors, depth layer colors, narrative mood colors","transform: translateY(scroll), position: fixed/sticky, perspective: 1px, scroll-triggered animations","Brand storytelling, product launches, case studies, portfolios, annual reports, marketing campaigns","E-commerce, dashboards, mobile-first, SEO-critical, accessibility-required",✓ Full,✓ Full,❌ Poor,❌ Poor (motion),✗ Low,✓ High,"GSAP ScrollTrigger 10/10, Locomotive Scroll 10/10",2020s Modern,High,"Design a parallax storytelling page. Use: scroll-driven narrative, layered backgrounds (3-5 layers), fixed/sticky sections, cinematic transitions, progressive disclosure, full-screen chapters, depth perception.","position: fixed/sticky, transform: translateY(calc()), perspective: 1px, z-index layering, scroll-snap-type, Intersection Observer for triggers, will-change: transform","☐ Layers parallax smoothly, ☐ Story flows naturally, ☐ Mobile alternative provided, ☐ Performance optimized, ☐ Skip option available, ☐ Reduced motion fallback","--parallax-speed-bg: 0.3, --parallax-speed-mid: 0.6, --parallax-speed-fg: 1, --section-height: 100vh, --transition-duration: 600ms, --perspective: 1px"
|
||||||
|
50,Swiss Modernism 2.0,General,"Grid system, Helvetica, modular, asymmetric, international style, rational, clean, mathematical spacing","#000000, #FFFFFF, #F5F5F5, single vibrant accent only","Minimal secondary, accent for emphasis only, no gradients","display: grid, grid-template-columns: repeat(12 1fr), gap: 1rem, mathematical ratios, clear hierarchy","Corporate sites, architecture, editorial, SaaS, museums, professional services, documentation","Playful brands, children's sites, entertainment, gaming, emotional storytelling",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AAA,✓ High,✓ High,"Tailwind 10/10, Bootstrap 9/10, Foundation 10/10",1950s Swiss + 2020s,Low,"Design with Swiss Modernism 2.0. Use: strict grid system (12 columns), Helvetica/Inter fonts, mathematical spacing, asymmetric balance, high contrast, minimal decoration, clean hierarchy, single accent color.","display: grid, grid-template-columns: repeat(12, 1fr), gap: 1rem (8px base unit), font-family: Inter/Helvetica, font-weight: 400-700, color: #000/#FFF, single accent","☐ 12-column grid strict, ☐ Spacing mathematical, ☐ Typography hierarchy clear, ☐ Single accent only, ☐ No decorations, ☐ High contrast verified","--grid-columns: 12, --grid-gap: 1rem, --base-unit: 8px, --font-primary: Inter, --color-text: #000000, --color-bg: #FFFFFF, --accent: single vibrant"
|
||||||
|
51,HUD / Sci-Fi FUI,General,"Futuristic, technical, wireframe, neon, data, transparency, iron man, sci-fi, interface","Neon Cyan #00FFFF, Holographic Blue #0080FF, Alert Red #FF0000","Transparent Black, Grid Lines #333333","Glow effects, scanning animations, ticker text, blinking markers, fine line drawing","Sci-fi games, space tech, cybersecurity, movie props, immersive dashboards","Standard corporate, reading heavy content, accessible public services",✓ Low,✓ Full,⚠ Moderate (renders),⚠ Poor (thin lines),◐ Medium,✗ Low,"React 9/10, Canvas 10/10",2010s Sci-Fi,High,"Design a futuristic HUD (Heads Up Display) or FUI. Use: thin lines (1px), neon cyan/blue on black, technical markers, decorative brackets, data visualization, monospaced tech fonts, glowing elements, transparency.","border: 1px solid rgba(0,255,255,0.5), color: #00FFFF, background: transparent or rgba(0,0,0,0.8), font-family: monospace, text-shadow: 0 0 5px cyan","☐ Fine lines 1px, ☐ Neon glow text/borders, ☐ Monospaced font, ☐ Dark/Transparent BG, ☐ Decorative tech markers, ☐ Holographic feel","--hud-color: #00FFFF, --bg-color: rgba(0,10,20,0.9), --line-width: 1px, --glow: 0 0 5px, --font: monospace"
|
||||||
|
52,Pixel Art,General,"Retro, 8-bit, 16-bit, gaming, blocky, nostalgic, pixelated, arcade","Primary colors (NES Palette), brights, limited palette","Black outlines, shading via dithering or block colors","Frame-by-frame sprite animation, blinking cursor, instant transitions, marquee text","Indie games, retro tools, creative portfolios, nostalgia marketing, Web3/NFT","Professional corporate, modern SaaS, high-res photography sites",✓ Full,✓ Full,⚡ Excellent,✓ Good (if contrast ok),✓ High,◐ Medium,"CSS (box-shadow) 8/10, Canvas 10/10",1980s Arcade,Medium,"Design a pixel art inspired interface. Use: pixelated fonts, 8-bit or 16-bit aesthetic, sharp edges (image-rendering: pixelated), limited color palette, blocky UI elements, retro gaming feel.","font-family: 'Press Start 2P', image-rendering: pixelated, box-shadow: 4px 0 0 #000 (pixel border), no anti-aliasing","☐ Pixelated fonts loaded, ☐ Images sharp (no blur), ☐ CSS box-shadow for pixel borders, ☐ Retro palette, ☐ Blocky layout","--pixel-size: 4px, --font: pixel font, --border-style: pixel-shadow, --anti-alias: none"
|
||||||
|
53,Bento Grids,General,"Apple-style, modular, cards, organized, clean, hierarchy, grid, rounded, soft","Off-white #F5F5F7, Clean White #FFFFFF, Text #1D1D1F","Subtle accents, soft shadows, blurred backdrops","Hover scale (1.02), soft shadow expansion, smooth layout shifts, content reveal","Product features, dashboards, personal sites, marketing summaries, galleries","Long-form reading, data tables, complex forms",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AA,✓ High,✓ High,"CSS Grid 10/10, Tailwind 10/10",2020s Apple/Linear,Low,"Design a Bento Grid layout. Use: modular grid system, rounded corners (16-24px), different card sizes (1x1, 2x1, 2x2), card-based hierarchy, soft backgrounds (#F5F5F7), subtle borders, content-first, Apple-style aesthetic.","display: grid, grid-template-columns: repeat(auto-fit, minmax(...)), gap: 1rem, border-radius: 20px, background: #FFF, box-shadow: subtle","☐ Grid layout (CSS Grid), ☐ Rounded corners 16-24px, ☐ Varied card spans, ☐ Content fits card size, ☐ Responsive re-flow, ☐ Apple-like aesthetic","--grid-gap: 20px, --card-radius: 24px, --card-bg: #FFFFFF, --page-bg: #F5F5F7, --shadow: soft"
|
||||||
|
55,Spatial UI (VisionOS),General,"Glass, depth, immersion, spatial, translucent, gaze, gesture, apple, vision-pro","Frosted Glass #FFFFFF (15-30% opacity), System White","Vibrant system colors for active states, deep shadows for depth","Parallax depth, dynamic lighting response, gaze-hover effects, smooth scale on focus","Spatial computing apps, VR/AR interfaces, immersive media, futuristic dashboards","Text-heavy documents, high-contrast requirements, non-3D capable devices",✓ Full,✓ Full,⚠ Moderate (blur cost),⚠ Contrast risks,✓ High (if adapted),✓ High,"SwiftUI, React (Three.js/Fiber)",2024 Spatial Era,High,"Design a VisionOS-style spatial interface. Use: frosted glass panels, depth layers, translucent backgrounds (15-30% opacity), vibrant colors for active states, gaze-hover effects, floating windows, immersive feel.","backdrop-filter: blur(40px) saturate(180%), background: rgba(255,255,255,0.2), border-radius: 24px, box-shadow: 0 8px 32px rgba(0,0,0,0.1), transform: scale on focus, depth via shadows","☐ Glass effect visible, ☐ Depth layers clear, ☐ Hover states defined, ☐ Colors vibrant on active, ☐ Floating feel achieved, ☐ Contrast maintained","--glass-bg: rgba(255,255,255,0.2), --glass-blur: 40px, --glass-saturate: 180%, --window-radius: 24px, --depth-shadow: 0 8px 32px rgba(0,0,0,0.1), --focus-scale: 1.02"
|
||||||
|
56,E-Ink / Paper,General,"Paper-like, matte, high contrast, texture, reading, calm, slow tech, monochrome","Off-White #FDFBF7, Paper White #F5F5F5, Ink Black #1A1A1A","Pencil Grey #4A4A4A, Highlighter Yellow #FFFF00 (accent)","No motion blur, distinct page turns, grain/noise texture, sharp transitions (no fade)","Reading apps, digital newspapers, minimal journals, distraction-free writing, slow-living brands","Gaming, video platforms, high-energy marketing, dark mode dependent apps",✓ Full,✗ Low (inverted only),⚡ Excellent,✓ WCAG AAA,✓ High,✓ Medium,"Tailwind 10/10, CSS 10/10",2020s Digital Well-being,Low,"Design an e-ink/paper style interface. Use: high contrast black on off-white, paper texture, no animations (instant transitions), reading-focused, minimal UI chrome, distraction-free, calm aesthetic, monochrome.","background: #FDFBF7 (paper white), color: #1A1A1A, transition: none, font-family: serif for reading, no gradients, border: 1px solid #E0E0E0, texture overlay (noise)","☐ Paper background color, ☐ High contrast text, ☐ No animations, ☐ Reading optimized, ☐ Distraction-free, ☐ Print-friendly","--paper-bg: #FDFBF7, --ink-color: #1A1A1A, --pencil-grey: #4A4A4A, --border-color: #E0E0E0, --font-reading: Georgia, --transition: none"
|
||||||
|
57,Gen Z Chaos / Maximalism,General,"Chaos, clutter, stickers, raw, collage, mixed media, loud, internet culture, ironic","Clashing Brights: #FF00FF, #00FF00, #FFFF00, #0000FF","Gradients, rainbow, glitch, noise, heavily saturated mix","Marquee scrolls, jitter, sticker layering, GIF overload, random placement, drag-and-drop","Gen Z lifestyle brands, music artists, creative portfolios, viral marketing, fashion","Corporate, government, healthcare, banking, serious tools",✓ Full,✓ Full,⚠ Poor (heavy assets),❌ Poor,◐ Medium,✓ High (Viral),CSS-in-JS 8/10,2023+ Internet Core,High,"Design a Gen Z chaos maximalist interface. Use: clashing bright colors, sticker overlays, collage aesthetic, raw/unpolished feel, mixed media, ironic elements, loud typography, GIF-heavy, internet culture references.","mix-blend-mode: multiply/screen, transform: rotate(random), animation: jitter, marquee text, position: absolute for scattered elements, filter: saturate(150%), z-index chaos","☐ Colors clash intentionally, ☐ Stickers/overlays present, ☐ Layout chaotic but usable, ☐ GIFs optimized, ☐ Mobile scrollable, ☐ Performance acceptable","--chaos-pink: #FF00FF, --chaos-green: #00FF00, --chaos-yellow: #FFFF00, --chaos-blue: #0000FF, --jitter-amount: 5deg, --saturate: 150%"
|
||||||
|
58,Biomimetic / Organic 2.0,General,"Nature-inspired, cellular, fluid, breathing, generative, algorithms, life-like","Cellular Pink #FF9999, Chlorophyll Green #00FF41, Bioluminescent Blue","Deep Ocean #001E3C, Coral #FF7F50, Organic gradients","Breathing animations, fluid morphing, generative growth, physics-based movement","Sustainability tech, biotech, advanced health, meditation, generative art platforms","Standard SaaS, data grids, strict corporate, accounting",✓ Full,✓ Full,⚠ Moderate,✓ Good,✓ Good,✓ High,"Canvas 10/10, WebGL 10/10",2024+ Generative,High,"Design a biomimetic organic interface. Use: cellular/fluid shapes, breathing animations, generative patterns, bioluminescent colors, physics-based movement, nature algorithms, life-like elements, flowing gradients.","SVG morphing (SMIL or GSAP), canvas for generative, animation: breathing (scale pulse), filter: blur for organic, clip-path for cellular, WebGL for advanced, physics libraries","☐ Organic shapes present, ☐ Animations feel alive, ☐ Generative elements, ☐ Performance monitored, ☐ Mobile fallback, ☐ Accessibility alt content","--cellular-pink: #FF9999, --chlorophyll: #00FF41, --bioluminescent: #00FFFF, --breathing-duration: 4s, --morph-ease: cubic-bezier(0.4, 0, 0.2, 1), --organic-blur: 20px"
|
||||||
|
59,Anti-Polish / Raw Aesthetic,General,"Hand-drawn, collage, scanned textures, unfinished, imperfect, authentic, human, sketch, raw marks, creative process","Paper White #FAFAF8, Pencil Grey #4A4A4A, Marker Black #1A1A1A, Kraft Brown #C4A77D","Watercolor washes, pencil shading, ink splatters, tape textures, aged paper tones","No smooth transitions, hand-drawn animations, paper texture overlays, jitter effects, sketch reveal","Creative portfolios, artist sites, indie brands, handmade products, authentic storytelling, editorial","Corporate enterprise, fintech, healthcare, government, polished SaaS",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AA,✓ High,✓ High,"CSS 10/10, SVG 10/10",2025+ Anti-Digital,Low,"Design with anti-polish raw aesthetic. Use: hand-drawn elements, scanned textures, unfinished look, paper/pencil textures, collage style, authentic imperfection, sketch marks, tape/sticker overlays, human touch.","background: url(paper-texture.png), filter: grayscale() contrast(), border: hand-drawn SVG, transform: rotate(small random), no smooth transitions, sketch-style fonts, opacity variations","☐ Textures loaded, ☐ Hand-drawn elements present, ☐ Imperfections intentional, ☐ Authentic feel achieved, ☐ Performance ok with textures, ☐ Accessibility maintained","--paper-bg: #FAFAF8, --pencil-color: #4A4A4A, --marker-black: #1A1A1A, --kraft-brown: #C4A77D, --sketch-rotation: random(-3deg, 3deg), --texture-opacity: 0.3"
|
||||||
|
60,Tactile Digital / Deformable UI,General,"Jelly buttons, chrome, clay, squishy, deformable, bouncy, physical, tactile feedback, press response","Gradient metallics, Chrome Silver #C0C0C0, Jelly Pink #FF9ECD, Soft Blue #87CEEB","Glossy highlights, shadow depth, reflection effects, material-specific colors","Press deformation (scale + squish), bounce-back (cubic-bezier), material response, haptic-like feedback, spring physics","Modern mobile apps, playful brands, entertainment, gaming UI, consumer products, interactive demos","Enterprise software, data dashboards, accessibility-critical, professional tools",✓ Full,✓ Full,⚠ Good,⚠ Motion sensitive,✓ High,✓ Very High,"Framer Motion 10/10, React Spring 10/10, GSAP 10/10",2025+ Tactile Era,Medium,"Design a tactile deformable interface. Use: jelly/squishy buttons, press deformation effect, bounce-back animations, chrome/clay materials, spring physics, haptic-like feedback, material response, 3D depth on interaction.","transform: scale(0.95) on active, animation: bounce (cubic-bezier(0.34, 1.56, 0.64, 1)), box-shadow: inset for press, filter: brightness on press, spring physics (react-spring/framer-motion)","☐ Press effect visible, ☐ Bounce-back smooth, ☐ Material feels tactile, ☐ Spring physics tuned, ☐ Mobile touch responsive, ☐ Reduced motion option","--press-scale: 0.95, --bounce-duration: 400ms, --spring-stiffness: 300, --spring-damping: 20, --material-glossy: linear-gradient(135deg, white 0%, transparent 60%), --depth-shadow: 0 10px 30px rgba(0,0,0,0.2)"
|
||||||
|
61,Nature Distilled,General,"Muted earthy, skin tones, wood, soil, sand, terracotta, warmth, organic materials, handmade warmth","Terracotta #C67B5C, Sand Beige #D4C4A8, Warm Clay #B5651D, Soft Cream #F5F0E1","Earth Brown #8B4513, Olive Green #6B7B3C, Warm Stone #9C8B7A, muted gradients","Subtle parallax, natural easing (ease-out), texture overlays, grain effects, soft shadows","Wellness brands, sustainable products, artisan goods, organic food, spa/beauty, home decor","Tech startups, gaming, nightlife, corporate finance, high-energy brands",✓ Full,◐ Partial,⚡ Excellent,✓ WCAG AA,✓ High,✓ High,"Tailwind 10/10, CSS 10/10",2025+ Handmade Warmth,Low,"Design with nature distilled aesthetic. Use: muted earthy colors (terracotta, sand, olive), organic materials feel, warm tones, handmade warmth, natural textures, artisan quality, sustainable vibe, soft gradients.","background: warm earth tones, color: #C67B5C #D4C4A8 #6B7B3C, border-radius: organic (varied), box-shadow: soft natural, texture overlays (grain), font: humanist sans-serif","☐ Earth tones dominant, ☐ Warm feel achieved, ☐ Textures subtle, ☐ Handmade quality, ☐ Sustainable messaging, ☐ Calming aesthetic","--terracotta: #C67B5C, --sand-beige: #D4C4A8, --warm-clay: #B5651D, --soft-cream: #F5F0E1, --olive-green: #6B7B3C, --grain-opacity: 0.1"
|
||||||
|
62,Interactive Cursor Design,General,"Custom cursor, cursor as tool, hover effects, cursor feedback, pointer transformation, cursor trail, magnetic cursor","Brand-dependent, cursor accent color, high contrast for visibility","Trail colors, hover state colors, magnetic zone indicators, feedback colors","Cursor scale on hover, magnetic pull to elements, cursor morphing, trail effects, blend mode cursors, click feedback","Creative portfolios, interactive experiences, agency sites, product showcases, gaming, entertainment","Mobile-first (no cursor), accessibility-critical, data-heavy dashboards, forms",✓ Full,✓ Full,⚡ Good,⚠ Not for touch/SR,✗ No cursor,✓ High,"GSAP 10/10, Framer Motion 10/10, Custom JS 10/10",2025+ Interactive,Medium,"Design with interactive cursor effects. Use: custom cursor, cursor morphing on hover, magnetic cursor pull, cursor trails, blend mode cursors, click feedback animations, cursor as interaction tool, pointer transformation.","cursor: none (custom), position: fixed for cursor element, mix-blend-mode: difference, transform on hover targets, magnetic effect (JS position lerp), trail with opacity fade, scale on click","☐ Custom cursor works, ☐ Hover morph smooth, ☐ Magnetic pull subtle, ☐ Trail performance ok, ☐ Click feedback visible, ☐ Touch fallback provided","--cursor-size: 20px, --cursor-hover-scale: 1.5, --magnetic-distance: 100px, --trail-length: 10, --trail-fade: 0.1, --blend-mode: difference"
|
||||||
|
63,Voice-First Multimodal,General,"Voice UI, multimodal, audio feedback, conversational, hands-free, ambient, contextual, speech recognition","Calm neutrals: Soft White #FAFAFA, Muted Blue #6B8FAF, Gentle Purple #9B8FBB","Audio waveform colors, status indicators (listening/processing/speaking), success/error tones","Voice waveform visualization, listening pulse, processing spinner, speak animation, smooth transitions","Voice assistants, accessibility apps, hands-free tools, smart home, automotive UI, cooking apps","Visual-heavy content, data entry, complex forms, noisy environments",✓ Full,✓ Full,⚡ Excellent,✓ Excellent,✓ High,✓ High,"Web Speech API 10/10, React 10/10",2025+ Voice Era,Medium,"Design a voice-first multimodal interface. Use: voice waveform visualization, listening state indicator, speaking animation, minimal visible UI, audio feedback cues, hands-free optimized, conversational flow, ambient design.","Web Speech API integration, canvas for waveform, animation: pulse for listening, status indicators (color change), audio visualization (Web Audio API), minimal chrome, large touch targets","☐ Voice recognition works, ☐ Visual feedback clear, ☐ Listening state obvious, ☐ Speaking animation smooth, ☐ Fallback UI provided, ☐ Accessibility excellent","--listening-color: #6B8FAF, --speaking-color: #22C55E, --waveform-height: 60px, --pulse-duration: 1.5s, --indicator-size: 24px, --voice-accent: #9B8FBB"
|
||||||
|
64,3D Product Preview,General,"360 product view, rotatable, zoomable, touch-to-spin, AR preview, product configurator, interactive 3D model","Product-dependent, neutral backgrounds: Soft Grey #E8E8E8, Pure White #FFFFFF","Shadow gradients, reflection planes, environment lighting colors, accent highlights","Drag-to-rotate, pinch-to-zoom, spin animation, AR placement, material switching, smooth orbit controls","E-commerce, furniture, fashion, automotive, electronics, jewelry, product configurators","Content-heavy sites, blogs, dashboards, low-bandwidth, accessibility-critical",◐ Partial,◐ Partial,❌ Poor (3D rendering),⚠ Alt content needed,◐ Medium,✓ Very High,"Three.js 10/10, model-viewer 10/10, Spline 9/10",2025+ E-commerce 3D,High,"Design a 3D product preview interface. Use: 360° rotation, drag-to-spin, pinch-to-zoom, AR preview button, material/color switcher, hotspot annotations, orbit controls, product configurator, smooth rendering.","Three.js or model-viewer, OrbitControls, touch events for rotation, WebXR for AR, canvas with WebGL, loading placeholder, LOD for performance, environment lighting","☐ 3D model loads fast, ☐ Rotation smooth, ☐ Zoom works (pinch/scroll), ☐ AR button functional, ☐ Colors switchable, ☐ Mobile touch works","--canvas-bg: #F5F5F5, --hotspot-color: #3B82F6, --loading-spinner: primary, --rotation-speed: 0.5, --zoom-min: 0.5, --zoom-max: 2"
|
||||||
|
65,Gradient Mesh / Aurora Evolved,General,"Complex gradients, mesh gradients, multi-color blend, aurora effect, flowing colors, iridescent, holographic, prismatic","Multi-stop gradients: Cyan #00FFFF, Magenta #FF00FF, Yellow #FFFF00, Blue #0066FF, Green #00FF66","Complementary mesh points, smooth color transitions, iridescent overlays, chromatic shifts","CSS mesh-gradient (experimental), SVG gradients, canvas gradients, smooth color morphing, flowing animation","Hero sections, backgrounds, creative brands, music platforms, fashion, lifestyle, premium products","Data interfaces, text-heavy content, accessibility-critical, conservative brands",✓ Full,✓ Full,⚠ Good,⚠ Text contrast,✓ Good,✓ High,"CSS 8/10, SVG 10/10, Canvas 10/10",2025+ Gradient Evolution,Medium,"Design with gradient mesh aurora effect. Use: multi-color mesh gradients, flowing color transitions, aurora/northern lights feel, iridescent overlays, holographic shimmer, prismatic effects, smooth color morphing.","background: conic-gradient or mesh (SVG), animation: gradient flow (background-position), filter: hue-rotate for shimmer, mix-blend-mode: screen, canvas for complex mesh, multiple gradient layers","☐ Mesh gradient visible, ☐ Colors flow smoothly, ☐ Aurora effect achieved, ☐ Performance acceptable, ☐ Text remains readable, ☐ Mobile renders ok","--mesh-color-1: #00FFFF, --mesh-color-2: #FF00FF, --mesh-color-3: #FFFF00, --mesh-color-4: #00FF66, --flow-duration: 10s, --shimmer-intensity: 0.3"
|
||||||
|
66,Editorial Grid / Magazine,General,"Magazine layout, asymmetric grid, editorial typography, pull quotes, drop caps, column layout, print-inspired","High contrast: Black #000000, White #FFFFFF, accent brand color","Muted supporting, pull quote highlights, byline colors, section dividers","Smooth scroll, reveal on scroll, parallax images, text animations, page-flip transitions","News sites, blogs, magazines, editorial content, long-form articles, journalism, publishing","Dashboards, apps, e-commerce catalogs, real-time data, short-form content",✓ Full,✓ Full,⚡ Excellent,✓ WCAG AAA,✓ High,✓ Medium,"CSS Grid 10/10, Tailwind 10/10",2020s Editorial Digital,Low,"Design an editorial magazine layout. Use: asymmetric grid, pull quotes, drop caps, multi-column text, large imagery, bylines, section dividers, print-inspired typography, article hierarchy, white space balance.","display: grid with named areas, column-count for text, ::first-letter for drop caps, blockquote styling, figure/figcaption, gap variations, font: serif for body, variable widths","☐ Grid asymmetric, ☐ Typography editorial, ☐ Pull quotes styled, ☐ Drop caps present, ☐ Images large/impactful, ☐ Mobile reflows well","--grid-cols: asymmetric, --body-font: Georgia/Merriweather, --heading-font: bold sans, --drop-cap-size: 4em, --pull-quote-size: 1.5em, --column-gap: 2rem"
|
||||||
|
67,Chromatic Aberration / RGB Split,General,"RGB split, color fringing, glitch, retro tech, VHS, analog error, distortion, lens effect","Offset RGB: Red #FF0000, Green #00FF00, Blue #0000FF, Black #000000","Neon accents, scan lines, noise overlays, error colors","RGB offset animation, glitch timing, scan line movement, noise flicker, distortion on hover","Music platforms, gaming, tech brands, creative portfolios, nightlife, entertainment, video platforms","Corporate, healthcare, finance, accessibility-critical, elderly users",✓ Full,✓ Dark preferred,⚠ Good,⚠ Can cause strain,◐ Medium,✓ High,"CSS filters 10/10, GSAP 10/10",2020s Retro-Tech,Medium,"Design with chromatic aberration RGB split effect. Use: color channel offset (R/G/B), glitch aesthetic, retro tech feel, VHS error look, lens distortion, scan lines, noise overlay, analog imperfection.","filter: drop-shadow with offset colors, text-shadow: RGB offset (-2px 0 red, 2px 0 cyan), animation: glitch (random offset), ::before for scanlines, mix-blend-mode: screen for overlays","☐ RGB split visible, ☐ Glitch effect controlled, ☐ Scan lines subtle, ☐ Performance ok, ☐ Readability maintained, ☐ Reduced motion option","--rgb-offset: 2px, --red-channel: #FF0000, --green-channel: #00FF00, --blue-channel: #0000FF, --glitch-duration: 0.3s, --scanline-opacity: 0.1"
|
||||||
|
68,Vintage Analog / Retro Film,General,"Film grain, VHS, cassette tape, polaroid, analog warmth, faded colors, light leaks, vintage photography","Faded Cream #F5E6C8, Warm Sepia #D4A574, Muted Teal #4A7B7C, Soft Pink #E8B4B8","Grain overlays, light leak oranges, shadow blues, vintage paper tones, desaturated accents","Film grain overlay, VHS tracking effect, polaroid shake, fade-in transitions, light leak animations","Photography portfolios, music/vinyl brands, vintage fashion, nostalgia marketing, film industry, cafes","Modern tech, SaaS, healthcare, children's apps, corporate enterprise",✓ Full,◐ Partial,⚡ Good,✓ WCAG AA,✓ High,✓ High,"CSS filters 10/10, Canvas 9/10",1970s-90s Analog Revival,Medium,"Design with vintage analog film aesthetic. Use: film grain overlay, faded/desaturated colors, warm sepia tones, light leaks, VHS tracking effect, polaroid frame, analog warmth, nostalgic photography feel.","filter: sepia() contrast() saturate(0.8), background: noise texture overlay, animation: VHS tracking (transform skew), light leak gradient overlay, border for polaroid frame, grain via SVG filter","☐ Film grain visible, ☐ Colors faded/warm, ☐ Light leaks present, ☐ Nostalgic feel achieved, ☐ Performance with filters, ☐ Images look vintage","--sepia-amount: 20%, --contrast: 1.1, --saturation: 0.8, --grain-opacity: 0.15, --light-leak-color: rgba(255,200,100,0.2), --warm-tint: #F5E6C8"
|
||||||
|
@@ -0,0 +1,58 @@
|
|||||||
|
No,Font Pairing Name,Category,Heading Font,Body Font,Mood/Style Keywords,Best For,Google Fonts URL,CSS Import,Tailwind Config,Notes
|
||||||
|
1,Classic Elegant,"Serif + Sans",Playfair Display,Inter,"elegant, luxury, sophisticated, timeless, premium, editorial","Luxury brands, fashion, spa, beauty, editorial, magazines, high-end e-commerce","https://fonts.google.com/share?selection.family=Inter:wght@300;400;500;600;700|Playfair+Display:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Playfair+Display:wght@400;500;600;700&display=swap');","fontFamily: { serif: ['Playfair Display', 'serif'], sans: ['Inter', 'sans-serif'] }","High contrast between elegant heading and clean body. Perfect for luxury/premium."
|
||||||
|
2,Modern Professional,"Sans + Sans",Poppins,Open Sans,"modern, professional, clean, corporate, friendly, approachable","SaaS, corporate sites, business apps, startups, professional services","https://fonts.google.com/share?selection.family=Open+Sans:wght@300;400;500;600;700|Poppins:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;500;600;700&family=Poppins:wght@400;500;600;700&display=swap');","fontFamily: { heading: ['Poppins', 'sans-serif'], body: ['Open Sans', 'sans-serif'] }","Geometric Poppins for headings, humanist Open Sans for readability."
|
||||||
|
3,Tech Startup,"Sans + Sans",Space Grotesk,DM Sans,"tech, startup, modern, innovative, bold, futuristic","Tech companies, startups, SaaS, developer tools, AI products","https://fonts.google.com/share?selection.family=DM+Sans:wght@400;500;700|Space+Grotesk:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&family=Space+Grotesk:wght@400;500;600;700&display=swap');","fontFamily: { heading: ['Space Grotesk', 'sans-serif'], body: ['DM Sans', 'sans-serif'] }","Space Grotesk has unique character, DM Sans is highly readable."
|
||||||
|
4,Editorial Classic,"Serif + Serif",Cormorant Garamond,Libre Baskerville,"editorial, classic, literary, traditional, refined, bookish","Publishing, blogs, news sites, literary magazines, book covers","https://fonts.google.com/share?selection.family=Cormorant+Garamond:wght@400;500;600;700|Libre+Baskerville:wght@400;700","@import url('https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@400;500;600;700&family=Libre+Baskerville:wght@400;700&display=swap');","fontFamily: { heading: ['Cormorant Garamond', 'serif'], body: ['Libre Baskerville', 'serif'] }","All-serif pairing for traditional editorial feel."
|
||||||
|
5,Minimal Swiss,"Sans + Sans",Inter,Inter,"minimal, clean, swiss, functional, neutral, professional","Dashboards, admin panels, documentation, enterprise apps, design systems","https://fonts.google.com/share?selection.family=Inter:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');","fontFamily: { sans: ['Inter', 'sans-serif'] }","Single font family with weight variations. Ultimate simplicity."
|
||||||
|
6,Playful Creative,"Display + Sans",Fredoka,Nunito,"playful, friendly, fun, creative, warm, approachable","Children's apps, educational, gaming, creative tools, entertainment","https://fonts.google.com/share?selection.family=Fredoka:wght@400;500;600;700|Nunito:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Fredoka:wght@400;500;600;700&family=Nunito:wght@300;400;500;600;700&display=swap');","fontFamily: { heading: ['Fredoka', 'sans-serif'], body: ['Nunito', 'sans-serif'] }","Rounded, friendly fonts perfect for playful UIs."
|
||||||
|
7,Bold Statement,"Display + Sans",Bebas Neue,Source Sans 3,"bold, impactful, strong, dramatic, modern, headlines","Marketing sites, portfolios, agencies, event pages, sports","https://fonts.google.com/share?selection.family=Bebas+Neue|Source+Sans+3:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Source+Sans+3:wght@300;400;500;600;700&display=swap');","fontFamily: { display: ['Bebas Neue', 'sans-serif'], body: ['Source Sans 3', 'sans-serif'] }","Bebas Neue for large headlines only. All-caps display font."
|
||||||
|
8,Wellness Calm,"Serif + Sans",Lora,Raleway,"calm, wellness, health, relaxing, natural, organic","Health apps, wellness, spa, meditation, yoga, organic brands","https://fonts.google.com/share?selection.family=Lora:wght@400;500;600;700|Raleway:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Lora:wght@400;500;600;700&family=Raleway:wght@300;400;500;600;700&display=swap');","fontFamily: { serif: ['Lora', 'serif'], sans: ['Raleway', 'sans-serif'] }","Lora's organic curves with Raleway's elegant simplicity."
|
||||||
|
9,Developer Mono,"Mono + Sans",JetBrains Mono,IBM Plex Sans,"code, developer, technical, precise, functional, hacker","Developer tools, documentation, code editors, tech blogs, CLI apps","https://fonts.google.com/share?selection.family=IBM+Plex+Sans:wght@300;400;500;600;700|JetBrains+Mono:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600;700&display=swap');","fontFamily: { mono: ['JetBrains Mono', 'monospace'], sans: ['IBM Plex Sans', 'sans-serif'] }","JetBrains for code, IBM Plex for UI. Developer-focused."
|
||||||
|
10,Retro Vintage,"Display + Serif",Abril Fatface,Merriweather,"retro, vintage, nostalgic, dramatic, decorative, bold","Vintage brands, breweries, restaurants, creative portfolios, posters","https://fonts.google.com/share?selection.family=Abril+Fatface|Merriweather:wght@300;400;700","@import url('https://fonts.googleapis.com/css2?family=Abril+Fatface&family=Merriweather:wght@300;400;700&display=swap');","fontFamily: { display: ['Abril Fatface', 'serif'], body: ['Merriweather', 'serif'] }","Abril Fatface for hero headlines only. High-impact vintage feel."
|
||||||
|
11,Geometric Modern,"Sans + Sans",Outfit,Work Sans,"geometric, modern, clean, balanced, contemporary, versatile","General purpose, portfolios, agencies, modern brands, landing pages","https://fonts.google.com/share?selection.family=Outfit:wght@300;400;500;600;700|Work+Sans:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600;700&family=Work+Sans:wght@300;400;500;600;700&display=swap');","fontFamily: { heading: ['Outfit', 'sans-serif'], body: ['Work Sans', 'sans-serif'] }","Both geometric but Outfit more distinctive for headings."
|
||||||
|
12,Luxury Serif,"Serif + Sans",Cormorant,Montserrat,"luxury, high-end, fashion, elegant, refined, premium","Fashion brands, luxury e-commerce, jewelry, high-end services","https://fonts.google.com/share?selection.family=Cormorant:wght@400;500;600;700|Montserrat:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Cormorant:wght@400;500;600;700&family=Montserrat:wght@300;400;500;600;700&display=swap');","fontFamily: { serif: ['Cormorant', 'serif'], sans: ['Montserrat', 'sans-serif'] }","Cormorant's elegance with Montserrat's geometric precision."
|
||||||
|
13,Friendly SaaS,"Sans + Sans",Plus Jakarta Sans,Plus Jakarta Sans,"friendly, modern, saas, clean, approachable, professional","SaaS products, web apps, dashboards, B2B, productivity tools","https://fonts.google.com/share?selection.family=Plus+Jakarta+Sans:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700&display=swap');","fontFamily: { sans: ['Plus Jakarta Sans', 'sans-serif'] }","Single versatile font. Modern alternative to Inter."
|
||||||
|
14,News Editorial,"Serif + Sans",Newsreader,Roboto,"news, editorial, journalism, trustworthy, readable, informative","News sites, blogs, magazines, journalism, content-heavy sites","https://fonts.google.com/share?selection.family=Newsreader:wght@400;500;600;700|Roboto:wght@300;400;500;700","@import url('https://fonts.googleapis.com/css2?family=Newsreader:wght@400;500;600;700&family=Roboto:wght@300;400;500;700&display=swap');","fontFamily: { serif: ['Newsreader', 'serif'], sans: ['Roboto', 'sans-serif'] }","Newsreader designed for long-form reading. Roboto for UI."
|
||||||
|
15,Handwritten Charm,"Script + Sans",Caveat,Quicksand,"handwritten, personal, friendly, casual, warm, charming","Personal blogs, invitations, creative portfolios, lifestyle brands","https://fonts.google.com/share?selection.family=Caveat:wght@400;500;600;700|Quicksand:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Caveat:wght@400;500;600;700&family=Quicksand:wght@300;400;500;600;700&display=swap');","fontFamily: { script: ['Caveat', 'cursive'], sans: ['Quicksand', 'sans-serif'] }","Use Caveat sparingly for accents. Quicksand for body."
|
||||||
|
16,Corporate Trust,"Sans + Sans",Lexend,Source Sans 3,"corporate, trustworthy, accessible, readable, professional, clean","Enterprise, government, healthcare, finance, accessibility-focused","https://fonts.google.com/share?selection.family=Lexend:wght@300;400;500;600;700|Source+Sans+3:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Lexend:wght@300;400;500;600;700&family=Source+Sans+3:wght@300;400;500;600;700&display=swap');","fontFamily: { heading: ['Lexend', 'sans-serif'], body: ['Source Sans 3', 'sans-serif'] }","Lexend designed for readability. Excellent accessibility."
|
||||||
|
17,Brutalist Raw,"Mono + Mono",Space Mono,Space Mono,"brutalist, raw, technical, monospace, minimal, stark","Brutalist designs, developer portfolios, experimental, tech art","https://fonts.google.com/share?selection.family=Space+Mono:wght@400;700","@import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&display=swap');","fontFamily: { mono: ['Space Mono', 'monospace'] }","All-mono for raw brutalist aesthetic. Limited weights."
|
||||||
|
18,Fashion Forward,"Sans + Sans",Syne,Manrope,"fashion, avant-garde, creative, bold, artistic, edgy","Fashion brands, creative agencies, art galleries, design studios","https://fonts.google.com/share?selection.family=Manrope:wght@300;400;500;600;700|Syne:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Manrope:wght@300;400;500;600;700&family=Syne:wght@400;500;600;700&display=swap');","fontFamily: { heading: ['Syne', 'sans-serif'], body: ['Manrope', 'sans-serif'] }","Syne's unique character for headlines. Manrope for readability."
|
||||||
|
19,Soft Rounded,"Sans + Sans",Varela Round,Nunito Sans,"soft, rounded, friendly, approachable, warm, gentle","Children's products, pet apps, friendly brands, wellness, soft UI","https://fonts.google.com/share?selection.family=Nunito+Sans:wght@300;400;500;600;700|Varela+Round","@import url('https://fonts.googleapis.com/css2?family=Nunito+Sans:wght@300;400;500;600;700&family=Varela+Round&display=swap');","fontFamily: { heading: ['Varela Round', 'sans-serif'], body: ['Nunito Sans', 'sans-serif'] }","Both rounded and friendly. Perfect for soft UI designs."
|
||||||
|
20,Premium Sans,"Sans + Sans",Satoshi,General Sans,"premium, modern, clean, sophisticated, versatile, balanced","Premium brands, modern agencies, SaaS, portfolios, startups","https://fonts.google.com/share?selection.family=DM+Sans:wght@400;500;700","@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;700&display=swap');","fontFamily: { sans: ['DM Sans', 'sans-serif'] }","Note: Satoshi/General Sans on Fontshare. DM Sans as Google alternative."
|
||||||
|
21,Vietnamese Friendly,"Sans + Sans",Be Vietnam Pro,Noto Sans,"vietnamese, international, readable, clean, multilingual, accessible","Vietnamese sites, multilingual apps, international products","https://fonts.google.com/share?selection.family=Be+Vietnam+Pro:wght@300;400;500;600;700|Noto+Sans:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Be+Vietnam+Pro:wght@300;400;500;600;700&family=Noto+Sans:wght@300;400;500;600;700&display=swap');","fontFamily: { sans: ['Be Vietnam Pro', 'Noto Sans', 'sans-serif'] }","Be Vietnam Pro excellent Vietnamese support. Noto as fallback."
|
||||||
|
22,Japanese Elegant,"Serif + Sans",Noto Serif JP,Noto Sans JP,"japanese, elegant, traditional, modern, multilingual, readable","Japanese sites, Japanese restaurants, cultural sites, anime/manga","https://fonts.google.com/share?selection.family=Noto+Sans+JP:wght@300;400;500;700|Noto+Serif+JP:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@300;400;500;700&family=Noto+Serif+JP:wght@400;500;600;700&display=swap');","fontFamily: { serif: ['Noto Serif JP', 'serif'], sans: ['Noto Sans JP', 'sans-serif'] }","Noto fonts excellent Japanese support. Traditional + modern feel."
|
||||||
|
23,Korean Modern,"Sans + Sans",Noto Sans KR,Noto Sans KR,"korean, modern, clean, professional, multilingual, readable","Korean sites, K-beauty, K-pop, Korean businesses, multilingual","https://fonts.google.com/share?selection.family=Noto+Sans+KR:wght@300;400;500;700","@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@300;400;500;700&display=swap');","fontFamily: { sans: ['Noto Sans KR', 'sans-serif'] }","Clean Korean typography. Single font with weight variations."
|
||||||
|
24,Chinese Traditional,"Serif + Sans",Noto Serif TC,Noto Sans TC,"chinese, traditional, elegant, cultural, multilingual, readable","Traditional Chinese sites, cultural content, Taiwan/Hong Kong markets","https://fonts.google.com/share?selection.family=Noto+Sans+TC:wght@300;400;500;700|Noto+Serif+TC:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@300;400;500;700&family=Noto+Serif+TC:wght@400;500;600;700&display=swap');","fontFamily: { serif: ['Noto Serif TC', 'serif'], sans: ['Noto Sans TC', 'sans-serif'] }","Traditional Chinese character support. Elegant pairing."
|
||||||
|
25,Chinese Simplified,"Sans + Sans",Noto Sans SC,Noto Sans SC,"chinese, simplified, modern, professional, multilingual, readable","Simplified Chinese sites, mainland China market, business apps","https://fonts.google.com/share?selection.family=Noto+Sans+SC:wght@300;400;500;700","@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;700&display=swap');","fontFamily: { sans: ['Noto Sans SC', 'sans-serif'] }","Simplified Chinese support. Clean modern look."
|
||||||
|
26,Arabic Elegant,"Serif + Sans",Noto Naskh Arabic,Noto Sans Arabic,"arabic, elegant, traditional, cultural, RTL, readable","Arabic sites, Middle East market, Islamic content, bilingual sites","https://fonts.google.com/share?selection.family=Noto+Naskh+Arabic:wght@400;500;600;700|Noto+Sans+Arabic:wght@300;400;500;700","@import url('https://fonts.googleapis.com/css2?family=Noto+Naskh+Arabic:wght@400;500;600;700&family=Noto+Sans+Arabic:wght@300;400;500;700&display=swap');","fontFamily: { serif: ['Noto Naskh Arabic', 'serif'], sans: ['Noto Sans Arabic', 'sans-serif'] }","RTL support. Naskh for traditional, Sans for modern Arabic."
|
||||||
|
27,Thai Modern,"Sans + Sans",Noto Sans Thai,Noto Sans Thai,"thai, modern, readable, clean, multilingual, accessible","Thai sites, Southeast Asia, tourism, Thai restaurants","https://fonts.google.com/share?selection.family=Noto+Sans+Thai:wght@300;400;500;700","@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Thai:wght@300;400;500;700&display=swap');","fontFamily: { sans: ['Noto Sans Thai', 'sans-serif'] }","Clean Thai typography. Excellent readability."
|
||||||
|
28,Hebrew Modern,"Sans + Sans",Noto Sans Hebrew,Noto Sans Hebrew,"hebrew, modern, RTL, clean, professional, readable","Hebrew sites, Israeli market, Jewish content, bilingual sites","https://fonts.google.com/share?selection.family=Noto+Sans+Hebrew:wght@300;400;500;700","@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+Hebrew:wght@300;400;500;700&display=swap');","fontFamily: { sans: ['Noto Sans Hebrew', 'sans-serif'] }","RTL support. Clean modern Hebrew typography."
|
||||||
|
29,Legal Professional,"Serif + Sans",EB Garamond,Lato,"legal, professional, traditional, trustworthy, formal, authoritative","Law firms, legal services, contracts, formal documents, government","https://fonts.google.com/share?selection.family=EB+Garamond:wght@400;500;600;700|Lato:wght@300;400;700","@import url('https://fonts.googleapis.com/css2?family=EB+Garamond:wght@400;500;600;700&family=Lato:wght@300;400;700&display=swap');","fontFamily: { serif: ['EB Garamond', 'serif'], sans: ['Lato', 'sans-serif'] }","EB Garamond for authority. Lato for clean body text."
|
||||||
|
30,Medical Clean,"Sans + Sans",Figtree,Noto Sans,"medical, clean, accessible, professional, healthcare, trustworthy","Healthcare, medical clinics, pharma, health apps, accessibility","https://fonts.google.com/share?selection.family=Figtree:wght@300;400;500;600;700|Noto+Sans:wght@300;400;500;700","@import url('https://fonts.googleapis.com/css2?family=Figtree:wght@300;400;500;600;700&family=Noto+Sans:wght@300;400;500;700&display=swap');","fontFamily: { heading: ['Figtree', 'sans-serif'], body: ['Noto Sans', 'sans-serif'] }","Clean, accessible fonts for medical contexts."
|
||||||
|
31,Financial Trust,"Sans + Sans",IBM Plex Sans,IBM Plex Sans,"financial, trustworthy, professional, corporate, banking, serious","Banks, finance, insurance, investment, fintech, enterprise","https://fonts.google.com/share?selection.family=IBM+Plex+Sans:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:wght@300;400;500;600;700&display=swap');","fontFamily: { sans: ['IBM Plex Sans', 'sans-serif'] }","IBM Plex conveys trust and professionalism. Excellent for data."
|
||||||
|
32,Real Estate Luxury,"Serif + Sans",Cinzel,Josefin Sans,"real estate, luxury, elegant, sophisticated, property, premium","Real estate, luxury properties, architecture, interior design","https://fonts.google.com/share?selection.family=Cinzel:wght@400;500;600;700|Josefin+Sans:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Cinzel:wght@400;500;600;700&family=Josefin+Sans:wght@300;400;500;600;700&display=swap');","fontFamily: { serif: ['Cinzel', 'serif'], sans: ['Josefin Sans', 'sans-serif'] }","Cinzel's elegance for headlines. Josefin for modern body."
|
||||||
|
33,Restaurant Menu,"Serif + Sans",Playfair Display SC,Karla,"restaurant, menu, culinary, elegant, foodie, hospitality","Restaurants, cafes, food blogs, culinary, hospitality","https://fonts.google.com/share?selection.family=Karla:wght@300;400;500;600;700|Playfair+Display+SC:wght@400;700","@import url('https://fonts.googleapis.com/css2?family=Karla:wght@300;400;500;600;700&family=Playfair+Display+SC:wght@400;700&display=swap');","fontFamily: { display: ['Playfair Display SC', 'serif'], sans: ['Karla', 'sans-serif'] }","Small caps Playfair for menu headers. Karla for descriptions."
|
||||||
|
34,Art Deco,"Display + Sans",Poiret One,Didact Gothic,"art deco, vintage, 1920s, elegant, decorative, gatsby","Vintage events, art deco themes, luxury hotels, classic cocktails","https://fonts.google.com/share?selection.family=Didact+Gothic|Poiret+One","@import url('https://fonts.googleapis.com/css2?family=Didact+Gothic&family=Poiret+One&display=swap');","fontFamily: { display: ['Poiret One', 'sans-serif'], sans: ['Didact Gothic', 'sans-serif'] }","Poiret One for art deco headlines only. Didact for body."
|
||||||
|
35,Magazine Style,"Serif + Sans",Libre Bodoni,Public Sans,"magazine, editorial, publishing, refined, journalism, print","Magazines, online publications, editorial content, journalism","https://fonts.google.com/share?selection.family=Libre+Bodoni:wght@400;500;600;700|Public+Sans:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Libre+Bodoni:wght@400;500;600;700&family=Public+Sans:wght@300;400;500;600;700&display=swap');","fontFamily: { serif: ['Libre Bodoni', 'serif'], sans: ['Public Sans', 'sans-serif'] }","Bodoni's editorial elegance. Public Sans for clean UI."
|
||||||
|
36,Crypto/Web3,"Sans + Sans",Orbitron,Exo 2,"crypto, web3, futuristic, tech, blockchain, digital","Crypto platforms, NFT, blockchain, web3, futuristic tech","https://fonts.google.com/share?selection.family=Exo+2:wght@300;400;500;600;700|Orbitron:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Exo+2:wght@300;400;500;600;700&family=Orbitron:wght@400;500;600;700&display=swap');","fontFamily: { display: ['Orbitron', 'sans-serif'], body: ['Exo 2', 'sans-serif'] }","Orbitron for futuristic headers. Exo 2 for readable body."
|
||||||
|
37,Gaming Bold,"Display + Sans",Russo One,Chakra Petch,"gaming, bold, action, esports, competitive, energetic","Gaming, esports, action games, competitive sports, entertainment","https://fonts.google.com/share?selection.family=Chakra+Petch:wght@300;400;500;600;700|Russo+One","@import url('https://fonts.googleapis.com/css2?family=Chakra+Petch:wght@300;400;500;600;700&family=Russo+One&display=swap');","fontFamily: { display: ['Russo One', 'sans-serif'], body: ['Chakra Petch', 'sans-serif'] }","Russo One for impact. Chakra Petch for techy body text."
|
||||||
|
38,Indie/Craft,"Display + Sans",Amatic SC,Cabin,"indie, craft, handmade, artisan, organic, creative","Craft brands, indie products, artisan, handmade, organic products","https://fonts.google.com/share?selection.family=Amatic+SC:wght@400;700|Cabin:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Amatic+SC:wght@400;700&family=Cabin:wght@400;500;600;700&display=swap');","fontFamily: { display: ['Amatic SC', 'sans-serif'], sans: ['Cabin', 'sans-serif'] }","Amatic for handwritten feel. Cabin for readable body."
|
||||||
|
39,Startup Bold,"Sans + Sans",Clash Display,Satoshi,"startup, bold, modern, innovative, confident, dynamic","Startups, pitch decks, product launches, bold brands","https://fonts.google.com/share?selection.family=Outfit:wght@400;500;600;700|Rubik:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;500;600;700&family=Rubik:wght@300;400;500;600;700&display=swap');","fontFamily: { heading: ['Outfit', 'sans-serif'], body: ['Rubik', 'sans-serif'] }","Note: Clash Display on Fontshare. Outfit as Google alternative."
|
||||||
|
40,E-commerce Clean,"Sans + Sans",Rubik,Nunito Sans,"ecommerce, clean, shopping, product, retail, conversion","E-commerce, online stores, product pages, retail, shopping","https://fonts.google.com/share?selection.family=Nunito+Sans:wght@300;400;500;600;700|Rubik:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Nunito+Sans:wght@300;400;500;600;700&family=Rubik:wght@300;400;500;600;700&display=swap');","fontFamily: { heading: ['Rubik', 'sans-serif'], body: ['Nunito Sans', 'sans-serif'] }","Clean readable fonts perfect for product descriptions."
|
||||||
|
41,Academic/Research,"Serif + Sans",Crimson Pro,Atkinson Hyperlegible,"academic, research, scholarly, accessible, readable, educational","Universities, research papers, academic journals, educational","https://fonts.google.com/share?selection.family=Atkinson+Hyperlegible:wght@400;700|Crimson+Pro:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible:wght@400;700&family=Crimson+Pro:wght@400;500;600;700&display=swap');","fontFamily: { serif: ['Crimson Pro', 'serif'], sans: ['Atkinson Hyperlegible', 'sans-serif'] }","Crimson for scholarly headlines. Atkinson for accessibility."
|
||||||
|
42,Dashboard Data,"Mono + Sans",Fira Code,Fira Sans,"dashboard, data, analytics, code, technical, precise","Dashboards, analytics, data visualization, admin panels","https://fonts.google.com/share?selection.family=Fira+Code:wght@400;500;600;700|Fira+Sans:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500;600;700&family=Fira+Sans:wght@300;400;500;600;700&display=swap');","fontFamily: { mono: ['Fira Code', 'monospace'], sans: ['Fira Sans', 'sans-serif'] }","Fira family cohesion. Code for data, Sans for labels."
|
||||||
|
43,Music/Entertainment,"Display + Sans",Righteous,Poppins,"music, entertainment, fun, energetic, bold, performance","Music platforms, entertainment, events, festivals, performers","https://fonts.google.com/share?selection.family=Poppins:wght@300;400;500;600;700|Righteous","@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&family=Righteous&display=swap');","fontFamily: { display: ['Righteous', 'sans-serif'], sans: ['Poppins', 'sans-serif'] }","Righteous for bold entertainment headers. Poppins for body."
|
||||||
|
44,Minimalist Portfolio,"Sans + Sans",Archivo,Space Grotesk,"minimal, portfolio, designer, creative, clean, artistic","Design portfolios, creative professionals, minimalist brands","https://fonts.google.com/share?selection.family=Archivo:wght@300;400;500;600;700|Space+Grotesk:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Archivo:wght@300;400;500;600;700&family=Space+Grotesk:wght@300;400;500;600;700&display=swap');","fontFamily: { heading: ['Space Grotesk', 'sans-serif'], body: ['Archivo', 'sans-serif'] }","Space Grotesk for distinctive headers. Archivo for clean body."
|
||||||
|
45,Kids/Education,"Display + Sans",Baloo 2,Comic Neue,"kids, education, playful, friendly, colorful, learning","Children's apps, educational games, kid-friendly content","https://fonts.google.com/share?selection.family=Baloo+2:wght@400;500;600;700|Comic+Neue:wght@300;400;700","@import url('https://fonts.googleapis.com/css2?family=Baloo+2:wght@400;500;600;700&family=Comic+Neue:wght@300;400;700&display=swap');","fontFamily: { display: ['Baloo 2', 'sans-serif'], sans: ['Comic Neue', 'sans-serif'] }","Fun, playful fonts for children. Comic Neue is readable comic style."
|
||||||
|
46,Wedding/Romance,"Script + Serif",Great Vibes,Cormorant Infant,"wedding, romance, elegant, script, invitation, feminine","Wedding sites, invitations, romantic brands, bridal","https://fonts.google.com/share?selection.family=Cormorant+Infant:wght@300;400;500;600;700|Great+Vibes","@import url('https://fonts.googleapis.com/css2?family=Cormorant+Infant:wght@300;400;500;600;700&family=Great+Vibes&display=swap');","fontFamily: { script: ['Great Vibes', 'cursive'], serif: ['Cormorant Infant', 'serif'] }","Great Vibes for elegant accents. Cormorant for readable text."
|
||||||
|
47,Science/Tech,"Sans + Sans",Exo,Roboto Mono,"science, technology, research, data, futuristic, precise","Science, research, tech documentation, data-heavy sites","https://fonts.google.com/share?selection.family=Exo:wght@300;400;500;600;700|Roboto+Mono:wght@300;400;500;700","@import url('https://fonts.googleapis.com/css2?family=Exo:wght@300;400;500;600;700&family=Roboto+Mono:wght@300;400;500;700&display=swap');","fontFamily: { sans: ['Exo', 'sans-serif'], mono: ['Roboto Mono', 'monospace'] }","Exo for modern tech feel. Roboto Mono for code/data."
|
||||||
|
48,Accessibility First,"Sans + Sans",Atkinson Hyperlegible,Atkinson Hyperlegible,"accessible, readable, inclusive, WCAG, dyslexia-friendly, clear","Accessibility-critical sites, government, healthcare, inclusive design","https://fonts.google.com/share?selection.family=Atkinson+Hyperlegible:wght@400;700","@import url('https://fonts.googleapis.com/css2?family=Atkinson+Hyperlegible:wght@400;700&display=swap');","fontFamily: { sans: ['Atkinson Hyperlegible', 'sans-serif'] }","Designed for maximum legibility. Excellent for accessibility."
|
||||||
|
49,Sports/Fitness,"Sans + Sans",Barlow Condensed,Barlow,"sports, fitness, athletic, energetic, condensed, action","Sports, fitness, gyms, athletic brands, competition","https://fonts.google.com/share?selection.family=Barlow+Condensed:wght@400;500;600;700|Barlow:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Barlow+Condensed:wght@400;500;600;700&family=Barlow:wght@300;400;500;600;700&display=swap');","fontFamily: { display: ['Barlow Condensed', 'sans-serif'], body: ['Barlow', 'sans-serif'] }","Condensed for impact headlines. Regular Barlow for body."
|
||||||
|
50,Luxury Minimalist,"Serif + Sans",Bodoni Moda,Jost,"luxury, minimalist, high-end, sophisticated, refined, premium","Luxury minimalist brands, high-end fashion, premium products","https://fonts.google.com/share?selection.family=Bodoni+Moda:wght@400;500;600;700|Jost:wght@300;400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Bodoni+Moda:wght@400;500;600;700&family=Jost:wght@300;400;500;600;700&display=swap');","fontFamily: { serif: ['Bodoni Moda', 'serif'], sans: ['Jost', 'sans-serif'] }","Bodoni's high contrast elegance. Jost for geometric body."
|
||||||
|
51,Tech/HUD Mono,"Mono + Mono",Share Tech Mono,Fira Code,"tech, futuristic, hud, sci-fi, data, monospaced, precise","Sci-fi interfaces, developer tools, cybersecurity, dashboards","https://fonts.google.com/share?selection.family=Fira+Code:wght@300;400;500;600;700|Share+Tech+Mono","@import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@300;400;500;600;700&family=Share+Tech+Mono&display=swap');","fontFamily: { hud: ['Share Tech Mono', 'monospace'], code: ['Fira Code', 'monospace'] }","Share Tech Mono has that classic sci-fi look."
|
||||||
|
52,Pixel Retro,"Display + Sans",Press Start 2P,VT323,"pixel, retro, gaming, 8-bit, nostalgic, arcade","Pixel art games, retro websites, creative portfolios","https://fonts.google.com/share?selection.family=Press+Start+2P|VT323","@import url('https://fonts.googleapis.com/css2?family=Press+Start+2P&family=VT323&display=swap');","fontFamily: { pixel: ['Press Start 2P', 'cursive'], terminal: ['VT323', 'monospace'] }","Press Start 2P is very wide/large. VT323 is better for body text."
|
||||||
|
53,Neubrutalist Bold,"Display + Sans",Lexend Mega,Public Sans,"bold, neubrutalist, loud, strong, geometric, quirky","Neubrutalist designs, Gen Z brands, bold marketing","https://fonts.google.com/share?selection.family=Lexend+Mega:wght@100..900|Public+Sans:wght@100..900","@import url('https://fonts.googleapis.com/css2?family=Lexend+Mega:wght@100..900&family=Public+Sans:wght@100..900&display=swap');","fontFamily: { mega: ['Lexend Mega', 'sans-serif'], body: ['Public Sans', 'sans-serif'] }","Lexend Mega has distinct character and variable weight."
|
||||||
|
54,Academic/Archival,"Serif + Serif",EB Garamond,Crimson Text,"academic, old-school, university, research, serious, traditional","University sites, archives, research papers, history","https://fonts.google.com/share?selection.family=Crimson+Text:wght@400;600;700|EB+Garamond:wght@400;500;600;700;800","@import url('https://fonts.googleapis.com/css2?family=Crimson+Text:wght@400;600;700&family=EB+Garamond:wght@400;500;600;700;800&display=swap');","fontFamily: { classic: ['EB Garamond', 'serif'], text: ['Crimson Text', 'serif'] }","Classic academic aesthetic. Very legible."
|
||||||
|
55,Spatial Clear,"Sans + Sans",Inter,Inter,"spatial, legible, glass, system, clean, neutral","Spatial computing, AR/VR, glassmorphism interfaces","https://fonts.google.com/share?selection.family=Inter:wght@300;400;500;600","@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&display=swap');","fontFamily: { sans: ['Inter', 'sans-serif'] }","Optimized for readability on dynamic backgrounds."
|
||||||
|
56,Kinetic Motion,"Display + Mono",Syncopate,Space Mono,"kinetic, motion, futuristic, speed, wide, tech","Music festivals, automotive, high-energy brands","https://fonts.google.com/share?selection.family=Space+Mono:wght@400;700|Syncopate:wght@400;700","@import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&family=Syncopate:wght@400;700&display=swap');","fontFamily: { display: ['Syncopate', 'sans-serif'], mono: ['Space Mono', 'monospace'] }","Syncopate's wide stance works well with motion effects."
|
||||||
|
57,Gen Z Brutal,"Display + Sans",Anton,Epilogue,"brutal, loud, shouty, meme, internet, bold","Gen Z marketing, streetwear, viral campaigns","https://fonts.google.com/share?selection.family=Anton|Epilogue:wght@400;500;600;700","@import url('https://fonts.googleapis.com/css2?family=Anton&family=Epilogue:wght@400;500;600;700&display=swap');","fontFamily: { display: ['Anton', 'sans-serif'], body: ['Epilogue', 'sans-serif'] }","Anton is impactful and condensed. Good for stickers/badges."
|
||||||
|
@@ -0,0 +1,101 @@
|
|||||||
|
No,UI_Category,Recommended_Pattern,Style_Priority,Color_Mood,Typography_Mood,Key_Effects,Decision_Rules,Anti_Patterns,Severity
|
||||||
|
1,SaaS (General),Hero + Features + CTA,Glassmorphism + Flat Design,Trust blue + Accent contrast,Professional + Hierarchy,Subtle hover (200-250ms) + Smooth transitions,"{""if_ux_focused"": ""prioritize-minimalism"", ""if_data_heavy"": ""add-glassmorphism""}",Excessive animation + Dark mode by default,HIGH
|
||||||
|
2,Micro SaaS,Minimal & Direct + Demo,Flat Design + Vibrant & Block,Vibrant primary + White space,Bold + Clean typography,Large CTA hover (300ms) + Scroll reveal,"{""if_quick_onboarding"": ""reduce-steps"", ""if_demo_available"": ""feature-interactive-demo""}",Complex onboarding flow + Cluttered layout,HIGH
|
||||||
|
3,E-commerce,Feature-Rich Showcase,Vibrant & Block-based,Brand primary + Success green,Engaging + Clear hierarchy,Card hover lift (200ms) + Scale effect,"{""if_luxury"": ""switch-to-liquid-glass"", ""if_conversion_focused"": ""add-urgency-colors""}",Flat design without depth + Text-heavy pages,HIGH
|
||||||
|
4,E-commerce Luxury,Feature-Rich Showcase,Liquid Glass + Glassmorphism,Premium colors + Minimal accent,Elegant + Refined typography,Chromatic aberration + Fluid animations (400-600ms),"{""if_checkout"": ""emphasize-trust"", ""if_hero_needed"": ""use-3d-hyperrealism""}",Vibrant & Block-based + Playful colors,HIGH
|
||||||
|
5,Healthcare App,Social Proof-Focused,Neumorphism + Accessible & Ethical,Calm blue + Health green,Readable + Large type (16px+),Soft box-shadow + Smooth press (150ms),"{""must_have"": ""wcag-aaa-compliance"", ""if_medication"": ""red-alert-colors""}",Bright neon colors + Motion-heavy animations + AI purple/pink gradients,HIGH
|
||||||
|
6,Fintech/Crypto,Conversion-Optimized,Glassmorphism + Dark Mode (OLED),Dark tech colors + Vibrant accents,Modern + Confident typography,Real-time chart animations + Alert pulse/glow,"{""must_have"": ""security-badges"", ""if_real_time"": ""add-streaming-data""}",Light backgrounds + No security indicators,HIGH
|
||||||
|
7,Education,Feature-Rich Showcase,Claymorphism + Micro-interactions,Playful colors + Clear hierarchy,Friendly + Engaging typography,Soft press (200ms) + Fluffy elements,"{""if_gamification"": ""add-progress-animation"", ""if_children"": ""increase-playfulness""}",Dark modes + Complex jargon,MEDIUM
|
||||||
|
8,Portfolio/Personal,Storytelling-Driven,Motion-Driven + Minimalism,Brand primary + Artistic,Expressive + Variable typography,Parallax (3-5 layers) + Scroll-triggered reveals,"{""if_creative_field"": ""add-brutalism"", ""if_minimal_portfolio"": ""reduce-motion""}",Corporate templates + Generic layouts,MEDIUM
|
||||||
|
9,Government/Public,Minimal & Direct,Accessible & Ethical + Minimalism,Professional blue + High contrast,Clear + Large typography,Clear focus rings (3-4px) + Skip links,"{""must_have"": ""wcag-aaa"", ""must_have"": ""keyboard-navigation""}",Ornate design + Low contrast + Motion effects + AI purple/pink gradients,HIGH
|
||||||
|
10,Fintech (Banking),Trust & Authority,Minimalism + Accessible & Ethical,Navy + Trust Blue + Gold,Professional + Trustworthy,Smooth state transitions + Number animations,"{""must_have"": ""security-first"", ""if_dashboard"": ""use-dark-mode""}",Playful design + Unclear fees + AI purple/pink gradients,HIGH
|
||||||
|
11,Social Media App,Feature-Rich Showcase,Vibrant & Block-based + Motion-Driven,Vibrant + Engagement colors,Modern + Bold typography,Large scroll animations + Icon animations,"{""if_engagement_metric"": ""add-motion"", ""if_content_focused"": ""minimize-chrome""}",Heavy skeuomorphism + Accessibility ignored,MEDIUM
|
||||||
|
12,Startup Landing,Hero-Centric + Trust,Motion-Driven + Vibrant & Block,Bold primaries + Accent contrast,Modern + Energetic typography,Scroll-triggered animations + Parallax,"{""if_pre_launch"": ""use-waitlist-pattern"", ""if_video_ready"": ""add-hero-video""}",Static design + No video + Poor mobile,HIGH
|
||||||
|
13,Gaming,Feature-Rich Showcase,3D & Hyperrealism + Retro-Futurism,Vibrant + Neon + Immersive,Bold + Impactful typography,WebGL 3D rendering + Glitch effects,"{""if_competitive"": ""add-real-time-stats"", ""if_casual"": ""increase-playfulness""}",Minimalist design + Static assets,HIGH
|
||||||
|
14,Creative Agency,Storytelling-Driven,Brutalism + Motion-Driven,Bold primaries + Artistic freedom,Bold + Expressive typography,CRT scanlines + Neon glow + Glitch effects,"{""must_have"": ""case-studies"", ""if_boutique"": ""increase-artistic-freedom""}",Corporate minimalism + Hidden portfolio,HIGH
|
||||||
|
15,Wellness/Mental Health,Social Proof-Focused,Neumorphism + Accessible & Ethical,Calm Pastels + Trust colors,Calming + Readable typography,Soft press + Breathing animations,"{""must_have"": ""privacy-first"", ""if_meditation"": ""add-breathing-animation""}",Bright neon + Motion overload,HIGH
|
||||||
|
16,Restaurant/Food,Hero-Centric + Conversion,Vibrant & Block-based + Motion-Driven,Warm colors (Orange Red Brown),Appetizing + Clear typography,Food image reveal + Menu hover effects,"{""must_have"": ""high_quality_images"", ""if_delivery"": ""emphasize-speed""}",Low-quality imagery + Outdated hours,HIGH
|
||||||
|
17,Real Estate,Hero-Centric + Feature-Rich,Glassmorphism + Minimalism,Trust Blue + Gold + White,Professional + Confident,3D property tour zoom + Map hover,"{""if_luxury"": ""add-3d-models"", ""must_have"": ""map-integration""}",Poor photos + No virtual tours,HIGH
|
||||||
|
18,Travel/Tourism,Storytelling-Driven + Hero,Aurora UI + Motion-Driven,Vibrant destination + Sky Blue,Inspirational + Engaging,Destination parallax + Itinerary animations,"{""if_experience_focused"": ""use-storytelling"", ""must_have"": ""mobile-booking""}",Generic photos + Complex booking,HIGH
|
||||||
|
19,SaaS Dashboard,Data-Dense Dashboard,Data-Dense + Heat Map,Cool to Hot gradients + Neutral grey,Clear + Readable typography,Hover tooltips + Chart zoom + Real-time pulse,"{""must_have"": ""real-time-updates"", ""if_large_dataset"": ""prioritize-performance""}",Ornate design + Slow rendering,HIGH
|
||||||
|
20,B2B SaaS Enterprise,Feature-Rich Showcase,Trust & Authority + Minimal,Professional blue + Neutral grey,Formal + Clear typography,Subtle section transitions + Feature reveals,"{""must_have"": ""case-studies"", ""must_have"": ""roi-messaging""}",Playful design + Hidden features + AI purple/pink gradients,HIGH
|
||||||
|
21,Music/Entertainment,Feature-Rich Showcase,Dark Mode (OLED) + Vibrant & Block-based,Dark (#121212) + Vibrant accents + Album art colors,Modern + Bold typography,Waveform visualization + Playlist animations,"{""must_have"": ""audio-player-ux"", ""if_discovery_focused"": ""add-playlist-recommendations""}",Cluttered layout + Poor audio player UX,HIGH
|
||||||
|
22,Video Streaming/OTT,Hero-Centric + Feature-Rich,Dark Mode (OLED) + Motion-Driven,Dark bg + Poster colors + Brand accent,Bold + Engaging typography,Video player animations + Content carousel (parallax),"{""must_have"": ""continue-watching"", ""if_personalized"": ""add-recommendations""}",Static layout + Slow video player,HIGH
|
||||||
|
23,Job Board/Recruitment,Conversion-Optimized + Feature-Rich,Flat Design + Minimalism,Professional Blue + Success Green + Neutral,Clear + Professional typography,Search/filter animations + Application flow,"{""must_have"": ""advanced-search"", ""if_salary_focused"": ""highlight-compensation""}",Outdated forms + Hidden filters,HIGH
|
||||||
|
24,Marketplace (P2P),Feature-Rich Showcase + Social Proof,Vibrant & Block-based + Flat Design,Trust colors + Category colors + Success green,Modern + Engaging typography,Review star animations + Listing hover effects,"{""must_have"": ""seller-profiles"", ""must_have"": ""secure-payment""}",Low trust signals + Confusing layout,HIGH
|
||||||
|
25,Logistics/Delivery,Feature-Rich Showcase + Real-Time,Minimalism + Flat Design,Blue (#2563EB) + Orange (tracking) + Green,Clear + Functional typography,Real-time tracking animation + Status pulse,"{""must_have"": ""tracking-map"", ""must_have"": ""delivery-updates""}",Static tracking + No map integration + AI purple/pink gradients,HIGH
|
||||||
|
26,Agriculture/Farm Tech,Feature-Rich Showcase,Organic Biophilic + Flat Design,Earth Green (#4A7C23) + Brown + Sky Blue,Clear + Informative typography,Data visualization + Weather animations,"{""must_have"": ""sensor-dashboard"", ""if_crop_focused"": ""add-health-indicators""}",Generic design + Ignored accessibility + AI purple/pink gradients,MEDIUM
|
||||||
|
27,Construction/Architecture,Hero-Centric + Feature-Rich,Minimalism + 3D & Hyperrealism,Grey (#4A4A4A) + Orange (safety) + Blueprint Blue,Professional + Bold typography,3D model viewer + Timeline animations,"{""must_have"": ""project-portfolio"", ""if_team_collaboration"": ""add-real-time-updates""}",2D-only layouts + Poor image quality + AI purple/pink gradients,HIGH
|
||||||
|
28,Automotive/Car Dealership,Hero-Centric + Feature-Rich,Motion-Driven + 3D & Hyperrealism,Brand colors + Metallic + Dark/Light,Bold + Confident typography,360 product view + Configurator animations,"{""must_have"": ""vehicle-comparison"", ""must_have"": ""financing-calculator""}",Static product pages + Poor UX,HIGH
|
||||||
|
29,Photography Studio,Storytelling-Driven + Hero-Centric,Motion-Driven + Minimalism,Black + White + Minimal accent,Elegant + Minimal typography,Full-bleed gallery + Before/after reveal,"{""must_have"": ""portfolio-showcase"", ""if_booking"": ""add-calendar-system""}",Heavy text + Poor image showcase,HIGH
|
||||||
|
30,Coworking Space,Hero-Centric + Feature-Rich,Vibrant & Block-based + Glassmorphism,Energetic colors + Wood tones + Brand,Modern + Engaging typography,Space tour video + Amenity reveal animations,"{""must_have"": ""virtual-tour"", ""must_have"": ""booking-system""}",Outdated photos + Confusing layout,MEDIUM
|
||||||
|
31,Cleaning Service,Conversion-Optimized + Trust,Soft UI Evolution + Flat Design,Fresh Blue (#00B4D8) + Clean White + Green,Friendly + Clear typography,Before/after gallery + Service package reveal,"{""must_have"": ""price-transparency"", ""must_have"": ""trust-badges""}",Poor before/after imagery + Hidden pricing,HIGH
|
||||||
|
32,Home Services,Conversion-Optimized + Trust,Flat Design + Trust & Authority,Trust Blue + Safety Orange + Grey,Professional + Clear typography,Emergency contact highlight + Service menu animations,"{""must_have"": ""emergency-contact"", ""must_have"": ""certifications-display""}",Hidden contact info + No certifications,HIGH
|
||||||
|
33,Childcare/Daycare,Social Proof-Focused + Trust,Claymorphism + Vibrant & Block-based,Playful pastels + Safe colors + Warm,Friendly + Playful typography,Parent portal animations + Activity gallery reveal,"{""must_have"": ""parent-communication"", ""must_have"": ""safety-certifications""}",Generic design + Hidden safety info,HIGH
|
||||||
|
34,Senior Care/Elderly,Trust & Authority + Accessible,Accessible & Ethical + Soft UI Evolution,Calm Blue + Warm neutrals + Large text,Large + Clear typography (18px+),Large touch targets + Clear navigation,"{""must_have"": ""wcag-aaa"", ""must_have"": ""family-portal""}",Small text + Complex navigation + AI purple/pink gradients,HIGH
|
||||||
|
35,Medical Clinic,Trust & Authority + Conversion,Accessible & Ethical + Minimalism,Medical Blue (#0077B6) + Trust White,Professional + Readable typography,Online booking flow + Doctor profile reveals,"{""must_have"": ""appointment-booking"", ""must_have"": ""insurance-info""}",Outdated interface + Confusing booking + AI purple/pink gradients,HIGH
|
||||||
|
36,Pharmacy/Drug Store,Conversion-Optimized + Trust,Flat Design + Accessible & Ethical,Pharmacy Green + Trust Blue + Clean White,Clear + Functional typography,Prescription upload flow + Refill reminders,"{""must_have"": ""prescription-management"", ""must_have"": ""drug-interaction-warnings""}",Confusing layout + Privacy concerns + AI purple/pink gradients,HIGH
|
||||||
|
37,Dental Practice,Social Proof-Focused + Conversion,Soft UI Evolution + Minimalism,Fresh Blue + White + Smile Yellow,Friendly + Professional typography,Before/after gallery + Patient testimonial carousel,"{""must_have"": ""before-after-gallery"", ""must_have"": ""appointment-system""}",Poor imagery + No testimonials,HIGH
|
||||||
|
38,Veterinary Clinic,Social Proof-Focused + Trust,Claymorphism + Accessible & Ethical,Caring Blue + Pet colors + Warm,Friendly + Welcoming typography,Pet profile management + Service animations,"{""must_have"": ""pet-portal"", ""must_have"": ""emergency-contact""}",Generic design + Hidden services,MEDIUM
|
||||||
|
39,News/Media Platform,Hero-Centric + Feature-Rich,Minimalism + Flat Design,Brand colors + High contrast,Clear + Readable typography,Breaking news badge + Article reveal animations,"{""must_have"": ""mobile-first-reading"", ""must_have"": ""category-navigation""}",Cluttered layout + Slow loading,HIGH
|
||||||
|
40,Legal Services,Trust & Authority + Minimal,Trust & Authority + Minimalism,Navy Blue (#1E3A5F) + Gold + White,Professional + Authoritative typography,Practice area reveal + Attorney profile animations,"{""must_have"": ""case-results"", ""must_have"": ""credential-display""}",Outdated design + Hidden credentials + AI purple/pink gradients,HIGH
|
||||||
|
41,Beauty/Spa/Wellness Service,Hero-Centric + Social Proof,Soft UI Evolution + Neumorphism,Soft pastels (Pink Sage Cream) + Gold accents,Elegant + Calming typography,Soft shadows + Smooth transitions (200-300ms) + Gentle hover,"{""must_have"": ""booking-system"", ""must_have"": ""before-after-gallery"", ""if_luxury"": ""add-gold-accents""}",Bright neon colors + Harsh animations + Dark mode,HIGH
|
||||||
|
42,Service Landing Page,Hero-Centric + Trust & Authority,Minimalism + Social Proof-Focused,Brand primary + Trust colors,Professional + Clear typography,Testimonial carousel + CTA hover (200ms),"{""must_have"": ""social-proof"", ""must_have"": ""clear-cta""}",Complex navigation + Hidden contact info,HIGH
|
||||||
|
43,B2B Service,Feature-Rich Showcase + Trust,Trust & Authority + Minimalism,Professional blue + Neutral grey,Formal + Clear typography,Section transitions + Feature reveals,"{""must_have"": ""case-studies"", ""must_have"": ""roi-messaging""}",Playful design + Hidden credentials + AI purple/pink gradients,HIGH
|
||||||
|
44,Financial Dashboard,Data-Dense Dashboard,Dark Mode (OLED) + Data-Dense,Dark bg + Red/Green alerts + Trust blue,Clear + Readable typography,Real-time number animations + Alert pulse,"{""must_have"": ""real-time-updates"", ""must_have"": ""high-contrast""}",Light mode default + Slow rendering,HIGH
|
||||||
|
45,Analytics Dashboard,Data-Dense + Drill-Down,Data-Dense + Heat Map,Cool→Hot gradients + Neutral grey,Clear + Functional typography,Hover tooltips + Chart zoom + Filter animations,"{""must_have"": ""data-export"", ""if_large_dataset"": ""virtualize-lists""}",Ornate design + No filtering,HIGH
|
||||||
|
46,Productivity Tool,Interactive Demo + Feature-Rich,Flat Design + Micro-interactions,Clear hierarchy + Functional colors,Clean + Efficient typography,Quick actions (150ms) + Task animations,"{""must_have"": ""keyboard-shortcuts"", ""if_collaboration"": ""add-real-time-cursors""}",Complex onboarding + Slow performance,HIGH
|
||||||
|
47,Design System/Component Library,Feature-Rich + Documentation,Minimalism + Accessible & Ethical,Clear hierarchy + Code-like structure,Monospace + Clear typography,Code copy animations + Component previews,"{""must_have"": ""search"", ""must_have"": ""code-examples""}",Poor documentation + No live preview,HIGH
|
||||||
|
48,AI/Chatbot Platform,Interactive Demo + Minimal,AI-Native UI + Minimalism,Neutral + AI Purple (#6366F1),Modern + Clear typography,Streaming text + Typing indicators + Fade-in,"{""must_have"": ""conversational-ui"", ""must_have"": ""context-awareness""}",Heavy chrome + Slow response feedback,HIGH
|
||||||
|
49,NFT/Web3 Platform,Feature-Rich Showcase,Cyberpunk UI + Glassmorphism,Dark + Neon + Gold (#FFD700),Bold + Modern typography,Wallet connect animations + Transaction feedback,"{""must_have"": ""wallet-integration"", ""must_have"": ""gas-fees-display""}",Light mode default + No transaction status,HIGH
|
||||||
|
50,Creator Economy Platform,Social Proof + Feature-Rich,Vibrant & Block-based + Bento Box Grid,Vibrant + Brand colors,Modern + Bold typography,Engagement counter animations + Profile reveals,"{""must_have"": ""creator-profiles"", ""must_have"": ""monetization-display""}",Generic layout + Hidden earnings,MEDIUM
|
||||||
|
51,Sustainability/ESG Platform,Trust & Authority + Data,Organic Biophilic + Minimalism,Green (#228B22) + Earth tones,Clear + Informative typography,Progress indicators + Impact animations,"{""must_have"": ""data-transparency"", ""must_have"": ""certification-badges""}",Greenwashing visuals + No data,HIGH
|
||||||
|
52,Remote Work/Collaboration,Feature-Rich + Real-Time,Soft UI Evolution + Minimalism,Calm Blue + Neutral grey,Clean + Readable typography,Real-time presence indicators + Notification badges,"{""must_have"": ""status-indicators"", ""must_have"": ""video-integration""}",Cluttered interface + No presence,HIGH
|
||||||
|
53,Pet Tech App,Storytelling + Feature-Rich,Claymorphism + Vibrant & Block-based,Playful + Warm colors,Friendly + Playful typography,Pet profile animations + Health tracking charts,"{""must_have"": ""pet-profiles"", ""if_health"": ""add-vet-integration""}",Generic design + No personality,MEDIUM
|
||||||
|
54,Smart Home/IoT Dashboard,Real-Time Monitoring,Glassmorphism + Dark Mode (OLED),Dark + Status indicator colors,Clear + Functional typography,Device status pulse + Quick action animations,"{""must_have"": ""real-time-controls"", ""must_have"": ""energy-monitoring""}",Slow updates + No automation,HIGH
|
||||||
|
55,EV/Charging Ecosystem,Hero-Centric + Feature-Rich,Minimalism + Aurora UI,Electric Blue (#009CD1) + Green,Modern + Clear typography,Range estimation animations + Map interactions,"{""must_have"": ""charging-map"", ""must_have"": ""range-calculator""}",Poor map UX + Hidden costs,HIGH
|
||||||
|
56,Subscription Box Service,Feature-Rich + Conversion,Vibrant & Block-based + Motion-Driven,Brand + Excitement colors,Engaging + Clear typography,Unboxing reveal animations + Product carousel,"{""must_have"": ""personalization-quiz"", ""must_have"": ""subscription-management""}",Confusing pricing + No unboxing preview,HIGH
|
||||||
|
57,Podcast Platform,Storytelling + Feature-Rich,Dark Mode (OLED) + Minimalism,Dark + Audio waveform accents,Modern + Clear typography,Waveform visualizations + Episode transitions,"{""must_have"": ""audio-player-ux"", ""must_have"": ""episode-discovery""}",Poor audio player + Cluttered layout,HIGH
|
||||||
|
58,Dating App,Social Proof + Feature-Rich,Vibrant & Block-based + Motion-Driven,Warm + Romantic (Pink/Red gradients),Modern + Friendly typography,Profile card swipe + Match animations,"{""must_have"": ""profile-cards"", ""must_have"": ""safety-features""}",Generic profiles + No safety,HIGH
|
||||||
|
59,Micro-Credentials/Badges,Trust & Authority + Feature,Minimalism + Flat Design,Trust Blue + Gold (#FFD700),Professional + Clear typography,Badge reveal animations + Progress tracking,"{""must_have"": ""credential-verification"", ""must_have"": ""progress-display""}",No verification + Hidden progress,MEDIUM
|
||||||
|
60,Knowledge Base/Documentation,FAQ + Minimal,Minimalism + Accessible & Ethical,Clean hierarchy + Minimal color,Clear + Readable typography,Search highlight + Smooth scrolling,"{""must_have"": ""search-first"", ""must_have"": ""version-switching""}",Poor navigation + No search,HIGH
|
||||||
|
61,Hyperlocal Services,Conversion + Feature-Rich,Minimalism + Vibrant & Block-based,Location markers + Trust colors,Clear + Functional typography,Map hover + Provider card reveals,"{""must_have"": ""map-integration"", ""must_have"": ""booking-system""}",No map + Hidden reviews,HIGH
|
||||||
|
62,Luxury/Premium Brand,Storytelling + Feature-Rich,Liquid Glass + Glassmorphism,Black + Gold (#FFD700) + White,Elegant + Refined typography,Slow parallax + Premium reveals (400-600ms),"{""must_have"": ""high-quality-imagery"", ""must_have"": ""storytelling""}",Cheap visuals + Fast animations,HIGH
|
||||||
|
63,Fitness/Gym App,Feature-Rich + Data,Vibrant & Block-based + Dark Mode (OLED),Energetic (Orange #FF6B35) + Dark bg,Bold + Motivational typography,Progress ring animations + Achievement unlocks,"{""must_have"": ""progress-tracking"", ""must_have"": ""workout-plans""}",Static design + No gamification,HIGH
|
||||||
|
64,Hotel/Hospitality,Hero-Centric + Social Proof,Liquid Glass + Minimalism,Warm neutrals + Gold (#D4AF37),Elegant + Welcoming typography,Room gallery + Amenity reveals,"{""must_have"": ""room-booking"", ""must_have"": ""virtual-tour""}",Poor photos + Complex booking,HIGH
|
||||||
|
65,Wedding/Event Planning,Storytelling + Social Proof,Soft UI Evolution + Aurora UI,Soft Pink (#FFD6E0) + Gold + Cream,Elegant + Romantic typography,Gallery reveals + Timeline animations,"{""must_have"": ""portfolio-gallery"", ""must_have"": ""planning-tools""}",Generic templates + No portfolio,HIGH
|
||||||
|
66,Insurance Platform,Conversion + Trust,Trust & Authority + Flat Design,Trust Blue (#0066CC) + Green + Neutral,Clear + Professional typography,Quote calculator animations + Policy comparison,"{""must_have"": ""quote-calculator"", ""must_have"": ""policy-comparison""}",Confusing pricing + No trust signals + AI purple/pink gradients,HIGH
|
||||||
|
67,Banking/Traditional Finance,Trust & Authority + Feature,Minimalism + Accessible & Ethical,Navy (#0A1628) + Trust Blue + Gold,Professional + Trustworthy typography,Smooth number animations + Security indicators,"{""must_have"": ""security-first"", ""must_have"": ""accessibility""}",Playful design + Poor security UX + AI purple/pink gradients,HIGH
|
||||||
|
68,Online Course/E-learning,Feature-Rich + Social Proof,Claymorphism + Vibrant & Block-based,Vibrant learning colors + Progress green,Friendly + Engaging typography,Progress bar animations + Certificate reveals,"{""must_have"": ""progress-tracking"", ""must_have"": ""video-player""}",Boring design + No gamification,HIGH
|
||||||
|
69,Non-profit/Charity,Storytelling + Trust,Accessible & Ethical + Organic Biophilic,Cause-related colors + Trust + Warm,Heartfelt + Readable typography,Impact counter animations + Story reveals,"{""must_have"": ""impact-stories"", ""must_have"": ""donation-transparency""}",No impact data + Hidden financials,HIGH
|
||||||
|
70,Florist/Plant Shop,Hero-Centric + Conversion,Organic Biophilic + Vibrant & Block-based,Natural Green + Floral pinks/purples,Elegant + Natural typography,Product reveal + Seasonal transitions,"{""must_have"": ""delivery-scheduling"", ""must_have"": ""care-guides""}",Poor imagery + No seasonal content,MEDIUM
|
||||||
|
71,Bakery/Cafe,Hero-Centric + Conversion,Vibrant & Block-based + Soft UI Evolution,Warm Brown + Cream + Appetizing accents,Warm + Inviting typography,Menu hover + Order animations,"{""must_have"": ""menu-display"", ""must_have"": ""online-ordering""}",Poor food photos + Hidden hours,HIGH
|
||||||
|
72,Coffee Shop,Hero-Centric + Minimal,Minimalism + Organic Biophilic,Coffee Brown (#6F4E37) + Cream + Warm,Cozy + Clean typography,Menu transitions + Loyalty animations,"{""must_have"": ""menu"", ""if_loyalty"": ""add-rewards-system""}",Generic design + No atmosphere,MEDIUM
|
||||||
|
73,Brewery/Winery,Storytelling + Hero-Centric,Motion-Driven + Storytelling-Driven,Deep amber/burgundy + Gold + Craft,Artisanal + Heritage typography,Tasting note reveals + Heritage timeline,"{""must_have"": ""product-showcase"", ""must_have"": ""story-heritage""}",Generic product pages + No story,HIGH
|
||||||
|
74,Airline,Conversion + Feature-Rich,Minimalism + Glassmorphism,Sky Blue + Brand colors + Trust,Clear + Professional typography,Flight search animations + Boarding pass reveals,"{""must_have"": ""flight-search"", ""must_have"": ""mobile-first""}",Complex booking + Poor mobile,HIGH
|
||||||
|
75,Magazine/Blog,Storytelling + Hero-Centric,Swiss Modernism 2.0 + Motion-Driven,Editorial colors + Brand + Clean white,Editorial + Elegant typography,Article transitions + Category reveals,"{""must_have"": ""article-showcase"", ""must_have"": ""newsletter-signup""}",Poor typography + Slow loading,HIGH
|
||||||
|
76,Freelancer Platform,Feature-Rich + Conversion,Flat Design + Minimalism,Professional Blue + Success Green,Clear + Professional typography,Skill match animations + Review reveals,"{""must_have"": ""portfolio-display"", ""must_have"": ""skill-matching""}",Poor profiles + No reviews,HIGH
|
||||||
|
77,Consulting Firm,Trust & Authority + Minimal,Trust & Authority + Minimalism,Navy + Gold + Professional grey,Authoritative + Clear typography,Case study reveals + Team profiles,"{""must_have"": ""case-studies"", ""must_have"": ""thought-leadership""}",Generic content + No credentials + AI purple/pink gradients,HIGH
|
||||||
|
78,Marketing Agency,Storytelling + Feature-Rich,Brutalism + Motion-Driven,Bold brand colors + Creative freedom,Bold + Expressive typography,Portfolio reveals + Results animations,"{""must_have"": ""portfolio"", ""must_have"": ""results-metrics""}",Boring design + Hidden work,HIGH
|
||||||
|
79,Event Management,Hero-Centric + Feature-Rich,Vibrant & Block-based + Motion-Driven,Event theme colors + Excitement accents,Bold + Engaging typography,Countdown timer + Registration flow,"{""must_have"": ""registration"", ""must_have"": ""agenda-display""}",Confusing registration + No countdown,HIGH
|
||||||
|
80,Conference/Webinar Platform,Feature-Rich + Conversion,Glassmorphism + Minimalism,Professional Blue + Video accent,Professional + Clear typography,Live stream integration + Agenda transitions,"{""must_have"": ""registration"", ""must_have"": ""speaker-profiles""}",Poor video UX + No networking,HIGH
|
||||||
|
81,Membership/Community,Social Proof + Conversion,Vibrant & Block-based + Soft UI Evolution,Community brand colors + Engagement,Friendly + Engaging typography,Member counter + Benefit reveals,"{""must_have"": ""member-benefits"", ""must_have"": ""pricing-tiers""}",Hidden benefits + No community proof,HIGH
|
||||||
|
82,Newsletter Platform,Minimal + Conversion,Minimalism + Flat Design,Brand primary + Clean white + CTA,Clean + Readable typography,Subscribe form + Archive reveals,"{""must_have"": ""subscribe-form"", ""must_have"": ""sample-content""}",Complex signup + No preview,MEDIUM
|
||||||
|
83,Digital Products/Downloads,Feature-Rich + Conversion,Vibrant & Block-based + Motion-Driven,Product colors + Brand + Success green,Modern + Clear typography,Product preview + Instant delivery animations,"{""must_have"": ""product-preview"", ""must_have"": ""instant-delivery""}",No preview + Slow delivery,HIGH
|
||||||
|
84,Church/Religious Organization,Hero-Centric + Social Proof,Accessible & Ethical + Soft UI Evolution,Warm Gold + Deep Purple/Blue + White,Welcoming + Clear typography,Service time highlights + Event calendar,"{""must_have"": ""service-times"", ""must_have"": ""community-events""}",Outdated design + Hidden info,MEDIUM
|
||||||
|
85,Sports Team/Club,Hero-Centric + Feature-Rich,Vibrant & Block-based + Motion-Driven,Team colors + Energetic accents,Bold + Impactful typography,Score animations + Schedule reveals,"{""must_have"": ""schedule"", ""must_have"": ""roster""}",Static content + Poor fan engagement,HIGH
|
||||||
|
86,Museum/Gallery,Storytelling + Feature-Rich,Minimalism + Motion-Driven,Art-appropriate neutrals + Exhibition accents,Elegant + Minimal typography,Virtual tour + Collection reveals,"{""must_have"": ""virtual-tour"", ""must_have"": ""exhibition-info""}",Cluttered layout + No online access,HIGH
|
||||||
|
87,Theater/Cinema,Hero-Centric + Conversion,Dark Mode (OLED) + Motion-Driven,Dark + Spotlight accents + Gold,Dramatic + Bold typography,Seat selection + Trailer reveals,"{""must_have"": ""showtimes"", ""must_have"": ""seat-selection""}",Poor booking UX + No trailers,HIGH
|
||||||
|
88,Language Learning App,Feature-Rich + Social Proof,Claymorphism + Vibrant & Block-based,Playful colors + Progress indicators,Friendly + Clear typography,Progress animations + Achievement unlocks,"{""must_have"": ""progress-tracking"", ""must_have"": ""gamification""}",Boring design + No motivation,HIGH
|
||||||
|
89,Coding Bootcamp,Feature-Rich + Social Proof,Dark Mode (OLED) + Minimalism,Code editor colors + Brand + Success,Technical + Clear typography,Terminal animations + Career outcome reveals,"{""must_have"": ""curriculum"", ""must_have"": ""career-outcomes""}",Light mode only + Hidden results,HIGH
|
||||||
|
90,Cybersecurity Platform,Trust & Authority + Real-Time,Cyberpunk UI + Dark Mode (OLED),Matrix Green (#00FF00) + Deep Black,Technical + Clear typography,Threat visualization + Alert animations,"{""must_have"": ""real-time-monitoring"", ""must_have"": ""threat-display""}",Light mode + Poor data viz,HIGH
|
||||||
|
91,Developer Tool/IDE,Minimal + Documentation,Dark Mode (OLED) + Minimalism,Dark syntax theme + Blue focus,Monospace + Functional typography,Syntax highlighting + Command palette,"{""must_have"": ""keyboard-shortcuts"", ""must_have"": ""documentation""}",Light mode default + Slow performance,HIGH
|
||||||
|
92,Biotech/Life Sciences,Storytelling + Data,Glassmorphism + Clean Science,Sterile White + DNA Blue + Life Green,Scientific + Clear typography,Data visualization + Research reveals,"{""must_have"": ""data-accuracy"", ""must_have"": ""clean-aesthetic""}",Cluttered data + Poor credibility,HIGH
|
||||||
|
93,Space Tech/Aerospace,Immersive + Feature-Rich,Holographic/HUD + Dark Mode,Deep Space Black + Star White + Metallic,Futuristic + Precise typography,Telemetry animations + 3D renders,"{""must_have"": ""high-tech-feel"", ""must_have"": ""precision-data""}",Generic design + No immersion,HIGH
|
||||||
|
94,Architecture/Interior,Portfolio + Hero-Centric,Exaggerated Minimalism + High Imagery,Monochrome + Gold Accent + High Imagery,Architectural + Elegant typography,Project gallery + Blueprint reveals,"{""must_have"": ""high-res-images"", ""must_have"": ""project-portfolio""}",Poor imagery + Cluttered layout,HIGH
|
||||||
|
95,Quantum Computing,Immersive + Interactive,Holographic/HUD + Dark Mode,Quantum Blue (#00FFFF) + Deep Black,Futuristic + Scientific typography,Probability visualizations + Qubit state animations,"{""must_have"": ""complexity-visualization"", ""must_have"": ""scientific-credibility""}",Generic tech design + No viz,HIGH
|
||||||
|
96,Biohacking/Longevity App,Data-Dense + Storytelling,Biomimetic/Organic 2.0 + Minimalism,Cellular Pink/Red + DNA Blue + White,Scientific + Clear typography,Biological data viz + Progress animations,"{""must_have"": ""data-privacy"", ""must_have"": ""scientific-credibility""}",Generic health app + No privacy,HIGH
|
||||||
|
97,Autonomous Drone Fleet,Real-Time + Feature-Rich,HUD/Sci-Fi FUI + Real-Time,Tactical Green + Alert Red + Map Dark,Technical + Functional typography,Telemetry animations + 3D spatial awareness,"{""must_have"": ""real-time-telemetry"", ""must_have"": ""safety-alerts""}",Slow updates + Poor spatial viz,HIGH
|
||||||
|
98,Generative Art Platform,Showcase + Feature-Rich,Minimalism + Gen Z Chaos,Neutral (#F5F5F5) + User Content,Minimal + Content-focused typography,Gallery masonry + Minting animations,"{""must_have"": ""fast-loading"", ""must_have"": ""creator-attribution""}",Heavy chrome + Slow loading,HIGH
|
||||||
|
99,Spatial Computing OS,Immersive + Interactive,Spatial UI (VisionOS) + Glassmorphism,Frosted Glass + System Colors + Depth,Spatial + Readable typography,Depth hierarchy + Gaze interactions,"{""must_have"": ""depth-hierarchy"", ""must_have"": ""environment-awareness""}",2D design + No spatial depth,HIGH
|
||||||
|
100,Sustainable Energy/Climate,Data + Trust,Organic Biophilic + E-Ink/Paper,Earth Green + Sky Blue + Solar Yellow,Clear + Informative typography,Impact viz + Progress animations,"{""must_have"": ""data-transparency"", ""must_have"": ""impact-visualization""}",Greenwashing + No real data,HIGH
|
||||||
|
@@ -0,0 +1,100 @@
|
|||||||
|
No,Category,Issue,Platform,Description,Do,Don't,Code Example Good,Code Example Bad,Severity
|
||||||
|
1,Navigation,Smooth Scroll,Web,Anchor links should scroll smoothly to target section,Use scroll-behavior: smooth on html element,Jump directly without transition,html { scroll-behavior: smooth; },<a href='#section'> without CSS,High
|
||||||
|
2,Navigation,Sticky Navigation,Web,Fixed nav should not obscure content,Add padding-top to body equal to nav height,Let nav overlap first section content,pt-20 (if nav is h-20),No padding compensation,Medium
|
||||||
|
3,Navigation,Active State,All,Current page/section should be visually indicated,Highlight active nav item with color/underline,No visual feedback on current location,text-primary border-b-2,All links same style,Medium
|
||||||
|
4,Navigation,Back Button,Mobile,Users expect back to work predictably,Preserve navigation history properly,Break browser/app back button behavior,history.pushState(),location.replace(),High
|
||||||
|
5,Navigation,Deep Linking,All,URLs should reflect current state for sharing,Update URL on state/view changes,Static URLs for dynamic content,Use query params or hash,Single URL for all states,Medium
|
||||||
|
6,Navigation,Breadcrumbs,Web,Show user location in site hierarchy,Use for sites with 3+ levels of depth,Use for flat single-level sites,Home > Category > Product,Only on deep nested pages,Low
|
||||||
|
7,Animation,Excessive Motion,All,Too many animations cause distraction and motion sickness,Animate 1-2 key elements per view maximum,Animate everything that moves,Single hero animation,animate-bounce on 5+ elements,High
|
||||||
|
8,Animation,Duration Timing,All,Animations should feel responsive not sluggish,Use 150-300ms for micro-interactions,Use animations longer than 500ms for UI,transition-all duration-200,duration-1000,Medium
|
||||||
|
9,Animation,Reduced Motion,All,Respect user's motion preferences,Check prefers-reduced-motion media query,Ignore accessibility motion settings,@media (prefers-reduced-motion: reduce),No motion query check,High
|
||||||
|
10,Animation,Loading States,All,Show feedback during async operations,Use skeleton screens or spinners,Leave UI frozen with no feedback,animate-pulse skeleton,Blank screen while loading,High
|
||||||
|
11,Animation,Hover vs Tap,All,Hover effects don't work on touch devices,Use click/tap for primary interactions,Rely only on hover for important actions,onClick handler,onMouseEnter only,High
|
||||||
|
12,Animation,Continuous Animation,All,Infinite animations are distracting,Use for loading indicators only,Use for decorative elements,animate-spin on loader,animate-bounce on icons,Medium
|
||||||
|
13,Animation,Transform Performance,Web,Some CSS properties trigger expensive repaints,Use transform and opacity for animations,Animate width/height/top/left properties,transform: translateY(),top: 10px animation,Medium
|
||||||
|
14,Animation,Easing Functions,All,Linear motion feels robotic,Use ease-out for entering ease-in for exiting,Use linear for UI transitions,ease-out,linear,Low
|
||||||
|
15,Layout,Z-Index Management,Web,Stacking context conflicts cause hidden elements,Define z-index scale system (10 20 30 50),Use arbitrary large z-index values,z-10 z-20 z-50,z-[9999],High
|
||||||
|
16,Layout,Overflow Hidden,Web,Hidden overflow can clip important content,Test all content fits within containers,Blindly apply overflow-hidden,overflow-auto with scroll,overflow-hidden truncating content,Medium
|
||||||
|
17,Layout,Fixed Positioning,Web,Fixed elements can overlap or be inaccessible,Account for safe areas and other fixed elements,Stack multiple fixed elements carelessly,Fixed nav + fixed bottom with gap,Multiple overlapping fixed elements,Medium
|
||||||
|
18,Layout,Stacking Context,Web,New stacking contexts reset z-index,Understand what creates new stacking context,Expect z-index to work across contexts,Parent with z-index isolates children,z-index: 9999 not working,Medium
|
||||||
|
19,Layout,Content Jumping,Web,Layout shift when content loads is jarring,Reserve space for async content,Let images/content push layout around,aspect-ratio or fixed height,No dimensions on images,High
|
||||||
|
20,Layout,Viewport Units,Web,100vh can be problematic on mobile browsers,Use dvh or account for mobile browser chrome,Use 100vh for full-screen mobile layouts,min-h-dvh or min-h-screen,h-screen on mobile,Medium
|
||||||
|
21,Layout,Container Width,Web,Content too wide is hard to read,Limit max-width for text content (65-75ch),Let text span full viewport width,max-w-prose or max-w-3xl,Full width paragraphs,Medium
|
||||||
|
22,Touch,Touch Target Size,Mobile,Small buttons are hard to tap accurately,Minimum 44x44px touch targets,Tiny clickable areas,min-h-[44px] min-w-[44px],w-6 h-6 buttons,High
|
||||||
|
23,Touch,Touch Spacing,Mobile,Adjacent touch targets need adequate spacing,Minimum 8px gap between touch targets,Tightly packed clickable elements,gap-2 between buttons,gap-0 or gap-1,Medium
|
||||||
|
24,Touch,Gesture Conflicts,Mobile,Custom gestures can conflict with system,Avoid horizontal swipe on main content,Override system gestures,Vertical scroll primary,Horizontal swipe carousel only,Medium
|
||||||
|
25,Touch,Tap Delay,Mobile,300ms tap delay feels laggy,Use touch-action CSS or fastclick,Default mobile tap handling,touch-action: manipulation,No touch optimization,Medium
|
||||||
|
26,Touch,Pull to Refresh,Mobile,Accidental refresh is frustrating,Disable where not needed,Enable by default everywhere,overscroll-behavior: contain,Default overscroll,Low
|
||||||
|
27,Touch,Haptic Feedback,Mobile,Tactile feedback improves interaction feel,Use for confirmations and important actions,Overuse vibration feedback,navigator.vibrate(10),Vibrate on every tap,Low
|
||||||
|
28,Interaction,Focus States,All,Keyboard users need visible focus indicators,Use visible focus rings on interactive elements,Remove focus outline without replacement,focus:ring-2 focus:ring-blue-500,outline-none without alternative,High
|
||||||
|
29,Interaction,Hover States,Web,Visual feedback on interactive elements,Change cursor and add subtle visual change,No hover feedback on clickable elements,hover:bg-gray-100 cursor-pointer,No hover style,Medium
|
||||||
|
30,Interaction,Active States,All,Show immediate feedback on press/click,Add pressed/active state visual change,No feedback during interaction,active:scale-95,No active state,Medium
|
||||||
|
31,Interaction,Disabled States,All,Clearly indicate non-interactive elements,Reduce opacity and change cursor,Confuse disabled with normal state,opacity-50 cursor-not-allowed,Same style as enabled,Medium
|
||||||
|
32,Interaction,Loading Buttons,All,Prevent double submission during async actions,Disable button and show loading state,Allow multiple clicks during processing,disabled={loading} spinner,Button clickable while loading,High
|
||||||
|
33,Interaction,Error Feedback,All,Users need to know when something fails,Show clear error messages near problem,Silent failures with no feedback,Red border + error message,No indication of error,High
|
||||||
|
34,Interaction,Success Feedback,All,Confirm successful actions to users,Show success message or visual change,No confirmation of completed action,Toast notification or checkmark,Action completes silently,Medium
|
||||||
|
35,Interaction,Confirmation Dialogs,All,Prevent accidental destructive actions,Confirm before delete/irreversible actions,Delete without confirmation,Are you sure modal,Direct delete on click,High
|
||||||
|
36,Accessibility,Color Contrast,All,Text must be readable against background,Minimum 4.5:1 ratio for normal text,Low contrast text,#333 on white (7:1),#999 on white (2.8:1),High
|
||||||
|
37,Accessibility,Color Only,All,Don't convey information by color alone,Use icons/text in addition to color,Red/green only for error/success,Red text + error icon,Red border only for error,High
|
||||||
|
38,Accessibility,Alt Text,All,Images need text alternatives,Descriptive alt text for meaningful images,Empty or missing alt attributes,alt='Dog playing in park',alt='' for content images,High
|
||||||
|
39,Accessibility,Heading Hierarchy,Web,Screen readers use headings for navigation,Use sequential heading levels h1-h6,Skip heading levels or misuse for styling,h1 then h2 then h3,h1 then h4,Medium
|
||||||
|
40,Accessibility,ARIA Labels,All,Interactive elements need accessible names,Add aria-label for icon-only buttons,Icon buttons without labels,aria-label='Close menu',<button><Icon/></button>,High
|
||||||
|
41,Accessibility,Keyboard Navigation,Web,All functionality accessible via keyboard,Tab order matches visual order,Keyboard traps or illogical tab order,tabIndex for custom order,Unreachable elements,High
|
||||||
|
42,Accessibility,Screen Reader,All,Content should make sense when read aloud,Use semantic HTML and ARIA properly,Div soup with no semantics,<nav> <main> <article>,<div> for everything,Medium
|
||||||
|
43,Accessibility,Form Labels,All,Inputs must have associated labels,Use label with for attribute or wrap input,Placeholder-only inputs,<label for='email'>,placeholder='Email' only,High
|
||||||
|
44,Accessibility,Error Messages,All,Error messages must be announced,Use aria-live or role=alert for errors,Visual-only error indication,role='alert',Red border only,High
|
||||||
|
45,Accessibility,Skip Links,Web,Allow keyboard users to skip navigation,Provide skip to main content link,No skip link on nav-heavy pages,Skip to main content link,100 tabs to reach content,Medium
|
||||||
|
46,Performance,Image Optimization,All,Large images slow page load,Use appropriate size and format (WebP),Unoptimized full-size images,srcset with multiple sizes,4000px image for 400px display,High
|
||||||
|
47,Performance,Lazy Loading,All,Load content as needed,Lazy load below-fold images and content,Load everything upfront,loading='lazy',All images eager load,Medium
|
||||||
|
48,Performance,Code Splitting,Web,Large bundles slow initial load,Split code by route/feature,Single large bundle,dynamic import(),All code in main bundle,Medium
|
||||||
|
49,Performance,Caching,Web,Repeat visits should be fast,Set appropriate cache headers,No caching strategy,Cache-Control headers,Every request hits server,Medium
|
||||||
|
50,Performance,Font Loading,Web,Web fonts can block rendering,Use font-display swap or optional,Invisible text during font load,font-display: swap,FOIT (Flash of Invisible Text),Medium
|
||||||
|
51,Performance,Third Party Scripts,Web,External scripts can block rendering,Load non-critical scripts async/defer,Synchronous third-party scripts,async or defer attribute,<script src='...'> in head,Medium
|
||||||
|
52,Performance,Bundle Size,Web,Large JavaScript slows interaction,Monitor and minimize bundle size,Ignore bundle size growth,Bundle analyzer,No size monitoring,Medium
|
||||||
|
53,Performance,Render Blocking,Web,CSS/JS can block first paint,Inline critical CSS defer non-critical,Large blocking CSS files,Critical CSS inline,All CSS in head,Medium
|
||||||
|
54,Forms,Input Labels,All,Every input needs a visible label,Always show label above or beside input,Placeholder as only label,<label>Email</label><input>,placeholder='Email' only,High
|
||||||
|
55,Forms,Error Placement,All,Errors should appear near the problem,Show error below related input,Single error message at top of form,Error under each field,All errors at form top,Medium
|
||||||
|
56,Forms,Inline Validation,All,Validate as user types or on blur,Validate on blur for most fields,Validate only on submit,onBlur validation,Submit-only validation,Medium
|
||||||
|
57,Forms,Input Types,All,Use appropriate input types,Use email tel number url etc,Text input for everything,type='email',type='text' for email,Medium
|
||||||
|
58,Forms,Autofill Support,Web,Help browsers autofill correctly,Use autocomplete attribute properly,Block or ignore autofill,autocomplete='email',autocomplete='off' everywhere,Medium
|
||||||
|
59,Forms,Required Indicators,All,Mark required fields clearly,Use asterisk or (required) text,No indication of required fields,* required indicator,Guess which are required,Medium
|
||||||
|
60,Forms,Password Visibility,All,Let users see password while typing,Toggle to show/hide password,No visibility toggle,Show/hide password button,Password always hidden,Medium
|
||||||
|
61,Forms,Submit Feedback,All,Confirm form submission status,Show loading then success/error state,No feedback after submit,Loading -> Success message,Button click with no response,High
|
||||||
|
62,Forms,Input Affordance,All,Inputs should look interactive,Use distinct input styling,Inputs that look like plain text,Border/background on inputs,Borderless inputs,Medium
|
||||||
|
63,Forms,Mobile Keyboards,Mobile,Show appropriate keyboard for input type,Use inputmode attribute,Default keyboard for all inputs,inputmode='numeric',Text keyboard for numbers,Medium
|
||||||
|
64,Responsive,Mobile First,Web,Design for mobile then enhance for larger,Start with mobile styles then add breakpoints,Desktop-first causing mobile issues,Default mobile + md: lg: xl:,Desktop default + max-width queries,Medium
|
||||||
|
65,Responsive,Breakpoint Testing,Web,Test at all common screen sizes,Test at 320 375 414 768 1024 1440,Only test on your device,Multiple device testing,Single device development,Medium
|
||||||
|
66,Responsive,Touch Friendly,Web,Mobile layouts need touch-sized targets,Increase touch targets on mobile,Same tiny buttons on mobile,Larger buttons on mobile,Desktop-sized targets on mobile,High
|
||||||
|
67,Responsive,Readable Font Size,All,Text must be readable on all devices,Minimum 16px body text on mobile,Tiny text on mobile,text-base or larger,text-xs for body text,High
|
||||||
|
68,Responsive,Viewport Meta,Web,Set viewport for mobile devices,Use width=device-width initial-scale=1,Missing or incorrect viewport,<meta name='viewport'...>,No viewport meta tag,High
|
||||||
|
69,Responsive,Horizontal Scroll,Web,Avoid horizontal scrolling,Ensure content fits viewport width,Content wider than viewport,max-w-full overflow-x-hidden,Horizontal scrollbar on mobile,High
|
||||||
|
70,Responsive,Image Scaling,Web,Images should scale with container,Use max-width: 100% on images,Fixed width images overflow,max-w-full h-auto,width='800' fixed,Medium
|
||||||
|
71,Responsive,Table Handling,Web,Tables can overflow on mobile,Use horizontal scroll or card layout,Wide tables breaking layout,overflow-x-auto wrapper,Table overflows viewport,Medium
|
||||||
|
72,Typography,Line Height,All,Adequate line height improves readability,Use 1.5-1.75 for body text,Cramped or excessive line height,leading-relaxed (1.625),leading-none (1),Medium
|
||||||
|
73,Typography,Line Length,Web,Long lines are hard to read,Limit to 65-75 characters per line,Full-width text on large screens,max-w-prose,Full viewport width text,Medium
|
||||||
|
74,Typography,Font Size Scale,All,Consistent type hierarchy aids scanning,Use consistent modular scale,Random font sizes,Type scale (12 14 16 18 24 32),Arbitrary sizes,Medium
|
||||||
|
75,Typography,Font Loading,Web,Fonts should load without layout shift,Reserve space with fallback font,Layout shift when fonts load,font-display: swap + similar fallback,No fallback font,Medium
|
||||||
|
76,Typography,Contrast Readability,All,Body text needs good contrast,Use darker text on light backgrounds,Gray text on gray background,text-gray-900 on white,text-gray-400 on gray-100,High
|
||||||
|
77,Typography,Heading Clarity,All,Headings should stand out from body,Clear size/weight difference,Headings similar to body text,Bold + larger size,Same size as body,Medium
|
||||||
|
78,Feedback,Loading Indicators,All,Show system status during waits,Show spinner/skeleton for operations > 300ms,No feedback during loading,Skeleton or spinner,Frozen UI,High
|
||||||
|
79,Feedback,Empty States,All,Guide users when no content exists,Show helpful message and action,Blank empty screens,No items yet. Create one!,Empty white space,Medium
|
||||||
|
80,Feedback,Error Recovery,All,Help users recover from errors,Provide clear next steps,Error without recovery path,Try again button + help link,Error message only,Medium
|
||||||
|
81,Feedback,Progress Indicators,All,Show progress for multi-step processes,Step indicators or progress bar,No indication of progress,Step 2 of 4 indicator,No step information,Medium
|
||||||
|
82,Feedback,Toast Notifications,All,Transient messages for non-critical info,Auto-dismiss after 3-5 seconds,Toasts that never disappear,Auto-dismiss toast,Persistent toast,Medium
|
||||||
|
83,Feedback,Confirmation Messages,All,Confirm successful actions,Brief success message,Silent success,Saved successfully toast,No confirmation,Medium
|
||||||
|
84,Content,Truncation,All,Handle long content gracefully,Truncate with ellipsis and expand option,Overflow or broken layout,line-clamp-2 with expand,Overflow or cut off,Medium
|
||||||
|
85,Content,Date Formatting,All,Use locale-appropriate date formats,Use relative or locale-aware dates,Ambiguous date formats,2 hours ago or locale format,01/02/03,Low
|
||||||
|
86,Content,Number Formatting,All,Format large numbers for readability,Use thousand separators or abbreviations,Long unformatted numbers,"1.2K or 1,234",1234567,Low
|
||||||
|
87,Content,Placeholder Content,All,Show realistic placeholders during dev,Use realistic sample data,Lorem ipsum everywhere,Real sample content,Lorem ipsum,Low
|
||||||
|
88,Onboarding,User Freedom,All,Users should be able to skip tutorials,Provide Skip and Back buttons,Force linear unskippable tour,Skip Tutorial button,Locked overlay until finished,Medium
|
||||||
|
89,Search,Autocomplete,Web,Help users find results faster,Show predictions as user types,Require full type and enter,Debounced fetch + dropdown,No suggestions,Medium
|
||||||
|
90,Search,No Results,Web,Dead ends frustrate users,Show 'No results' with suggestions,Blank screen or '0 results',Try searching for X instead,No results found.,Medium
|
||||||
|
91,Data Entry,Bulk Actions,Web,Editing one by one is tedious,Allow multi-select and bulk edit,Single row actions only,Checkbox column + Action bar,Repeated actions per row,Low
|
||||||
|
92,AI Interaction,Disclaimer,All,Users need to know they talk to AI,Clearly label AI generated content,Present AI as human,AI Assistant label,Fake human name without label,High
|
||||||
|
93,AI Interaction,Streaming,All,Waiting for full text is slow,Stream text response token by token,Show loading spinner for 10s+,Typewriter effect,Spinner until 100% complete,Medium
|
||||||
|
94,Spatial UI,Gaze Hover,VisionOS,Elements should respond to eye tracking before pinch,Scale/highlight element on look,Static element until pinch,hoverEffect(),onTap only,High
|
||||||
|
95,Spatial UI,Depth Layering,VisionOS,UI needs Z-depth to separate content from environment,Use glass material and z-offset,Flat opaque panels blocking view,.glassBackgroundEffect(),bg-white,Medium
|
||||||
|
96,Sustainability,Auto-Play Video,Web,Video consumes massive data and energy,Click-to-play or pause when off-screen,Auto-play high-res video loops,playsInline muted preload='none',autoplay loop,Medium
|
||||||
|
97,Sustainability,Asset Weight,Web,Heavy 3D/Image assets increase carbon footprint,Compress and lazy load 3D models,Load 50MB textures,Draco compression,Raw .obj files,Medium
|
||||||
|
98,AI Interaction,Feedback Loop,All,AI needs user feedback to improve,Thumps up/down or 'Regenerate',Static output only,Feedback component,Read-only text,Low
|
||||||
|
99,Accessibility,Motion Sensitivity,All,Parallax/Scroll-jacking causes nausea,Respect prefers-reduced-motion,Force scroll effects,@media (prefers-reduced-motion),ScrollTrigger.create(),High
|
||||||
|
@@ -0,0 +1,31 @@
|
|||||||
|
No,Category,Issue,Keywords,Platform,Description,Do,Don't,Code Example Good,Code Example Bad,Severity
|
||||||
|
1,Accessibility,Icon Button Labels,icon button aria-label,Web,Icon-only buttons must have accessible names,Add aria-label to icon buttons,Icon button without label,"<button aria-label='Close'><XIcon /></button>","<button><XIcon /></button>",Critical
|
||||||
|
2,Accessibility,Form Control Labels,form input label aria,Web,All form controls need labels or aria-label,Use label element or aria-label,Input without accessible name,"<label for='email'>Email</label><input id='email' />","<input placeholder='Email' />",Critical
|
||||||
|
3,Accessibility,Keyboard Handlers,keyboard onclick onkeydown,Web,Interactive elements must support keyboard interaction,Add onKeyDown alongside onClick,Click-only interaction,"<div onClick={fn} onKeyDown={fn} tabIndex={0}>","<div onClick={fn}>",High
|
||||||
|
4,Accessibility,Semantic HTML,semantic button a label,Web,Use semantic HTML before ARIA attributes,Use button/a/label elements,Div with role attribute,"<button onClick={fn}>Submit</button>","<div role='button' onClick={fn}>Submit</div>",High
|
||||||
|
5,Accessibility,Aria Live,aria-live polite async,Web,Async updates need aria-live for screen readers,Add aria-live='polite' for dynamic content,Silent async updates,"<div aria-live='polite'>{status}</div>","<div>{status}</div> // no announcement",Medium
|
||||||
|
6,Accessibility,Decorative Icons,aria-hidden decorative icon,Web,Decorative icons should be hidden from screen readers,Add aria-hidden='true' to decorative icons,Decorative icon announced,"<Icon aria-hidden='true' />","<Icon /> // announced as 'image'",Medium
|
||||||
|
7,Focus,Visible Focus States,focus-visible outline ring,Web,All interactive elements need visible focus states,Use :focus-visible with ring/outline,No focus indication,"focus-visible:ring-2 focus-visible:ring-blue-500","outline-none // no replacement",Critical
|
||||||
|
8,Focus,Never Remove Outline,outline-none focus replacement,Web,Never remove outline without providing replacement,Replace outline with visible alternative,Remove outline completely,"focus:outline-none focus:ring-2","focus:outline-none // nothing else",Critical
|
||||||
|
9,Focus,Checkbox Radio Hit Target,checkbox radio label target,Web,Checkbox/radio must share hit target with label,Wrap input and label together,Separate tiny checkbox,"<label class='flex gap-2'><input type='checkbox' /><span>Option</span></label>","<input type='checkbox' id='x' /><label for='x'>Option</label>",Medium
|
||||||
|
10,Forms,Autocomplete Attribute,autocomplete input form,Web,Inputs need autocomplete attribute for autofill,Add appropriate autocomplete value,Missing autocomplete,"<input autocomplete='email' type='email' />","<input type='email' />",High
|
||||||
|
11,Forms,Semantic Input Types,input type email tel url,Web,Use semantic input type attributes,Use email/tel/url/number types,text type for everything,"<input type='email' />","<input type='text' /> // for email",Medium
|
||||||
|
12,Forms,Never Block Paste,paste onpaste password,Web,Never prevent paste functionality,Allow paste on all inputs,Block paste on password/code,"<input type='password' />","<input onPaste={e => e.preventDefault()} />",High
|
||||||
|
13,Forms,Spellcheck Disable,spellcheck email code,Web,Disable spellcheck on emails and codes,Set spellcheck='false' on codes,Spellcheck on technical input,"<input spellCheck='false' type='email' />","<input type='email' /> // red squiggles",Low
|
||||||
|
14,Forms,Submit Button Enabled,submit button disabled loading,Web,Keep submit enabled and show spinner during requests,Show loading spinner keep enabled,Disable button during submit,"<button>{loading ? <Spinner /> : 'Submit'}</button>","<button disabled={loading}>Submit</button>",Medium
|
||||||
|
15,Forms,Inline Errors,error message inline focus,Web,Show error messages inline near the problem field,Inline error with focus on first error,Single error at top,"<input /><span class='text-red-500'>{error}</span>","<div class='error'>{allErrors}</div> // at top",High
|
||||||
|
16,Performance,Virtualize Lists,virtualize list 50 items,Web,Virtualize lists exceeding 50 items,Use virtual list for large datasets,Render all items,"<VirtualList items={items} />","items.map(item => <Item />)",High
|
||||||
|
17,Performance,Avoid Layout Reads,layout read render getboundingclientrect,Web,Avoid layout reads during render phase,Read layout in effects or callbacks,getBoundingClientRect in render,"useEffect(() => { el.getBoundingClientRect() })","const rect = el.getBoundingClientRect() // in render",Medium
|
||||||
|
18,Performance,Batch DOM Operations,batch dom write read,Web,Group DOM operations to minimize reflows,Batch writes then reads,Interleave reads and writes,"writes.forEach(w => w()); reads.forEach(r => r())","write(); read(); write(); read(); // thrashing",Medium
|
||||||
|
19,Performance,Preconnect CDN,preconnect link cdn,Web,Add preconnect links for CDN domains,Preconnect to known domains,"<link rel='preconnect' href='https://cdn.example.com' />","// no preconnect hint",Low
|
||||||
|
20,Performance,Lazy Load Images,lazy loading image below-fold,Web,Lazy-load images below the fold,Use loading='lazy' for below-fold images,Load all images eagerly,"<img loading='lazy' src='...' />","<img src='...' /> // above fold only",Medium
|
||||||
|
21,State,URL Reflects State,url state query params,Web,URL should reflect current UI state,Sync filters/tabs/pagination to URL,State only in memory,"?tab=settings&page=2","useState only // lost on refresh",High
|
||||||
|
22,State,Deep Linking,deep link stateful component,Web,Stateful components should support deep-linking,Enable sharing current view via URL,No shareable state,"router.push({ query: { ...filters } })","setFilters(f) // not in URL",Medium
|
||||||
|
23,State,Confirm Destructive Actions,confirm destructive delete modal,Web,Destructive actions require confirmation,Show confirmation dialog before delete,Delete without confirmation,"if (confirm('Delete?')) delete()","onClick={delete} // no confirmation",High
|
||||||
|
24,Typography,Proper Unicode,unicode ellipsis quotes,Web,Use proper Unicode characters,Use ... curly quotes proper dashes,ASCII approximations,"'Hello...' with proper ellipsis","'Hello...' with three dots",Low
|
||||||
|
25,Typography,Text Overflow,truncate line-clamp overflow,Web,Handle text overflow properly,Use truncate/line-clamp/break-words,Text overflows container,"<p class='truncate'>Long text...</p>","<p>Long text...</p> // overflows",Medium
|
||||||
|
26,Typography,Non-Breaking Spaces,nbsp unit brand,Web,Use non-breaking spaces for units and brand names,Use between number and unit,"10 kg or Next.js 14","10 kg // may wrap",Low
|
||||||
|
27,Anti-Pattern,No Zoom Disable,viewport zoom disable,Web,Never disable zoom in viewport meta,Allow user zoom,"<meta name='viewport' content='width=device-width'>","<meta name='viewport' content='maximum-scale=1'>",Critical
|
||||||
|
28,Anti-Pattern,No Transition All,transition all specific,Web,Avoid transition: all - specify properties,Transition specific properties,transition: all,"transition-colors duration-200","transition-all duration-200",Medium
|
||||||
|
29,Anti-Pattern,Outline Replacement,outline-none ring focus,Web,Never use outline-none without replacement,Provide visible focus replacement,Remove outline with nothing,"focus:outline-none focus:ring-2 focus:ring-blue-500","focus:outline-none // alone",Critical
|
||||||
|
30,Anti-Pattern,No Hardcoded Dates,date format intl locale,Web,Use Intl for date/number formatting,Use Intl.DateTimeFormat,Hardcoded date format,"new Intl.DateTimeFormat('en').format(date)","date.toLocaleDateString() // or manual format",Medium
|
||||||
|
@@ -0,0 +1,253 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
UI/UX Pro Max Core - BM25 search engine for UI/UX style guides
|
||||||
|
"""
|
||||||
|
|
||||||
|
import csv
|
||||||
|
import re
|
||||||
|
from pathlib import Path
|
||||||
|
from math import log
|
||||||
|
from collections import defaultdict
|
||||||
|
|
||||||
|
# ============ CONFIGURATION ============
|
||||||
|
DATA_DIR = Path(__file__).parent.parent / "data"
|
||||||
|
MAX_RESULTS = 3
|
||||||
|
|
||||||
|
CSV_CONFIG = {
|
||||||
|
"style": {
|
||||||
|
"file": "styles.csv",
|
||||||
|
"search_cols": ["Style Category", "Keywords", "Best For", "Type", "AI Prompt Keywords"],
|
||||||
|
"output_cols": ["Style Category", "Type", "Keywords", "Primary Colors", "Effects & Animation", "Best For", "Performance", "Accessibility", "Framework Compatibility", "Complexity", "AI Prompt Keywords", "CSS/Technical Keywords", "Implementation Checklist", "Design System Variables"]
|
||||||
|
},
|
||||||
|
"color": {
|
||||||
|
"file": "colors.csv",
|
||||||
|
"search_cols": ["Product Type", "Notes"],
|
||||||
|
"output_cols": ["Product Type", "Primary (Hex)", "Secondary (Hex)", "CTA (Hex)", "Background (Hex)", "Text (Hex)", "Notes"]
|
||||||
|
},
|
||||||
|
"chart": {
|
||||||
|
"file": "charts.csv",
|
||||||
|
"search_cols": ["Data Type", "Keywords", "Best Chart Type", "Accessibility Notes"],
|
||||||
|
"output_cols": ["Data Type", "Keywords", "Best Chart Type", "Secondary Options", "Color Guidance", "Accessibility Notes", "Library Recommendation", "Interactive Level"]
|
||||||
|
},
|
||||||
|
"landing": {
|
||||||
|
"file": "landing.csv",
|
||||||
|
"search_cols": ["Pattern Name", "Keywords", "Conversion Optimization", "Section Order"],
|
||||||
|
"output_cols": ["Pattern Name", "Keywords", "Section Order", "Primary CTA Placement", "Color Strategy", "Conversion Optimization"]
|
||||||
|
},
|
||||||
|
"product": {
|
||||||
|
"file": "products.csv",
|
||||||
|
"search_cols": ["Product Type", "Keywords", "Primary Style Recommendation", "Key Considerations"],
|
||||||
|
"output_cols": ["Product Type", "Keywords", "Primary Style Recommendation", "Secondary Styles", "Landing Page Pattern", "Dashboard Style (if applicable)", "Color Palette Focus"]
|
||||||
|
},
|
||||||
|
"ux": {
|
||||||
|
"file": "ux-guidelines.csv",
|
||||||
|
"search_cols": ["Category", "Issue", "Description", "Platform"],
|
||||||
|
"output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"]
|
||||||
|
},
|
||||||
|
"typography": {
|
||||||
|
"file": "typography.csv",
|
||||||
|
"search_cols": ["Font Pairing Name", "Category", "Mood/Style Keywords", "Best For", "Heading Font", "Body Font"],
|
||||||
|
"output_cols": ["Font Pairing Name", "Category", "Heading Font", "Body Font", "Mood/Style Keywords", "Best For", "Google Fonts URL", "CSS Import", "Tailwind Config", "Notes"]
|
||||||
|
},
|
||||||
|
"icons": {
|
||||||
|
"file": "icons.csv",
|
||||||
|
"search_cols": ["Category", "Icon Name", "Keywords", "Best For"],
|
||||||
|
"output_cols": ["Category", "Icon Name", "Keywords", "Library", "Import Code", "Usage", "Best For", "Style"]
|
||||||
|
},
|
||||||
|
"react": {
|
||||||
|
"file": "react-performance.csv",
|
||||||
|
"search_cols": ["Category", "Issue", "Keywords", "Description"],
|
||||||
|
"output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"]
|
||||||
|
},
|
||||||
|
"web": {
|
||||||
|
"file": "web-interface.csv",
|
||||||
|
"search_cols": ["Category", "Issue", "Keywords", "Description"],
|
||||||
|
"output_cols": ["Category", "Issue", "Platform", "Description", "Do", "Don't", "Code Example Good", "Code Example Bad", "Severity"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
STACK_CONFIG = {
|
||||||
|
"html-tailwind": {"file": "stacks/html-tailwind.csv"},
|
||||||
|
"react": {"file": "stacks/react.csv"},
|
||||||
|
"nextjs": {"file": "stacks/nextjs.csv"},
|
||||||
|
"astro": {"file": "stacks/astro.csv"},
|
||||||
|
"vue": {"file": "stacks/vue.csv"},
|
||||||
|
"nuxtjs": {"file": "stacks/nuxtjs.csv"},
|
||||||
|
"nuxt-ui": {"file": "stacks/nuxt-ui.csv"},
|
||||||
|
"svelte": {"file": "stacks/svelte.csv"},
|
||||||
|
"swiftui": {"file": "stacks/swiftui.csv"},
|
||||||
|
"react-native": {"file": "stacks/react-native.csv"},
|
||||||
|
"flutter": {"file": "stacks/flutter.csv"},
|
||||||
|
"shadcn": {"file": "stacks/shadcn.csv"},
|
||||||
|
"jetpack-compose": {"file": "stacks/jetpack-compose.csv"}
|
||||||
|
}
|
||||||
|
|
||||||
|
# Common columns for all stacks
|
||||||
|
_STACK_COLS = {
|
||||||
|
"search_cols": ["Category", "Guideline", "Description", "Do", "Don't"],
|
||||||
|
"output_cols": ["Category", "Guideline", "Description", "Do", "Don't", "Code Good", "Code Bad", "Severity", "Docs URL"]
|
||||||
|
}
|
||||||
|
|
||||||
|
AVAILABLE_STACKS = list(STACK_CONFIG.keys())
|
||||||
|
|
||||||
|
|
||||||
|
# ============ BM25 IMPLEMENTATION ============
|
||||||
|
class BM25:
|
||||||
|
"""BM25 ranking algorithm for text search"""
|
||||||
|
|
||||||
|
def __init__(self, k1=1.5, b=0.75):
|
||||||
|
self.k1 = k1
|
||||||
|
self.b = b
|
||||||
|
self.corpus = []
|
||||||
|
self.doc_lengths = []
|
||||||
|
self.avgdl = 0
|
||||||
|
self.idf = {}
|
||||||
|
self.doc_freqs = defaultdict(int)
|
||||||
|
self.N = 0
|
||||||
|
|
||||||
|
def tokenize(self, text):
|
||||||
|
"""Lowercase, split, remove punctuation, filter short words"""
|
||||||
|
text = re.sub(r'[^\w\s]', ' ', str(text).lower())
|
||||||
|
return [w for w in text.split() if len(w) > 2]
|
||||||
|
|
||||||
|
def fit(self, documents):
|
||||||
|
"""Build BM25 index from documents"""
|
||||||
|
self.corpus = [self.tokenize(doc) for doc in documents]
|
||||||
|
self.N = len(self.corpus)
|
||||||
|
if self.N == 0:
|
||||||
|
return
|
||||||
|
self.doc_lengths = [len(doc) for doc in self.corpus]
|
||||||
|
self.avgdl = sum(self.doc_lengths) / self.N
|
||||||
|
|
||||||
|
for doc in self.corpus:
|
||||||
|
seen = set()
|
||||||
|
for word in doc:
|
||||||
|
if word not in seen:
|
||||||
|
self.doc_freqs[word] += 1
|
||||||
|
seen.add(word)
|
||||||
|
|
||||||
|
for word, freq in self.doc_freqs.items():
|
||||||
|
self.idf[word] = log((self.N - freq + 0.5) / (freq + 0.5) + 1)
|
||||||
|
|
||||||
|
def score(self, query):
|
||||||
|
"""Score all documents against query"""
|
||||||
|
query_tokens = self.tokenize(query)
|
||||||
|
scores = []
|
||||||
|
|
||||||
|
for idx, doc in enumerate(self.corpus):
|
||||||
|
score = 0
|
||||||
|
doc_len = self.doc_lengths[idx]
|
||||||
|
term_freqs = defaultdict(int)
|
||||||
|
for word in doc:
|
||||||
|
term_freqs[word] += 1
|
||||||
|
|
||||||
|
for token in query_tokens:
|
||||||
|
if token in self.idf:
|
||||||
|
tf = term_freqs[token]
|
||||||
|
idf = self.idf[token]
|
||||||
|
numerator = tf * (self.k1 + 1)
|
||||||
|
denominator = tf + self.k1 * (1 - self.b + self.b * doc_len / self.avgdl)
|
||||||
|
score += idf * numerator / denominator
|
||||||
|
|
||||||
|
scores.append((idx, score))
|
||||||
|
|
||||||
|
return sorted(scores, key=lambda x: x[1], reverse=True)
|
||||||
|
|
||||||
|
|
||||||
|
# ============ SEARCH FUNCTIONS ============
|
||||||
|
def _load_csv(filepath):
|
||||||
|
"""Load CSV and return list of dicts"""
|
||||||
|
with open(filepath, 'r', encoding='utf-8') as f:
|
||||||
|
return list(csv.DictReader(f))
|
||||||
|
|
||||||
|
|
||||||
|
def _search_csv(filepath, search_cols, output_cols, query, max_results):
|
||||||
|
"""Core search function using BM25"""
|
||||||
|
if not filepath.exists():
|
||||||
|
return []
|
||||||
|
|
||||||
|
data = _load_csv(filepath)
|
||||||
|
|
||||||
|
# Build documents from search columns
|
||||||
|
documents = [" ".join(str(row.get(col, "")) for col in search_cols) for row in data]
|
||||||
|
|
||||||
|
# BM25 search
|
||||||
|
bm25 = BM25()
|
||||||
|
bm25.fit(documents)
|
||||||
|
ranked = bm25.score(query)
|
||||||
|
|
||||||
|
# Get top results with score > 0
|
||||||
|
results = []
|
||||||
|
for idx, score in ranked[:max_results]:
|
||||||
|
if score > 0:
|
||||||
|
row = data[idx]
|
||||||
|
results.append({col: row.get(col, "") for col in output_cols if col in row})
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def detect_domain(query):
|
||||||
|
"""Auto-detect the most relevant domain from query"""
|
||||||
|
query_lower = query.lower()
|
||||||
|
|
||||||
|
domain_keywords = {
|
||||||
|
"color": ["color", "palette", "hex", "#", "rgb"],
|
||||||
|
"chart": ["chart", "graph", "visualization", "trend", "bar", "pie", "scatter", "heatmap", "funnel"],
|
||||||
|
"landing": ["landing", "page", "cta", "conversion", "hero", "testimonial", "pricing", "section"],
|
||||||
|
"product": ["saas", "ecommerce", "e-commerce", "fintech", "healthcare", "gaming", "portfolio", "crypto", "dashboard"],
|
||||||
|
"style": ["style", "design", "ui", "minimalism", "glassmorphism", "neumorphism", "brutalism", "dark mode", "flat", "aurora", "prompt", "css", "implementation", "variable", "checklist", "tailwind"],
|
||||||
|
"ux": ["ux", "usability", "accessibility", "wcag", "touch", "scroll", "animation", "keyboard", "navigation", "mobile"],
|
||||||
|
"typography": ["font", "typography", "heading", "serif", "sans"],
|
||||||
|
"icons": ["icon", "icons", "lucide", "heroicons", "symbol", "glyph", "pictogram", "svg icon"],
|
||||||
|
"react": ["react", "next.js", "nextjs", "suspense", "memo", "usecallback", "useeffect", "rerender", "bundle", "waterfall", "barrel", "dynamic import", "rsc", "server component"],
|
||||||
|
"web": ["aria", "focus", "outline", "semantic", "virtualize", "autocomplete", "form", "input type", "preconnect"]
|
||||||
|
}
|
||||||
|
|
||||||
|
scores = {domain: sum(1 for kw in keywords if kw in query_lower) for domain, keywords in domain_keywords.items()}
|
||||||
|
best = max(scores, key=scores.get)
|
||||||
|
return best if scores[best] > 0 else "style"
|
||||||
|
|
||||||
|
|
||||||
|
def search(query, domain=None, max_results=MAX_RESULTS):
|
||||||
|
"""Main search function with auto-domain detection"""
|
||||||
|
if domain is None:
|
||||||
|
domain = detect_domain(query)
|
||||||
|
|
||||||
|
config = CSV_CONFIG.get(domain, CSV_CONFIG["style"])
|
||||||
|
filepath = DATA_DIR / config["file"]
|
||||||
|
|
||||||
|
if not filepath.exists():
|
||||||
|
return {"error": f"File not found: {filepath}", "domain": domain}
|
||||||
|
|
||||||
|
results = _search_csv(filepath, config["search_cols"], config["output_cols"], query, max_results)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"domain": domain,
|
||||||
|
"query": query,
|
||||||
|
"file": config["file"],
|
||||||
|
"count": len(results),
|
||||||
|
"results": results
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def search_stack(query, stack, max_results=MAX_RESULTS):
|
||||||
|
"""Search stack-specific guidelines"""
|
||||||
|
if stack not in STACK_CONFIG:
|
||||||
|
return {"error": f"Unknown stack: {stack}. Available: {', '.join(AVAILABLE_STACKS)}"}
|
||||||
|
|
||||||
|
filepath = DATA_DIR / STACK_CONFIG[stack]["file"]
|
||||||
|
|
||||||
|
if not filepath.exists():
|
||||||
|
return {"error": f"Stack file not found: {filepath}", "stack": stack}
|
||||||
|
|
||||||
|
results = _search_csv(filepath, _STACK_COLS["search_cols"], _STACK_COLS["output_cols"], query, max_results)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"domain": "stack",
|
||||||
|
"stack": stack,
|
||||||
|
"query": query,
|
||||||
|
"file": STACK_CONFIG[stack]["file"],
|
||||||
|
"count": len(results),
|
||||||
|
"results": results
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,114 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
UI/UX Pro Max Search - BM25 search engine for UI/UX style guides
|
||||||
|
Usage: python search.py "<query>" [--domain <domain>] [--stack <stack>] [--max-results 3]
|
||||||
|
python search.py "<query>" --design-system [-p "Project Name"]
|
||||||
|
python search.py "<query>" --design-system --persist [-p "Project Name"] [--page "dashboard"]
|
||||||
|
|
||||||
|
Domains: style, prompt, color, chart, landing, product, ux, typography
|
||||||
|
Stacks: html-tailwind, react, nextjs
|
||||||
|
|
||||||
|
Persistence (Master + Overrides pattern):
|
||||||
|
--persist Save design system to design-system/MASTER.md
|
||||||
|
--page Also create a page-specific override file in design-system/pages/
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import sys
|
||||||
|
import io
|
||||||
|
from core import CSV_CONFIG, AVAILABLE_STACKS, MAX_RESULTS, search, search_stack
|
||||||
|
from design_system import generate_design_system, persist_design_system
|
||||||
|
|
||||||
|
# Force UTF-8 for stdout/stderr to handle emojis on Windows (cp1252 default)
|
||||||
|
if sys.stdout.encoding and sys.stdout.encoding.lower() != 'utf-8':
|
||||||
|
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||||||
|
if sys.stderr.encoding and sys.stderr.encoding.lower() != 'utf-8':
|
||||||
|
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
|
||||||
|
|
||||||
|
|
||||||
|
def format_output(result):
|
||||||
|
"""Format results for Claude consumption (token-optimized)"""
|
||||||
|
if "error" in result:
|
||||||
|
return f"Error: {result['error']}"
|
||||||
|
|
||||||
|
output = []
|
||||||
|
if result.get("stack"):
|
||||||
|
output.append(f"## UI Pro Max Stack Guidelines")
|
||||||
|
output.append(f"**Stack:** {result['stack']} | **Query:** {result['query']}")
|
||||||
|
else:
|
||||||
|
output.append(f"## UI Pro Max Search Results")
|
||||||
|
output.append(f"**Domain:** {result['domain']} | **Query:** {result['query']}")
|
||||||
|
output.append(f"**Source:** {result['file']} | **Found:** {result['count']} results\n")
|
||||||
|
|
||||||
|
for i, row in enumerate(result['results'], 1):
|
||||||
|
output.append(f"### Result {i}")
|
||||||
|
for key, value in row.items():
|
||||||
|
value_str = str(value)
|
||||||
|
if len(value_str) > 300:
|
||||||
|
value_str = value_str[:300] + "..."
|
||||||
|
output.append(f"- **{key}:** {value_str}")
|
||||||
|
output.append("")
|
||||||
|
|
||||||
|
return "\n".join(output)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
parser = argparse.ArgumentParser(description="UI Pro Max Search")
|
||||||
|
parser.add_argument("query", help="Search query")
|
||||||
|
parser.add_argument("--domain", "-d", choices=list(CSV_CONFIG.keys()), help="Search domain")
|
||||||
|
parser.add_argument("--stack", "-s", choices=AVAILABLE_STACKS, help="Stack-specific search (html-tailwind, react, nextjs)")
|
||||||
|
parser.add_argument("--max-results", "-n", type=int, default=MAX_RESULTS, help="Max results (default: 3)")
|
||||||
|
parser.add_argument("--json", action="store_true", help="Output as JSON")
|
||||||
|
# Design system generation
|
||||||
|
parser.add_argument("--design-system", "-ds", action="store_true", help="Generate complete design system recommendation")
|
||||||
|
parser.add_argument("--project-name", "-p", type=str, default=None, help="Project name for design system output")
|
||||||
|
parser.add_argument("--format", "-f", choices=["ascii", "markdown"], default="ascii", help="Output format for design system")
|
||||||
|
# Persistence (Master + Overrides pattern)
|
||||||
|
parser.add_argument("--persist", action="store_true", help="Save design system to design-system/MASTER.md (creates hierarchical structure)")
|
||||||
|
parser.add_argument("--page", type=str, default=None, help="Create page-specific override file in design-system/pages/")
|
||||||
|
parser.add_argument("--output-dir", "-o", type=str, default=None, help="Output directory for persisted files (default: current directory)")
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
# Design system takes priority
|
||||||
|
if args.design_system:
|
||||||
|
result = generate_design_system(
|
||||||
|
args.query,
|
||||||
|
args.project_name,
|
||||||
|
args.format,
|
||||||
|
persist=args.persist,
|
||||||
|
page=args.page,
|
||||||
|
output_dir=args.output_dir
|
||||||
|
)
|
||||||
|
print(result)
|
||||||
|
|
||||||
|
# Print persistence confirmation
|
||||||
|
if args.persist:
|
||||||
|
project_slug = args.project_name.lower().replace(' ', '-') if args.project_name else "default"
|
||||||
|
print("\n" + "=" * 60)
|
||||||
|
print(f"✅ Design system persisted to design-system/{project_slug}/")
|
||||||
|
print(f" 📄 design-system/{project_slug}/MASTER.md (Global Source of Truth)")
|
||||||
|
if args.page:
|
||||||
|
page_filename = args.page.lower().replace(' ', '-')
|
||||||
|
print(f" 📄 design-system/{project_slug}/pages/{page_filename}.md (Page Overrides)")
|
||||||
|
print("")
|
||||||
|
print(f"📖 Usage: When building a page, check design-system/{project_slug}/pages/[page].md first.")
|
||||||
|
print(f" If exists, its rules override MASTER.md. Otherwise, use MASTER.md.")
|
||||||
|
print("=" * 60)
|
||||||
|
# Stack search
|
||||||
|
elif args.stack:
|
||||||
|
result = search_stack(args.query, args.stack, args.max_results)
|
||||||
|
if args.json:
|
||||||
|
import json
|
||||||
|
print(json.dumps(result, indent=2, ensure_ascii=False))
|
||||||
|
else:
|
||||||
|
print(format_output(result))
|
||||||
|
# Domain search
|
||||||
|
else:
|
||||||
|
result = search(args.query, args.domain, args.max_results)
|
||||||
|
if args.json:
|
||||||
|
import json
|
||||||
|
print(json.dumps(result, indent=2, ensure_ascii=False))
|
||||||
|
else:
|
||||||
|
print(format_output(result))
|
||||||
+41
@@ -0,0 +1,41 @@
|
|||||||
|
# Python
|
||||||
|
backend/.venv/
|
||||||
|
backend/__pycache__/
|
||||||
|
backend/**/__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*.egg-info/
|
||||||
|
.pytest_cache/
|
||||||
|
|
||||||
|
# 本地数据库与敏感会话(切勿提交)
|
||||||
|
backend/kefu.db
|
||||||
|
backend/kefu.db-journal
|
||||||
|
backend/sessions/
|
||||||
|
*.env
|
||||||
|
.env.*
|
||||||
|
|
||||||
|
# Node
|
||||||
|
frontend/node_modules/
|
||||||
|
frontend/dist/
|
||||||
|
backend/rpa_engine/douyin_im/static/node_modules/
|
||||||
|
|
||||||
|
# 日志与临时文件
|
||||||
|
*.log
|
||||||
|
logs/
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
|
||||||
|
# Playwright 浏览器缓存
|
||||||
|
playwright-browsers/
|
||||||
|
douyin-im-collector/.venv/
|
||||||
|
douyin-im-collector/playwright-browsers/
|
||||||
|
douyin-im-collector/douyin_storage_state.json
|
||||||
|
douyin-im-collector/.browser_ready
|
||||||
|
douyin-im-collector/build/
|
||||||
|
douyin-im-collector/dist/
|
||||||
|
# ms-playwright/
|
||||||
|
|
||||||
|
# 用户上传/诊断
|
||||||
|
assets/
|
||||||
+210
@@ -0,0 +1,210 @@
|
|||||||
|
# 本地安装说明
|
||||||
|
|
||||||
|
本文档用于在本机从零部署「抖音多账号自动回复」系统。**仅供本地使用,请勿将含 Cookie/数据库的目录提交到 GitHub。**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 一、环境要求
|
||||||
|
|
||||||
|
| 组件 | 版本建议 | 用途 |
|
||||||
|
|------|----------|------|
|
||||||
|
| **Windows** | 10 / 11 | 当前脚本以 Windows 为主 |
|
||||||
|
| **Python** | 3.10 ~ 3.11 | 后端 FastAPI、Playwright、IM 签名 |
|
||||||
|
| **Node.js** | 18 LTS 或 20 LTS | `a_bogus` / `bd-ticket-guard` 签名(PyExecJS 调用) |
|
||||||
|
| **npm** | 随 Node 安装 | 前端依赖、IM 静态 JS 依赖 |
|
||||||
|
|
||||||
|
安装后可在 PowerShell 中确认:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python --version
|
||||||
|
node --version
|
||||||
|
npm --version
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、一键安装(推荐)
|
||||||
|
|
||||||
|
在项目根目录 `d:\file\kefu` 双击或执行:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\install.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
脚本会自动完成:
|
||||||
|
|
||||||
|
1. 创建 Python 虚拟环境 `backend\.venv`
|
||||||
|
2. 安装 `backend\requirements.txt` 全部 Python 包
|
||||||
|
3. 安装 Playwright Chromium 浏览器
|
||||||
|
4. 安装 IM 签名依赖(`backend\rpa_engine\douyin_im\static` 下的 `jsrsasign`)
|
||||||
|
5. 安装前端依赖(`frontend\node_modules`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、手动安装(分步)
|
||||||
|
|
||||||
|
### 1. 后端 Python 依赖
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd backend
|
||||||
|
python -m venv .venv
|
||||||
|
.\.venv\Scripts\pip install -U pip
|
||||||
|
.\.venv\Scripts\pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Playwright 浏览器(登录 / 采集凭证必需)
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd backend
|
||||||
|
$env:PLAYWRIGHT_BROWSERS_PATH = "$env:LOCALAPPDATA\ms-playwright"
|
||||||
|
.\.venv\Scripts\playwright install chromium
|
||||||
|
```
|
||||||
|
|
||||||
|
> 建议设置 `PLAYWRIGHT_BROWSERS_PATH`,避免浏览器被装到临时目录后找不到。`start_backend.bat` 已内置该变量。
|
||||||
|
|
||||||
|
### 3. IM 签名 Node 依赖(发送私信必需)
|
||||||
|
|
||||||
|
抖音私信 `a_bogus`、`bd-ticket-guard` 签名依赖 Node 与 `jsrsasign`:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd backend\rpa_engine\douyin_im\static
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
依赖定义见:`backend\rpa_engine\douyin_im\static\package.json`(仅 `jsrsasign`)。
|
||||||
|
|
||||||
|
### 4. 前端依赖
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd frontend
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 四、依赖清单汇总
|
||||||
|
|
||||||
|
### Python(`backend/requirements.txt`)
|
||||||
|
|
||||||
|
| 包 | 作用 |
|
||||||
|
|----|------|
|
||||||
|
| fastapi / uvicorn | Web API 服务 |
|
||||||
|
| sqlalchemy / aiosqlite | SQLite 异步数据库 |
|
||||||
|
| playwright | 浏览器登录、采集 Cookie / IM 凭证 |
|
||||||
|
| httpx / requests / websockets / websocket-client | IM HTTP / WebSocket |
|
||||||
|
| PyExecJS | 调用 Node 生成 a_bogus 等签名 |
|
||||||
|
| protobuf / protobuf3_to_dict | 抖音 IM Protobuf 编解码 |
|
||||||
|
| python-jose / passlib / bcrypt | 登录鉴权(JWT + 密码) |
|
||||||
|
| pydantic / python-multipart | 请求校验与表单 |
|
||||||
|
|
||||||
|
### Node(两处)
|
||||||
|
|
||||||
|
| 路径 | 依赖 | 作用 |
|
||||||
|
|------|------|------|
|
||||||
|
| `backend/rpa_engine/douyin_im/static/` | jsrsasign | IM 发送签名 |
|
||||||
|
| `frontend/` | vue, ant-design-vue, axios, pinia, vite 等 | 管理后台界面 |
|
||||||
|
|
||||||
|
### 系统级(非 pip/npm)
|
||||||
|
|
||||||
|
| 组件 | 作用 |
|
||||||
|
|------|------|
|
||||||
|
| Chromium(Playwright 安装) | 扫码登录、补全 sessionid / web_protect |
|
||||||
|
| Node.js 可执行文件 | PyExecJS 运行时 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 五、启动服务
|
||||||
|
|
||||||
|
### 后端
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# 项目根目录
|
||||||
|
.\start_backend.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
或:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd backend
|
||||||
|
$env:PLAYWRIGHT_BROWSERS_PATH = "$env:LOCALAPPDATA\ms-playwright"
|
||||||
|
.\.venv\Scripts\uvicorn main:app --host 0.0.0.0 --port 8000
|
||||||
|
```
|
||||||
|
|
||||||
|
API 地址:`http://localhost:8000`
|
||||||
|
|
||||||
|
### 前端
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd frontend
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
控制台地址:一般为 `http://localhost:5173`
|
||||||
|
|
||||||
|
默认管理员(首次启动自动创建):`admin` / `admin123`
|
||||||
|
生产环境请设置环境变量 `KEFU_SECRET_KEY`、`KEFU_ADMIN_PASSWORD`。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 六、常见问题
|
||||||
|
|
||||||
|
### 1. 启动报「找不到 uvicorn / playwright」
|
||||||
|
|
||||||
|
未执行安装步骤,请运行 `install.bat` 或第三节手动安装。
|
||||||
|
|
||||||
|
### 2. 私信发送报 7911 / 签名相关错误
|
||||||
|
|
||||||
|
- 确认 **Node.js 已安装** 且在 PATH 中:`node --version`
|
||||||
|
- 确认 IM 静态目录已 `npm install`:
|
||||||
|
```powershell
|
||||||
|
dir backend\rpa_engine\douyin_im\static\node_modules\jsrsasign
|
||||||
|
```
|
||||||
|
- 在账号管理里用「浏览器模式」重新登录并打开一次私信页,刷新 `web_protect` / `keys`
|
||||||
|
|
||||||
|
### 3. 浏览器打不开 / Playwright 报错
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd backend
|
||||||
|
.\.venv\Scripts\playwright install chromium
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 前端 `npm run dev` 失败
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
cd frontend
|
||||||
|
Remove-Item -Recurse -Force node_modules -ErrorAction SilentlyContinue
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 七、不要提交到 GitHub 的内容
|
||||||
|
|
||||||
|
以下目录/文件含运行数据或体积过大,**仅保留本地**:
|
||||||
|
|
||||||
|
- `backend/.venv/`
|
||||||
|
- `backend/kefu.db`(账号、规则、日志)
|
||||||
|
- `backend/sessions/`(Cookie 等)
|
||||||
|
- `frontend/node_modules/`、`frontend/dist/`
|
||||||
|
- `backend/rpa_engine/douyin_im/static/node_modules/`
|
||||||
|
- `.env`、含密钥的配置
|
||||||
|
|
||||||
|
根目录已提供 `.gitignore` 模板,可按需使用。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 八、更新依赖
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
# 后端
|
||||||
|
cd backend
|
||||||
|
.\.venv\Scripts\pip install -r requirements.txt
|
||||||
|
|
||||||
|
# IM 签名
|
||||||
|
cd rpa_engine\douyin_im\static
|
||||||
|
npm install
|
||||||
|
|
||||||
|
# 前端
|
||||||
|
cd ..\..\..\frontend
|
||||||
|
npm install
|
||||||
|
```
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
"""用户可添加抖音账号数量限制(限制功能已移除,保留接口兼容)。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from sqlalchemy import func, select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from models.models import Account, User
|
||||||
|
from .roles import is_admin
|
||||||
|
|
||||||
|
UNLIMITED_ACCOUNTS = -1
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_max_accounts(value: int | None, role: str = "operator") -> int:
|
||||||
|
if is_admin(role):
|
||||||
|
return UNLIMITED_ACCOUNTS
|
||||||
|
if value is None:
|
||||||
|
return 3
|
||||||
|
try:
|
||||||
|
parsed = int(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return 3
|
||||||
|
if parsed < 0:
|
||||||
|
return UNLIMITED_ACCOUNTS
|
||||||
|
return parsed
|
||||||
|
|
||||||
|
|
||||||
|
def account_limit_for_user(user: User) -> int | None:
|
||||||
|
"""账号数量/并发限制已移除,始终不限制。"""
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
async def count_user_accounts(db: AsyncSession, user_id: int) -> int:
|
||||||
|
result = await db.execute(
|
||||||
|
select(func.count()).select_from(Account).where(Account.owner_id == user_id)
|
||||||
|
)
|
||||||
|
return int(result.scalar() or 0)
|
||||||
|
|
||||||
|
|
||||||
|
async def count_user_account_breakdown(db: AsyncSession, user_id: int) -> dict[str, int]:
|
||||||
|
"""统计用户名下托管账号:总数 / 可用 / 额度停用。"""
|
||||||
|
total = await count_user_accounts(db, user_id)
|
||||||
|
if total <= 0:
|
||||||
|
return {"total": 0, "active": 0, "disabled": 0}
|
||||||
|
disabled_result = await db.execute(
|
||||||
|
select(func.count())
|
||||||
|
.select_from(Account)
|
||||||
|
.where(Account.owner_id == user_id, Account.quota_disabled.is_(True))
|
||||||
|
)
|
||||||
|
disabled = int(disabled_result.scalar() or 0)
|
||||||
|
active = max(0, total - disabled)
|
||||||
|
return {"total": total, "active": active, "disabled": disabled}
|
||||||
|
|
||||||
|
|
||||||
|
async def ensure_can_add_account(db: AsyncSession, user: User) -> None:
|
||||||
|
"""账号数量限制已移除,任何用户可添加任意数量账号。"""
|
||||||
|
return
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""账号额度与 quota_disabled 同步。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Awaitable, Callable
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from models.models import Account, User
|
||||||
|
from .account_limits import account_limit_for_user
|
||||||
|
|
||||||
|
QUOTA_DISABLED_MESSAGE = "账号额度不足,该账号已被系统停用"
|
||||||
|
|
||||||
|
|
||||||
|
async def sync_user_account_quota(
|
||||||
|
db: AsyncSession,
|
||||||
|
user: User,
|
||||||
|
*,
|
||||||
|
stop_worker: Callable[[int], Awaitable[None]] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""按 max_accounts 同步停用状态:保留最早创建的账号,超额账号禁用并停止托管。"""
|
||||||
|
limit = account_limit_for_user(user)
|
||||||
|
|
||||||
|
result = await db.execute(
|
||||||
|
select(Account)
|
||||||
|
.where(Account.owner_id == user.id)
|
||||||
|
.order_by(Account.created_at.asc(), Account.id.asc())
|
||||||
|
)
|
||||||
|
accounts = list(result.scalars().all())
|
||||||
|
|
||||||
|
disabled_ids: list[int] = []
|
||||||
|
enabled_ids: list[int] = []
|
||||||
|
|
||||||
|
if limit is None:
|
||||||
|
for acc in accounts:
|
||||||
|
if acc.quota_disabled:
|
||||||
|
acc.quota_disabled = False
|
||||||
|
if (acc.error_message or "").strip() == QUOTA_DISABLED_MESSAGE:
|
||||||
|
acc.error_message = None
|
||||||
|
enabled_ids.append(acc.id)
|
||||||
|
return {"disabled_ids": disabled_ids, "enabled_ids": enabled_ids, "limit": None}
|
||||||
|
|
||||||
|
for idx, acc in enumerate(accounts):
|
||||||
|
if idx < limit:
|
||||||
|
if acc.quota_disabled:
|
||||||
|
acc.quota_disabled = False
|
||||||
|
if (acc.error_message or "").strip() == QUOTA_DISABLED_MESSAGE:
|
||||||
|
acc.error_message = None
|
||||||
|
enabled_ids.append(acc.id)
|
||||||
|
else:
|
||||||
|
if not acc.quota_disabled:
|
||||||
|
acc.quota_disabled = True
|
||||||
|
acc.error_message = QUOTA_DISABLED_MESSAGE
|
||||||
|
acc.status = "offline"
|
||||||
|
acc.qr_code_base64 = None
|
||||||
|
disabled_ids.append(acc.id)
|
||||||
|
if stop_worker:
|
||||||
|
await stop_worker(acc.id)
|
||||||
|
|
||||||
|
return {"disabled_ids": disabled_ids, "enabled_ids": enabled_ids, "limit": limit}
|
||||||
|
|
||||||
|
|
||||||
|
async def default_stop_worker(account_id: int) -> None:
|
||||||
|
from main import manager
|
||||||
|
|
||||||
|
await manager.stop_worker(account_id)
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
from fastapi import Depends, HTTPException, status
|
||||||
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from models.database import get_db
|
||||||
|
from models.models import User
|
||||||
|
from .jwt_utils import decode_access_token
|
||||||
|
from .roles import can_manage_users, can_write, is_admin
|
||||||
|
|
||||||
|
bearer_scheme = HTTPBearer(auto_error=False)
|
||||||
|
|
||||||
|
|
||||||
|
async def get_current_user(
|
||||||
|
credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
) -> User:
|
||||||
|
if not credentials or not credentials.credentials:
|
||||||
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="未登录或令牌缺失")
|
||||||
|
payload = decode_access_token(credentials.credentials)
|
||||||
|
if not payload or not payload.get("sub"):
|
||||||
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="登录已过期,请重新登录")
|
||||||
|
try:
|
||||||
|
user_id = int(payload["sub"])
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="无效令牌")
|
||||||
|
|
||||||
|
result = await db.execute(select(User).where(User.id == user_id))
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
if not user or not user.is_active:
|
||||||
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="用户不存在或已禁用")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
async def require_admin(user: User = Depends(get_current_user)) -> User:
|
||||||
|
if not is_admin(user.role):
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="需要管理员权限")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
async def require_write(user: User = Depends(get_current_user)) -> User:
|
||||||
|
if not can_write(user.role):
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="当前角色只读,无法执行此操作")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
async def require_user_manager(user: User = Depends(get_current_user)) -> User:
|
||||||
|
if not can_manage_users(user.role):
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="需要管理员权限")
|
||||||
|
return user
|
||||||
@@ -0,0 +1,378 @@
|
|||||||
|
"""发送邮箱验证邮件(标准库 SMTP)。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import smtplib
|
||||||
|
import ssl
|
||||||
|
from dataclasses import asdict
|
||||||
|
from email.mime.multipart import MIMEMultipart
|
||||||
|
from email.mime.text import MIMEText
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from .email_templates import build_password_reset_content, build_test_email_content, build_verify_email_content
|
||||||
|
from .system_settings import SystemSettingsData
|
||||||
|
|
||||||
|
logger = logging.getLogger("auth.email")
|
||||||
|
|
||||||
|
SMTP_TIMEOUT_SECONDS = 45
|
||||||
|
# 阿里企业邮自定义域名 SMTP(如 smtp.xxiaw.com)常出现 535,官方地址可正常认证
|
||||||
|
ALIBABA_SMTP_OFFICIAL = "smtp.mxhichina.com"
|
||||||
|
_SSL_CONTEXT = ssl.create_default_context()
|
||||||
|
|
||||||
|
|
||||||
|
def _ssl_context(*, insecure: bool = False) -> ssl.SSLContext:
|
||||||
|
if not insecure:
|
||||||
|
return _SSL_CONTEXT
|
||||||
|
ctx = ssl.create_default_context()
|
||||||
|
ctx.check_hostname = False
|
||||||
|
ctx.verify_mode = ssl.CERT_NONE
|
||||||
|
return ctx
|
||||||
|
|
||||||
|
|
||||||
|
def _connect_ssl(host: str, port: int) -> smtplib.SMTP:
|
||||||
|
try:
|
||||||
|
return smtplib.SMTP_SSL(
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
timeout=SMTP_TIMEOUT_SECONDS,
|
||||||
|
context=_ssl_context(insecure=False),
|
||||||
|
)
|
||||||
|
except ssl.SSLCertVerificationError:
|
||||||
|
logger.warning(
|
||||||
|
"SMTP SSL certificate hostname mismatch for %s, retry without verify",
|
||||||
|
host,
|
||||||
|
)
|
||||||
|
return smtplib.SMTP_SSL(
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
timeout=SMTP_TIMEOUT_SECONDS,
|
||||||
|
context=_ssl_context(insecure=True),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _starttls(server: smtplib.SMTP, host: str) -> None:
|
||||||
|
try:
|
||||||
|
server.starttls(context=_ssl_context(insecure=False))
|
||||||
|
except ssl.SSLCertVerificationError:
|
||||||
|
logger.warning(
|
||||||
|
"SMTP STARTTLS certificate hostname mismatch for %s, retry without verify",
|
||||||
|
host,
|
||||||
|
)
|
||||||
|
server.starttls(context=_ssl_context(insecure=True))
|
||||||
|
|
||||||
|
|
||||||
|
def build_verification_link(token: str, settings: SystemSettingsData) -> str:
|
||||||
|
return f"{settings.app_url_normalized()}/#/login?verify_token={token}"
|
||||||
|
|
||||||
|
|
||||||
|
def build_password_reset_link(token: str, settings: SystemSettingsData) -> str:
|
||||||
|
return f"{settings.app_url_normalized()}/#/login?reset_token={token}"
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_smtp_mode(settings: SystemSettingsData) -> tuple[int, bool, bool]:
|
||||||
|
"""返回 (port, use_ssl, use_starttls)。"""
|
||||||
|
port = int(settings.smtp_port or 587)
|
||||||
|
use_ssl = bool(settings.smtp_use_ssl) or port == 465
|
||||||
|
# 465 只能 implicit SSL,绝不能 plain + STARTTLS
|
||||||
|
if port == 465:
|
||||||
|
use_ssl = True
|
||||||
|
use_starttls = False
|
||||||
|
elif port == 587:
|
||||||
|
use_ssl = False
|
||||||
|
use_starttls = bool(settings.smtp_use_tls)
|
||||||
|
else:
|
||||||
|
use_ssl = bool(settings.smtp_use_ssl)
|
||||||
|
use_starttls = bool(settings.smtp_use_tls) and not use_ssl
|
||||||
|
return port, use_ssl, use_starttls
|
||||||
|
|
||||||
|
|
||||||
|
def _open_smtp(settings: SystemSettingsData) -> smtplib.SMTP:
|
||||||
|
host = settings.smtp_host.strip()
|
||||||
|
port, use_ssl, use_starttls = resolve_smtp_mode(settings)
|
||||||
|
logger.info(
|
||||||
|
"SMTP connect host=%s port=%s ssl=%s starttls=%s user=%s",
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
use_ssl,
|
||||||
|
use_starttls,
|
||||||
|
settings.smtp_user or "",
|
||||||
|
)
|
||||||
|
|
||||||
|
if use_ssl:
|
||||||
|
server = _connect_ssl(host, port)
|
||||||
|
server.ehlo()
|
||||||
|
return server
|
||||||
|
|
||||||
|
server = smtplib.SMTP(host, port, timeout=SMTP_TIMEOUT_SECONDS)
|
||||||
|
server.ehlo()
|
||||||
|
if use_starttls:
|
||||||
|
_starttls(server, host)
|
||||||
|
server.ehlo()
|
||||||
|
return server
|
||||||
|
|
||||||
|
|
||||||
|
def _close_smtp(server: smtplib.SMTP) -> None:
|
||||||
|
try:
|
||||||
|
server.quit()
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
server.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _login_smtp(server: smtplib.SMTP, settings: SystemSettingsData) -> tuple[smtplib.SMTP, bool]:
|
||||||
|
"""登录 SMTP,返回 (server, 是否使用了阿里官方地址回退)。"""
|
||||||
|
user = (settings.smtp_user or "").strip()
|
||||||
|
pwd = settings.smtp_password
|
||||||
|
if not user:
|
||||||
|
return server, False
|
||||||
|
if not pwd:
|
||||||
|
raise RuntimeError("未填写 SMTP 密码,请在设置中填写登录密码或客户端安全密码后重试")
|
||||||
|
try:
|
||||||
|
server.login(user, pwd)
|
||||||
|
return server, False
|
||||||
|
except smtplib.SMTPAuthenticationError as exc:
|
||||||
|
host = (settings.smtp_host or "").strip().lower()
|
||||||
|
if host == ALIBABA_SMTP_OFFICIAL:
|
||||||
|
raise RuntimeError(_format_login_error(exc, settings)) from exc
|
||||||
|
logger.warning(
|
||||||
|
"SMTP auth failed on %s (%s), retrying via %s",
|
||||||
|
host,
|
||||||
|
exc,
|
||||||
|
ALIBABA_SMTP_OFFICIAL,
|
||||||
|
)
|
||||||
|
_close_smtp(server)
|
||||||
|
fallback = SystemSettingsData(**{**asdict(settings), "smtp_host": ALIBABA_SMTP_OFFICIAL})
|
||||||
|
fallback_server = _open_smtp(fallback)
|
||||||
|
try:
|
||||||
|
fallback_server.login(user, pwd)
|
||||||
|
except Exception as retry_exc:
|
||||||
|
_close_smtp(fallback_server)
|
||||||
|
raise RuntimeError(_format_login_error(exc, settings)) from retry_exc
|
||||||
|
return fallback_server, True
|
||||||
|
|
||||||
|
|
||||||
|
def _format_login_error(exc: Exception, settings: SystemSettingsData) -> str:
|
||||||
|
if isinstance(exc, smtplib.SMTPAuthenticationError):
|
||||||
|
return _format_smtp_error(exc, settings)
|
||||||
|
if isinstance(exc, smtplib.SMTPServerDisconnected):
|
||||||
|
return (
|
||||||
|
"SMTP 服务器在登录时断开连接,通常不是加密方式问题,而是密码错误或账号未授权 SMTP。"
|
||||||
|
f"请确认用户名 {settings.smtp_user or ''} 与密码/客户端安全密码正确,"
|
||||||
|
"并在阿里企业邮后台开启「允许使用第三方客户端」。"
|
||||||
|
"若使用自定义域名 SMTP(如 smtp.xxiaw.com)仍失败,可改用 smtp.mxhichina.com 后重试。"
|
||||||
|
)
|
||||||
|
return _format_smtp_error(exc, settings)
|
||||||
|
|
||||||
|
|
||||||
|
def _format_smtp_error(exc: Exception, settings: SystemSettingsData) -> str:
|
||||||
|
msg = str(exc).strip() or exc.__class__.__name__
|
||||||
|
port, use_ssl, use_starttls = resolve_smtp_mode(settings)
|
||||||
|
hints: list[str] = []
|
||||||
|
|
||||||
|
if isinstance(exc, ssl.SSLCertVerificationError):
|
||||||
|
hints.append(
|
||||||
|
f"SSL 证书域名与 {settings.smtp_host} 不匹配(阿里企业邮自定义域名常见),"
|
||||||
|
"系统已尝试跳过证书校验;若仍失败请改用 smtp.mxhichina.com"
|
||||||
|
)
|
||||||
|
return f"{msg}。{' '.join(hints)}"
|
||||||
|
|
||||||
|
if isinstance(exc, smtplib.SMTPAuthenticationError):
|
||||||
|
host = (settings.smtp_host or "").strip().lower()
|
||||||
|
if host != ALIBABA_SMTP_OFFICIAL and host.startswith("smtp."):
|
||||||
|
hints.append(
|
||||||
|
f"若使用自定义域名 SMTP({settings.smtp_host}),阿里企业邮常返回 535;"
|
||||||
|
f"请将 SMTP 服务器改为 {ALIBABA_SMTP_OFFICIAL} 后重试"
|
||||||
|
)
|
||||||
|
hints.append(
|
||||||
|
"SMTP 登录失败:请确认登录用户名为完整邮箱地址,"
|
||||||
|
"密码为邮箱登录密码或阿里企业邮「客户端安全密码」(非网页登录密码时需在邮箱设置中单独生成)"
|
||||||
|
)
|
||||||
|
hints.append("请在阿里企业邮管理后台确认已开启「允许使用第三方客户端」")
|
||||||
|
return f"{msg}。{' '.join(hints)}"
|
||||||
|
|
||||||
|
lower = msg.lower()
|
||||||
|
if "connection unexpectedly closed" in lower and port == 465 and not use_ssl:
|
||||||
|
hints.append("465 端口必须使用 SSL 加密,不能勾选 STARTTLS")
|
||||||
|
elif "connection unexpectedly closed" in lower and port == 465:
|
||||||
|
if use_ssl:
|
||||||
|
hints.append(
|
||||||
|
"连接已建立但在后续步骤失败:请重点检查 SMTP 密码/客户端安全密码,"
|
||||||
|
"或尝试将服务器改为 smtp.mxhichina.com"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
hints.append("465 端口必须使用 SSL 加密,请选择「SSL / TLS(端口 465)」")
|
||||||
|
if "timed out" in lower or "timeout" in lower or "10060" in lower:
|
||||||
|
if port == 587:
|
||||||
|
hints.append(
|
||||||
|
f"587 端口 STARTTLS 连接 {settings.smtp_host} 超时:"
|
||||||
|
"该服务器可能仅支持 465 SSL,请将端口改为 465 并选择 SSL 加密"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
hints.append(
|
||||||
|
f"无法在 {SMTP_TIMEOUT_SECONDS}s 内连接 {settings.smtp_host}:{port},"
|
||||||
|
"请检查服务器地址、端口、防火墙/安全组是否放行出站 SMTP"
|
||||||
|
)
|
||||||
|
if "authentication" in lower or "535" in lower:
|
||||||
|
hints.append("认证失败:请检查 SMTP 密码/客户端安全密码是否正确")
|
||||||
|
|
||||||
|
if hints:
|
||||||
|
return f"{msg}。{' '.join(hints)}"
|
||||||
|
return msg
|
||||||
|
|
||||||
|
|
||||||
|
def diagnose_smtp(settings: SystemSettingsData) -> dict[str, Any]:
|
||||||
|
"""分步检测 SMTP 连接,便于定位配置问题。"""
|
||||||
|
host = (settings.smtp_host or "").strip()
|
||||||
|
port, use_ssl, use_starttls = resolve_smtp_mode(settings)
|
||||||
|
result: dict[str, Any] = {
|
||||||
|
"host": host,
|
||||||
|
"port": port,
|
||||||
|
"mode": "ssl" if use_ssl else ("starttls" if use_starttls else "plain"),
|
||||||
|
"steps": [],
|
||||||
|
"ok": False,
|
||||||
|
}
|
||||||
|
if not host:
|
||||||
|
result["steps"].append({"step": "config", "ok": False, "message": "未填写 SMTP 服务器"})
|
||||||
|
return result
|
||||||
|
|
||||||
|
server: smtplib.SMTP | None = None
|
||||||
|
try:
|
||||||
|
server = _open_smtp(settings)
|
||||||
|
result["steps"].append({"step": "connect", "ok": True, "message": "连接成功"})
|
||||||
|
except Exception as exc:
|
||||||
|
result["steps"].append(
|
||||||
|
{"step": "connect", "ok": False, "message": _format_smtp_error(exc, settings)}
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
|
||||||
|
try:
|
||||||
|
if settings.smtp_user:
|
||||||
|
if not settings.smtp_password:
|
||||||
|
raise RuntimeError("未填写 SMTP 密码,请在设置中填写登录密码或客户端安全密码后重试")
|
||||||
|
host_before = (settings.smtp_host or "").strip().lower()
|
||||||
|
server, used_fallback = _login_smtp(server, settings)
|
||||||
|
login_msg = "登录成功"
|
||||||
|
if used_fallback and host_before != ALIBABA_SMTP_OFFICIAL:
|
||||||
|
login_msg = (
|
||||||
|
f"登录成功(已通过 {ALIBABA_SMTP_OFFICIAL} 认证,"
|
||||||
|
f"建议将 SMTP 服务器改为 {ALIBABA_SMTP_OFFICIAL})"
|
||||||
|
)
|
||||||
|
result["steps"].append({"step": "login", "ok": True, "message": login_msg})
|
||||||
|
else:
|
||||||
|
result["steps"].append({"step": "login", "ok": True, "message": "未配置用户名,跳过登录"})
|
||||||
|
result["ok"] = True
|
||||||
|
except Exception as exc:
|
||||||
|
result["steps"].append(
|
||||||
|
{"step": "login", "ok": False, "message": _format_login_error(exc, settings)}
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
if server:
|
||||||
|
try:
|
||||||
|
server.quit()
|
||||||
|
except Exception:
|
||||||
|
server.close()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def _send_sync(
|
||||||
|
settings: SystemSettingsData,
|
||||||
|
to_email: str,
|
||||||
|
subject: str,
|
||||||
|
html_body: str,
|
||||||
|
text_body: str,
|
||||||
|
) -> None:
|
||||||
|
if not settings.smtp_configured():
|
||||||
|
raise RuntimeError("SMTP 未配置,无法发送邮件")
|
||||||
|
|
||||||
|
smtp_from = (settings.smtp_from or settings.smtp_user or "").strip()
|
||||||
|
msg = MIMEMultipart("alternative")
|
||||||
|
msg["Subject"] = subject
|
||||||
|
msg["From"] = smtp_from
|
||||||
|
msg["To"] = to_email
|
||||||
|
msg.attach(MIMEText(text_body, "plain", "utf-8"))
|
||||||
|
msg.attach(MIMEText(html_body, "html", "utf-8"))
|
||||||
|
|
||||||
|
server = _open_smtp(settings)
|
||||||
|
try:
|
||||||
|
if settings.smtp_user:
|
||||||
|
try:
|
||||||
|
server, _ = _login_smtp(server, settings)
|
||||||
|
except RuntimeError:
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(_format_login_error(exc, settings)) from exc
|
||||||
|
server.sendmail(smtp_from, [to_email], msg.as_string())
|
||||||
|
except RuntimeError:
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(_format_smtp_error(exc, settings)) from exc
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
server.quit()
|
||||||
|
except Exception:
|
||||||
|
server.close()
|
||||||
|
|
||||||
|
|
||||||
|
async def send_password_reset_email(
|
||||||
|
to_email: str,
|
||||||
|
username: str,
|
||||||
|
token: str,
|
||||||
|
settings: SystemSettingsData,
|
||||||
|
) -> str:
|
||||||
|
"""发送密码重置邮件,返回重置链接。"""
|
||||||
|
link = build_password_reset_link(token, settings)
|
||||||
|
expire_hours = int(settings.email_verify_token_hours or 24)
|
||||||
|
subject, text_body, html_body = build_password_reset_content(
|
||||||
|
settings, username, to_email, link, expire_hours
|
||||||
|
)
|
||||||
|
|
||||||
|
if settings.smtp_configured():
|
||||||
|
await asyncio.to_thread(_send_sync, settings, to_email, subject, html_body, text_body)
|
||||||
|
logger.info("Password reset email sent to %s", to_email)
|
||||||
|
else:
|
||||||
|
logger.warning(
|
||||||
|
"SMTP 未配置,密码重置链接: user=%s email=%s link=%s",
|
||||||
|
username,
|
||||||
|
to_email,
|
||||||
|
link,
|
||||||
|
)
|
||||||
|
return link
|
||||||
|
|
||||||
|
|
||||||
|
async def send_verification_email(
|
||||||
|
to_email: str,
|
||||||
|
username: str,
|
||||||
|
token: str,
|
||||||
|
settings: SystemSettingsData,
|
||||||
|
) -> str:
|
||||||
|
"""发送验证邮件,返回验证链接。"""
|
||||||
|
link = build_verification_link(token, settings)
|
||||||
|
subject, text_body, html_body = build_verify_email_content(
|
||||||
|
settings, username, to_email, link
|
||||||
|
)
|
||||||
|
|
||||||
|
if settings.smtp_configured():
|
||||||
|
await asyncio.to_thread(_send_sync, settings, to_email, subject, html_body, text_body)
|
||||||
|
logger.info("Verification email sent to %s", to_email)
|
||||||
|
else:
|
||||||
|
logger.warning(
|
||||||
|
"SMTP 未配置,验证链接: user=%s email=%s link=%s",
|
||||||
|
username,
|
||||||
|
to_email,
|
||||||
|
link,
|
||||||
|
)
|
||||||
|
return link
|
||||||
|
|
||||||
|
|
||||||
|
async def send_test_email(to_email: str, settings: SystemSettingsData) -> None:
|
||||||
|
diagnosis = await asyncio.to_thread(diagnose_smtp, settings)
|
||||||
|
if not diagnosis.get("ok"):
|
||||||
|
failed = next((s for s in diagnosis.get("steps", []) if not s.get("ok")), None)
|
||||||
|
raise RuntimeError(failed["message"] if failed else "SMTP 连接检测失败")
|
||||||
|
|
||||||
|
subject, text_body, html_body = build_test_email_content(settings, to_email)
|
||||||
|
await asyncio.to_thread(_send_sync, settings, to_email, subject, html_body, text_body)
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
"""邮件模板渲染。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import html
|
||||||
|
import re
|
||||||
|
|
||||||
|
from .system_settings import (
|
||||||
|
APP_NAME,
|
||||||
|
DEFAULT_EMAIL_TEST_BODY,
|
||||||
|
DEFAULT_EMAIL_TEST_HTML,
|
||||||
|
DEFAULT_EMAIL_TEST_SUBJECT,
|
||||||
|
DEFAULT_EMAIL_VERIFY_BODY,
|
||||||
|
DEFAULT_EMAIL_VERIFY_HTML,
|
||||||
|
DEFAULT_EMAIL_VERIFY_SUBJECT,
|
||||||
|
DEFAULT_PASSWORD_RESET_BODY,
|
||||||
|
DEFAULT_PASSWORD_RESET_HTML,
|
||||||
|
DEFAULT_PASSWORD_RESET_SUBJECT,
|
||||||
|
SystemSettingsData,
|
||||||
|
)
|
||||||
|
|
||||||
|
_TEMPLATE_VAR_PATTERN = re.compile(r"\{(\w+)\}")
|
||||||
|
|
||||||
|
|
||||||
|
def render_email_template(template: str, **context: str) -> str:
|
||||||
|
"""安全渲染邮件模板,未知占位符保留原样。"""
|
||||||
|
value = template or ""
|
||||||
|
|
||||||
|
def replacer(match: re.Match) -> str:
|
||||||
|
key = match.group(1)
|
||||||
|
return context.get(key, match.group(0))
|
||||||
|
|
||||||
|
return _TEMPLATE_VAR_PATTERN.sub(replacer, value)
|
||||||
|
|
||||||
|
|
||||||
|
def _text_to_html(text: str) -> str:
|
||||||
|
escaped = html.escape(text or "")
|
||||||
|
return f'<pre style="font-family:sans-serif;white-space:pre-wrap;margin:0;">{escaped}</pre>'
|
||||||
|
|
||||||
|
|
||||||
|
def build_verify_email_content(
|
||||||
|
settings: SystemSettingsData,
|
||||||
|
username: str,
|
||||||
|
to_email: str,
|
||||||
|
link: str,
|
||||||
|
) -> tuple[str, str, str]:
|
||||||
|
context = {
|
||||||
|
"username": username,
|
||||||
|
"email": to_email,
|
||||||
|
"link": link,
|
||||||
|
"app_name": APP_NAME,
|
||||||
|
}
|
||||||
|
subject_tpl = settings.email_verify_subject or DEFAULT_EMAIL_VERIFY_SUBJECT
|
||||||
|
body_tpl = settings.email_verify_body or DEFAULT_EMAIL_VERIFY_BODY
|
||||||
|
html_tpl = settings.email_verify_html or ""
|
||||||
|
|
||||||
|
subject = render_email_template(subject_tpl, **context)
|
||||||
|
text_body = render_email_template(body_tpl, **context)
|
||||||
|
if html_tpl.strip():
|
||||||
|
html_body = render_email_template(html_tpl, **context)
|
||||||
|
else:
|
||||||
|
html_body = _text_to_html(text_body)
|
||||||
|
return subject, text_body, html_body
|
||||||
|
|
||||||
|
|
||||||
|
def build_password_reset_content(
|
||||||
|
settings: SystemSettingsData,
|
||||||
|
username: str,
|
||||||
|
to_email: str,
|
||||||
|
link: str,
|
||||||
|
expire_hours: int,
|
||||||
|
) -> tuple[str, str, str]:
|
||||||
|
context = {
|
||||||
|
"username": username,
|
||||||
|
"email": to_email,
|
||||||
|
"link": link,
|
||||||
|
"app_name": APP_NAME,
|
||||||
|
"expire_hours": str(expire_hours),
|
||||||
|
}
|
||||||
|
subject = render_email_template(DEFAULT_PASSWORD_RESET_SUBJECT, **context)
|
||||||
|
text_body = render_email_template(DEFAULT_PASSWORD_RESET_BODY, **context)
|
||||||
|
html_body = render_email_template(DEFAULT_PASSWORD_RESET_HTML, **context)
|
||||||
|
return subject, text_body, html_body
|
||||||
|
|
||||||
|
|
||||||
|
def build_test_email_content(settings: SystemSettingsData, to_email: str) -> tuple[str, str, str]:
|
||||||
|
context = {
|
||||||
|
"username": "测试用户",
|
||||||
|
"email": to_email,
|
||||||
|
"link": settings.app_url_normalized(),
|
||||||
|
"app_name": APP_NAME,
|
||||||
|
}
|
||||||
|
subject_tpl = settings.email_test_subject or DEFAULT_EMAIL_TEST_SUBJECT
|
||||||
|
body_tpl = settings.email_test_body or DEFAULT_EMAIL_TEST_BODY
|
||||||
|
html_tpl = settings.email_test_html or ""
|
||||||
|
|
||||||
|
subject = render_email_template(subject_tpl, **context)
|
||||||
|
text_body = render_email_template(body_tpl, **context)
|
||||||
|
if html_tpl.strip():
|
||||||
|
html_body = render_email_template(html_tpl, **context)
|
||||||
|
else:
|
||||||
|
html_body = _text_to_html(text_body)
|
||||||
|
return subject, text_body, html_body
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"""邮箱验证令牌创建与校验。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import secrets
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from sqlalchemy import delete, select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from models.models import EmailVerificationToken, User
|
||||||
|
|
||||||
|
|
||||||
|
def _token_expires_at(hours: int) -> datetime:
|
||||||
|
return datetime.utcnow() + timedelta(hours=max(1, min(168, int(hours or 24))))
|
||||||
|
|
||||||
|
|
||||||
|
async def invalidate_user_tokens(db: AsyncSession, user_id: int) -> None:
|
||||||
|
await db.execute(
|
||||||
|
delete(EmailVerificationToken).where(EmailVerificationToken.user_id == user_id)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def create_verification_token(
|
||||||
|
db: AsyncSession,
|
||||||
|
user: User,
|
||||||
|
expire_hours: int = 24,
|
||||||
|
) -> str:
|
||||||
|
await invalidate_user_tokens(db, user.id)
|
||||||
|
token = secrets.token_urlsafe(32)
|
||||||
|
db.add(
|
||||||
|
EmailVerificationToken(
|
||||||
|
user_id=user.id,
|
||||||
|
token=token,
|
||||||
|
expires_at=_token_expires_at(expire_hours),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
await db.flush()
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
async def verify_email_token(db: AsyncSession, token: str) -> User | None:
|
||||||
|
value = (token or "").strip()
|
||||||
|
if not value:
|
||||||
|
return None
|
||||||
|
|
||||||
|
result = await db.execute(
|
||||||
|
select(EmailVerificationToken, User)
|
||||||
|
.join(User, User.id == EmailVerificationToken.user_id)
|
||||||
|
.where(EmailVerificationToken.token == value)
|
||||||
|
)
|
||||||
|
row = result.first()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
|
||||||
|
record, user = row
|
||||||
|
if record.expires_at < datetime.utcnow():
|
||||||
|
await db.delete(record)
|
||||||
|
await db.flush()
|
||||||
|
return None
|
||||||
|
|
||||||
|
user.email_verified = True
|
||||||
|
user.email_verified_at = datetime.utcnow()
|
||||||
|
await db.delete(record)
|
||||||
|
await db.flush()
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def mask_email(email: str) -> str:
|
||||||
|
value = (email or "").strip()
|
||||||
|
if "@" not in value:
|
||||||
|
return value
|
||||||
|
local, domain = value.split("@", 1)
|
||||||
|
if len(local) <= 2:
|
||||||
|
masked_local = local[0] + "*"
|
||||||
|
else:
|
||||||
|
masked_local = local[0] + "*" * (len(local) - 2) + local[-1]
|
||||||
|
return f"{masked_local}@{domain}"
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import os
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from jose import JWTError, jwt
|
||||||
|
|
||||||
|
SECRET_KEY = os.getenv("KEFU_SECRET_KEY", "kefu-dev-secret-change-in-production")
|
||||||
|
ALGORITHM = "HS256"
|
||||||
|
ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("KEFU_TOKEN_EXPIRE_MINUTES", str(60 * 24)))
|
||||||
|
|
||||||
|
|
||||||
|
def create_access_token(subject: str, extra: Optional[dict[str, Any]] = None) -> str:
|
||||||
|
expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||||
|
payload = {"sub": subject, "exp": expire}
|
||||||
|
if extra:
|
||||||
|
payload.update(extra)
|
||||||
|
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
|
||||||
|
|
||||||
|
|
||||||
|
def decode_access_token(token: str) -> Optional[dict[str, Any]]:
|
||||||
|
try:
|
||||||
|
return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||||
|
except JWTError:
|
||||||
|
return None
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
"""密码重置令牌创建与校验。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import secrets
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from sqlalchemy import delete, select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from models.models import PasswordResetToken, User
|
||||||
|
|
||||||
|
|
||||||
|
def _token_expires_at(hours: int) -> datetime:
|
||||||
|
return datetime.utcnow() + timedelta(hours=max(1, min(168, int(hours or 24))))
|
||||||
|
|
||||||
|
|
||||||
|
async def invalidate_user_reset_tokens(db: AsyncSession, user_id: int) -> None:
|
||||||
|
await db.execute(
|
||||||
|
delete(PasswordResetToken).where(PasswordResetToken.user_id == user_id)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def create_password_reset_token(
|
||||||
|
db: AsyncSession,
|
||||||
|
user: User,
|
||||||
|
expire_hours: int = 24,
|
||||||
|
) -> str:
|
||||||
|
await invalidate_user_reset_tokens(db, user.id)
|
||||||
|
token = secrets.token_urlsafe(32)
|
||||||
|
db.add(
|
||||||
|
PasswordResetToken(
|
||||||
|
user_id=user.id,
|
||||||
|
token=token,
|
||||||
|
expires_at=_token_expires_at(expire_hours),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
await db.flush()
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
async def verify_password_reset_token(db: AsyncSession, token: str) -> User | None:
|
||||||
|
value = (token or "").strip()
|
||||||
|
if not value:
|
||||||
|
return None
|
||||||
|
|
||||||
|
result = await db.execute(
|
||||||
|
select(PasswordResetToken, User)
|
||||||
|
.join(User, User.id == PasswordResetToken.user_id)
|
||||||
|
.where(PasswordResetToken.token == value)
|
||||||
|
)
|
||||||
|
row = result.first()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
|
||||||
|
record, user = row
|
||||||
|
if record.expires_at < datetime.utcnow():
|
||||||
|
await db.delete(record)
|
||||||
|
await db.flush()
|
||||||
|
return None
|
||||||
|
|
||||||
|
await db.delete(record)
|
||||||
|
await db.flush()
|
||||||
|
return user
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
from passlib.context import CryptContext
|
||||||
|
|
||||||
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||||
|
|
||||||
|
|
||||||
|
def hash_password(password: str) -> str:
|
||||||
|
return pwd_context.hash(password)
|
||||||
|
|
||||||
|
|
||||||
|
def verify_password(plain: str, hashed: str) -> bool:
|
||||||
|
return pwd_context.verify(plain, hashed)
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
from typing import Iterable
|
||||||
|
|
||||||
|
ROLE_ADMIN = "admin"
|
||||||
|
ROLE_OPERATOR = "operator"
|
||||||
|
ROLE_VIEWER = "viewer"
|
||||||
|
|
||||||
|
ALL_ROLES = (ROLE_ADMIN, ROLE_OPERATOR, ROLE_VIEWER)
|
||||||
|
|
||||||
|
ROLE_LABELS = {
|
||||||
|
ROLE_ADMIN: "管理员",
|
||||||
|
ROLE_OPERATOR: "运营",
|
||||||
|
ROLE_VIEWER: "只读",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def is_admin(role: str) -> bool:
|
||||||
|
return role == ROLE_ADMIN
|
||||||
|
|
||||||
|
|
||||||
|
def can_write(role: str) -> bool:
|
||||||
|
return role in (ROLE_ADMIN, ROLE_OPERATOR)
|
||||||
|
|
||||||
|
|
||||||
|
def can_manage_users(role: str) -> bool:
|
||||||
|
return role == ROLE_ADMIN
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_role(role: str) -> str:
|
||||||
|
if role not in ALL_ROLES:
|
||||||
|
raise ValueError(f"无效角色: {role}")
|
||||||
|
return role
|
||||||
@@ -0,0 +1,511 @@
|
|||||||
|
import logging
|
||||||
|
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from models.database import get_db
|
||||||
|
from models.models import User
|
||||||
|
from .account_limits import (
|
||||||
|
UNLIMITED_ACCOUNTS,
|
||||||
|
count_user_account_breakdown,
|
||||||
|
normalize_max_accounts,
|
||||||
|
)
|
||||||
|
from .account_quota import default_stop_worker, sync_user_account_quota
|
||||||
|
from .dependencies import get_current_user, require_user_manager
|
||||||
|
from .email_service import (
|
||||||
|
build_password_reset_link,
|
||||||
|
build_verification_link,
|
||||||
|
send_password_reset_email,
|
||||||
|
send_verification_email,
|
||||||
|
)
|
||||||
|
from .email_verification import create_verification_token, mask_email, verify_email_token
|
||||||
|
from .password_reset import create_password_reset_token, verify_password_reset_token
|
||||||
|
from .jwt_utils import create_access_token
|
||||||
|
from .passwords import hash_password, verify_password
|
||||||
|
from .roles import ALL_ROLES, ROLE_LABELS, ROLE_OPERATOR, ensure_role, is_admin
|
||||||
|
from .schemas import (
|
||||||
|
LoginRequest,
|
||||||
|
MessageResponse,
|
||||||
|
ForgotPasswordRequest,
|
||||||
|
ForgotPasswordResponse,
|
||||||
|
RegisterRequest,
|
||||||
|
RegisterResponse,
|
||||||
|
ResendVerificationRequest,
|
||||||
|
ResetPasswordRequest,
|
||||||
|
RolesResponse,
|
||||||
|
RoleInfo,
|
||||||
|
TokenResponse,
|
||||||
|
UserCreate,
|
||||||
|
UserResponse,
|
||||||
|
UserUpdate,
|
||||||
|
VerifyEmailRequest,
|
||||||
|
)
|
||||||
|
from .system_settings import SystemSettingsData, load_settings
|
||||||
|
|
||||||
|
logger = logging.getLogger("auth.router")
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||||
|
|
||||||
|
|
||||||
|
async def _build_user_response(db: AsyncSession, user: User, with_count: bool = False) -> UserResponse:
|
||||||
|
payload = UserResponse.model_validate(user)
|
||||||
|
if with_count:
|
||||||
|
breakdown = await count_user_account_breakdown(db, user.id)
|
||||||
|
payload.account_count = breakdown["total"]
|
||||||
|
payload.active_account_count = breakdown["active"]
|
||||||
|
payload.disabled_account_count = breakdown["disabled"]
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
async def _ensure_email_available(
|
||||||
|
db: AsyncSession,
|
||||||
|
email: str | None,
|
||||||
|
exclude_user_id: int | None = None,
|
||||||
|
) -> str | None:
|
||||||
|
value = (str(email).strip().lower() if email else "") or None
|
||||||
|
if not value:
|
||||||
|
return None
|
||||||
|
stmt = select(User).where(User.email == value)
|
||||||
|
if exclude_user_id:
|
||||||
|
stmt = stmt.where(User.id != exclude_user_id)
|
||||||
|
exists = await db.execute(stmt)
|
||||||
|
if exists.scalar_one_or_none():
|
||||||
|
raise HTTPException(status_code=400, detail="邮箱已被其他用户使用")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _apply_email_verified(user: User, verified: bool | None) -> None:
|
||||||
|
if verified is None:
|
||||||
|
return
|
||||||
|
user.email_verified = verified
|
||||||
|
if verified:
|
||||||
|
if not user.email_verified_at:
|
||||||
|
user.email_verified_at = datetime.utcnow()
|
||||||
|
else:
|
||||||
|
user.email_verified_at = None
|
||||||
|
|
||||||
|
|
||||||
|
def _email_not_verified_detail(user: User) -> dict:
|
||||||
|
return {
|
||||||
|
"code": "email_not_verified",
|
||||||
|
"message": "邮箱尚未验证,请先完成邮箱验证后再登录",
|
||||||
|
"email": mask_email(user.email or ""),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _email_not_bound_detail() -> dict:
|
||||||
|
return {
|
||||||
|
"code": "email_not_bound",
|
||||||
|
"message": "该账号未绑定邮箱,请联系管理员绑定邮箱后再登录",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _require_email_access(user: User, settings: SystemSettingsData) -> None:
|
||||||
|
if is_admin(user.role):
|
||||||
|
return
|
||||||
|
if settings.email_binding_required and not user.email:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail=_email_not_bound_detail(),
|
||||||
|
)
|
||||||
|
if not settings.email_verification_required:
|
||||||
|
return
|
||||||
|
if user.email_verified:
|
||||||
|
return
|
||||||
|
if user.email:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail=_email_not_verified_detail(user),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def _issue_token(user: User) -> TokenResponse:
|
||||||
|
token = create_access_token(str(user.id), {"role": user.role, "username": user.username})
|
||||||
|
return TokenResponse(access_token=token)
|
||||||
|
|
||||||
|
|
||||||
|
async def _send_user_verification(
|
||||||
|
db: AsyncSession,
|
||||||
|
user: User,
|
||||||
|
settings: SystemSettingsData,
|
||||||
|
) -> tuple[bool, str | None]:
|
||||||
|
if not user.email:
|
||||||
|
raise HTTPException(status_code=400, detail="该账号未绑定邮箱")
|
||||||
|
token = await create_verification_token(
|
||||||
|
db, user, expire_hours=settings.email_verify_token_hours
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
link = build_verification_link(token, settings)
|
||||||
|
if not settings.smtp_configured():
|
||||||
|
logger.warning(
|
||||||
|
"SMTP 未配置,验证链接: user=%s email=%s link=%s",
|
||||||
|
user.username,
|
||||||
|
user.email,
|
||||||
|
link,
|
||||||
|
)
|
||||||
|
dev_url = link if settings.debug_show_verify_link else None
|
||||||
|
return False, dev_url
|
||||||
|
try:
|
||||||
|
await send_verification_email(user.email, user.username, token, settings)
|
||||||
|
return True, None
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Send verification email failed for user=%s", user.username)
|
||||||
|
dev_url = link if settings.debug_show_verify_link else None
|
||||||
|
if dev_url:
|
||||||
|
return False, dev_url
|
||||||
|
raise HTTPException(status_code=400, detail=f"邮件发送失败:{exc}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/login", response_model=TokenResponse)
|
||||||
|
async def login(body: LoginRequest, db: AsyncSession = Depends(get_db)):
|
||||||
|
settings = await load_settings(db)
|
||||||
|
result = await db.execute(select(User).where(User.username == body.username.strip()))
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
if not user or not verify_password(body.password, user.password_hash):
|
||||||
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="用户名或密码错误")
|
||||||
|
if not user.is_active:
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="账号已禁用")
|
||||||
|
_require_email_access(user, settings)
|
||||||
|
return await _issue_token(user)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/register", response_model=RegisterResponse)
|
||||||
|
async def register(body: RegisterRequest, db: AsyncSession = Depends(get_db)):
|
||||||
|
settings = await load_settings(db)
|
||||||
|
if not settings.registration_enabled:
|
||||||
|
raise HTTPException(status_code=403, detail="当前未开放用户注册")
|
||||||
|
|
||||||
|
username = body.username.strip()
|
||||||
|
email = str(body.email).strip().lower()
|
||||||
|
|
||||||
|
exists = await db.execute(select(User).where(User.username == username))
|
||||||
|
if exists.scalar_one_or_none():
|
||||||
|
raise HTTPException(status_code=400, detail="用户名已存在")
|
||||||
|
|
||||||
|
exists = await db.execute(select(User).where(User.email == email))
|
||||||
|
if exists.scalar_one_or_none():
|
||||||
|
raise HTTPException(status_code=400, detail="邮箱已被注册")
|
||||||
|
|
||||||
|
verification_required = settings.email_verification_required
|
||||||
|
|
||||||
|
user = User(
|
||||||
|
username=username,
|
||||||
|
email=email,
|
||||||
|
password_hash=hash_password(body.password),
|
||||||
|
display_name=body.display_name or username,
|
||||||
|
role=ROLE_OPERATOR,
|
||||||
|
is_active=True,
|
||||||
|
email_verified=not verification_required,
|
||||||
|
email_verified_at=datetime.utcnow() if not verification_required else None,
|
||||||
|
max_accounts=max(0, int(settings.default_register_max_accounts or 3)),
|
||||||
|
)
|
||||||
|
db.add(user)
|
||||||
|
await db.flush()
|
||||||
|
|
||||||
|
if not verification_required:
|
||||||
|
await db.commit()
|
||||||
|
await db.refresh(user)
|
||||||
|
return RegisterResponse(
|
||||||
|
message="注册成功,可直接登录",
|
||||||
|
email=mask_email(user.email),
|
||||||
|
verification_sent=False,
|
||||||
|
verification_required=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
verification_sent, dev_url = await _send_user_verification(db, user, settings)
|
||||||
|
await db.refresh(user)
|
||||||
|
message = "注册成功,验证邮件已发送,请查收并完成验证后再登录"
|
||||||
|
if not verification_sent:
|
||||||
|
message = (
|
||||||
|
"注册成功。验证邮件未能发出,请使用下方链接或联系管理员检查 SMTP 配置"
|
||||||
|
if dev_url
|
||||||
|
else "注册成功。邮件服务未配置或发送失败,请联系管理员"
|
||||||
|
)
|
||||||
|
|
||||||
|
return RegisterResponse(
|
||||||
|
message=message,
|
||||||
|
email=mask_email(user.email),
|
||||||
|
verification_sent=verification_sent,
|
||||||
|
verification_required=True,
|
||||||
|
dev_verify_url=dev_url,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/verify-email", response_model=MessageResponse)
|
||||||
|
async def verify_email(body: VerifyEmailRequest, db: AsyncSession = Depends(get_db)):
|
||||||
|
user = await verify_email_token(db, body.token.strip())
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(status_code=400, detail="验证链接无效或已过期")
|
||||||
|
await db.commit()
|
||||||
|
return MessageResponse(message="邮箱验证成功,现在可以登录了")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/verify-email", response_model=MessageResponse)
|
||||||
|
async def verify_email_get(token: str = Query(..., min_length=8), db: AsyncSession = Depends(get_db)):
|
||||||
|
user = await verify_email_token(db, token.strip())
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(status_code=400, detail="验证链接无效或已过期")
|
||||||
|
await db.commit()
|
||||||
|
return MessageResponse(message="邮箱验证成功,现在可以登录了")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/forgot-password", response_model=ForgotPasswordResponse)
|
||||||
|
async def forgot_password(body: ForgotPasswordRequest, db: AsyncSession = Depends(get_db)):
|
||||||
|
settings = await load_settings(db)
|
||||||
|
if not settings.smtp_configured():
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="邮件服务未配置,请联系管理员重置密码",
|
||||||
|
)
|
||||||
|
|
||||||
|
email = str(body.email).strip().lower() if body.email else None
|
||||||
|
username = body.username.strip() if body.username else None
|
||||||
|
if not email and not username:
|
||||||
|
raise HTTPException(status_code=400, detail="请提供邮箱或用户名")
|
||||||
|
|
||||||
|
user = None
|
||||||
|
if email:
|
||||||
|
result = await db.execute(select(User).where(User.email == email))
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
if not user and username:
|
||||||
|
result = await db.execute(select(User).where(User.username == username))
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
generic = ForgotPasswordResponse(
|
||||||
|
message="若账号存在且已绑定邮箱,重置邮件将发送到注册邮箱",
|
||||||
|
email=mask_email(user.email if user and user.email else (email or "")),
|
||||||
|
reset_sent=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not user or not user.email or not user.is_active:
|
||||||
|
return generic
|
||||||
|
|
||||||
|
token = await create_password_reset_token(
|
||||||
|
db, user, expire_hours=settings.email_verify_token_hours
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
link = build_password_reset_link(token, settings)
|
||||||
|
try:
|
||||||
|
await send_password_reset_email(user.email, user.username, token, settings)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception("Send password reset email failed for user=%s", user.username)
|
||||||
|
dev_url = link if settings.debug_show_verify_link else None
|
||||||
|
if dev_url:
|
||||||
|
return ForgotPasswordResponse(
|
||||||
|
message="邮件发送失败,请使用下方开发重置链接",
|
||||||
|
email=mask_email(user.email),
|
||||||
|
reset_sent=False,
|
||||||
|
dev_reset_url=dev_url,
|
||||||
|
)
|
||||||
|
raise HTTPException(status_code=400, detail=f"邮件发送失败:{exc}") from exc
|
||||||
|
return ForgotPasswordResponse(
|
||||||
|
message="重置邮件已发送,请查收并按邮件说明设置新密码",
|
||||||
|
email=mask_email(user.email),
|
||||||
|
reset_sent=True,
|
||||||
|
dev_reset_url=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/reset-password", response_model=MessageResponse)
|
||||||
|
async def reset_password(body: ResetPasswordRequest, db: AsyncSession = Depends(get_db)):
|
||||||
|
user = await verify_password_reset_token(db, body.token.strip())
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(status_code=400, detail="重置链接无效或已过期")
|
||||||
|
if not user.is_active:
|
||||||
|
raise HTTPException(status_code=400, detail="账号已禁用,请联系管理员")
|
||||||
|
user.password_hash = hash_password(body.password)
|
||||||
|
await db.commit()
|
||||||
|
return MessageResponse(message="密码已重置,请使用新密码登录")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/resend-verification", response_model=RegisterResponse)
|
||||||
|
async def resend_verification(body: ResendVerificationRequest, db: AsyncSession = Depends(get_db)):
|
||||||
|
settings = await load_settings(db)
|
||||||
|
if not settings.email_verification_required:
|
||||||
|
raise HTTPException(status_code=400, detail="当前系统未开启邮箱验证")
|
||||||
|
email = str(body.email).strip().lower() if body.email else None
|
||||||
|
username = body.username.strip() if body.username else None
|
||||||
|
if not email and not username:
|
||||||
|
raise HTTPException(status_code=400, detail="请提供邮箱或用户名")
|
||||||
|
|
||||||
|
user = None
|
||||||
|
if email:
|
||||||
|
result = await db.execute(select(User).where(User.email == email))
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
if not user and username:
|
||||||
|
result = await db.execute(select(User).where(User.username == username))
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
return RegisterResponse(
|
||||||
|
message="若账号存在且未验证,验证邮件将发送到注册邮箱",
|
||||||
|
email=mask_email(email or ""),
|
||||||
|
verification_sent=True,
|
||||||
|
verification_required=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
if user.email_verified:
|
||||||
|
raise HTTPException(status_code=400, detail="该账号邮箱已验证,可直接登录")
|
||||||
|
|
||||||
|
verification_sent, dev_url = await _send_user_verification(db, user, settings)
|
||||||
|
message = (
|
||||||
|
"验证邮件已重新发送,请查收"
|
||||||
|
if verification_sent
|
||||||
|
else "邮件未能发出,请使用下方验证链接或联系管理员检查 SMTP 配置"
|
||||||
|
)
|
||||||
|
return RegisterResponse(
|
||||||
|
message=message,
|
||||||
|
email=mask_email(user.email or ""),
|
||||||
|
verification_sent=verification_sent,
|
||||||
|
verification_required=True,
|
||||||
|
dev_verify_url=dev_url,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/me", response_model=UserResponse)
|
||||||
|
async def get_me(user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)):
|
||||||
|
return await _build_user_response(db, user, with_count=True)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/roles", response_model=RolesResponse)
|
||||||
|
async def list_roles(_: User = Depends(get_current_user)):
|
||||||
|
return RolesResponse(
|
||||||
|
roles=[RoleInfo(value=r, label=ROLE_LABELS.get(r, r)) for r in ALL_ROLES]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
users_router = APIRouter(prefix="/api/users", tags=["users"])
|
||||||
|
|
||||||
|
|
||||||
|
@users_router.get("", response_model=list[UserResponse])
|
||||||
|
async def list_users(
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_: User = Depends(require_user_manager),
|
||||||
|
):
|
||||||
|
result = await db.execute(select(User).order_by(User.id.asc()))
|
||||||
|
users = result.scalars().all()
|
||||||
|
responses = []
|
||||||
|
for user in users:
|
||||||
|
responses.append(await _build_user_response(db, user, with_count=True))
|
||||||
|
return responses
|
||||||
|
|
||||||
|
|
||||||
|
@users_router.post("", response_model=UserResponse)
|
||||||
|
async def create_user(
|
||||||
|
body: UserCreate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_: User = Depends(require_user_manager),
|
||||||
|
):
|
||||||
|
settings = await load_settings(db)
|
||||||
|
exists = await db.execute(select(User).where(User.username == body.username))
|
||||||
|
if exists.scalar_one_or_none():
|
||||||
|
raise HTTPException(status_code=400, detail="用户名已存在")
|
||||||
|
try:
|
||||||
|
role = ensure_role(body.role)
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
email = await _ensure_email_available(db, str(body.email) if body.email else None)
|
||||||
|
if settings.email_binding_required and not is_admin(role) and not email:
|
||||||
|
raise HTTPException(status_code=400, detail="系统已开启「登录必须绑定邮箱」,请填写邮箱")
|
||||||
|
if email:
|
||||||
|
email_verified = body.email_verified
|
||||||
|
else:
|
||||||
|
email_verified = not settings.email_binding_required
|
||||||
|
user = User(
|
||||||
|
username=body.username.strip(),
|
||||||
|
password_hash=hash_password(body.password),
|
||||||
|
display_name=body.display_name or body.username,
|
||||||
|
role=role,
|
||||||
|
is_active=True,
|
||||||
|
email=email,
|
||||||
|
email_verified=email_verified,
|
||||||
|
email_verified_at=datetime.utcnow() if email and email_verified else None,
|
||||||
|
max_accounts=normalize_max_accounts(body.max_accounts, role),
|
||||||
|
)
|
||||||
|
db.add(user)
|
||||||
|
await db.commit()
|
||||||
|
await db.refresh(user)
|
||||||
|
return await _build_user_response(db, user, with_count=True)
|
||||||
|
|
||||||
|
|
||||||
|
@users_router.put("/{user_id}", response_model=UserResponse)
|
||||||
|
async def update_user(
|
||||||
|
user_id: int,
|
||||||
|
body: UserUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
current: User = Depends(require_user_manager),
|
||||||
|
):
|
||||||
|
result = await db.execute(select(User).where(User.id == user_id))
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(status_code=404, detail="用户不存在")
|
||||||
|
settings = await load_settings(db)
|
||||||
|
if user.id == current.id and body.is_active is False:
|
||||||
|
raise HTTPException(status_code=400, detail="不能禁用当前登录账号")
|
||||||
|
if body.display_name is not None:
|
||||||
|
user.display_name = body.display_name
|
||||||
|
if body.role is not None:
|
||||||
|
prev_role = user.role
|
||||||
|
try:
|
||||||
|
user.role = ensure_role(body.role)
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(status_code=400, detail=str(e))
|
||||||
|
if is_admin(user.role):
|
||||||
|
user.max_accounts = UNLIMITED_ACCOUNTS
|
||||||
|
await sync_user_account_quota(db, user, stop_worker=default_stop_worker)
|
||||||
|
elif is_admin(prev_role) and not is_admin(user.role):
|
||||||
|
settings = await load_settings(db)
|
||||||
|
user.max_accounts = max(0, int(settings.default_register_max_accounts or 3))
|
||||||
|
await sync_user_account_quota(db, user, stop_worker=default_stop_worker)
|
||||||
|
if body.is_active is not None:
|
||||||
|
user.is_active = body.is_active
|
||||||
|
if body.password:
|
||||||
|
user.password_hash = hash_password(body.password)
|
||||||
|
|
||||||
|
updates = body.model_dump(exclude_unset=True)
|
||||||
|
if "max_accounts" in updates and not is_admin(user.role):
|
||||||
|
user.max_accounts = normalize_max_accounts(updates["max_accounts"], user.role)
|
||||||
|
await sync_user_account_quota(db, user, stop_worker=default_stop_worker)
|
||||||
|
if "email" in updates:
|
||||||
|
raw_email = updates.get("email")
|
||||||
|
user.email = await _ensure_email_available(
|
||||||
|
db,
|
||||||
|
str(raw_email) if raw_email else None,
|
||||||
|
exclude_user_id=user.id,
|
||||||
|
)
|
||||||
|
if not user.email:
|
||||||
|
user.email_verified = not (
|
||||||
|
settings.email_binding_required and not is_admin(user.role)
|
||||||
|
)
|
||||||
|
user.email_verified_at = None
|
||||||
|
if "email_verified" in updates:
|
||||||
|
if not user.email:
|
||||||
|
raise HTTPException(status_code=400, detail="未绑定邮箱时无法设置验证状态")
|
||||||
|
_apply_email_verified(user, updates["email_verified"])
|
||||||
|
|
||||||
|
if settings.email_binding_required and not is_admin(user.role) and not user.email:
|
||||||
|
raise HTTPException(status_code=400, detail="系统已开启「登录必须绑定邮箱」,该用户需绑定邮箱")
|
||||||
|
|
||||||
|
await db.commit()
|
||||||
|
await db.refresh(user)
|
||||||
|
return await _build_user_response(db, user, with_count=True)
|
||||||
|
|
||||||
|
|
||||||
|
@users_router.delete("/{user_id}")
|
||||||
|
async def delete_user(
|
||||||
|
user_id: int,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
current: User = Depends(require_user_manager),
|
||||||
|
):
|
||||||
|
if user_id == current.id:
|
||||||
|
raise HTTPException(status_code=400, detail="不能删除当前登录账号")
|
||||||
|
result = await db.execute(select(User).where(User.id == user_id))
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(status_code=404, detail="用户不存在")
|
||||||
|
await db.delete(user)
|
||||||
|
await db.commit()
|
||||||
|
return {"message": "用户已删除"}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel, EmailStr, Field
|
||||||
|
|
||||||
|
from .roles import ALL_ROLES
|
||||||
|
|
||||||
|
|
||||||
|
class LoginRequest(BaseModel):
|
||||||
|
username: str
|
||||||
|
password: str
|
||||||
|
|
||||||
|
|
||||||
|
class RegisterRequest(BaseModel):
|
||||||
|
username: str = Field(min_length=2, max_length=50)
|
||||||
|
email: EmailStr
|
||||||
|
password: str = Field(min_length=6, max_length=128)
|
||||||
|
display_name: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class VerifyEmailRequest(BaseModel):
|
||||||
|
token: str = Field(min_length=8, max_length=128)
|
||||||
|
|
||||||
|
|
||||||
|
class ResendVerificationRequest(BaseModel):
|
||||||
|
email: Optional[EmailStr] = None
|
||||||
|
username: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ForgotPasswordRequest(BaseModel):
|
||||||
|
email: Optional[EmailStr] = None
|
||||||
|
username: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ResetPasswordRequest(BaseModel):
|
||||||
|
token: str = Field(min_length=8, max_length=128)
|
||||||
|
password: str = Field(min_length=6, max_length=128)
|
||||||
|
|
||||||
|
|
||||||
|
class ForgotPasswordResponse(BaseModel):
|
||||||
|
message: str
|
||||||
|
email: str
|
||||||
|
reset_sent: bool
|
||||||
|
dev_reset_url: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class TokenResponse(BaseModel):
|
||||||
|
access_token: str
|
||||||
|
token_type: str = "bearer"
|
||||||
|
|
||||||
|
|
||||||
|
class RegisterResponse(BaseModel):
|
||||||
|
message: str
|
||||||
|
email: str
|
||||||
|
verification_sent: bool
|
||||||
|
verification_required: bool = True
|
||||||
|
dev_verify_url: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class MessageResponse(BaseModel):
|
||||||
|
message: str
|
||||||
|
|
||||||
|
|
||||||
|
class UserResponse(BaseModel):
|
||||||
|
id: int
|
||||||
|
username: str
|
||||||
|
email: Optional[str] = None
|
||||||
|
display_name: Optional[str] = None
|
||||||
|
role: str
|
||||||
|
is_active: bool
|
||||||
|
email_verified: bool = False
|
||||||
|
max_accounts: int = 3
|
||||||
|
account_count: Optional[int] = None
|
||||||
|
active_account_count: Optional[int] = None
|
||||||
|
disabled_account_count: Optional[int] = None
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class UserCreate(BaseModel):
|
||||||
|
username: str = Field(min_length=2, max_length=50)
|
||||||
|
password: str = Field(min_length=6, max_length=128)
|
||||||
|
display_name: Optional[str] = None
|
||||||
|
role: str = "operator"
|
||||||
|
email: Optional[EmailStr] = None
|
||||||
|
email_verified: bool = True
|
||||||
|
max_accounts: int = Field(default=3, ge=0, le=999)
|
||||||
|
|
||||||
|
|
||||||
|
class UserUpdate(BaseModel):
|
||||||
|
display_name: Optional[str] = None
|
||||||
|
role: Optional[str] = None
|
||||||
|
is_active: Optional[bool] = None
|
||||||
|
password: Optional[str] = Field(default=None, min_length=6, max_length=128)
|
||||||
|
email: Optional[EmailStr] = None
|
||||||
|
email_verified: Optional[bool] = None
|
||||||
|
max_accounts: Optional[int] = Field(default=None, ge=0, le=999)
|
||||||
|
|
||||||
|
|
||||||
|
class RoleInfo(BaseModel):
|
||||||
|
value: str
|
||||||
|
label: str
|
||||||
|
|
||||||
|
|
||||||
|
class RolesResponse(BaseModel):
|
||||||
|
roles: list[RoleInfo]
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import HTTPException, status
|
||||||
|
from sqlalchemy import or_, select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from models.models import Account, AutoReplyRule, MessageLog, ReceivedMessageLog, SystemLog, User
|
||||||
|
from .roles import is_admin
|
||||||
|
|
||||||
|
|
||||||
|
async def get_owned_account(
|
||||||
|
db: AsyncSession,
|
||||||
|
user: User,
|
||||||
|
account_id: int,
|
||||||
|
*,
|
||||||
|
write: bool = False,
|
||||||
|
) -> Account:
|
||||||
|
result = await db.execute(select(Account).where(Account.id == account_id))
|
||||||
|
account = result.scalar_one_or_none()
|
||||||
|
if not account:
|
||||||
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="账号不存在")
|
||||||
|
if is_admin(user.role):
|
||||||
|
return account
|
||||||
|
if account.owner_id != user.id:
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="无权访问该账号")
|
||||||
|
if write and user.role == "viewer":
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="只读用户无法修改")
|
||||||
|
return account
|
||||||
|
|
||||||
|
|
||||||
|
def accounts_for_user(user: User):
|
||||||
|
stmt = select(Account)
|
||||||
|
if not is_admin(user.role):
|
||||||
|
stmt = stmt.where(Account.owner_id == user.id)
|
||||||
|
return stmt
|
||||||
|
|
||||||
|
|
||||||
|
async def owned_account_ids(db: AsyncSession, user: User) -> Optional[set[int]]:
|
||||||
|
if is_admin(user.role):
|
||||||
|
return None
|
||||||
|
result = await db.execute(select(Account.id).where(Account.owner_id == user.id))
|
||||||
|
return {row[0] for row in result.all()}
|
||||||
|
|
||||||
|
|
||||||
|
def logs_for_user(user: User, account_id: Optional[int] = None):
|
||||||
|
stmt = select(MessageLog)
|
||||||
|
if account_id is not None:
|
||||||
|
stmt = stmt.where(MessageLog.account_id == account_id)
|
||||||
|
if not is_admin(user.role):
|
||||||
|
owned = select(Account.id).where(Account.owner_id == user.id)
|
||||||
|
stmt = stmt.where(MessageLog.account_id.in_(owned))
|
||||||
|
return stmt
|
||||||
|
|
||||||
|
|
||||||
|
def received_logs_for_user(user: User, account_id: Optional[int] = None):
|
||||||
|
stmt = select(ReceivedMessageLog)
|
||||||
|
if account_id is not None:
|
||||||
|
stmt = stmt.where(ReceivedMessageLog.account_id == account_id)
|
||||||
|
if not is_admin(user.role):
|
||||||
|
owned = select(Account.id).where(Account.owner_id == user.id)
|
||||||
|
stmt = stmt.where(ReceivedMessageLog.account_id.in_(owned))
|
||||||
|
return stmt
|
||||||
|
|
||||||
|
|
||||||
|
def rules_for_user(user: User, account_id: Optional[int] = None):
|
||||||
|
stmt = select(AutoReplyRule)
|
||||||
|
if account_id is not None:
|
||||||
|
stmt = stmt.where(AutoReplyRule.account_id == account_id)
|
||||||
|
if is_admin(user.role):
|
||||||
|
return stmt
|
||||||
|
owned = select(Account.id).where(Account.owner_id == user.id)
|
||||||
|
return stmt.where(AutoReplyRule.account_id.in_(owned))
|
||||||
|
|
||||||
|
|
||||||
|
async def get_accessible_rule(db: AsyncSession, user: User, rule_id: int, *, write: bool = False) -> AutoReplyRule:
|
||||||
|
result = await db.execute(select(AutoReplyRule).where(AutoReplyRule.id == rule_id))
|
||||||
|
rule = result.scalar_one_or_none()
|
||||||
|
if not rule:
|
||||||
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="规则不存在")
|
||||||
|
|
||||||
|
if is_admin(user.role):
|
||||||
|
if write and user.role == "viewer":
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="只读用户无法修改")
|
||||||
|
return rule
|
||||||
|
|
||||||
|
if rule.account_id is None:
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="无权访问全局规则")
|
||||||
|
|
||||||
|
account = await get_owned_account(db, user, rule.account_id, write=write)
|
||||||
|
if rule.owner_id and rule.owner_id != user.id and account.owner_id != user.id:
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="无权访问该规则")
|
||||||
|
if write and user.role == "viewer":
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="只读用户无法修改")
|
||||||
|
return rule
|
||||||
|
|
||||||
|
|
||||||
|
def system_logs_for_user(user: User, account_id: Optional[int] = None):
|
||||||
|
stmt = select(SystemLog)
|
||||||
|
if account_id is not None:
|
||||||
|
stmt = stmt.where(SystemLog.account_id == account_id)
|
||||||
|
if not is_admin(user.role):
|
||||||
|
owned = select(Account.id).where(Account.owner_id == user.id)
|
||||||
|
stmt = stmt.where(
|
||||||
|
or_(
|
||||||
|
SystemLog.account_id.in_(owned),
|
||||||
|
SystemLog.account_id.is_(None),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return stmt
|
||||||
@@ -0,0 +1,346 @@
|
|||||||
|
from pydantic import BaseModel, EmailStr, Field
|
||||||
|
|
||||||
|
from dataclasses import asdict
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from models.database import get_db
|
||||||
|
from models.db_config import (
|
||||||
|
PASSWORD_PLACEHOLDER as DB_PASSWORD_PLACEHOLDER,
|
||||||
|
database_config_to_response,
|
||||||
|
persist_database_config,
|
||||||
|
test_database_connection,
|
||||||
|
)
|
||||||
|
from models.db_transfer import inspect_sqlite_source, migrate_sqlite_to_target
|
||||||
|
from models.models import User
|
||||||
|
from .dependencies import require_admin
|
||||||
|
from .email_service import send_test_email
|
||||||
|
from .system_settings import (
|
||||||
|
PASSWORD_PLACEHOLDER,
|
||||||
|
SystemSettingsData,
|
||||||
|
load_settings,
|
||||||
|
save_settings,
|
||||||
|
settings_to_admin_response,
|
||||||
|
settings_to_payment_response,
|
||||||
|
settings_to_public,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/settings", tags=["settings"])
|
||||||
|
|
||||||
|
|
||||||
|
class PublicSettingsResponse(BaseModel):
|
||||||
|
registration_enabled: bool
|
||||||
|
email_verification_required: bool
|
||||||
|
email_binding_required: bool
|
||||||
|
|
||||||
|
|
||||||
|
class SystemSettingsResponse(BaseModel):
|
||||||
|
registration_enabled: bool
|
||||||
|
email_verification_required: bool
|
||||||
|
email_binding_required: bool = False
|
||||||
|
email_verify_token_hours: int
|
||||||
|
auto_reply_delay_seconds: int = 0
|
||||||
|
auto_reply_cooldown_seconds: int = 60
|
||||||
|
app_url: str
|
||||||
|
default_register_max_accounts: int = 3
|
||||||
|
smtp_host: str
|
||||||
|
smtp_port: int
|
||||||
|
smtp_user: str
|
||||||
|
smtp_password: str = ""
|
||||||
|
smtp_password_configured: bool = False
|
||||||
|
smtp_from: str
|
||||||
|
smtp_use_tls: bool
|
||||||
|
smtp_use_ssl: bool = False
|
||||||
|
debug_show_verify_link: bool
|
||||||
|
email_verify_subject: str
|
||||||
|
email_verify_body: str
|
||||||
|
email_verify_html: str
|
||||||
|
email_test_subject: str
|
||||||
|
email_test_body: str
|
||||||
|
email_test_html: str
|
||||||
|
|
||||||
|
|
||||||
|
class SystemSettingsUpdate(BaseModel):
|
||||||
|
registration_enabled: bool | None = None
|
||||||
|
email_verification_required: bool | None = None
|
||||||
|
email_binding_required: bool | None = None
|
||||||
|
email_verify_token_hours: int | None = Field(default=None, ge=1, le=168)
|
||||||
|
auto_reply_delay_seconds: int | None = Field(default=None, ge=0, le=86400)
|
||||||
|
auto_reply_cooldown_seconds: int | None = Field(default=None, ge=0, le=86400)
|
||||||
|
app_url: str | None = None
|
||||||
|
default_register_max_accounts: int | None = Field(default=None, ge=0, le=999)
|
||||||
|
smtp_host: str | None = None
|
||||||
|
smtp_port: int | None = Field(default=None, ge=1, le=65535)
|
||||||
|
smtp_user: str | None = None
|
||||||
|
smtp_password: str | None = None
|
||||||
|
smtp_from: str | None = None
|
||||||
|
smtp_use_tls: bool | None = None
|
||||||
|
smtp_use_ssl: bool | None = None
|
||||||
|
debug_show_verify_link: bool | None = None
|
||||||
|
email_verify_subject: str | None = None
|
||||||
|
email_verify_body: str | None = None
|
||||||
|
email_verify_html: str | None = None
|
||||||
|
email_test_subject: str | None = None
|
||||||
|
email_test_body: str | None = None
|
||||||
|
email_test_html: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class TestEmailRequest(BaseModel):
|
||||||
|
to_email: EmailStr
|
||||||
|
smtp_host: str | None = None
|
||||||
|
smtp_port: int | None = Field(default=None, ge=1, le=65535)
|
||||||
|
smtp_user: str | None = None
|
||||||
|
smtp_password: str | None = None
|
||||||
|
smtp_from: str | None = None
|
||||||
|
smtp_use_tls: bool | None = None
|
||||||
|
smtp_use_ssl: bool | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class MessageResponse(BaseModel):
|
||||||
|
message: str
|
||||||
|
|
||||||
|
|
||||||
|
class DatabaseSettingsResponse(BaseModel):
|
||||||
|
db_type: str
|
||||||
|
db_host: str = ""
|
||||||
|
db_port: int = 0
|
||||||
|
db_user: str = ""
|
||||||
|
db_password: str = ""
|
||||||
|
db_password_configured: bool = False
|
||||||
|
db_name: str = ""
|
||||||
|
db_path: str = ""
|
||||||
|
database_url_display: str = ""
|
||||||
|
supported_types: list[str] = []
|
||||||
|
|
||||||
|
|
||||||
|
class DatabaseSettingsUpdate(BaseModel):
|
||||||
|
db_type: str
|
||||||
|
db_host: str | None = None
|
||||||
|
db_port: int | None = Field(default=None, ge=1, le=65535)
|
||||||
|
db_user: str | None = None
|
||||||
|
db_password: str | None = None
|
||||||
|
db_name: str | None = None
|
||||||
|
db_path: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class DatabaseTestRequest(BaseModel):
|
||||||
|
db_type: str
|
||||||
|
db_host: str | None = None
|
||||||
|
db_port: int | None = Field(default=None, ge=1, le=65535)
|
||||||
|
db_user: str | None = None
|
||||||
|
db_password: str | None = None
|
||||||
|
db_name: str | None = None
|
||||||
|
db_path: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class DatabaseMigratePreviewResponse(BaseModel):
|
||||||
|
source_path: str
|
||||||
|
exists: bool
|
||||||
|
tables: dict[str, int]
|
||||||
|
total_rows: int
|
||||||
|
|
||||||
|
|
||||||
|
class DatabaseMigrateRequest(DatabaseTestRequest):
|
||||||
|
source_db_path: str | None = None
|
||||||
|
clear_target: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class DatabaseMigrateResponse(BaseModel):
|
||||||
|
message: str
|
||||||
|
source_path: str
|
||||||
|
target_type: str
|
||||||
|
target_url: str
|
||||||
|
tables: dict[str, int]
|
||||||
|
total_rows: int
|
||||||
|
|
||||||
|
|
||||||
|
class PaymentSettingsResponse(BaseModel):
|
||||||
|
app_url: str
|
||||||
|
payment_enabled: bool = False
|
||||||
|
payment_demo_mode: bool = True
|
||||||
|
wechat_pay_enabled: bool = False
|
||||||
|
alipay_pay_enabled: bool = False
|
||||||
|
account_slot_unit_price: float = 9.9
|
||||||
|
account_slot_purchase_min: int = 1
|
||||||
|
account_slot_purchase_max: int = 20
|
||||||
|
wechat_app_id: str = ""
|
||||||
|
wechat_mch_id: str = ""
|
||||||
|
wechat_api_v3_key: str = ""
|
||||||
|
wechat_api_v3_key_configured: bool = False
|
||||||
|
wechat_cert_serial: str = ""
|
||||||
|
wechat_private_key: str = ""
|
||||||
|
wechat_private_key_configured: bool = False
|
||||||
|
wechat_pay_configured: bool = False
|
||||||
|
alipay_app_id: str = ""
|
||||||
|
alipay_private_key: str = ""
|
||||||
|
alipay_private_key_configured: bool = False
|
||||||
|
alipay_public_key: str = ""
|
||||||
|
alipay_sandbox: bool = False
|
||||||
|
alipay_configured: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class PaymentSettingsUpdate(BaseModel):
|
||||||
|
payment_enabled: bool | None = None
|
||||||
|
payment_demo_mode: bool | None = None
|
||||||
|
wechat_pay_enabled: bool | None = None
|
||||||
|
alipay_pay_enabled: bool | None = None
|
||||||
|
account_slot_unit_price: float | None = Field(default=None, ge=0.01, le=99999)
|
||||||
|
account_slot_purchase_min: int | None = Field(default=None, ge=1, le=100)
|
||||||
|
account_slot_purchase_max: int | None = Field(default=None, ge=1, le=100)
|
||||||
|
wechat_app_id: str | None = None
|
||||||
|
wechat_mch_id: str | None = None
|
||||||
|
wechat_api_v3_key: str | None = None
|
||||||
|
wechat_cert_serial: str | None = None
|
||||||
|
wechat_private_key: str | None = None
|
||||||
|
alipay_app_id: str | None = None
|
||||||
|
alipay_private_key: str | None = None
|
||||||
|
alipay_public_key: str | None = None
|
||||||
|
alipay_sandbox: bool | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/public", response_model=PublicSettingsResponse)
|
||||||
|
async def get_public_settings(db: AsyncSession = Depends(get_db)):
|
||||||
|
data = await load_settings(db)
|
||||||
|
return PublicSettingsResponse(**settings_to_public(data))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=SystemSettingsResponse)
|
||||||
|
async def get_system_settings(
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_: User = Depends(require_admin),
|
||||||
|
):
|
||||||
|
data = await load_settings(db)
|
||||||
|
return SystemSettingsResponse(**settings_to_admin_response(data))
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("", response_model=SystemSettingsResponse)
|
||||||
|
async def update_system_settings(
|
||||||
|
body: SystemSettingsUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_: User = Depends(require_admin),
|
||||||
|
):
|
||||||
|
updates = body.model_dump(exclude_unset=True)
|
||||||
|
if "app_url" in updates and updates["app_url"]:
|
||||||
|
updates["app_url"] = updates["app_url"].strip().rstrip("/")
|
||||||
|
data = await save_settings(db, updates)
|
||||||
|
return SystemSettingsResponse(**settings_to_admin_response(data))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/payment", response_model=PaymentSettingsResponse)
|
||||||
|
async def get_payment_settings(
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_: User = Depends(require_admin),
|
||||||
|
):
|
||||||
|
data = await load_settings(db)
|
||||||
|
return PaymentSettingsResponse(**settings_to_payment_response(data))
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/payment", response_model=PaymentSettingsResponse)
|
||||||
|
async def update_payment_settings(
|
||||||
|
body: PaymentSettingsUpdate,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_: User = Depends(require_admin),
|
||||||
|
):
|
||||||
|
updates = body.model_dump(exclude_unset=True)
|
||||||
|
data = await save_settings(db, updates)
|
||||||
|
return PaymentSettingsResponse(**settings_to_payment_response(data))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/test-email", response_model=MessageResponse)
|
||||||
|
async def test_smtp_email(
|
||||||
|
body: TestEmailRequest,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_: User = Depends(require_admin),
|
||||||
|
):
|
||||||
|
data = await load_settings(db)
|
||||||
|
overrides = body.model_dump(exclude_unset=True, exclude={"to_email"})
|
||||||
|
if overrides:
|
||||||
|
merged = asdict(data)
|
||||||
|
for key, value in overrides.items():
|
||||||
|
if value is None:
|
||||||
|
continue
|
||||||
|
if key == "smtp_password":
|
||||||
|
pwd = str(value).strip()
|
||||||
|
if not pwd or pwd == PASSWORD_PLACEHOLDER:
|
||||||
|
continue
|
||||||
|
merged[key] = value
|
||||||
|
data = SystemSettingsData(**merged)
|
||||||
|
if not data.smtp_configured():
|
||||||
|
raise HTTPException(status_code=400, detail="请先完整配置 SMTP 服务器与发件人")
|
||||||
|
try:
|
||||||
|
await send_test_email(str(body.to_email), data)
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
return MessageResponse(message=f"测试邮件已发送至 {body.to_email}")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/database", response_model=DatabaseSettingsResponse)
|
||||||
|
async def get_database_settings(_: User = Depends(require_admin)):
|
||||||
|
return DatabaseSettingsResponse(**database_config_to_response())
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/database", response_model=MessageResponse)
|
||||||
|
async def update_database_settings(
|
||||||
|
body: DatabaseSettingsUpdate,
|
||||||
|
_: User = Depends(require_admin),
|
||||||
|
):
|
||||||
|
payload = body.model_dump(exclude_unset=True)
|
||||||
|
if payload.get("db_password") in (None, "", DB_PASSWORD_PLACEHOLDER):
|
||||||
|
payload.pop("db_password", None)
|
||||||
|
try:
|
||||||
|
await test_database_connection(payload)
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=f"连接测试失败: {exc}") from exc
|
||||||
|
try:
|
||||||
|
persist_database_config(payload)
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(status_code=500, detail=f"写入配置失败: {exc}") from exc
|
||||||
|
return MessageResponse(message="数据库配置已保存至 .env,请重启后端服务后生效")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/database/test", response_model=MessageResponse)
|
||||||
|
async def test_database_settings(
|
||||||
|
body: DatabaseTestRequest,
|
||||||
|
_: User = Depends(require_admin),
|
||||||
|
):
|
||||||
|
payload = body.model_dump(exclude_unset=True)
|
||||||
|
if payload.get("db_password") in (None, "", DB_PASSWORD_PLACEHOLDER):
|
||||||
|
payload.pop("db_password", None)
|
||||||
|
try:
|
||||||
|
await test_database_connection(payload)
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
return MessageResponse(message="数据库连接测试成功")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/database/migrate/preview", response_model=DatabaseMigratePreviewResponse)
|
||||||
|
async def preview_database_migration(
|
||||||
|
source_db_path: str | None = None,
|
||||||
|
_: User = Depends(require_admin),
|
||||||
|
):
|
||||||
|
return DatabaseMigratePreviewResponse(**await inspect_sqlite_source(source_db_path))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/database/migrate", response_model=DatabaseMigrateResponse)
|
||||||
|
async def migrate_database_data(
|
||||||
|
body: DatabaseMigrateRequest,
|
||||||
|
_: User = Depends(require_admin),
|
||||||
|
):
|
||||||
|
payload = body.model_dump(exclude_unset=True)
|
||||||
|
clear_target = bool(payload.pop("clear_target", False))
|
||||||
|
if payload.get("db_password") in (None, "", DB_PASSWORD_PLACEHOLDER):
|
||||||
|
payload.pop("db_password", None)
|
||||||
|
try:
|
||||||
|
await test_database_connection(payload)
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=f"目标库连接失败: {exc}") from exc
|
||||||
|
try:
|
||||||
|
result = await migrate_sqlite_to_target(payload, clear_target=clear_target)
|
||||||
|
except FileNotFoundError as exc:
|
||||||
|
raise HTTPException(status_code=404, detail=str(exc)) from exc
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(status_code=500, detail=f"迁移失败: {exc}") from exc
|
||||||
|
return DatabaseMigrateResponse(**result)
|
||||||
@@ -0,0 +1,366 @@
|
|||||||
|
"""系统功能配置(数据库存储 + 内存缓存)。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from dataclasses import asdict, dataclass, fields
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from models.models import AppConfig
|
||||||
|
|
||||||
|
CONFIG_ROW_ID = 1
|
||||||
|
PASSWORD_PLACEHOLDER = "******"
|
||||||
|
APP_NAME = "抖音回复助手"
|
||||||
|
|
||||||
|
DEFAULT_EMAIL_VERIFY_SUBJECT = f"【{APP_NAME}】请验证您的邮箱"
|
||||||
|
DEFAULT_EMAIL_VERIFY_BODY = (
|
||||||
|
"您好 {username},\n\n"
|
||||||
|
"感谢注册{app_name}。请点击以下链接完成邮箱验证:\n"
|
||||||
|
"{link}\n\n"
|
||||||
|
"如非本人操作,请忽略此邮件。\n"
|
||||||
|
)
|
||||||
|
DEFAULT_EMAIL_VERIFY_HTML = (
|
||||||
|
"<p>您好 <strong>{username}</strong>,</p>"
|
||||||
|
"<p>感谢注册{app_name}。请点击下方按钮完成邮箱验证:</p>"
|
||||||
|
'<p><a href="{link}" style="display:inline-block;padding:10px 18px;'
|
||||||
|
'background:#aa3bff;color:#fff;text-decoration:none;border-radius:6px;">'
|
||||||
|
"验证邮箱</a></p>"
|
||||||
|
'<p>或复制链接到浏览器:<br><a href="{link}">{link}</a></p>'
|
||||||
|
'<p style="color:#888;font-size:12px;">如非本人操作,请忽略此邮件。</p>'
|
||||||
|
)
|
||||||
|
DEFAULT_EMAIL_TEST_SUBJECT = f"【{APP_NAME}】SMTP 测试邮件"
|
||||||
|
DEFAULT_EMAIL_TEST_BODY = "这是一封 SMTP 配置测试邮件。若您收到此邮件,说明邮件服务已配置正确。"
|
||||||
|
DEFAULT_EMAIL_TEST_HTML = (
|
||||||
|
"<p>这是一封 <strong>SMTP 配置测试</strong> 邮件。</p>"
|
||||||
|
"<p>若您收到此邮件,说明邮件服务已配置正确。</p>"
|
||||||
|
)
|
||||||
|
DEFAULT_PASSWORD_RESET_SUBJECT = f"【{APP_NAME}】重置您的登录密码"
|
||||||
|
DEFAULT_PASSWORD_RESET_BODY = (
|
||||||
|
"您好 {username},\n\n"
|
||||||
|
"我们收到了重置 {app_name} 账号密码的请求。请点击以下链接设置新密码:\n"
|
||||||
|
"{link}\n\n"
|
||||||
|
"链接有效期 {expire_hours} 小时。如非本人操作,请忽略此邮件。\n"
|
||||||
|
)
|
||||||
|
DEFAULT_PASSWORD_RESET_HTML = (
|
||||||
|
"<p>您好 <strong>{username}</strong>,</p>"
|
||||||
|
"<p>我们收到了重置 {app_name} 账号密码的请求。请点击下方按钮设置新密码:</p>"
|
||||||
|
'<p><a href="{link}" style="display:inline-block;padding:10px 18px;'
|
||||||
|
'background:#aa3bff;color:#fff;text-decoration:none;border-radius:6px;">'
|
||||||
|
"重置密码</a></p>"
|
||||||
|
'<p>或复制链接到浏览器:<br><a href="{link}">{link}</a></p>'
|
||||||
|
'<p style="color:#888;font-size:12px;">链接有效期 {expire_hours} 小时。如非本人操作,请忽略此邮件。</p>'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SystemSettingsData:
|
||||||
|
registration_enabled: bool = True
|
||||||
|
email_verification_required: bool = True
|
||||||
|
email_binding_required: bool = False
|
||||||
|
email_verify_token_hours: int = 24
|
||||||
|
auto_reply_delay_seconds: int = 0
|
||||||
|
auto_reply_cooldown_seconds: int = 60
|
||||||
|
app_url: str = "http://localhost:8800"
|
||||||
|
smtp_host: str = ""
|
||||||
|
smtp_port: int = 587
|
||||||
|
smtp_user: str = ""
|
||||||
|
smtp_password: str = ""
|
||||||
|
smtp_from: str = ""
|
||||||
|
smtp_use_tls: bool = True
|
||||||
|
smtp_use_ssl: bool = False
|
||||||
|
debug_show_verify_link: bool = False
|
||||||
|
default_register_max_accounts: int = 3
|
||||||
|
payment_enabled: bool = False
|
||||||
|
payment_demo_mode: bool = True
|
||||||
|
wechat_pay_enabled: bool = False
|
||||||
|
alipay_pay_enabled: bool = False
|
||||||
|
account_slot_unit_price: float = 9.9
|
||||||
|
account_slot_purchase_min: int = 1
|
||||||
|
account_slot_purchase_max: int = 20
|
||||||
|
wechat_app_id: str = ""
|
||||||
|
wechat_mch_id: str = ""
|
||||||
|
wechat_api_v3_key: str = ""
|
||||||
|
wechat_cert_serial: str = ""
|
||||||
|
wechat_private_key: str = ""
|
||||||
|
alipay_app_id: str = ""
|
||||||
|
alipay_private_key: str = ""
|
||||||
|
alipay_public_key: str = ""
|
||||||
|
alipay_sandbox: bool = False
|
||||||
|
email_verify_subject: str = DEFAULT_EMAIL_VERIFY_SUBJECT
|
||||||
|
email_verify_body: str = DEFAULT_EMAIL_VERIFY_BODY
|
||||||
|
email_verify_html: str = DEFAULT_EMAIL_VERIFY_HTML
|
||||||
|
email_test_subject: str = DEFAULT_EMAIL_TEST_SUBJECT
|
||||||
|
email_test_body: str = DEFAULT_EMAIL_TEST_BODY
|
||||||
|
email_test_html: str = DEFAULT_EMAIL_TEST_HTML
|
||||||
|
|
||||||
|
def smtp_configured(self) -> bool:
|
||||||
|
sender = (self.smtp_from or self.smtp_user or "").strip()
|
||||||
|
return bool(self.smtp_host.strip() and sender)
|
||||||
|
|
||||||
|
def app_url_normalized(self) -> str:
|
||||||
|
return (self.app_url or "http://localhost:8800").rstrip("/")
|
||||||
|
|
||||||
|
def wechat_pay_configured(self) -> bool:
|
||||||
|
return bool(
|
||||||
|
self.wechat_app_id.strip()
|
||||||
|
and self.wechat_mch_id.strip()
|
||||||
|
and self.wechat_api_v3_key.strip()
|
||||||
|
and self.wechat_cert_serial.strip()
|
||||||
|
and self.wechat_private_key.strip()
|
||||||
|
)
|
||||||
|
|
||||||
|
def alipay_configured(self) -> bool:
|
||||||
|
return bool(
|
||||||
|
self.alipay_app_id.strip()
|
||||||
|
and self.alipay_private_key.strip()
|
||||||
|
and self.alipay_public_key.strip()
|
||||||
|
)
|
||||||
|
|
||||||
|
def payment_channel_available(self, channel: str) -> bool:
|
||||||
|
if channel == "wechat":
|
||||||
|
return self.wechat_pay_enabled and self.wechat_pay_configured()
|
||||||
|
if channel == "alipay":
|
||||||
|
return self.alipay_pay_enabled and self.alipay_configured()
|
||||||
|
return False
|
||||||
|
|
||||||
|
def payment_channel_selectable(self, channel: str) -> bool:
|
||||||
|
"""用户可选的支付渠道(含演示模式)。"""
|
||||||
|
if channel == "wechat":
|
||||||
|
if not self.wechat_pay_enabled:
|
||||||
|
return False
|
||||||
|
return self.wechat_pay_configured() or (
|
||||||
|
self.payment_demo_mode and self.payment_enabled
|
||||||
|
)
|
||||||
|
if channel == "alipay":
|
||||||
|
if not self.alipay_pay_enabled:
|
||||||
|
return False
|
||||||
|
return self.alipay_configured() or (
|
||||||
|
self.payment_demo_mode and self.payment_enabled
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
def available_payment_channels(self) -> list[str]:
|
||||||
|
channels = []
|
||||||
|
if self.payment_channel_selectable("wechat"):
|
||||||
|
channels.append("wechat")
|
||||||
|
if self.payment_channel_selectable("alipay"):
|
||||||
|
channels.append("alipay")
|
||||||
|
return channels
|
||||||
|
|
||||||
|
|
||||||
|
_settings_cache: SystemSettingsData | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def _coerce_bool(value: Any, default: bool) -> bool:
|
||||||
|
if isinstance(value, bool):
|
||||||
|
return value
|
||||||
|
if isinstance(value, str):
|
||||||
|
return value.lower() in ("1", "true", "yes", "on")
|
||||||
|
if value is None:
|
||||||
|
return default
|
||||||
|
return bool(value)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_settings(raw: dict[str, Any]) -> SystemSettingsData:
|
||||||
|
base = SystemSettingsData()
|
||||||
|
allowed = {f.name for f in fields(SystemSettingsData)}
|
||||||
|
merged: dict[str, Any] = {}
|
||||||
|
for key in allowed:
|
||||||
|
if key in raw:
|
||||||
|
merged[key] = raw[key]
|
||||||
|
if "smtp_port" in merged:
|
||||||
|
try:
|
||||||
|
merged["smtp_port"] = int(merged["smtp_port"])
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
merged["smtp_port"] = base.smtp_port
|
||||||
|
if "email_verify_token_hours" in merged:
|
||||||
|
try:
|
||||||
|
merged["email_verify_token_hours"] = max(
|
||||||
|
1, min(168, int(merged["email_verify_token_hours"]))
|
||||||
|
)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
merged["email_verify_token_hours"] = base.email_verify_token_hours
|
||||||
|
if "auto_reply_cooldown_seconds" in merged:
|
||||||
|
try:
|
||||||
|
merged["auto_reply_cooldown_seconds"] = max(
|
||||||
|
0, min(86400, int(merged["auto_reply_cooldown_seconds"]))
|
||||||
|
)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
merged["auto_reply_cooldown_seconds"] = base.auto_reply_cooldown_seconds
|
||||||
|
if "auto_reply_delay_seconds" in merged:
|
||||||
|
try:
|
||||||
|
merged["auto_reply_delay_seconds"] = max(
|
||||||
|
0, min(86400, int(merged["auto_reply_delay_seconds"]))
|
||||||
|
)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
merged["auto_reply_delay_seconds"] = base.auto_reply_delay_seconds
|
||||||
|
if "default_register_max_accounts" in merged:
|
||||||
|
try:
|
||||||
|
merged["default_register_max_accounts"] = max(
|
||||||
|
0, min(999, int(merged["default_register_max_accounts"]))
|
||||||
|
)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
merged["default_register_max_accounts"] = base.default_register_max_accounts
|
||||||
|
if "account_slot_unit_price" in merged:
|
||||||
|
try:
|
||||||
|
merged["account_slot_unit_price"] = max(
|
||||||
|
0.01, min(99999.0, float(merged["account_slot_unit_price"]))
|
||||||
|
)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
merged["account_slot_unit_price"] = base.account_slot_unit_price
|
||||||
|
for int_key, lo, hi in (
|
||||||
|
("account_slot_purchase_min", 1, 100),
|
||||||
|
("account_slot_purchase_max", 1, 100),
|
||||||
|
):
|
||||||
|
if int_key in merged:
|
||||||
|
try:
|
||||||
|
merged[int_key] = max(lo, min(hi, int(merged[int_key])))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
merged[int_key] = getattr(base, int_key)
|
||||||
|
for bool_key in (
|
||||||
|
"registration_enabled",
|
||||||
|
"email_verification_required",
|
||||||
|
"email_binding_required",
|
||||||
|
"smtp_use_tls",
|
||||||
|
"smtp_use_ssl",
|
||||||
|
"debug_show_verify_link",
|
||||||
|
"payment_enabled",
|
||||||
|
"payment_demo_mode",
|
||||||
|
"wechat_pay_enabled",
|
||||||
|
"alipay_pay_enabled",
|
||||||
|
"alipay_sandbox",
|
||||||
|
):
|
||||||
|
if bool_key in merged:
|
||||||
|
merged[bool_key] = _coerce_bool(merged[bool_key], getattr(base, bool_key))
|
||||||
|
return SystemSettingsData(**{**asdict(base), **merged})
|
||||||
|
|
||||||
|
|
||||||
|
def get_cached_settings() -> SystemSettingsData:
|
||||||
|
global _settings_cache
|
||||||
|
if _settings_cache is None:
|
||||||
|
_settings_cache = SystemSettingsData()
|
||||||
|
return _settings_cache
|
||||||
|
|
||||||
|
|
||||||
|
def set_cached_settings(data: SystemSettingsData) -> None:
|
||||||
|
global _settings_cache
|
||||||
|
_settings_cache = data
|
||||||
|
|
||||||
|
|
||||||
|
async def load_settings(db: AsyncSession) -> SystemSettingsData:
|
||||||
|
result = await db.execute(select(AppConfig).where(AppConfig.id == CONFIG_ROW_ID))
|
||||||
|
row = result.scalar_one_or_none()
|
||||||
|
if not row or not row.data:
|
||||||
|
data = SystemSettingsData()
|
||||||
|
set_cached_settings(data)
|
||||||
|
return data
|
||||||
|
try:
|
||||||
|
payload = json.loads(row.data)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
payload = {}
|
||||||
|
data = _parse_settings(payload if isinstance(payload, dict) else {})
|
||||||
|
set_cached_settings(data)
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
async def ensure_default_settings(db: AsyncSession) -> SystemSettingsData:
|
||||||
|
result = await db.execute(select(AppConfig).where(AppConfig.id == CONFIG_ROW_ID))
|
||||||
|
row = result.scalar_one_or_none()
|
||||||
|
if row:
|
||||||
|
return await load_settings(db)
|
||||||
|
data = SystemSettingsData()
|
||||||
|
row = AppConfig(
|
||||||
|
id=CONFIG_ROW_ID,
|
||||||
|
data=json.dumps(asdict(data), ensure_ascii=False),
|
||||||
|
updated_at=datetime.utcnow(),
|
||||||
|
)
|
||||||
|
db.add(row)
|
||||||
|
await db.commit()
|
||||||
|
set_cached_settings(data)
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
async def save_settings(db: AsyncSession, updates: dict[str, Any]) -> SystemSettingsData:
|
||||||
|
current = await load_settings(db)
|
||||||
|
merged = asdict(current)
|
||||||
|
for key, value in updates.items():
|
||||||
|
if key not in merged or value is None:
|
||||||
|
continue
|
||||||
|
if key == "smtp_password":
|
||||||
|
pwd = str(value).strip()
|
||||||
|
if not pwd or pwd == PASSWORD_PLACEHOLDER:
|
||||||
|
continue
|
||||||
|
merged[key] = pwd
|
||||||
|
continue
|
||||||
|
if key in ("wechat_api_v3_key", "wechat_private_key", "alipay_private_key"):
|
||||||
|
secret = str(value).strip()
|
||||||
|
if not secret or secret == PASSWORD_PLACEHOLDER:
|
||||||
|
continue
|
||||||
|
merged[key] = secret
|
||||||
|
continue
|
||||||
|
merged[key] = value
|
||||||
|
data = _parse_settings(merged)
|
||||||
|
|
||||||
|
result = await db.execute(select(AppConfig).where(AppConfig.id == CONFIG_ROW_ID))
|
||||||
|
row = result.scalar_one_or_none()
|
||||||
|
if not row:
|
||||||
|
row = AppConfig(id=CONFIG_ROW_ID, data="{}", updated_at=datetime.utcnow())
|
||||||
|
db.add(row)
|
||||||
|
row.data = json.dumps(asdict(data), ensure_ascii=False)
|
||||||
|
row.updated_at = datetime.utcnow()
|
||||||
|
await db.commit()
|
||||||
|
set_cached_settings(data)
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def settings_to_public(data: SystemSettingsData) -> dict[str, bool]:
|
||||||
|
return {
|
||||||
|
"registration_enabled": data.registration_enabled,
|
||||||
|
"email_verification_required": data.email_verification_required,
|
||||||
|
"email_binding_required": data.email_binding_required,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def settings_to_admin_response(data: SystemSettingsData) -> dict[str, Any]:
|
||||||
|
payload = asdict(data)
|
||||||
|
payload["smtp_password"] = PASSWORD_PLACEHOLDER if data.smtp_password else ""
|
||||||
|
payload["smtp_password_configured"] = bool(data.smtp_password)
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
PAYMENT_SETTING_KEYS = (
|
||||||
|
"payment_enabled",
|
||||||
|
"payment_demo_mode",
|
||||||
|
"wechat_pay_enabled",
|
||||||
|
"alipay_pay_enabled",
|
||||||
|
"account_slot_unit_price",
|
||||||
|
"account_slot_purchase_min",
|
||||||
|
"account_slot_purchase_max",
|
||||||
|
"wechat_app_id",
|
||||||
|
"wechat_mch_id",
|
||||||
|
"wechat_api_v3_key",
|
||||||
|
"wechat_cert_serial",
|
||||||
|
"wechat_private_key",
|
||||||
|
"alipay_app_id",
|
||||||
|
"alipay_private_key",
|
||||||
|
"alipay_public_key",
|
||||||
|
"alipay_sandbox",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def settings_to_payment_response(data: SystemSettingsData) -> dict[str, Any]:
|
||||||
|
payload = {key: getattr(data, key) for key in PAYMENT_SETTING_KEYS}
|
||||||
|
payload["app_url"] = data.app_url
|
||||||
|
payload["wechat_api_v3_key"] = PASSWORD_PLACEHOLDER if data.wechat_api_v3_key else ""
|
||||||
|
payload["wechat_api_v3_key_configured"] = bool(data.wechat_api_v3_key)
|
||||||
|
payload["wechat_private_key"] = PASSWORD_PLACEHOLDER if data.wechat_private_key else ""
|
||||||
|
payload["wechat_private_key_configured"] = bool(data.wechat_private_key)
|
||||||
|
payload["alipay_private_key"] = PASSWORD_PLACEHOLDER if data.alipay_private_key else ""
|
||||||
|
payload["alipay_private_key_configured"] = bool(data.alipay_private_key)
|
||||||
|
payload["wechat_pay_configured"] = data.wechat_pay_configured()
|
||||||
|
payload["alipay_configured"] = data.alipay_configured()
|
||||||
|
return payload
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# 宝塔一键修复:权限 + 安装依赖 + 提示正确启动命令
|
||||||
|
# SSH 执行: bash /www/wwwroot/douyin/backend/baota_fix.sh
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
BACKEND="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
ROOT="$(cd "$BACKEND/.." && pwd)"
|
||||||
|
# shellcheck source=lib/resolve_python.sh
|
||||||
|
source "$BACKEND/lib/resolve_python.sh"
|
||||||
|
|
||||||
|
echo "========================================"
|
||||||
|
echo " 宝塔环境修复"
|
||||||
|
echo "========================================"
|
||||||
|
|
||||||
|
# 权限
|
||||||
|
chown -R www:www "$ROOT" 2>/dev/null || true
|
||||||
|
chmod +x "$BACKEND/baota_start.sh" "$BACKEND/baota_init.sh" 2>/dev/null || true
|
||||||
|
chmod +x "$ROOT/install.sh" "$ROOT/start_web.sh" "$ROOT/start_backend.sh" 2>/dev/null || true
|
||||||
|
if [ -d "$BACKEND/.venv/bin" ]; then
|
||||||
|
chmod -R 755 "$BACKEND/.venv"
|
||||||
|
chmod +x "$BACKEND/.venv/bin/"* 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
echo "[OK] 权限已修复"
|
||||||
|
|
||||||
|
if [ -n "${KEFU_PYTHON:-}" ] && [ -x "$KEFU_PYTHON" ]; then
|
||||||
|
PY="$KEFU_PYTHON"
|
||||||
|
if ! "$PY" -c "import ssl" 2>/dev/null; then
|
||||||
|
echo "[错误] KEFU_PYTHON 无 SSL: $KEFU_PYTHON"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
PY="$(resolve_python "$BACKEND" "$ROOT")" || {
|
||||||
|
echo
|
||||||
|
echo "请先编译可用 Python:"
|
||||||
|
echo " AUTO_BUILD_PYTHON=1 bash $ROOT/install.sh"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
fi
|
||||||
|
echo "[OK] Python: $PY ($("$PY" -V 2>&1))"
|
||||||
|
|
||||||
|
if ! "$PY" -c "import ssl" 2>/dev/null; then
|
||||||
|
echo "[错误] 该 Python 无 SSL,请换环境或执行: AUTO_BUILD_PYTHON=1 $ROOT/install.sh"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "[1/3] pip install requirements..."
|
||||||
|
"$PY" -m pip install -U pip
|
||||||
|
"$PY" -m pip install -r "$BACKEND/requirements.txt"
|
||||||
|
echo "[OK] Python 依赖已安装"
|
||||||
|
|
||||||
|
echo "[2/3] 校验 uvicorn..."
|
||||||
|
"$PY" -c "import uvicorn, fastapi; print(' uvicorn + fastapi OK')"
|
||||||
|
|
||||||
|
echo "[3/3] 可选:完整初始化 Playwright/前端"
|
||||||
|
echo " bash $BACKEND/baota_init.sh"
|
||||||
|
echo
|
||||||
|
echo "========================================"
|
||||||
|
echo " 请在宝塔面板修改以下配置:"
|
||||||
|
echo
|
||||||
|
echo " 项目路径: $BACKEND"
|
||||||
|
echo " 启动命令: bash $BACKEND/baota_start.sh"
|
||||||
|
echo " 初始化命令: bash $BACKEND/baota_init.sh"
|
||||||
|
echo " 依赖包: $BACKEND/requirements.txt"
|
||||||
|
echo
|
||||||
|
echo " 不要用:"
|
||||||
|
echo " backend/.venv/bin/uvicorn (不存在)"
|
||||||
|
echo " start_web.bat (Windows 脚本,Linux 不能运行)"
|
||||||
|
echo "========================================"
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# 宝塔 Python 项目 - 项目初始化命令
|
||||||
|
# 在面板填写: /www/wwwroot/douyin/backend/baota_init.sh
|
||||||
|
# 执行时机: 宝塔创建虚拟环境并 pip install requirements.txt 之后
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
BACKEND="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
ROOT="$(cd "$BACKEND/.." && pwd)"
|
||||||
|
# shellcheck source=lib/resolve_python.sh
|
||||||
|
source "$BACKEND/lib/resolve_python.sh"
|
||||||
|
|
||||||
|
PY="$(resolve_python "$BACKEND" "$ROOT")"
|
||||||
|
ensure_uvicorn "$PY" "$BACKEND"
|
||||||
|
|
||||||
|
echo "========================================"
|
||||||
|
echo " 抖音客服 - 宝塔项目初始化"
|
||||||
|
echo " Python: $("$PY" -V 2>&1) @ $PY"
|
||||||
|
echo "========================================"
|
||||||
|
|
||||||
|
# 校验 Python
|
||||||
|
"$PY" -c "import ssl; print('[OK] OpenSSL:', ssl.OPENSSL_VERSION)"
|
||||||
|
|
||||||
|
echo "[1/4] Playwright Chromium..."
|
||||||
|
KEFU_PYTHON="$PY" bash "$BACKEND/baota_playwright.sh"
|
||||||
|
|
||||||
|
echo "[2/4] IM 签名 Node 依赖..."
|
||||||
|
if command -v npm &>/dev/null; then
|
||||||
|
cd "$BACKEND/rpa_engine/douyin_im/static"
|
||||||
|
npm install --no-fund --no-audit
|
||||||
|
else
|
||||||
|
echo "[警告] 未找到 npm,请宝塔安装 Node 18+ 后重新运行本脚本"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "[3/4] 前端依赖与构建..."
|
||||||
|
if command -v npm &>/dev/null && [ -f "$ROOT/frontend/package.json" ]; then
|
||||||
|
cd "$ROOT/frontend"
|
||||||
|
npm install --no-fund --no-audit
|
||||||
|
npm run build
|
||||||
|
else
|
||||||
|
echo "[警告] 跳过前端构建"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "[4/4] 校验..."
|
||||||
|
cd "$BACKEND"
|
||||||
|
"$PY" -c "import fastapi, uvicorn, playwright; print(' 核心包 OK')"
|
||||||
|
[ -f "$ROOT/frontend/dist/index.html" ] && echo " 前端静态 OK" || echo "[警告] 未找到 frontend/dist"
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "========================================"
|
||||||
|
echo " 宝塔初始化完成"
|
||||||
|
echo " 启动命令请用: bash $BACKEND/baota_start.sh"
|
||||||
|
echo "========================================"
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# 安装 Playwright Chromium(Linux 宝塔/无桌面服务器)
|
||||||
|
# 用法: bash /www/wwwroot/douyin/backend/baota_playwright.sh
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
BACKEND="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
ROOT="$(cd "$BACKEND/.." && pwd)"
|
||||||
|
# shellcheck source=lib/resolve_python.sh
|
||||||
|
source "$BACKEND/lib/resolve_python.sh"
|
||||||
|
|
||||||
|
PY="${KEFU_PYTHON:-}"
|
||||||
|
if [ -z "$PY" ]; then
|
||||||
|
PY="$(resolve_python "$BACKEND" "$ROOT")"
|
||||||
|
fi
|
||||||
|
|
||||||
|
export PLAYWRIGHT_BROWSERS_PATH="${PLAYWRIGHT_BROWSERS_PATH:-$ROOT/playwright-browsers}"
|
||||||
|
mkdir -p "$PLAYWRIGHT_BROWSERS_PATH"
|
||||||
|
chown -R www:www "$PLAYWRIGHT_BROWSERS_PATH" 2>/dev/null || true
|
||||||
|
|
||||||
|
echo "========================================"
|
||||||
|
echo " Playwright Chromium 安装"
|
||||||
|
echo " Python: $PY"
|
||||||
|
echo " 目录: $PLAYWRIGHT_BROWSERS_PATH"
|
||||||
|
echo "========================================"
|
||||||
|
|
||||||
|
echo "[1/4] 安装系统依赖(需 root)..."
|
||||||
|
if [ "$(uname -s)" = "Linux" ]; then
|
||||||
|
if [ "$(id -u)" -eq 0 ]; then
|
||||||
|
# 优先用 dnf(阿里云 Linux 3 / Anolis / RHEL 8+),回退到 yum
|
||||||
|
DNF=""
|
||||||
|
if command -v dnf &>/dev/null; then
|
||||||
|
DNF="dnf"
|
||||||
|
elif command -v yum &>/dev/null; then
|
||||||
|
DNF="yum"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -n "$DNF" ]; then
|
||||||
|
# Chromium 运行库 + Xvfb 虚拟显示(无桌面服务器跑有头浏览器扫码登录必需)
|
||||||
|
"$DNF" install -y atk at-spi2-atk cups-libs libdrm libXcomposite libXdamage \
|
||||||
|
libXrandr mesa-libgbm pango alsa-lib nss nspr libxkbcommon \
|
||||||
|
libXScrnSaver gtk3 xorg-x11-server-Xvfb 2>/dev/null || true
|
||||||
|
elif command -v apt-get &>/dev/null; then
|
||||||
|
apt-get update
|
||||||
|
apt-get install -y libnss3 libnspr4 libatk1.0-0 libatk-bridge2.0-0 \
|
||||||
|
libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 \
|
||||||
|
libxfixes3 libxrandr2 libgbm1 libpango-1.0-0 libcairo2 libasound2 \
|
||||||
|
libatspi2.0-0 libxshmfence1 xvfb 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
"$PY" -m playwright install-deps chromium || true
|
||||||
|
else
|
||||||
|
echo " 非 root,跳过 install-deps / Xvfb(若启动失败请 sudo 执行本脚本)"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "[2/4] 安装 pyvirtualdisplay(自动拉起 Xvfb 虚拟显示)..."
|
||||||
|
# requirements.txt 已含 pyvirtualdisplay;这里兜底确保 venv 内已安装
|
||||||
|
"$PY" -m pip show pyvirtualdisplay &>/dev/null \
|
||||||
|
|| "$PY" -m pip install "pyvirtualdisplay==3.0" || true
|
||||||
|
|
||||||
|
echo "[3/4] 下载 Chromium..."
|
||||||
|
"$PY" -m playwright install chromium
|
||||||
|
|
||||||
|
echo "[4/4] 校验..."
|
||||||
|
CHROME=$(find "$PLAYWRIGHT_BROWSERS_PATH" -name chrome -type f 2>/dev/null | head -1)
|
||||||
|
if [ -n "$CHROME" ] && [ -x "$CHROME" ]; then
|
||||||
|
echo "[OK] 浏览器: $CHROME"
|
||||||
|
chmod +x "$CHROME" 2>/dev/null || true
|
||||||
|
chown -R www:www "$PLAYWRIGHT_BROWSERS_PATH" 2>/dev/null || true
|
||||||
|
else
|
||||||
|
echo "[错误] 未找到 chrome 可执行文件,请检查网络或磁盘空间"
|
||||||
|
ls -la "$PLAYWRIGHT_BROWSERS_PATH" 2>/dev/null || true
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo
|
||||||
|
# 校验虚拟显示链路:无桌面 Linux 上扫码登录依赖 Xvfb + pyvirtualdisplay
|
||||||
|
if [ "$(uname -s)" = "Linux" ] && [ -z "${DISPLAY:-}" ]; then
|
||||||
|
XVFB_OK=0
|
||||||
|
command -v Xvfb &>/dev/null && XVFB_OK=1
|
||||||
|
PVD_OK=0
|
||||||
|
"$PY" -c "import pyvirtualdisplay" &>/dev/null && PVD_OK=1
|
||||||
|
if [ "$XVFB_OK" = "1" ] && [ "$PVD_OK" = "1" ]; then
|
||||||
|
echo "[OK] Xvfb + pyvirtualdisplay 就绪,云端可直接点「登录」用手机扫码"
|
||||||
|
else
|
||||||
|
echo "[警告] 扫码登录所需的虚拟显示未就绪:"
|
||||||
|
[ "$XVFB_OK" = "0" ] && echo " - 缺少 Xvfb,请 root 执行: dnf install -y xorg-x11-server-Xvfb"
|
||||||
|
[ "$PVD_OK" = "0" ] && echo " - 缺少 pyvirtualdisplay,请执行: $PY -m pip install pyvirtualdisplay==3.0"
|
||||||
|
echo " 或改用: xvfb-run -a bash $ROOT/start_web.sh 启动服务"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "请将以下写入 .env 或宝塔环境变量:"
|
||||||
|
echo " PLAYWRIGHT_BROWSERS_PATH=$PLAYWRIGHT_BROWSERS_PATH"
|
||||||
|
echo
|
||||||
|
echo "安装完成,重启项目: bash $BACKEND/baota_start.sh"
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# 宝塔 Python 项目 - 启动命令
|
||||||
|
# 面板「启动命令」必须填这一行(不要用 .venv/bin/uvicorn):
|
||||||
|
# bash /www/wwwroot/douyin/backend/baota_start.sh
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
BACKEND="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
ROOT="$(cd "$BACKEND/.." && pwd)"
|
||||||
|
# shellcheck source=lib/resolve_python.sh
|
||||||
|
source "$BACKEND/lib/resolve_python.sh"
|
||||||
|
|
||||||
|
cd "$BACKEND"
|
||||||
|
|
||||||
|
PY="$(resolve_python "$BACKEND" "$ROOT")"
|
||||||
|
ensure_uvicorn "$PY" "$BACKEND"
|
||||||
|
|
||||||
|
export PLAYWRIGHT_BROWSERS_PATH="${PLAYWRIGHT_BROWSERS_PATH:-$ROOT/playwright-browsers}"
|
||||||
|
export KEFU_SERVE_WEB="${KEFU_SERVE_WEB:-true}"
|
||||||
|
export KEFU_STATIC_DIR="${KEFU_STATIC_DIR:-$ROOT/frontend/dist}"
|
||||||
|
|
||||||
|
# 启动前检查 Chromium(缺失时给出明确提示)
|
||||||
|
if ! find "$PLAYWRIGHT_BROWSERS_PATH" -name chrome -type f 2>/dev/null | grep -q .; then
|
||||||
|
echo "[警告] 未找到 Chromium,请执行: bash $BACKEND/baota_playwright.sh" >&2
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -f "$ROOT/.env" ]; then
|
||||||
|
set -a
|
||||||
|
# shellcheck disable=SC1090
|
||||||
|
source "$ROOT/.env"
|
||||||
|
set +a
|
||||||
|
fi
|
||||||
|
|
||||||
|
HOST="${KEFU_HOST:-0.0.0.0}"
|
||||||
|
PORT="${KEFU_PORT:-8000}"
|
||||||
|
|
||||||
|
echo "[baota] Python: $PY"
|
||||||
|
echo "[baota] Listen: http://${HOST}:${PORT}"
|
||||||
|
|
||||||
|
exec "$PY" -m uvicorn main:app --host "$HOST" --port "$PORT"
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# 宝塔/服务器快速诊断:服务是否在跑、端口是否监听
|
||||||
|
set -uo pipefail
|
||||||
|
|
||||||
|
BACKEND="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
ROOT="$(cd "$BACKEND/.." && pwd)"
|
||||||
|
PORT="${KEFU_PORT:-8000}"
|
||||||
|
|
||||||
|
echo "========================================"
|
||||||
|
echo " 抖音客服 - 运行诊断"
|
||||||
|
echo "========================================"
|
||||||
|
echo
|
||||||
|
|
||||||
|
echo "[1] 端口 ${PORT} 监听状态:"
|
||||||
|
if command -v ss &>/dev/null; then
|
||||||
|
ss -tlnp | grep ":${PORT} " || echo " -> 未监听(服务未启动)"
|
||||||
|
elif command -v netstat &>/dev/null; then
|
||||||
|
netstat -tlnp 2>/dev/null | grep ":${PORT} " || echo " -> 未监听(服务未启动)"
|
||||||
|
else
|
||||||
|
echo " (无法检测,请安装 ss 或 netstat)"
|
||||||
|
fi
|
||||||
|
echo
|
||||||
|
|
||||||
|
echo "[2] Python 环境:"
|
||||||
|
BROKEN_BT="/home/www/server/pyporject_evn/versions/3.11.15/bin/python"
|
||||||
|
if [ -x "$BROKEN_BT" ] && ! "$BROKEN_BT" -c "import ssl" 2>/dev/null; then
|
||||||
|
echo " [X] 宝塔 Python 无 SSL(不可用): $BROKEN_BT"
|
||||||
|
echo " 修复: AUTO_BUILD_PYTHON=1 bash $ROOT/install.sh"
|
||||||
|
fi
|
||||||
|
if [ -f "$BACKEND/lib/resolve_python.sh" ]; then
|
||||||
|
# shellcheck source=lib/resolve_python.sh
|
||||||
|
source "$BACKEND/lib/resolve_python.sh"
|
||||||
|
if PY="$(resolve_python "$BACKEND" "$ROOT" 2>/dev/null)"; then
|
||||||
|
echo " Python: $PY"
|
||||||
|
"$PY" -V 2>&1 | sed 's/^/ /'
|
||||||
|
if "$PY" -c "import ssl" 2>/dev/null; then
|
||||||
|
"$PY" -c "import ssl; print(' SSL:', ssl.OPENSSL_VERSION)"
|
||||||
|
else
|
||||||
|
echo " SSL: 无(不可用)"
|
||||||
|
fi
|
||||||
|
if "$PY" -c "import uvicorn" 2>/dev/null; then
|
||||||
|
echo " uvicorn: 已安装"
|
||||||
|
else
|
||||||
|
echo " uvicorn: 未安装 -> 运行 bash $BACKEND/baota_fix.sh"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo " 未找到可用 Python 3.10+"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
command -v python && python -V || echo " 未找到 python"
|
||||||
|
fi
|
||||||
|
echo
|
||||||
|
|
||||||
|
echo "[3] 前端静态:"
|
||||||
|
if [ -f "$ROOT/frontend/dist/index.html" ]; then
|
||||||
|
echo " OK: $ROOT/frontend/dist/index.html"
|
||||||
|
else
|
||||||
|
echo " 缺失 -> 运行 bash $BACKEND/baota_init.sh"
|
||||||
|
fi
|
||||||
|
echo
|
||||||
|
|
||||||
|
echo "[4] 宝塔项目进程:"
|
||||||
|
ps aux 2>/dev/null | grep -E "uvicorn|douyin" | grep -v grep || echo " 未发现 uvicorn 进程"
|
||||||
|
echo
|
||||||
|
|
||||||
|
echo "[5] 防火墙(CentOS firewalld):"
|
||||||
|
if command -v firewall-cmd &>/dev/null && systemctl is-active firewalld &>/dev/null; then
|
||||||
|
firewall-cmd --list-ports 2>/dev/null | grep -q "${PORT}" \
|
||||||
|
&& echo " 端口 ${PORT} 已放行" \
|
||||||
|
|| echo " 端口 ${PORT} 未放行 -> firewall-cmd --add-port=${PORT}/tcp --permanent && firewall-cmd --reload"
|
||||||
|
else
|
||||||
|
echo " firewalld 未运行或未安装(可忽略,检查云服务器安全组)"
|
||||||
|
fi
|
||||||
|
echo
|
||||||
|
|
||||||
|
echo "========================================"
|
||||||
|
echo " 若端口未监听,按顺序执行:"
|
||||||
|
echo " 若宝塔 Python 无 SSL,必须先编译可用 Python:"
|
||||||
|
echo " AUTO_BUILD_PYTHON=1 bash $ROOT/install.sh"
|
||||||
|
echo " KEFU_PYTHON=/usr/local/python3.11/bin/python3.11 bash $BACKEND/baota_fix.sh"
|
||||||
|
echo " bash $BACKEND/baota_init.sh"
|
||||||
|
echo " 宝塔启动命令: bash $BACKEND/baota_start.sh"
|
||||||
|
echo
|
||||||
|
echo " 手动测试启动:"
|
||||||
|
echo " bash $BACKEND/baota_start.sh"
|
||||||
|
echo "========================================"
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# 使用宝塔「Python环境管理」安装的 Python 完成项目配置
|
||||||
|
# 用法: bash /www/wwwroot/douyin/backend/baota_use_panel_python.sh
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
BACKEND="$(cd "$(dirname "$0")" && pwd)"
|
||||||
|
ROOT="$(cd "$BACKEND/.." && pwd)"
|
||||||
|
|
||||||
|
echo "========================================"
|
||||||
|
echo " 宝塔 Python 环境配置"
|
||||||
|
echo "========================================"
|
||||||
|
echo
|
||||||
|
|
||||||
|
# 扫描宝塔 Python(环境管理 / Python项目)
|
||||||
|
PY=""
|
||||||
|
for base in \
|
||||||
|
/home/www/server/pyporject_evn/versions \
|
||||||
|
/www/server/pyporject_evn/versions \
|
||||||
|
/www/server/panel/pyenv/versions; do
|
||||||
|
[ -d "$base" ] || continue
|
||||||
|
for ver_dir in $(ls -d "$base"/* 2>/dev/null | sort -V -r); do
|
||||||
|
for name in python3 python; do
|
||||||
|
candidate="$ver_dir/bin/$name"
|
||||||
|
[ -x "$candidate" ] || continue
|
||||||
|
ver="$("$candidate" -V 2>&1 | awk '{print $2}')"
|
||||||
|
echo "[发现] $candidate ($ver)"
|
||||||
|
if ! "$candidate" -c "import sys; sys.exit(0 if sys.version_info>=(3,10) else 1)" 2>/dev/null; then
|
||||||
|
echo " 跳过: 版本低于 3.10"
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
if ! "$candidate" -c "import ssl" 2>/dev/null; then
|
||||||
|
echo " 跳过: 无 SSL(需在宝塔重装 Python 前先 yum install openssl-devel)"
|
||||||
|
continue
|
||||||
|
fi
|
||||||
|
PY="$candidate"
|
||||||
|
echo " -> 选用"
|
||||||
|
break 3
|
||||||
|
done
|
||||||
|
done
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ -z "$PY" ]; then
|
||||||
|
echo
|
||||||
|
echo "[错误] 未找到可用的宝塔 Python 3.10+(需带 SSL)。"
|
||||||
|
echo
|
||||||
|
echo "请在宝塔面板操作:"
|
||||||
|
echo " 1) 软件商店 -> Python项目管理器 -> 环境管理"
|
||||||
|
echo " 2) SSH 先执行: yum install -y openssl openssl-devel"
|
||||||
|
echo " 3) 环境管理 -> 安装 Python 3.11"
|
||||||
|
echo " 4) 重新运行本脚本"
|
||||||
|
echo
|
||||||
|
echo "若已安装但仍无 SSL,卸载该版本后重装。"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "[OK] 使用宝塔 Python: $PY"
|
||||||
|
"$PY" -c "import ssl; print('[OK] OpenSSL:', ssl.OPENSSL_VERSION)"
|
||||||
|
echo
|
||||||
|
|
||||||
|
export KEFU_PYTHON="$PY"
|
||||||
|
export PLAYWRIGHT_BROWSERS_PATH="${PLAYWRIGHT_BROWSERS_PATH:-$ROOT/playwright-browsers}"
|
||||||
|
|
||||||
|
echo "[1/4] 安装 Python 依赖..."
|
||||||
|
"$PY" -m pip install -U pip
|
||||||
|
"$PY" -m pip install -r "$BACKEND/requirements.txt"
|
||||||
|
echo
|
||||||
|
|
||||||
|
echo "[2/4] 创建项目 venv(可选,便于宝塔启动)..."
|
||||||
|
"$PY" -m venv "$BACKEND/.venv" --clear
|
||||||
|
"$BACKEND/.venv/bin/python" -m pip install -U pip -q
|
||||||
|
"$BACKEND/.venv/bin/pip" install -r "$BACKEND/requirements.txt"
|
||||||
|
chmod -R 755 "$BACKEND/.venv"
|
||||||
|
chown -R www:www "$BACKEND/.venv" 2>/dev/null || true
|
||||||
|
echo " venv: $BACKEND/.venv"
|
||||||
|
echo
|
||||||
|
|
||||||
|
echo "[3/4] Playwright Chromium..."
|
||||||
|
KEFU_PYTHON="$BACKEND/.venv/bin/python" bash "$BACKEND/baota_playwright.sh"
|
||||||
|
echo
|
||||||
|
|
||||||
|
echo "[4/4] 前端与 IM 依赖..."
|
||||||
|
if command -v npm &>/dev/null; then
|
||||||
|
cd "$BACKEND/rpa_engine/douyin_im/static" && npm install --no-fund --no-audit
|
||||||
|
cd "$ROOT/frontend" && npm install --no-fund --no-audit && npm run build
|
||||||
|
else
|
||||||
|
echo "[警告] 未安装 Node.js,请宝塔安装 Node 18+ 后手动 npm install"
|
||||||
|
fi
|
||||||
|
|
||||||
|
chown -R www:www "$ROOT" 2>/dev/null || true
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "========================================"
|
||||||
|
echo " 配置完成"
|
||||||
|
echo
|
||||||
|
echo " 宝塔 Python项目 设置:"
|
||||||
|
echo " 项目路径: $BACKEND"
|
||||||
|
echo " Python环境: 选环境管理里的 3.11"
|
||||||
|
echo " 启动命令: bash $BACKEND/baota_start.sh"
|
||||||
|
echo " 依赖包: $BACKEND/requirements.txt"
|
||||||
|
echo
|
||||||
|
echo " .env 添加:"
|
||||||
|
echo " PLAYWRIGHT_BROWSERS_PATH=$PLAYWRIGHT_BROWSERS_PATH"
|
||||||
|
echo "========================================"
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 318 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 296 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 2.6 KiB |
@@ -0,0 +1,116 @@
|
|||||||
|
"""桌面客户端在线升级:发布配置(存 AppConfig 行)+ 安装包文件管理。
|
||||||
|
|
||||||
|
发布配置以 JSON 形式存放在 app_config 表的 id=DESKTOP_CONFIG_ROW_ID 行,
|
||||||
|
安装包文件落在 backend/uploads/desktop/ 下。仅管理员可读写。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from dataclasses import asdict, dataclass, fields
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from models.models import AppConfig
|
||||||
|
|
||||||
|
# app_config 表里给桌面发布单独用一行(系统设置用的是 id=1)
|
||||||
|
DESKTOP_CONFIG_ROW_ID = 2
|
||||||
|
|
||||||
|
INSTALLER_DIR = os.path.join(os.path.dirname(__file__), "uploads", "desktop")
|
||||||
|
INSTALLER_FILENAME = "DouyinHostedDesktop-Setup.exe"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class DesktopReleaseData:
|
||||||
|
version: str = "" # 已发布的最新版本号,如 1.0.1
|
||||||
|
force: bool = False # true=强制升级(不可跳过)
|
||||||
|
notes: str = "" # 更新说明
|
||||||
|
installer_name: str = "" # 上传时的原始文件名
|
||||||
|
installer_size: int = 0 # 安装包字节数
|
||||||
|
installer_url: str = "" # 外部安装包直链(填写后优先于本地上传文件)
|
||||||
|
updated_at: str = "" # 最近一次发布/上传时间
|
||||||
|
|
||||||
|
|
||||||
|
def package_ready(data: "DesktopReleaseData") -> bool:
|
||||||
|
"""是否具备可供客户端下载的安装包:外部直链 或 本地已上传文件。"""
|
||||||
|
return bool((data.installer_url or "").strip()) or installer_exists()
|
||||||
|
|
||||||
|
|
||||||
|
def installer_path() -> str:
|
||||||
|
return os.path.join(INSTALLER_DIR, INSTALLER_FILENAME)
|
||||||
|
|
||||||
|
|
||||||
|
def installer_exists() -> bool:
|
||||||
|
p = installer_path()
|
||||||
|
return os.path.isfile(p) and os.path.getsize(p) > 0
|
||||||
|
|
||||||
|
|
||||||
|
def _coerce_bool(value: Any, default: bool) -> bool:
|
||||||
|
if isinstance(value, bool):
|
||||||
|
return value
|
||||||
|
if isinstance(value, str):
|
||||||
|
return value.lower() in ("1", "true", "yes", "on")
|
||||||
|
if value is None:
|
||||||
|
return default
|
||||||
|
return bool(value)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse(raw: dict[str, Any]) -> DesktopReleaseData:
|
||||||
|
base = DesktopReleaseData()
|
||||||
|
allowed = {f.name for f in fields(DesktopReleaseData)}
|
||||||
|
merged = {k: raw[k] for k in allowed if k in raw}
|
||||||
|
if "force" in merged:
|
||||||
|
merged["force"] = _coerce_bool(merged["force"], base.force)
|
||||||
|
if "installer_size" in merged:
|
||||||
|
try:
|
||||||
|
merged["installer_size"] = int(merged["installer_size"])
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
merged["installer_size"] = base.installer_size
|
||||||
|
return DesktopReleaseData(**{**asdict(base), **merged})
|
||||||
|
|
||||||
|
|
||||||
|
async def load_release(db: AsyncSession) -> DesktopReleaseData:
|
||||||
|
row = (
|
||||||
|
await db.execute(select(AppConfig).where(AppConfig.id == DESKTOP_CONFIG_ROW_ID))
|
||||||
|
).scalar_one_or_none()
|
||||||
|
if not row or not row.data:
|
||||||
|
return DesktopReleaseData()
|
||||||
|
try:
|
||||||
|
payload = json.loads(row.data)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
payload = {}
|
||||||
|
return _parse(payload if isinstance(payload, dict) else {})
|
||||||
|
|
||||||
|
|
||||||
|
async def save_release(db: AsyncSession, updates: dict[str, Any]) -> DesktopReleaseData:
|
||||||
|
current = await load_release(db)
|
||||||
|
merged = asdict(current)
|
||||||
|
for key, value in updates.items():
|
||||||
|
if key not in merged or value is None:
|
||||||
|
continue
|
||||||
|
merged[key] = value
|
||||||
|
data = _parse(merged)
|
||||||
|
data.updated_at = datetime.utcnow().isoformat()
|
||||||
|
|
||||||
|
row = (
|
||||||
|
await db.execute(select(AppConfig).where(AppConfig.id == DESKTOP_CONFIG_ROW_ID))
|
||||||
|
).scalar_one_or_none()
|
||||||
|
if not row:
|
||||||
|
row = AppConfig(id=DESKTOP_CONFIG_ROW_ID, data="{}", updated_at=datetime.utcnow())
|
||||||
|
db.add(row)
|
||||||
|
row.data = json.dumps(asdict(data), ensure_ascii=False)
|
||||||
|
row.updated_at = datetime.utcnow()
|
||||||
|
await db.commit()
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def remove_installer() -> None:
|
||||||
|
p = installer_path()
|
||||||
|
try:
|
||||||
|
if os.path.exists(p):
|
||||||
|
os.remove(p)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
"""桌面客户端在线升级接口。
|
||||||
|
|
||||||
|
公开接口(桌面客户端启动时调用,无需登录):
|
||||||
|
GET /api/desktop/latest 返回最新版本清单 {version,url,force,notes},无发布时返回 {}
|
||||||
|
GET /api/desktop/download 下载安装包
|
||||||
|
|
||||||
|
管理员接口(仅 admin):
|
||||||
|
GET /api/desktop/release 读取当前发布配置
|
||||||
|
PUT /api/desktop/release 修改版本号/强制升级/更新说明
|
||||||
|
POST /api/desktop/release/installer 上传安装包(.exe)
|
||||||
|
DELETE /api/desktop/release/installer 删除安装包(即停用在线升级)
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from auth.dependencies import require_admin
|
||||||
|
from auth.system_settings import get_cached_settings
|
||||||
|
from desktop_release import (
|
||||||
|
INSTALLER_DIR,
|
||||||
|
installer_exists,
|
||||||
|
installer_path,
|
||||||
|
load_release,
|
||||||
|
package_ready,
|
||||||
|
remove_installer,
|
||||||
|
save_release,
|
||||||
|
)
|
||||||
|
from models.database import get_db
|
||||||
|
from models.models import User
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/desktop", tags=["desktop-update"])
|
||||||
|
|
||||||
|
_MAX_INSTALLER_BYTES = 500 * 1024 * 1024 # 500MB 上限,足够覆盖安装包
|
||||||
|
|
||||||
|
|
||||||
|
class DesktopReleaseResponse(BaseModel):
|
||||||
|
version: str = ""
|
||||||
|
force: bool = False
|
||||||
|
notes: str = ""
|
||||||
|
installer_name: str = ""
|
||||||
|
installer_size: int = 0
|
||||||
|
installer_url: str = ""
|
||||||
|
updated_at: str = ""
|
||||||
|
has_installer: bool = False # 本地是否已上传安装包文件
|
||||||
|
package_ready: bool = False # 是否具备可下载安装包(外链或本地文件)
|
||||||
|
download_url: str = "" # 本地上传文件的下载地址
|
||||||
|
|
||||||
|
|
||||||
|
class DesktopReleaseUpdate(BaseModel):
|
||||||
|
version: str | None = Field(default=None, max_length=40)
|
||||||
|
force: bool | None = None
|
||||||
|
notes: str | None = Field(default=None, max_length=4000)
|
||||||
|
installer_url: str | None = Field(default=None, max_length=1000)
|
||||||
|
|
||||||
|
|
||||||
|
def _public_base(request: Request) -> str:
|
||||||
|
"""构造给客户端用的绝对地址:优先后台配置的 app_url,本地址兜底用请求来源。"""
|
||||||
|
try:
|
||||||
|
app_url = get_cached_settings().app_url_normalized()
|
||||||
|
except Exception:
|
||||||
|
app_url = ""
|
||||||
|
if not app_url or "localhost" in app_url or "127.0.0.1" in app_url:
|
||||||
|
app_url = str(request.base_url).rstrip("/")
|
||||||
|
return app_url
|
||||||
|
|
||||||
|
|
||||||
|
def _to_response(data, request: Request) -> DesktopReleaseResponse:
|
||||||
|
return DesktopReleaseResponse(
|
||||||
|
version=data.version,
|
||||||
|
force=data.force,
|
||||||
|
notes=data.notes,
|
||||||
|
installer_name=data.installer_name,
|
||||||
|
installer_size=data.installer_size,
|
||||||
|
installer_url=(data.installer_url or "").strip(),
|
||||||
|
updated_at=data.updated_at,
|
||||||
|
has_installer=installer_exists(),
|
||||||
|
package_ready=package_ready(data),
|
||||||
|
download_url=f"{_public_base(request)}/api/desktop/download",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 公开接口 ----------
|
||||||
|
|
||||||
|
@router.get("/latest")
|
||||||
|
async def desktop_latest(request: Request, db: AsyncSession = Depends(get_db)):
|
||||||
|
"""桌面客户端启动检查更新。未发布或安装包缺失时返回空对象。"""
|
||||||
|
data = await load_release(db)
|
||||||
|
if not data.version or not package_ready(data):
|
||||||
|
return {}
|
||||||
|
external = (data.installer_url or "").strip()
|
||||||
|
download_url = external or f"{_public_base(request)}/api/desktop/download"
|
||||||
|
return {
|
||||||
|
"version": data.version,
|
||||||
|
"url": download_url,
|
||||||
|
"force": bool(data.force),
|
||||||
|
"notes": data.notes or "",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/download")
|
||||||
|
async def desktop_download(db: AsyncSession = Depends(get_db)):
|
||||||
|
"""下载安装包。"""
|
||||||
|
if not installer_exists():
|
||||||
|
raise HTTPException(status_code=404, detail="安装包不存在")
|
||||||
|
return FileResponse(
|
||||||
|
installer_path(),
|
||||||
|
media_type="application/octet-stream",
|
||||||
|
filename="DouyinHostedDesktop-Setup.exe",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------- 管理员接口 ----------
|
||||||
|
|
||||||
|
@router.get("/release", response_model=DesktopReleaseResponse)
|
||||||
|
async def get_release(
|
||||||
|
request: Request,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_: User = Depends(require_admin),
|
||||||
|
):
|
||||||
|
data = await load_release(db)
|
||||||
|
return _to_response(data, request)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/release", response_model=DesktopReleaseResponse)
|
||||||
|
async def update_release(
|
||||||
|
body: DesktopReleaseUpdate,
|
||||||
|
request: Request,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_: User = Depends(require_admin),
|
||||||
|
):
|
||||||
|
updates = body.model_dump(exclude_unset=True)
|
||||||
|
if "version" in updates and updates["version"] is not None:
|
||||||
|
updates["version"] = updates["version"].strip()
|
||||||
|
if "notes" in updates and updates["notes"] is not None:
|
||||||
|
updates["notes"] = updates["notes"].strip()
|
||||||
|
if "installer_url" in updates and updates["installer_url"] is not None:
|
||||||
|
url = updates["installer_url"].strip()
|
||||||
|
if url and not url.lower().startswith(("http://", "https://")):
|
||||||
|
raise HTTPException(status_code=400, detail="安装包网址需以 http:// 或 https:// 开头")
|
||||||
|
updates["installer_url"] = url
|
||||||
|
data = await save_release(db, updates)
|
||||||
|
return _to_response(data, request)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/release/installer", response_model=DesktopReleaseResponse)
|
||||||
|
async def upload_installer(
|
||||||
|
request: Request,
|
||||||
|
file: UploadFile = File(...),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_: User = Depends(require_admin),
|
||||||
|
):
|
||||||
|
filename = (file.filename or "").strip()
|
||||||
|
if not filename.lower().endswith(".exe"):
|
||||||
|
raise HTTPException(status_code=400, detail="请上传 .exe 安装包")
|
||||||
|
|
||||||
|
os.makedirs(INSTALLER_DIR, exist_ok=True)
|
||||||
|
tmp_path = installer_path() + ".uploading"
|
||||||
|
size = 0
|
||||||
|
try:
|
||||||
|
with open(tmp_path, "wb") as f:
|
||||||
|
while True:
|
||||||
|
chunk = await file.read(1024 * 1024)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
size += len(chunk)
|
||||||
|
if size > _MAX_INSTALLER_BYTES:
|
||||||
|
raise HTTPException(status_code=400, detail="安装包超过 500MB 上限")
|
||||||
|
f.write(chunk)
|
||||||
|
except HTTPException:
|
||||||
|
if os.path.exists(tmp_path):
|
||||||
|
os.remove(tmp_path)
|
||||||
|
raise
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
if os.path.exists(tmp_path):
|
||||||
|
os.remove(tmp_path)
|
||||||
|
raise HTTPException(status_code=500, detail=f"保存安装包失败: {exc}") from exc
|
||||||
|
|
||||||
|
if size == 0:
|
||||||
|
if os.path.exists(tmp_path):
|
||||||
|
os.remove(tmp_path)
|
||||||
|
raise HTTPException(status_code=400, detail="安装包为空")
|
||||||
|
|
||||||
|
os.replace(tmp_path, installer_path())
|
||||||
|
data = await save_release(db, {"installer_name": filename, "installer_size": size})
|
||||||
|
return _to_response(data, request)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/release/installer", response_model=DesktopReleaseResponse)
|
||||||
|
async def delete_installer(
|
||||||
|
request: Request,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_: User = Depends(require_admin),
|
||||||
|
):
|
||||||
|
remove_installer()
|
||||||
|
data = await save_release(db, {"installer_name": "", "installer_size": 0})
|
||||||
|
return _to_response(data, request)
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"""帮助中心静态页面。"""
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
|
||||||
|
from settings import BACKEND_DIR, PROJECT_ROOT
|
||||||
|
|
||||||
|
HELP_STATIC_DIR = BACKEND_DIR / "static" / "help"
|
||||||
|
CREDENTIAL_TOOL_CANDIDATES = (
|
||||||
|
PROJECT_ROOT / "凭证采集工具.html",
|
||||||
|
HELP_STATIC_DIR / "credential-tool.html",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_credential_tool_html() -> Path:
|
||||||
|
for path in CREDENTIAL_TOOL_CANDIDATES:
|
||||||
|
if path.is_file():
|
||||||
|
return path
|
||||||
|
raise HTTPException(status_code=404, detail="凭证采集工具页面不存在")
|
||||||
|
|
||||||
|
|
||||||
|
def serve_credential_tool() -> FileResponse:
|
||||||
|
html_path = _resolve_credential_tool_html()
|
||||||
|
return FileResponse(
|
||||||
|
html_path,
|
||||||
|
media_type="text/html; charset=utf-8",
|
||||||
|
content_disposition_type="inline",
|
||||||
|
)
|
||||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 211 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 211 KiB |
@@ -0,0 +1,77 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# 共用:解析可用 Python(必须 3.10+ 且带 SSL,跳过宝塔坏环境)
|
||||||
|
_py_ok() {
|
||||||
|
local py="$1"
|
||||||
|
[ -n "$py" ] && [ -x "$py" ] || return 1
|
||||||
|
"$py" -c "import sys, ssl; sys.exit(0 if sys.version_info>=(3,10) else 1)" 2>/dev/null
|
||||||
|
}
|
||||||
|
|
||||||
|
resolve_python() {
|
||||||
|
local backend="${1:?}"
|
||||||
|
local root="${2:-$(cd "$backend/.." && pwd)}"
|
||||||
|
local py="" candidate ver_dir
|
||||||
|
|
||||||
|
# 不 source 宝塔环境,避免 PATH 被坏 Python 污染
|
||||||
|
local -a candidates=()
|
||||||
|
|
||||||
|
candidates+=("$backend/.venv/bin/python")
|
||||||
|
candidates+=("/usr/local/python3.11/bin/python3.11")
|
||||||
|
candidates+=("/usr/local/python3.10/bin/python3.10")
|
||||||
|
candidates+=("/usr/bin/python3.11")
|
||||||
|
candidates+=("/usr/bin/python3.10")
|
||||||
|
candidates+=("/usr/local/bin/python3.11")
|
||||||
|
candidates+=("/usr/local/bin/python3.10")
|
||||||
|
|
||||||
|
# 动态扫描宝塔 Python(不写死版本号)
|
||||||
|
for base in \
|
||||||
|
/home/www/server/pyporject_evn/versions \
|
||||||
|
/www/server/pyporject_evn/versions \
|
||||||
|
/www/server/panel/pyenv/versions; do
|
||||||
|
[ -d "$base" ] || continue
|
||||||
|
for ver_dir in $(ls -d "$base"/* 2>/dev/null | sort -V -r); do
|
||||||
|
for name in python3.11 python3.10 python3 python; do
|
||||||
|
candidates+=("$ver_dir/bin/$name")
|
||||||
|
done
|
||||||
|
done
|
||||||
|
done
|
||||||
|
|
||||||
|
candidates+=("$(command -v python3.11 2>/dev/null || true)")
|
||||||
|
candidates+=("$(command -v python3.10 2>/dev/null || true)")
|
||||||
|
candidates+=("$(command -v python3 2>/dev/null || true)")
|
||||||
|
candidates+=("$(command -v python 2>/dev/null || true)")
|
||||||
|
|
||||||
|
declare -A seen=()
|
||||||
|
for candidate in "${candidates[@]}"; do
|
||||||
|
[ -n "$candidate" ] || continue
|
||||||
|
[ -n "${seen[$candidate]:-}" ] && continue
|
||||||
|
seen[$candidate]=1
|
||||||
|
if _py_ok "$candidate"; then
|
||||||
|
py="$candidate"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ -z "$py" ]; then
|
||||||
|
echo "[错误] 未找到带 SSL 的 Python 3.10+。" >&2
|
||||||
|
echo " 宝塔当前 Python 缺 _ssl,请执行:" >&2
|
||||||
|
echo " AUTO_BUILD_PYTHON=1 bash $root/install.sh" >&2
|
||||||
|
echo " 然后: KEFU_PYTHON=/usr/local/python3.11/bin/python3.11 bash $backend/baota_fix.sh" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
echo "$py"
|
||||||
|
}
|
||||||
|
|
||||||
|
ensure_uvicorn() {
|
||||||
|
local py="${1:?}"
|
||||||
|
local backend="${2:?}"
|
||||||
|
if "$py" -c "import uvicorn" 2>/dev/null; then
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
if ! "$py" -c "import ssl" 2>/dev/null; then
|
||||||
|
echo "[错误] $py 无 SSL,无法 pip install" >&2
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
echo "[修复] 正在安装 Python 依赖..." >&2
|
||||||
|
"$py" -m pip install -U pip -q
|
||||||
|
"$py" -m pip install -r "$backend/requirements.txt"
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
"""链接卡片落地页:带 SEO meta 与自动跳转。"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import html
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
from io import BytesIO
|
||||||
|
from typing import Optional, TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from fastapi import Request
|
||||||
|
|
||||||
|
_SLUG_RE = re.compile(r"^[a-zA-Z0-9_-]{6,64}$")
|
||||||
|
|
||||||
|
FAVICON_SIZE = 32
|
||||||
|
COVER_SIZE = 256
|
||||||
|
FAVICON_MIME = "image/png"
|
||||||
|
|
||||||
|
|
||||||
|
def generate_slug() -> str:
|
||||||
|
return secrets.token_urlsafe(9).replace("-", "_").replace(".", "_")[:12]
|
||||||
|
|
||||||
|
|
||||||
|
def is_valid_slug(slug: str) -> bool:
|
||||||
|
return bool(_SLUG_RE.match(slug or ""))
|
||||||
|
|
||||||
|
|
||||||
|
def public_base_url(request: Optional["Request"] = None) -> str:
|
||||||
|
env = os.getenv("KEFU_PUBLIC_BASE_URL", "").strip().rstrip("/")
|
||||||
|
if env:
|
||||||
|
return env
|
||||||
|
if request is not None:
|
||||||
|
return str(request.base_url).rstrip("/")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def absolute_media_url(path: str, request: Optional["Request"] = None) -> str:
|
||||||
|
path = (path or "").strip()
|
||||||
|
if not path:
|
||||||
|
return ""
|
||||||
|
if path.startswith("http://") or path.startswith("https://"):
|
||||||
|
return path
|
||||||
|
base = public_base_url(request)
|
||||||
|
if not base:
|
||||||
|
return path
|
||||||
|
if not path.startswith("/"):
|
||||||
|
path = f"/{path}"
|
||||||
|
return f"{base}{path}"
|
||||||
|
|
||||||
|
|
||||||
|
def favicon_mime(image_path: str) -> str:
|
||||||
|
ext = (image_path or "").rsplit(".", 1)[-1].lower()
|
||||||
|
return {
|
||||||
|
"svg": "image/svg+xml",
|
||||||
|
"png": "image/png",
|
||||||
|
"gif": "image/gif",
|
||||||
|
"webp": "image/webp",
|
||||||
|
"jpg": "image/jpeg",
|
||||||
|
"jpeg": "image/jpeg",
|
||||||
|
"ico": "image/x-icon",
|
||||||
|
}.get(ext, FAVICON_MIME)
|
||||||
|
|
||||||
|
|
||||||
|
def favicon_path_for_cover(cover_path: str) -> str:
|
||||||
|
"""由封面路径推导同名 favicon 文件路径。"""
|
||||||
|
path = (cover_path or "").strip()
|
||||||
|
if not path:
|
||||||
|
return ""
|
||||||
|
if path.endswith(".favicon.png"):
|
||||||
|
return path
|
||||||
|
if path.endswith(".png"):
|
||||||
|
return f"{path[:-4]}.favicon.png"
|
||||||
|
base, _ = os.path.splitext(path)
|
||||||
|
return f"{base}.favicon.png"
|
||||||
|
|
||||||
|
|
||||||
|
def media_path_to_disk(upload_dir: str, media_path: str) -> str:
|
||||||
|
prefix = "/api/media/link-cards/"
|
||||||
|
path = (media_path or "").strip()
|
||||||
|
if not path.startswith(prefix):
|
||||||
|
return ""
|
||||||
|
rel = path[len(prefix) :].replace("/", os.sep)
|
||||||
|
return os.path.join(upload_dir, rel)
|
||||||
|
|
||||||
|
|
||||||
|
def process_card_upload(raw: bytes) -> tuple[bytes, bytes]:
|
||||||
|
"""将任意位图转为封面 PNG (256x256) 与 favicon PNG (32x32)。"""
|
||||||
|
if not raw:
|
||||||
|
raise ValueError("图片为空")
|
||||||
|
try:
|
||||||
|
from PIL import Image
|
||||||
|
except ImportError as exc:
|
||||||
|
raise RuntimeError("服务器未安装 Pillow,无法转换 favicon") from exc
|
||||||
|
|
||||||
|
try:
|
||||||
|
with Image.open(BytesIO(raw)) as img:
|
||||||
|
if getattr(img, "is_animated", False):
|
||||||
|
img.seek(0)
|
||||||
|
if img.mode not in ("RGB", "RGBA"):
|
||||||
|
img = img.convert("RGBA")
|
||||||
|
else:
|
||||||
|
img = img.copy()
|
||||||
|
|
||||||
|
width, height = img.size
|
||||||
|
if width < 1 or height < 1:
|
||||||
|
raise ValueError("图片尺寸无效")
|
||||||
|
|
||||||
|
side = min(width, height)
|
||||||
|
left = (width - side) // 2
|
||||||
|
top = (height - side) // 2
|
||||||
|
square = img.crop((left, top, left + side, top + side))
|
||||||
|
|
||||||
|
resample = Image.Resampling.LANCZOS
|
||||||
|
cover = square.resize((COVER_SIZE, COVER_SIZE), resample)
|
||||||
|
favicon = square.resize((FAVICON_SIZE, FAVICON_SIZE), resample)
|
||||||
|
|
||||||
|
cover_buf = BytesIO()
|
||||||
|
cover.save(cover_buf, format="PNG", optimize=True)
|
||||||
|
favicon_buf = BytesIO()
|
||||||
|
favicon.save(favicon_buf, format="PNG", optimize=True)
|
||||||
|
return cover_buf.getvalue(), favicon_buf.getvalue()
|
||||||
|
except ValueError:
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
raise ValueError("无法识别图片格式,请上传 JPG、PNG、GIF 或 WebP") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_target_url(url: str) -> str:
|
||||||
|
url = (url or "").strip()
|
||||||
|
if not url:
|
||||||
|
return ""
|
||||||
|
if not url.startswith("http://") and not url.startswith("https://"):
|
||||||
|
url = f"https://{url}"
|
||||||
|
return url
|
||||||
|
|
||||||
|
|
||||||
|
def build_keywords(title: str, content: str) -> str:
|
||||||
|
parts = [p.strip() for p in (title, content) if p and p.strip()]
|
||||||
|
return ", ".join(dict.fromkeys(parts))
|
||||||
|
|
||||||
|
|
||||||
|
def render_link_card_page(
|
||||||
|
*,
|
||||||
|
title: str,
|
||||||
|
content: str,
|
||||||
|
keywords: str,
|
||||||
|
cover_url: str,
|
||||||
|
favicon_url: str,
|
||||||
|
target_url: str,
|
||||||
|
) -> str:
|
||||||
|
safe_title = html.escape(title or "跳转中")
|
||||||
|
safe_desc = html.escape(content or title or "")
|
||||||
|
safe_keywords = html.escape(keywords or build_keywords(title, content))
|
||||||
|
safe_cover = html.escape(cover_url or "")
|
||||||
|
safe_favicon = html.escape(favicon_url or cover_url or "")
|
||||||
|
redirect_url = normalize_target_url(target_url)
|
||||||
|
safe_target = html.escape(redirect_url)
|
||||||
|
js_target = json.dumps(redirect_url, ensure_ascii=False)
|
||||||
|
|
||||||
|
favicon_tag = ""
|
||||||
|
og_image_tag = ""
|
||||||
|
if safe_favicon:
|
||||||
|
favicon_tag = f' <link rel="icon" type="{FAVICON_MIME}" href="{safe_favicon}" />\n'
|
||||||
|
if safe_cover:
|
||||||
|
og_image_tag = f' <meta property="og:image" content="{safe_cover}" />\n'
|
||||||
|
|
||||||
|
return f"""<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<title>{safe_title}</title>
|
||||||
|
<meta name="description" content="{safe_desc}" />
|
||||||
|
<meta name="keywords" content="{safe_keywords}" />
|
||||||
|
<meta property="og:title" content="{safe_title}" />
|
||||||
|
<meta property="og:description" content="{safe_desc}" />
|
||||||
|
{og_image_tag}{favicon_tag} <meta http-equiv="refresh" content="0;url={safe_target}" />
|
||||||
|
<script>location.replace({js_target});</script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<p>正在跳转到目标页面…</p>
|
||||||
|
<p><a href="{safe_target}">若未自动跳转,请点击这里</a></p>
|
||||||
|
</body>
|
||||||
|
</html>"""
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
"""链接卡片 API 与公开落地页。"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, File, HTTPException, Request, UploadFile
|
||||||
|
from fastapi.responses import HTMLResponse
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from auth.dependencies import get_current_user, require_write
|
||||||
|
from link_cards import (
|
||||||
|
absolute_media_url,
|
||||||
|
build_keywords,
|
||||||
|
favicon_path_for_cover,
|
||||||
|
generate_slug,
|
||||||
|
is_valid_slug,
|
||||||
|
media_path_to_disk,
|
||||||
|
normalize_target_url,
|
||||||
|
process_card_upload,
|
||||||
|
public_base_url,
|
||||||
|
render_link_card_page,
|
||||||
|
)
|
||||||
|
from models.database import get_db
|
||||||
|
from models.models import LinkCardPage, User
|
||||||
|
|
||||||
|
router = APIRouter(tags=["link-cards"])
|
||||||
|
|
||||||
|
UPLOAD_DIR = os.path.join(os.path.dirname(__file__), "uploads", "link-cards")
|
||||||
|
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
class LinkCardUpsert(BaseModel):
|
||||||
|
id: Optional[int] = None
|
||||||
|
title: str = Field(..., min_length=1, max_length=200)
|
||||||
|
content: str = Field(default="", max_length=2000)
|
||||||
|
target_url: str = Field(..., min_length=1, max_length=2000)
|
||||||
|
image_path: str = Field(..., min_length=1, max_length=512)
|
||||||
|
|
||||||
|
|
||||||
|
class LinkCardResponse(BaseModel):
|
||||||
|
id: int
|
||||||
|
slug: str
|
||||||
|
title: str
|
||||||
|
content: str
|
||||||
|
target_url: str
|
||||||
|
image_path: str
|
||||||
|
page_url: str
|
||||||
|
cover_url: str
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class UploadImageResponse(BaseModel):
|
||||||
|
image_path: str
|
||||||
|
cover_url: str
|
||||||
|
|
||||||
|
|
||||||
|
async def _get_owned_card(
|
||||||
|
db: AsyncSession, user: User, card_id: int, *, write: bool = False
|
||||||
|
) -> LinkCardPage:
|
||||||
|
stmt = select(LinkCardPage).where(LinkCardPage.id == card_id)
|
||||||
|
card = (await db.execute(stmt)).scalar_one_or_none()
|
||||||
|
if not card or card.owner_id != user.id:
|
||||||
|
raise HTTPException(status_code=404, detail="卡片不存在")
|
||||||
|
if write and user.role == "viewer":
|
||||||
|
raise HTTPException(status_code=403, detail="无写入权限")
|
||||||
|
return card
|
||||||
|
|
||||||
|
|
||||||
|
def _card_response(card: LinkCardPage, request: Request) -> LinkCardResponse:
|
||||||
|
base = public_base_url(request)
|
||||||
|
page_url = f"{base}/p/{card.slug}" if base else f"/p/{card.slug}"
|
||||||
|
cover_url = absolute_media_url(card.image_path, request)
|
||||||
|
return LinkCardResponse(
|
||||||
|
id=card.id,
|
||||||
|
slug=card.slug,
|
||||||
|
title=card.title,
|
||||||
|
content=card.content or "",
|
||||||
|
target_url=card.target_url,
|
||||||
|
image_path=card.image_path,
|
||||||
|
page_url=page_url,
|
||||||
|
cover_url=cover_url,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/link-cards/upload-image", response_model=UploadImageResponse)
|
||||||
|
async def upload_link_card_image(
|
||||||
|
request: Request,
|
||||||
|
file: UploadFile = File(...),
|
||||||
|
user: User = Depends(require_write),
|
||||||
|
):
|
||||||
|
if not file.content_type or not file.content_type.startswith("image/"):
|
||||||
|
raise HTTPException(status_code=400, detail="仅支持上传图片文件")
|
||||||
|
if file.content_type == "image/svg+xml":
|
||||||
|
raise HTTPException(status_code=400, detail="请上传 JPG/PNG 等位图,系统将自动转为 favicon PNG")
|
||||||
|
|
||||||
|
raw = await file.read()
|
||||||
|
if not raw:
|
||||||
|
raise HTTPException(status_code=400, detail="图片为空")
|
||||||
|
if len(raw) > 4 * 1024 * 1024:
|
||||||
|
raise HTTPException(status_code=400, detail="图片大小不能超过 4MB")
|
||||||
|
|
||||||
|
try:
|
||||||
|
cover_bytes, favicon_bytes = process_card_upload(raw)
|
||||||
|
except RuntimeError as exc:
|
||||||
|
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
owner_dir = os.path.join(UPLOAD_DIR, str(user.id))
|
||||||
|
os.makedirs(owner_dir, exist_ok=True)
|
||||||
|
file_id = uuid.uuid4().hex
|
||||||
|
cover_filename = f"{file_id}.png"
|
||||||
|
favicon_filename = f"{file_id}.favicon.png"
|
||||||
|
cover_path = os.path.join(owner_dir, cover_filename)
|
||||||
|
favicon_path = os.path.join(owner_dir, favicon_filename)
|
||||||
|
with open(cover_path, "wb") as f:
|
||||||
|
f.write(cover_bytes)
|
||||||
|
with open(favicon_path, "wb") as f:
|
||||||
|
f.write(favicon_bytes)
|
||||||
|
|
||||||
|
image_path = f"/api/media/link-cards/{user.id}/{cover_filename}"
|
||||||
|
return UploadImageResponse(
|
||||||
|
image_path=image_path,
|
||||||
|
cover_url=absolute_media_url(image_path, request),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/api/link-cards", response_model=LinkCardResponse)
|
||||||
|
async def upsert_link_card(
|
||||||
|
body: LinkCardUpsert,
|
||||||
|
request: Request,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
user: User = Depends(require_write),
|
||||||
|
):
|
||||||
|
title = body.title.strip()
|
||||||
|
content = (body.content or "").strip()
|
||||||
|
target_url = normalize_target_url(body.target_url)
|
||||||
|
image_path = (body.image_path or "").strip()
|
||||||
|
|
||||||
|
if not title:
|
||||||
|
raise HTTPException(status_code=400, detail="请填写卡片标题")
|
||||||
|
if not target_url:
|
||||||
|
raise HTTPException(status_code=400, detail="请填写跳转链接")
|
||||||
|
if not image_path.startswith("/api/media/link-cards/"):
|
||||||
|
raise HTTPException(status_code=400, detail="请先上传卡片封面图")
|
||||||
|
|
||||||
|
if body.id:
|
||||||
|
card = await _get_owned_card(db, user, body.id, write=True)
|
||||||
|
card.title = title
|
||||||
|
card.content = content
|
||||||
|
card.target_url = target_url
|
||||||
|
card.image_path = image_path
|
||||||
|
card.updated_at = datetime.utcnow()
|
||||||
|
else:
|
||||||
|
slug = generate_slug()
|
||||||
|
for _ in range(5):
|
||||||
|
exists = (
|
||||||
|
await db.execute(select(LinkCardPage.id).where(LinkCardPage.slug == slug))
|
||||||
|
).scalar_one_or_none()
|
||||||
|
if not exists:
|
||||||
|
break
|
||||||
|
slug = generate_slug()
|
||||||
|
else:
|
||||||
|
raise HTTPException(status_code=500, detail="生成页面标识失败,请重试")
|
||||||
|
|
||||||
|
card = LinkCardPage(
|
||||||
|
owner_id=user.id,
|
||||||
|
slug=slug,
|
||||||
|
title=title,
|
||||||
|
content=content,
|
||||||
|
target_url=target_url,
|
||||||
|
image_path=image_path,
|
||||||
|
)
|
||||||
|
db.add(card)
|
||||||
|
|
||||||
|
await db.commit()
|
||||||
|
await db.refresh(card)
|
||||||
|
return _card_response(card, request)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/p/{slug}", response_class=HTMLResponse, include_in_schema=False)
|
||||||
|
async def serve_link_card_page(slug: str, request: Request, db: AsyncSession = Depends(get_db)):
|
||||||
|
if not is_valid_slug(slug):
|
||||||
|
raise HTTPException(status_code=404, detail="页面不存在")
|
||||||
|
|
||||||
|
stmt = select(LinkCardPage).where(LinkCardPage.slug == slug)
|
||||||
|
card = (await db.execute(stmt)).scalar_one_or_none()
|
||||||
|
if not card:
|
||||||
|
raise HTTPException(status_code=404, detail="页面不存在")
|
||||||
|
|
||||||
|
cover_url = absolute_media_url(card.image_path, request)
|
||||||
|
favicon_path = favicon_path_for_cover(card.image_path)
|
||||||
|
favicon_disk = media_path_to_disk(UPLOAD_DIR, favicon_path)
|
||||||
|
favicon_url = absolute_media_url(favicon_path, request) if favicon_disk and os.path.isfile(favicon_disk) else cover_url
|
||||||
|
html = render_link_card_page(
|
||||||
|
title=card.title,
|
||||||
|
content=card.content or "",
|
||||||
|
keywords=build_keywords(card.title, card.content or ""),
|
||||||
|
cover_url=cover_url,
|
||||||
|
favicon_url=favicon_url,
|
||||||
|
target_url=card.target_url,
|
||||||
|
)
|
||||||
|
return HTMLResponse(content=html, media_type="text/html; charset=utf-8")
|
||||||
+2425
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,28 @@
|
|||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
from sqlalchemy.orm import declarative_base, sessionmaker
|
||||||
|
|
||||||
|
from models.db_config import (
|
||||||
|
build_database_url,
|
||||||
|
create_database_engine,
|
||||||
|
read_database_config,
|
||||||
|
)
|
||||||
|
|
||||||
|
_config = read_database_config()
|
||||||
|
DATABASE_URL = build_database_url(_config)
|
||||||
|
engine = create_database_engine(_config)
|
||||||
|
AsyncSessionLocal = sessionmaker(
|
||||||
|
engine, class_=AsyncSession, expire_on_commit=False
|
||||||
|
)
|
||||||
|
Base = declarative_base()
|
||||||
|
|
||||||
|
|
||||||
|
async def get_db():
|
||||||
|
async with AsyncSessionLocal() as session:
|
||||||
|
try:
|
||||||
|
yield session
|
||||||
|
await session.commit()
|
||||||
|
except Exception:
|
||||||
|
await session.rollback()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
await session.close()
|
||||||
@@ -0,0 +1,252 @@
|
|||||||
|
"""数据库连接配置:支持 SQLite / MySQL / PostgreSQL。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
from urllib.parse import quote_plus
|
||||||
|
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
from sqlalchemy import text
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
|
||||||
|
|
||||||
|
BACKEND_DIR = Path(__file__).resolve().parent.parent
|
||||||
|
PROJECT_ROOT = BACKEND_DIR.parent
|
||||||
|
ENV_FILE = PROJECT_ROOT / ".env"
|
||||||
|
|
||||||
|
load_dotenv(ENV_FILE)
|
||||||
|
|
||||||
|
SUPPORTED_DB_TYPES = ("sqlite", "mysql", "postgresql")
|
||||||
|
PASSWORD_PLACEHOLDER = "******"
|
||||||
|
DEFAULT_SQLITE_PATH = BACKEND_DIR / "kefu.db"
|
||||||
|
|
||||||
|
|
||||||
|
def _env(name: str, default: str = "") -> str:
|
||||||
|
return (os.getenv(name) or default).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _env_int(name: str, default: int) -> int:
|
||||||
|
raw = _env(name)
|
||||||
|
if not raw:
|
||||||
|
return default
|
||||||
|
try:
|
||||||
|
return int(raw)
|
||||||
|
except ValueError:
|
||||||
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_db_type(value: str | None) -> str:
|
||||||
|
raw = (value or "sqlite").strip().lower()
|
||||||
|
if raw in ("postgres", "pgsql"):
|
||||||
|
return "postgresql"
|
||||||
|
if raw in SUPPORTED_DB_TYPES:
|
||||||
|
return raw
|
||||||
|
return "sqlite"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class DatabaseConfig:
|
||||||
|
db_type: str = "sqlite"
|
||||||
|
db_host: str = "127.0.0.1"
|
||||||
|
db_port: int = 0
|
||||||
|
db_user: str = ""
|
||||||
|
db_password: str = ""
|
||||||
|
db_name: str = "kefu"
|
||||||
|
db_path: str = ""
|
||||||
|
database_url: str = ""
|
||||||
|
|
||||||
|
def normalized_type(self) -> str:
|
||||||
|
return normalize_db_type(self.db_type)
|
||||||
|
|
||||||
|
def resolved_port(self) -> int:
|
||||||
|
if self.db_port:
|
||||||
|
return self.db_port
|
||||||
|
if self.normalized_type() == "mysql":
|
||||||
|
return 3306
|
||||||
|
if self.normalized_type() == "postgresql":
|
||||||
|
return 5432
|
||||||
|
return 0
|
||||||
|
|
||||||
|
def sqlite_path(self) -> Path:
|
||||||
|
if self.db_path:
|
||||||
|
path = Path(self.db_path)
|
||||||
|
if not path.is_absolute():
|
||||||
|
path = BACKEND_DIR / path
|
||||||
|
return path
|
||||||
|
if self.database_url and self.database_url.startswith("sqlite"):
|
||||||
|
# sqlite+aiosqlite:///path
|
||||||
|
raw = self.database_url.split("///", 1)[-1]
|
||||||
|
return Path(raw)
|
||||||
|
return DEFAULT_SQLITE_PATH
|
||||||
|
|
||||||
|
|
||||||
|
def read_database_config() -> DatabaseConfig:
|
||||||
|
explicit_url = _env("KEFU_DATABASE_URL")
|
||||||
|
db_type = normalize_db_type(_env("KEFU_DB_TYPE", "sqlite"))
|
||||||
|
db_path = _env("KEFU_DB_PATH")
|
||||||
|
if explicit_url and not _env("KEFU_DB_TYPE"):
|
||||||
|
lowered = explicit_url.lower()
|
||||||
|
if lowered.startswith("mysql"):
|
||||||
|
db_type = "mysql"
|
||||||
|
elif lowered.startswith("postgresql") or lowered.startswith("postgres"):
|
||||||
|
db_type = "postgresql"
|
||||||
|
elif lowered.startswith("sqlite"):
|
||||||
|
db_type = "sqlite"
|
||||||
|
return DatabaseConfig(
|
||||||
|
db_type=db_type,
|
||||||
|
db_host=_env("KEFU_DB_HOST", "127.0.0.1"),
|
||||||
|
db_port=_env_int("KEFU_DB_PORT", 0),
|
||||||
|
db_user=_env("KEFU_DB_USER"),
|
||||||
|
db_password=_env("KEFU_DB_PASSWORD"),
|
||||||
|
db_name=_env("KEFU_DB_NAME", "kefu"),
|
||||||
|
db_path=db_path,
|
||||||
|
database_url=explicit_url,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def build_database_url(config: DatabaseConfig | None = None) -> str:
|
||||||
|
cfg = config or read_database_config()
|
||||||
|
if cfg.database_url:
|
||||||
|
return cfg.database_url
|
||||||
|
|
||||||
|
db_type = cfg.normalized_type()
|
||||||
|
if db_type == "sqlite":
|
||||||
|
path = cfg.sqlite_path()
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
return f"sqlite+aiosqlite:///{path.as_posix()}"
|
||||||
|
|
||||||
|
user = quote_plus(cfg.db_user or "")
|
||||||
|
password = quote_plus(cfg.db_password or "")
|
||||||
|
host = cfg.db_host or "127.0.0.1"
|
||||||
|
port = cfg.resolved_port()
|
||||||
|
db_name = cfg.db_name or "kefu"
|
||||||
|
|
||||||
|
if db_type == "mysql":
|
||||||
|
auth = f"{user}:{password}@" if user else ""
|
||||||
|
return (
|
||||||
|
f"mysql+asyncmy://{auth}{host}:{port}/{db_name}"
|
||||||
|
"?charset=utf8mb4"
|
||||||
|
)
|
||||||
|
|
||||||
|
auth = f"{user}:{password}@" if user else ""
|
||||||
|
return f"postgresql+asyncpg://{auth}{host}:{port}/{db_name}"
|
||||||
|
|
||||||
|
|
||||||
|
def engine_kwargs_for_url(url: str) -> dict[str, Any]:
|
||||||
|
kwargs: dict[str, Any] = {"echo": False}
|
||||||
|
if not url.startswith("sqlite"):
|
||||||
|
kwargs["pool_pre_ping"] = True
|
||||||
|
kwargs["pool_recycle"] = 3600
|
||||||
|
# 默认连接池仅 pool_size=5 + max_overflow=10。多账号托管 + 前端并发请求时
|
||||||
|
# 容易耗尽连接导致请求阻塞/失败,这里放大连接池(可用环境变量覆盖)。
|
||||||
|
try:
|
||||||
|
_pool = int(os.getenv("KEFU_DB_POOL_SIZE", "20") or 20)
|
||||||
|
except ValueError:
|
||||||
|
_pool = 20
|
||||||
|
try:
|
||||||
|
_overflow = int(os.getenv("KEFU_DB_MAX_OVERFLOW", "40") or 40)
|
||||||
|
except ValueError:
|
||||||
|
_overflow = 40
|
||||||
|
kwargs["pool_size"] = max(5, _pool)
|
||||||
|
kwargs["max_overflow"] = max(0, _overflow)
|
||||||
|
kwargs["pool_timeout"] = 30
|
||||||
|
return kwargs
|
||||||
|
|
||||||
|
|
||||||
|
def create_database_engine(config: DatabaseConfig | None = None) -> AsyncEngine:
|
||||||
|
url = build_database_url(config)
|
||||||
|
return create_async_engine(url, **engine_kwargs_for_url(url))
|
||||||
|
|
||||||
|
|
||||||
|
def mask_database_url(url: str) -> str:
|
||||||
|
if "@" not in url or "://" not in url:
|
||||||
|
return url
|
||||||
|
scheme, rest = url.split("://", 1)
|
||||||
|
if "@" not in rest:
|
||||||
|
return url
|
||||||
|
creds, host_part = rest.rsplit("@", 1)
|
||||||
|
if ":" in creds:
|
||||||
|
user = creds.split(":", 1)[0]
|
||||||
|
return f"{scheme}://{user}:{PASSWORD_PLACEHOLDER}@{host_part}"
|
||||||
|
return f"{scheme}://{PASSWORD_PLACEHOLDER}@{host_part}"
|
||||||
|
|
||||||
|
|
||||||
|
def database_config_to_response(cfg: DatabaseConfig | None = None) -> dict[str, Any]:
|
||||||
|
cfg = cfg or read_database_config()
|
||||||
|
url = build_database_url(cfg)
|
||||||
|
return {
|
||||||
|
"db_type": cfg.normalized_type(),
|
||||||
|
"db_host": cfg.db_host,
|
||||||
|
"db_port": cfg.resolved_port(),
|
||||||
|
"db_user": cfg.db_user,
|
||||||
|
"db_name": cfg.db_name,
|
||||||
|
"db_path": str(cfg.sqlite_path()) if cfg.normalized_type() == "sqlite" else "",
|
||||||
|
"db_password": PASSWORD_PLACEHOLDER if cfg.db_password else "",
|
||||||
|
"db_password_configured": bool(cfg.db_password),
|
||||||
|
"database_url_display": mask_database_url(url),
|
||||||
|
"supported_types": list(SUPPORTED_DB_TYPES),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def persist_database_config(payload: dict[str, Any]) -> None:
|
||||||
|
"""将数据库配置写入项目根 .env 文件。"""
|
||||||
|
from dotenv import set_key
|
||||||
|
|
||||||
|
if not ENV_FILE.exists():
|
||||||
|
ENV_FILE.write_text("", encoding="utf-8")
|
||||||
|
|
||||||
|
db_type = normalize_db_type(payload.get("db_type"))
|
||||||
|
env_map = {
|
||||||
|
"KEFU_DB_TYPE": db_type,
|
||||||
|
"KEFU_DB_HOST": (payload.get("db_host") or "127.0.0.1").strip(),
|
||||||
|
"KEFU_DB_PORT": str(payload.get("db_port") or ""),
|
||||||
|
"KEFU_DB_USER": (payload.get("db_user") or "").strip(),
|
||||||
|
"KEFU_DB_NAME": (payload.get("db_name") or "kefu").strip(),
|
||||||
|
"KEFU_DB_PATH": (payload.get("db_path") or "").strip(),
|
||||||
|
}
|
||||||
|
|
||||||
|
password = payload.get("db_password")
|
||||||
|
if password and str(password).strip() not in ("", PASSWORD_PLACEHOLDER):
|
||||||
|
env_map["KEFU_DB_PASSWORD"] = str(password).strip()
|
||||||
|
|
||||||
|
# 清除完整 URL,避免与分项配置冲突
|
||||||
|
set_key(str(ENV_FILE), "KEFU_DATABASE_URL", "")
|
||||||
|
|
||||||
|
for key, value in env_map.items():
|
||||||
|
set_key(str(ENV_FILE), key, value or "")
|
||||||
|
|
||||||
|
# 让当前进程也能读到新值(重启后才会重建 engine)
|
||||||
|
for key, value in env_map.items():
|
||||||
|
os.environ[key] = value or ""
|
||||||
|
os.environ.pop("KEFU_DATABASE_URL", None)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_database_connection(payload: dict[str, Any]) -> None:
|
||||||
|
cfg = DatabaseConfig(
|
||||||
|
db_type=normalize_db_type(payload.get("db_type")),
|
||||||
|
db_host=(payload.get("db_host") or "127.0.0.1").strip(),
|
||||||
|
db_port=int(payload.get("db_port") or 0),
|
||||||
|
db_user=(payload.get("db_user") or "").strip(),
|
||||||
|
db_password=(payload.get("db_password") or "").strip(),
|
||||||
|
db_name=(payload.get("db_name") or "kefu").strip(),
|
||||||
|
db_path=(payload.get("db_path") or "").strip(),
|
||||||
|
)
|
||||||
|
|
||||||
|
current = read_database_config()
|
||||||
|
if cfg.db_password in ("", PASSWORD_PLACEHOLDER):
|
||||||
|
cfg.db_password = current.db_password
|
||||||
|
|
||||||
|
url = build_database_url(cfg)
|
||||||
|
engine = create_async_engine(url, **engine_kwargs_for_url(url))
|
||||||
|
try:
|
||||||
|
async with engine.connect() as conn:
|
||||||
|
await conn.execute(text("SELECT 1"))
|
||||||
|
except ModuleNotFoundError as exc:
|
||||||
|
driver = "asyncmy" if cfg.normalized_type() == "mysql" else "asyncpg"
|
||||||
|
raise RuntimeError(
|
||||||
|
f"缺少数据库驱动,请执行: pip install {driver}"
|
||||||
|
) from exc
|
||||||
|
finally:
|
||||||
|
await engine.dispose()
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
"""跨数据库兼容的轻量 schema 迁移。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from sqlalchemy import inspect, text
|
||||||
|
|
||||||
|
|
||||||
|
def _table_columns(conn, table: str) -> set[str]:
|
||||||
|
try:
|
||||||
|
insp = inspect(conn)
|
||||||
|
return {col["name"] for col in insp.get_columns(table)}
|
||||||
|
except Exception:
|
||||||
|
return set()
|
||||||
|
|
||||||
|
|
||||||
|
def _dialect(conn) -> str:
|
||||||
|
return conn.dialect.name
|
||||||
|
|
||||||
|
|
||||||
|
def _bool_default(conn, value: bool = True) -> str:
|
||||||
|
if _dialect(conn) == "postgresql":
|
||||||
|
return "TRUE" if value else "FALSE"
|
||||||
|
return "1" if value else "0"
|
||||||
|
|
||||||
|
|
||||||
|
def add_column_if_missing(conn, table: str, column: str, ddl_by_dialect: dict[str, str]) -> None:
|
||||||
|
cols = _table_columns(conn, table)
|
||||||
|
if not cols or column in cols:
|
||||||
|
return
|
||||||
|
dialect = _dialect(conn)
|
||||||
|
ddl = ddl_by_dialect.get(dialect) or ddl_by_dialect.get("default")
|
||||||
|
if ddl:
|
||||||
|
conn.execute(text(ddl))
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_accounts_table(conn) -> None:
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"accounts",
|
||||||
|
"cookie_data",
|
||||||
|
{"default": "ALTER TABLE accounts ADD COLUMN cookie_data TEXT"},
|
||||||
|
)
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"accounts",
|
||||||
|
"cookie_updated_at",
|
||||||
|
{
|
||||||
|
"default": "ALTER TABLE accounts ADD COLUMN cookie_updated_at DATETIME",
|
||||||
|
"postgresql": "ALTER TABLE accounts ADD COLUMN cookie_updated_at TIMESTAMP",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"accounts",
|
||||||
|
"im_session_data",
|
||||||
|
{"default": "ALTER TABLE accounts ADD COLUMN im_session_data TEXT"},
|
||||||
|
)
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"accounts",
|
||||||
|
"reply_delay_seconds",
|
||||||
|
{"default": "ALTER TABLE accounts ADD COLUMN reply_delay_seconds INTEGER DEFAULT 0"},
|
||||||
|
)
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"accounts",
|
||||||
|
"reply_cooldown_seconds",
|
||||||
|
{"default": "ALTER TABLE accounts ADD COLUMN reply_cooldown_seconds INTEGER"},
|
||||||
|
)
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"accounts",
|
||||||
|
"follow_welcome_enabled",
|
||||||
|
{
|
||||||
|
"default": "ALTER TABLE accounts ADD COLUMN follow_welcome_enabled BOOLEAN DEFAULT 0",
|
||||||
|
"postgresql": "ALTER TABLE accounts ADD COLUMN follow_welcome_enabled BOOLEAN DEFAULT FALSE",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"accounts",
|
||||||
|
"follow_welcome_content",
|
||||||
|
{"default": "ALTER TABLE accounts ADD COLUMN follow_welcome_content TEXT"},
|
||||||
|
)
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"accounts",
|
||||||
|
"owner_id",
|
||||||
|
{"default": "ALTER TABLE accounts ADD COLUMN owner_id INTEGER"},
|
||||||
|
)
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"accounts",
|
||||||
|
"user_agent",
|
||||||
|
{"default": "ALTER TABLE accounts ADD COLUMN user_agent TEXT"},
|
||||||
|
)
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"accounts",
|
||||||
|
"avatar_url",
|
||||||
|
{"default": "ALTER TABLE accounts ADD COLUMN avatar_url TEXT"},
|
||||||
|
)
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"accounts",
|
||||||
|
"douyin_uid",
|
||||||
|
{"default": "ALTER TABLE accounts ADD COLUMN douyin_uid VARCHAR(64)"},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_account_videos_table(conn) -> None:
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"account_videos",
|
||||||
|
"media_type",
|
||||||
|
{"default": "ALTER TABLE account_videos ADD COLUMN media_type VARCHAR(20)"},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_message_logs_table(conn) -> None:
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"message_logs",
|
||||||
|
"sender_avatar",
|
||||||
|
{"default": "ALTER TABLE message_logs ADD COLUMN sender_avatar TEXT"},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_rules_table(conn) -> None:
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"rules",
|
||||||
|
"owner_id",
|
||||||
|
{"default": "ALTER TABLE rules ADD COLUMN owner_id INTEGER"},
|
||||||
|
)
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"rules",
|
||||||
|
"sort_order",
|
||||||
|
{"default": "ALTER TABLE rules ADD COLUMN sort_order INTEGER DEFAULT 0"},
|
||||||
|
)
|
||||||
|
cols = _table_columns(conn, "rules")
|
||||||
|
if cols and "sort_order" in cols:
|
||||||
|
conn.execute(
|
||||||
|
text("UPDATE rules SET sort_order = id WHERE sort_order IS NULL OR sort_order = 0")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_users_table(conn) -> None:
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"users",
|
||||||
|
"email",
|
||||||
|
{"default": "ALTER TABLE users ADD COLUMN email VARCHAR(255)"},
|
||||||
|
)
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"users",
|
||||||
|
"email_verified",
|
||||||
|
{
|
||||||
|
"default": "ALTER TABLE users ADD COLUMN email_verified BOOLEAN DEFAULT 0",
|
||||||
|
"postgresql": "ALTER TABLE users ADD COLUMN email_verified BOOLEAN DEFAULT FALSE",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"users",
|
||||||
|
"email_verified_at",
|
||||||
|
{
|
||||||
|
"default": "ALTER TABLE users ADD COLUMN email_verified_at DATETIME",
|
||||||
|
"postgresql": "ALTER TABLE users ADD COLUMN email_verified_at TIMESTAMP",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"users",
|
||||||
|
"max_accounts",
|
||||||
|
{"default": "ALTER TABLE users ADD COLUMN max_accounts INTEGER DEFAULT 3"},
|
||||||
|
)
|
||||||
|
cols = _table_columns(conn, "users")
|
||||||
|
if not cols:
|
||||||
|
return
|
||||||
|
verified = _bool_default(conn, True)
|
||||||
|
conn.execute(text(f"UPDATE users SET email_verified = {verified} WHERE email_verified IS NULL"))
|
||||||
|
conn.execute(text("UPDATE users SET max_accounts = -1 WHERE role = 'admin'"))
|
||||||
|
conn.execute(text("UPDATE users SET max_accounts = 3 WHERE max_accounts IS NULL"))
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_payment_orders_table(conn) -> None:
|
||||||
|
cols = _table_columns(conn, "payment_orders")
|
||||||
|
if not cols:
|
||||||
|
return
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"payment_orders",
|
||||||
|
"slots_applied",
|
||||||
|
{
|
||||||
|
"default": "ALTER TABLE payment_orders ADD COLUMN slots_applied BOOLEAN DEFAULT 0",
|
||||||
|
"postgresql": "ALTER TABLE payment_orders ADD COLUMN slots_applied BOOLEAN DEFAULT FALSE",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
applied = _bool_default(conn, True)
|
||||||
|
conn.execute(
|
||||||
|
text(
|
||||||
|
"UPDATE payment_orders SET slots_applied = "
|
||||||
|
f"{applied} WHERE status = 'paid' AND (slots_applied IS NULL OR slots_applied = 0)"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_accounts_quota_disabled(conn) -> None:
|
||||||
|
cols = _table_columns(conn, "accounts")
|
||||||
|
if not cols:
|
||||||
|
return
|
||||||
|
add_column_if_missing(
|
||||||
|
conn,
|
||||||
|
"accounts",
|
||||||
|
"quota_disabled",
|
||||||
|
{
|
||||||
|
"default": "ALTER TABLE accounts ADD COLUMN quota_disabled BOOLEAN DEFAULT 0",
|
||||||
|
"postgresql": "ALTER TABLE accounts ADD COLUMN quota_disabled BOOLEAN DEFAULT FALSE",
|
||||||
|
},
|
||||||
|
)
|
||||||
@@ -0,0 +1,323 @@
|
|||||||
|
"""从 SQLite 源库迁移数据到目标数据库。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import date, datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from sqlalchemy import MetaData, insert, inspect, text
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncEngine
|
||||||
|
|
||||||
|
from models.database import Base
|
||||||
|
import models.models # noqa: F401 — 注册 ORM 表结构
|
||||||
|
from models.db_config import (
|
||||||
|
PASSWORD_PLACEHOLDER,
|
||||||
|
DatabaseConfig,
|
||||||
|
build_database_url,
|
||||||
|
create_database_engine,
|
||||||
|
mask_database_url,
|
||||||
|
read_database_config,
|
||||||
|
)
|
||||||
|
from models.db_migrate import (
|
||||||
|
migrate_accounts_quota_disabled,
|
||||||
|
migrate_accounts_table,
|
||||||
|
migrate_message_logs_table,
|
||||||
|
migrate_payment_orders_table,
|
||||||
|
migrate_rules_table,
|
||||||
|
migrate_users_table,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 按外键依赖顺序导入
|
||||||
|
MIGRATION_TABLES: tuple[str, ...] = (
|
||||||
|
"users",
|
||||||
|
"email_verification_tokens",
|
||||||
|
"password_reset_tokens",
|
||||||
|
"app_config",
|
||||||
|
"accounts",
|
||||||
|
"rules",
|
||||||
|
"message_logs",
|
||||||
|
"received_message_logs",
|
||||||
|
"system_logs",
|
||||||
|
"payment_orders",
|
||||||
|
)
|
||||||
|
|
||||||
|
BATCH_SIZE = 400
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_datetime(value: Any) -> Any:
|
||||||
|
if value is None or isinstance(value, (datetime, date)):
|
||||||
|
return value
|
||||||
|
if isinstance(value, str):
|
||||||
|
text_value = value.strip()
|
||||||
|
if not text_value:
|
||||||
|
return None
|
||||||
|
for fmt in ("%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
|
||||||
|
try:
|
||||||
|
return datetime.strptime(text_value, fmt)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
return datetime.fromisoformat(text_value.replace("Z", "+00:00"))
|
||||||
|
except ValueError:
|
||||||
|
return value
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_rows(rows: list[dict[str, Any]], tbl) -> list[dict[str, Any]]:
|
||||||
|
if not rows:
|
||||||
|
return rows
|
||||||
|
col_types = {column.name: column.type for column in tbl.columns}
|
||||||
|
normalized: list[dict[str, Any]] = []
|
||||||
|
for row in rows:
|
||||||
|
item = dict(row)
|
||||||
|
for key, col_type in col_types.items():
|
||||||
|
if key not in item or item[key] is None:
|
||||||
|
continue
|
||||||
|
type_name = col_type.__class__.__name__.lower()
|
||||||
|
if "datetime" in type_name or "timestamp" in type_name:
|
||||||
|
item[key] = _parse_datetime(item[key])
|
||||||
|
elif "boolean" in type_name and not isinstance(item[key], bool):
|
||||||
|
if isinstance(item[key], (int, float)):
|
||||||
|
item[key] = bool(item[key])
|
||||||
|
elif isinstance(item[key], str):
|
||||||
|
item[key] = item[key].strip().lower() in ("1", "true", "t", "yes")
|
||||||
|
normalized.append(item)
|
||||||
|
return normalized
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_sqlite_source_path(source_path: str | None = None) -> Path:
|
||||||
|
if source_path and str(source_path).strip():
|
||||||
|
path = Path(source_path.strip())
|
||||||
|
if not path.is_absolute():
|
||||||
|
from models.db_config import BACKEND_DIR
|
||||||
|
|
||||||
|
path = BACKEND_DIR / path
|
||||||
|
return path
|
||||||
|
from models.db_config import DEFAULT_SQLITE_PATH
|
||||||
|
|
||||||
|
return DEFAULT_SQLITE_PATH
|
||||||
|
|
||||||
|
|
||||||
|
def build_sqlite_config(path: Path) -> DatabaseConfig:
|
||||||
|
return DatabaseConfig(db_type="sqlite", db_path=str(path))
|
||||||
|
|
||||||
|
|
||||||
|
def _same_sqlite_target(source: Path, target: DatabaseConfig) -> bool:
|
||||||
|
if target.normalized_type() != "sqlite":
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
return source.resolve() == target.sqlite_path().resolve()
|
||||||
|
except OSError:
|
||||||
|
return str(source) == str(target.sqlite_path())
|
||||||
|
|
||||||
|
|
||||||
|
async def inspect_sqlite_source(source_path: str | None = None) -> dict[str, Any]:
|
||||||
|
path = resolve_sqlite_source_path(source_path)
|
||||||
|
if not path.exists():
|
||||||
|
return {
|
||||||
|
"source_path": str(path),
|
||||||
|
"exists": False,
|
||||||
|
"tables": {},
|
||||||
|
"total_rows": 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg = build_sqlite_config(path)
|
||||||
|
engine = create_database_engine(cfg)
|
||||||
|
tables: dict[str, int] = {}
|
||||||
|
total_rows = 0
|
||||||
|
try:
|
||||||
|
async with engine.connect() as conn:
|
||||||
|
for table in MIGRATION_TABLES:
|
||||||
|
if not await conn.run_sync(lambda sync_conn, t=table: inspect(sync_conn).has_table(t)):
|
||||||
|
tables[table] = 0
|
||||||
|
continue
|
||||||
|
count = await conn.scalar(text(f"SELECT COUNT(*) FROM {table}"))
|
||||||
|
row_count = int(count or 0)
|
||||||
|
tables[table] = row_count
|
||||||
|
total_rows += row_count
|
||||||
|
finally:
|
||||||
|
await engine.dispose()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"source_path": str(path),
|
||||||
|
"exists": True,
|
||||||
|
"tables": tables,
|
||||||
|
"total_rows": total_rows,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def _ensure_target_schema(engine: AsyncEngine) -> None:
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
await conn.run_sync(Base.metadata.create_all)
|
||||||
|
await conn.run_sync(migrate_accounts_table)
|
||||||
|
await conn.run_sync(migrate_rules_table)
|
||||||
|
await conn.run_sync(migrate_message_logs_table)
|
||||||
|
await conn.run_sync(migrate_users_table)
|
||||||
|
await conn.run_sync(migrate_payment_orders_table)
|
||||||
|
await conn.run_sync(migrate_accounts_quota_disabled)
|
||||||
|
|
||||||
|
|
||||||
|
async def _count_target_rows(engine: AsyncEngine) -> dict[str, int]:
|
||||||
|
counts: dict[str, int] = {}
|
||||||
|
async with engine.connect() as conn:
|
||||||
|
for table in MIGRATION_TABLES:
|
||||||
|
if not await conn.run_sync(lambda sync_conn, t=table: inspect(sync_conn).has_table(t)):
|
||||||
|
counts[table] = 0
|
||||||
|
continue
|
||||||
|
count = await conn.scalar(text(f"SELECT COUNT(*) FROM {table}"))
|
||||||
|
counts[table] = int(count or 0)
|
||||||
|
return counts
|
||||||
|
|
||||||
|
|
||||||
|
async def _fetch_table_rows(engine: AsyncEngine, table: str) -> list[dict[str, Any]]:
|
||||||
|
async with engine.connect() as conn:
|
||||||
|
if not await conn.run_sync(lambda sync_conn, t=table: inspect(sync_conn).has_table(t)):
|
||||||
|
return []
|
||||||
|
result = await conn.execute(text(f"SELECT * FROM {table} ORDER BY id"))
|
||||||
|
return [dict(row) for row in result.mappings()]
|
||||||
|
|
||||||
|
|
||||||
|
async def _clear_target_tables(engine: AsyncEngine) -> None:
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
dialect = conn.dialect.name
|
||||||
|
if dialect == "mysql":
|
||||||
|
await conn.execute(text("SET FOREIGN_KEY_CHECKS=0"))
|
||||||
|
for table in reversed(MIGRATION_TABLES):
|
||||||
|
if await conn.run_sync(lambda sync_conn, t=table: inspect(sync_conn).has_table(t)):
|
||||||
|
await conn.execute(text(f"DELETE FROM {table}"))
|
||||||
|
await conn.execute(text("SET FOREIGN_KEY_CHECKS=1"))
|
||||||
|
elif dialect == "postgresql":
|
||||||
|
existing = []
|
||||||
|
for table in MIGRATION_TABLES:
|
||||||
|
if await conn.run_sync(lambda sync_conn, t=table: inspect(sync_conn).has_table(t)):
|
||||||
|
existing.append(table)
|
||||||
|
if existing:
|
||||||
|
await conn.execute(
|
||||||
|
text(f"TRUNCATE {', '.join(existing)} RESTART IDENTITY CASCADE")
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
await conn.execute(text("PRAGMA foreign_keys=OFF"))
|
||||||
|
for table in reversed(MIGRATION_TABLES):
|
||||||
|
if await conn.run_sync(lambda sync_conn, t=table: inspect(sync_conn).has_table(t)):
|
||||||
|
await conn.execute(text(f"DELETE FROM {table}"))
|
||||||
|
await conn.execute(text("PRAGMA foreign_keys=ON"))
|
||||||
|
|
||||||
|
|
||||||
|
async def _insert_rows(engine: AsyncEngine, table: str, rows: list[dict[str, Any]]) -> int:
|
||||||
|
if not rows:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
tbl = Base.metadata.tables.get(table)
|
||||||
|
if tbl is None:
|
||||||
|
metadata = MetaData()
|
||||||
|
|
||||||
|
def _reflect(sync_conn) -> None:
|
||||||
|
metadata.reflect(sync_conn, only=[table])
|
||||||
|
|
||||||
|
async with engine.connect() as conn:
|
||||||
|
await conn.run_sync(_reflect)
|
||||||
|
tbl = metadata.tables[table]
|
||||||
|
|
||||||
|
inserted = 0
|
||||||
|
prepared_rows = _normalize_rows(rows, tbl)
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
for offset in range(0, len(prepared_rows), BATCH_SIZE):
|
||||||
|
batch = prepared_rows[offset : offset + BATCH_SIZE]
|
||||||
|
await conn.execute(insert(tbl), batch)
|
||||||
|
inserted += len(batch)
|
||||||
|
return inserted
|
||||||
|
|
||||||
|
|
||||||
|
async def _reset_auto_increment(engine: AsyncEngine) -> None:
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
dialect = conn.dialect.name
|
||||||
|
for table in MIGRATION_TABLES:
|
||||||
|
if not await conn.run_sync(lambda sync_conn, t=table: inspect(sync_conn).has_table(t)):
|
||||||
|
continue
|
||||||
|
max_id = await conn.scalar(text(f"SELECT COALESCE(MAX(id), 0) FROM {table}"))
|
||||||
|
if not max_id:
|
||||||
|
continue
|
||||||
|
next_id = int(max_id) + 1
|
||||||
|
if dialect == "mysql":
|
||||||
|
await conn.execute(text(f"ALTER TABLE {table} AUTO_INCREMENT = {next_id}"))
|
||||||
|
elif dialect == "postgresql":
|
||||||
|
await conn.execute(
|
||||||
|
text(
|
||||||
|
"SELECT setval("
|
||||||
|
f"pg_get_serial_sequence('{table}', 'id'), "
|
||||||
|
f"{next_id}, false)"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_target_config(payload: dict[str, Any]) -> DatabaseConfig:
|
||||||
|
current = read_database_config()
|
||||||
|
password = (payload.get("db_password") or "").strip()
|
||||||
|
if password in ("", PASSWORD_PLACEHOLDER):
|
||||||
|
password = current.db_password
|
||||||
|
return DatabaseConfig(
|
||||||
|
db_type=payload.get("db_type") or current.db_type,
|
||||||
|
db_host=(payload.get("db_host") or current.db_host or "127.0.0.1").strip(),
|
||||||
|
db_port=int(payload.get("db_port") or current.resolved_port() or 0),
|
||||||
|
db_user=(payload.get("db_user") or current.db_user).strip(),
|
||||||
|
db_password=password,
|
||||||
|
db_name=(payload.get("db_name") or current.db_name or "kefu").strip(),
|
||||||
|
db_path=(payload.get("db_path") or current.db_path).strip(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def migrate_sqlite_to_target(
|
||||||
|
payload: dict[str, Any],
|
||||||
|
*,
|
||||||
|
clear_target: bool = False,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
source_path = resolve_sqlite_source_path(payload.get("source_db_path"))
|
||||||
|
if not source_path.exists():
|
||||||
|
raise FileNotFoundError(f"SQLite 源文件不存在: {source_path}")
|
||||||
|
|
||||||
|
target_cfg = _build_target_config(payload)
|
||||||
|
if _same_sqlite_target(source_path, target_cfg):
|
||||||
|
raise ValueError("目标库不能与 SQLite 源文件相同,请指定不同的目标数据库")
|
||||||
|
|
||||||
|
source_cfg = build_sqlite_config(source_path)
|
||||||
|
source_engine = create_database_engine(source_cfg)
|
||||||
|
target_engine = create_database_engine(target_cfg)
|
||||||
|
|
||||||
|
try:
|
||||||
|
preview = await inspect_sqlite_source(str(source_path))
|
||||||
|
if preview["total_rows"] == 0:
|
||||||
|
raise ValueError("SQLite 源库中没有可迁移的数据")
|
||||||
|
|
||||||
|
await _ensure_target_schema(target_engine)
|
||||||
|
target_counts = await _count_target_rows(target_engine)
|
||||||
|
target_total = sum(target_counts.values())
|
||||||
|
if target_total > 0 and not clear_target:
|
||||||
|
raise ValueError(
|
||||||
|
f"目标库已有 {target_total} 条数据,请勾选「清空目标库后再导入」或先手动清空"
|
||||||
|
)
|
||||||
|
|
||||||
|
if clear_target and target_total > 0:
|
||||||
|
await _clear_target_tables(target_engine)
|
||||||
|
|
||||||
|
copied: dict[str, int] = {}
|
||||||
|
total_rows = 0
|
||||||
|
for table in MIGRATION_TABLES:
|
||||||
|
rows = await _fetch_table_rows(source_engine, table)
|
||||||
|
copied[table] = await _insert_rows(target_engine, table, rows)
|
||||||
|
total_rows += copied[table]
|
||||||
|
|
||||||
|
await _reset_auto_increment(target_engine)
|
||||||
|
finally:
|
||||||
|
await source_engine.dispose()
|
||||||
|
await target_engine.dispose()
|
||||||
|
|
||||||
|
target_type = target_cfg.normalized_type()
|
||||||
|
return {
|
||||||
|
"message": f"已从 SQLite 迁移 {total_rows} 条记录到 {target_type} 数据库",
|
||||||
|
"source_path": str(source_path),
|
||||||
|
"target_type": target_type,
|
||||||
|
"target_url": mask_database_url(build_database_url(target_cfg)),
|
||||||
|
"tables": copied,
|
||||||
|
"total_rows": total_rows,
|
||||||
|
}
|
||||||
@@ -0,0 +1,278 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey, Text, UniqueConstraint
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
from .database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class User(Base):
|
||||||
|
__tablename__ = "users"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
username = Column(String(50), unique=True, index=True, nullable=False)
|
||||||
|
email = Column(String(255), unique=True, index=True, nullable=True)
|
||||||
|
password_hash = Column(String(255), nullable=False)
|
||||||
|
display_name = Column(String(100), nullable=True)
|
||||||
|
role = Column(String(20), default="operator", index=True) # admin, operator, viewer
|
||||||
|
is_active = Column(Boolean, default=True)
|
||||||
|
email_verified = Column(Boolean, default=False)
|
||||||
|
email_verified_at = Column(DateTime, nullable=True)
|
||||||
|
max_accounts = Column(Integer, default=3)
|
||||||
|
created_at = Column(DateTime, default=datetime.utcnow)
|
||||||
|
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||||
|
|
||||||
|
accounts = relationship("Account", back_populates="owner")
|
||||||
|
verification_tokens = relationship(
|
||||||
|
"EmailVerificationToken",
|
||||||
|
back_populates="user",
|
||||||
|
cascade="all, delete-orphan",
|
||||||
|
)
|
||||||
|
password_reset_tokens = relationship(
|
||||||
|
"PasswordResetToken",
|
||||||
|
back_populates="user",
|
||||||
|
cascade="all, delete-orphan",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class EmailVerificationToken(Base):
|
||||||
|
__tablename__ = "email_verification_tokens"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
token = Column(String(128), unique=True, index=True, nullable=False)
|
||||||
|
expires_at = Column(DateTime, nullable=False)
|
||||||
|
created_at = Column(DateTime, default=datetime.utcnow)
|
||||||
|
|
||||||
|
user = relationship("User", back_populates="verification_tokens")
|
||||||
|
|
||||||
|
|
||||||
|
class PasswordResetToken(Base):
|
||||||
|
__tablename__ = "password_reset_tokens"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
token = Column(String(128), unique=True, index=True, nullable=False)
|
||||||
|
expires_at = Column(DateTime, nullable=False)
|
||||||
|
created_at = Column(DateTime, default=datetime.utcnow)
|
||||||
|
|
||||||
|
user = relationship("User", back_populates="password_reset_tokens")
|
||||||
|
|
||||||
|
|
||||||
|
class AppConfig(Base):
|
||||||
|
"""系统功能配置(单例行 id=1,JSON 存储)。"""
|
||||||
|
|
||||||
|
__tablename__ = "app_config"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True)
|
||||||
|
data = Column(Text, nullable=False, default="{}")
|
||||||
|
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||||
|
|
||||||
|
|
||||||
|
class Account(Base):
|
||||||
|
__tablename__ = "accounts"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
owner_id = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||||
|
username = Column(String(100), unique=True, index=True, nullable=True) # 登录后获取的用户名/ID
|
||||||
|
avatar_url = Column(String(512), nullable=True) # 登录后获取的头像 URL
|
||||||
|
douyin_uid = Column(String(64), nullable=True, index=True) # 抖音 UID
|
||||||
|
phone = Column(String(20), nullable=True) # 绑定的手机号(可选)
|
||||||
|
status = Column(String(50), default="offline") # offline, logging_in, online, error
|
||||||
|
cookie_path = Column(String(255), nullable=True) # 存储 cookie/session 的路径
|
||||||
|
cookie_data = Column(Text, nullable=True) # Playwright storage_state JSON
|
||||||
|
cookie_updated_at = Column(DateTime, nullable=True) # Cookie 最近更新时间
|
||||||
|
im_session_data = Column(Text, nullable=True) # IM 直连会话 (WS URL / device_id 等)
|
||||||
|
reply_delay_seconds = Column(Integer, default=0) # 账号回复排队间隔;0/NULL=继承系统默认
|
||||||
|
reply_cooldown_seconds = Column(Integer, nullable=True) # 自动回复冷却秒数;NULL=继承全局设置
|
||||||
|
follow_welcome_enabled = Column(Boolean, default=False) # 新粉丝关注后自动发送欢迎语
|
||||||
|
follow_welcome_content = Column(Text, nullable=True) # 关注欢迎语内容(空=不发)
|
||||||
|
user_agent = Column(Text, nullable=True) # 伪装设备头(User-Agent),空=默认
|
||||||
|
qr_code_base64 = Column(Text, nullable=True) # 当前登录二维码的 base64 字符串
|
||||||
|
error_message = Column(Text, nullable=True) # 错误信息
|
||||||
|
quota_disabled = Column(Boolean, default=False, index=True) # 额度不足被停用
|
||||||
|
created_at = Column(DateTime, default=datetime.utcnow)
|
||||||
|
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||||
|
|
||||||
|
# 关联
|
||||||
|
owner = relationship("User", back_populates="accounts")
|
||||||
|
rules = relationship("AutoReplyRule", back_populates="account", cascade="all, delete-orphan")
|
||||||
|
logs = relationship("MessageLog", back_populates="account", cascade="all, delete-orphan")
|
||||||
|
profile_detail = relationship(
|
||||||
|
"AccountProfileDetail",
|
||||||
|
back_populates="account",
|
||||||
|
uselist=False,
|
||||||
|
cascade="all, delete-orphan",
|
||||||
|
)
|
||||||
|
videos = relationship(
|
||||||
|
"AccountVideo",
|
||||||
|
back_populates="account",
|
||||||
|
cascade="all, delete-orphan",
|
||||||
|
order_by="AccountVideo.sort_order",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AccountProfileDetail(Base):
|
||||||
|
"""托管账号抖音详细资料(本地缓存)。"""
|
||||||
|
|
||||||
|
__tablename__ = "account_profile_details"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
account_id = Column(Integer, ForeignKey("accounts.id", ondelete="CASCADE"), unique=True, nullable=False, index=True)
|
||||||
|
uid = Column(String(64), nullable=True)
|
||||||
|
nickname = Column(String(200), nullable=True)
|
||||||
|
avatar_url = Column(String(512), nullable=True)
|
||||||
|
unique_id = Column(String(100), nullable=True)
|
||||||
|
signature = Column(Text, nullable=True)
|
||||||
|
sec_user_id = Column(String(255), nullable=True)
|
||||||
|
video_count = Column(Integer, nullable=True)
|
||||||
|
follower_count = Column(Integer, nullable=True)
|
||||||
|
following_count = Column(Integer, nullable=True)
|
||||||
|
total_favorited = Column(Integer, nullable=True)
|
||||||
|
favoriting_count = Column(Integer, nullable=True)
|
||||||
|
sync_message = Column(Text, nullable=True)
|
||||||
|
synced_at = Column(DateTime, nullable=True)
|
||||||
|
created_at = Column(DateTime, default=datetime.utcnow)
|
||||||
|
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||||
|
|
||||||
|
account = relationship("Account", back_populates="profile_detail")
|
||||||
|
|
||||||
|
|
||||||
|
class AccountVideo(Base):
|
||||||
|
"""托管账号已发布作品(本地缓存)。"""
|
||||||
|
|
||||||
|
__tablename__ = "account_videos"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
account_id = Column(Integer, ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
aweme_id = Column(String(64), nullable=False, index=True)
|
||||||
|
title = Column(Text, nullable=True)
|
||||||
|
cover_url = Column(String(1024), nullable=True)
|
||||||
|
video_url = Column(String(2048), nullable=True)
|
||||||
|
share_url = Column(String(1024), nullable=True)
|
||||||
|
create_time = Column(DateTime, nullable=True)
|
||||||
|
digg_count = Column(Integer, nullable=True)
|
||||||
|
comment_count = Column(Integer, nullable=True)
|
||||||
|
play_count = Column(Integer, nullable=True)
|
||||||
|
media_type = Column(String(20), nullable=True) # video, image, other
|
||||||
|
sort_order = Column(Integer, default=0, index=True)
|
||||||
|
synced_at = Column(DateTime, nullable=True)
|
||||||
|
created_at = Column(DateTime, default=datetime.utcnow)
|
||||||
|
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||||
|
|
||||||
|
account = relationship("Account", back_populates="videos")
|
||||||
|
|
||||||
|
class LinkCardPage(Base):
|
||||||
|
"""规则回复用的链接卡片落地页(带 SEO meta,打开后跳转至目标 URL)。"""
|
||||||
|
|
||||||
|
__tablename__ = "link_card_pages"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
owner_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
slug = Column(String(64), unique=True, index=True, nullable=False)
|
||||||
|
title = Column(String(200), nullable=False)
|
||||||
|
content = Column(Text, nullable=True)
|
||||||
|
target_url = Column(String(2000), nullable=False)
|
||||||
|
image_path = Column(String(512), nullable=False)
|
||||||
|
created_at = Column(DateTime, default=datetime.utcnow)
|
||||||
|
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||||
|
|
||||||
|
|
||||||
|
class AutoReplyRule(Base):
|
||||||
|
__tablename__ = "rules"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
owner_id = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True, index=True)
|
||||||
|
account_id = Column(Integer, ForeignKey("accounts.id", ondelete="CASCADE"), nullable=True) # 为空代表全局规则
|
||||||
|
keyword = Column(String(255), index=True) # 触发关键词,或者空代表兜底
|
||||||
|
reply_content = Column(Text) # 回复内容
|
||||||
|
match_type = Column(String(50), default="contains") # exact (精确), contains (包含), regex (正则), default (兜底)
|
||||||
|
sort_order = Column(Integer, default=0, index=True) # 规则优先级,越小越优先
|
||||||
|
is_active = Column(Boolean, default=True)
|
||||||
|
created_at = Column(DateTime, default=datetime.utcnow)
|
||||||
|
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||||
|
|
||||||
|
account = relationship("Account", back_populates="rules")
|
||||||
|
|
||||||
|
class MessageLog(Base):
|
||||||
|
__tablename__ = "message_logs"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
account_id = Column(Integer, ForeignKey("accounts.id", ondelete="CASCADE"))
|
||||||
|
sender_name = Column(String(100)) # 发送者名字
|
||||||
|
sender_id = Column(String(100), nullable=True) # 发送者唯一ID
|
||||||
|
sender_avatar = Column(String(512), nullable=True) # 发送者头像 URL
|
||||||
|
message_content = Column(Text) # 接收到的消息
|
||||||
|
reply_content = Column(Text, nullable=True) # 回复的消息
|
||||||
|
status = Column(String(50), default="received") # received, replied, ignored, failed
|
||||||
|
error_message = Column(Text, nullable=True)
|
||||||
|
created_at = Column(DateTime, default=datetime.utcnow)
|
||||||
|
|
||||||
|
account = relationship("Account", back_populates="logs")
|
||||||
|
|
||||||
|
|
||||||
|
class ReceivedMessageLog(Base):
|
||||||
|
"""接收消息原始日志:仅记录收到的消息,内容原样保存。"""
|
||||||
|
|
||||||
|
__tablename__ = "received_message_logs"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
account_id = Column(Integer, ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
conversation_id = Column(String(128), nullable=True, index=True)
|
||||||
|
sender_id = Column(String(100), nullable=True, index=True)
|
||||||
|
sender_name = Column(String(100), nullable=True)
|
||||||
|
sender_avatar = Column(String(512), nullable=True)
|
||||||
|
message_type = Column(Integer, nullable=True)
|
||||||
|
server_message_id = Column(String(64), nullable=True, index=True)
|
||||||
|
raw_content = Column(Text, nullable=False)
|
||||||
|
created_at = Column(DateTime, default=datetime.utcnow, index=True)
|
||||||
|
|
||||||
|
|
||||||
|
class FollowWelcomeLog(Base):
|
||||||
|
"""关注欢迎语去重表:每个账号对每个新粉丝只发送一次欢迎语(重启后仍生效)。"""
|
||||||
|
|
||||||
|
__tablename__ = "follow_welcome_logs"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
account_id = Column(Integer, ForeignKey("accounts.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
follower_uid = Column(String(64), nullable=False, index=True) # 新粉丝的抖音 UID
|
||||||
|
status = Column(String(20), default="sent") # sent, failed
|
||||||
|
detail = Column(Text, nullable=True)
|
||||||
|
created_at = Column(DateTime, default=datetime.utcnow)
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
UniqueConstraint("account_id", "follower_uid", name="uq_follow_welcome_account_follower"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class SystemLog(Base):
|
||||||
|
"""系统诊断日志:记录私信收发/连接/鉴权等链路事件,便于排查失败原因。"""
|
||||||
|
__tablename__ = "system_logs"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
account_id = Column(Integer, nullable=True, index=True) # 关联账号(可空,全局事件)
|
||||||
|
level = Column(String(20), default="info", index=True) # info, success, warning, error
|
||||||
|
category = Column(String(40), default="system", index=True) # ws, send, recv, auth, poll, system
|
||||||
|
event = Column(String(255)) # 事件标题
|
||||||
|
detail = Column(Text, nullable=True) # 详细原因
|
||||||
|
created_at = Column(DateTime, default=datetime.utcnow, index=True)
|
||||||
|
|
||||||
|
|
||||||
|
class PaymentOrder(Base):
|
||||||
|
"""账号额度购买订单。"""
|
||||||
|
|
||||||
|
__tablename__ = "payment_orders"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
order_no = Column(String(64), unique=True, index=True, nullable=False)
|
||||||
|
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||||
|
channel = Column(String(20), nullable=False) # wechat, alipay
|
||||||
|
slots = Column(Integer, nullable=False)
|
||||||
|
amount_fen = Column(Integer, nullable=False)
|
||||||
|
status = Column(String(20), default="pending", index=True) # pending, paid, expired, cancelled, refunded
|
||||||
|
slots_applied = Column(Boolean, default=False)
|
||||||
|
qr_code = Column(Text, nullable=True)
|
||||||
|
pay_url = Column(Text, nullable=True)
|
||||||
|
trade_no = Column(String(128), nullable=True)
|
||||||
|
notify_payload = Column(Text, nullable=True)
|
||||||
|
paid_at = Column(DateTime, nullable=True)
|
||||||
|
expires_at = Column(DateTime, nullable=False)
|
||||||
|
created_at = Column(DateTime, default=datetime.utcnow)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
"""支付宝当面付扫码(precreate)。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from base64 import b64decode, b64encode
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Any
|
||||||
|
from urllib.parse import quote_plus, urlencode
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from cryptography.hazmat.primitives import hashes, serialization
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import padding
|
||||||
|
|
||||||
|
from auth.system_settings import SystemSettingsData
|
||||||
|
|
||||||
|
logger = logging.getLogger("payments.alipay")
|
||||||
|
|
||||||
|
ALIPAY_GATEWAY = "https://openapi.alipay.com/gateway.do"
|
||||||
|
ALIPAY_SANDBOX_GATEWAY = "https://openapi-sandbox.dl.alipaydev.com/gateway.do"
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_pem(text: str, label: str) -> str:
|
||||||
|
body = text.strip()
|
||||||
|
if "BEGIN" in body:
|
||||||
|
return body
|
||||||
|
return f"-----BEGIN {label}-----\n{body}\n-----END {label}-----"
|
||||||
|
|
||||||
|
|
||||||
|
def _load_private_key(pem: str):
|
||||||
|
return serialization.load_pem_private_key(
|
||||||
|
_normalize_pem(pem, "RSA PRIVATE KEY").encode("utf-8"),
|
||||||
|
password=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _load_public_key(pem: str):
|
||||||
|
return serialization.load_pem_public_key(
|
||||||
|
_normalize_pem(pem, "PUBLIC KEY").encode("utf-8"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _sign_content(content: str, private_key) -> str:
|
||||||
|
signature = private_key.sign(
|
||||||
|
content.encode("utf-8"),
|
||||||
|
padding.PKCS1v15(),
|
||||||
|
hashes.SHA256(),
|
||||||
|
)
|
||||||
|
return b64encode(signature).decode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def _gateway(settings: SystemSettingsData) -> str:
|
||||||
|
return ALIPAY_SANDBOX_GATEWAY if settings.alipay_sandbox else ALIPAY_GATEWAY
|
||||||
|
|
||||||
|
|
||||||
|
def create_precreate_order(
|
||||||
|
settings: SystemSettingsData,
|
||||||
|
order_no: str,
|
||||||
|
subject: str,
|
||||||
|
amount_yuan: str,
|
||||||
|
notify_url: str,
|
||||||
|
) -> str:
|
||||||
|
"""创建当面付预下单,返回 qr_code 字符串。"""
|
||||||
|
private_key = _load_private_key(settings.alipay_private_key)
|
||||||
|
biz_content = {
|
||||||
|
"out_trade_no": order_no,
|
||||||
|
"total_amount": amount_yuan,
|
||||||
|
"subject": subject[:256],
|
||||||
|
}
|
||||||
|
params = {
|
||||||
|
"app_id": settings.alipay_app_id.strip(),
|
||||||
|
"method": "alipay.trade.precreate",
|
||||||
|
"format": "JSON",
|
||||||
|
"charset": "utf-8",
|
||||||
|
"sign_type": "RSA2",
|
||||||
|
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
||||||
|
"version": "1.0",
|
||||||
|
"notify_url": notify_url,
|
||||||
|
"biz_content": json.dumps(biz_content, ensure_ascii=False, separators=(",", ":")),
|
||||||
|
}
|
||||||
|
unsigned = "&".join(
|
||||||
|
f"{k}={quote_plus(str(v), safe='')}"
|
||||||
|
for k, v in sorted(params.items())
|
||||||
|
if v is not None and str(v) != ""
|
||||||
|
)
|
||||||
|
params["sign"] = _sign_content(unsigned, private_key)
|
||||||
|
with httpx.Client(timeout=30.0) as client:
|
||||||
|
resp = client.post(_gateway(settings), data=params)
|
||||||
|
resp.raise_for_status()
|
||||||
|
data = resp.json()
|
||||||
|
key = "alipay_trade_precreate_response"
|
||||||
|
result = data.get(key) or {}
|
||||||
|
if result.get("code") != "10000":
|
||||||
|
raise RuntimeError(result.get("sub_msg") or result.get("msg") or "支付宝下单失败")
|
||||||
|
qr_code = result.get("qr_code")
|
||||||
|
if not qr_code:
|
||||||
|
raise RuntimeError("支付宝未返回 qr_code")
|
||||||
|
return qr_code
|
||||||
|
|
||||||
|
|
||||||
|
def verify_notify(params: dict[str, Any], settings: SystemSettingsData) -> bool:
|
||||||
|
sign = params.get("sign")
|
||||||
|
if not sign:
|
||||||
|
return False
|
||||||
|
verify_params = {k: v for k, v in params.items() if k not in ("sign", "sign_type") and v is not None}
|
||||||
|
unsigned = "&".join(
|
||||||
|
f"{k}={v}"
|
||||||
|
for k, v in sorted(verify_params.items())
|
||||||
|
if str(v) != ""
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
public_key = _load_public_key(settings.alipay_public_key)
|
||||||
|
public_key.verify(
|
||||||
|
b64decode(sign),
|
||||||
|
unsigned.encode("utf-8"),
|
||||||
|
padding.PKCS1v15(),
|
||||||
|
hashes.SHA256(),
|
||||||
|
)
|
||||||
|
return True
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Alipay notify verify failed: %s", exc)
|
||||||
|
return False
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||||
|
from fastapi.responses import PlainTextResponse
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from auth.dependencies import get_current_user, require_admin
|
||||||
|
from auth.system_settings import load_settings
|
||||||
|
from models.database import get_db
|
||||||
|
from models.models import User
|
||||||
|
from . import service
|
||||||
|
from .schemas import (
|
||||||
|
AdminUpdateOrderStatusRequest,
|
||||||
|
CreatePaymentOrderRequest,
|
||||||
|
MessageResponse,
|
||||||
|
PaymentConfigResponse,
|
||||||
|
PaymentOrderListItem,
|
||||||
|
PaymentOrderListResponse,
|
||||||
|
PaymentOrderResponse,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/api/payments", tags=["payments"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/config", response_model=PaymentConfigResponse)
|
||||||
|
async def get_payment_config(
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
settings = await load_settings(db)
|
||||||
|
return PaymentConfigResponse(**service.payment_config_payload(settings))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/orders", response_model=PaymentOrderResponse)
|
||||||
|
async def create_payment_order(
|
||||||
|
body: CreatePaymentOrderRequest,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
order, demo_mode = await service.create_order(db, user, body.slots, body.channel)
|
||||||
|
return PaymentOrderResponse(**service.order_to_dict(order, demo_mode=demo_mode))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/orders", response_model=PaymentOrderListResponse)
|
||||||
|
async def list_payment_orders(
|
||||||
|
status: str | None = Query(default=None, description="pending/paid/expired/cancelled"),
|
||||||
|
channel: str | None = Query(default=None, description="wechat/alipay"),
|
||||||
|
page: int = Query(default=1, ge=1),
|
||||||
|
page_size: int = Query(default=20, ge=1, le=100),
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
if status and status not in service.ORDER_STATUSES:
|
||||||
|
raise HTTPException(status_code=400, detail="无效的订单状态")
|
||||||
|
data = await service.list_orders(
|
||||||
|
db,
|
||||||
|
user,
|
||||||
|
status=status,
|
||||||
|
channel=channel,
|
||||||
|
page=page,
|
||||||
|
page_size=page_size,
|
||||||
|
)
|
||||||
|
return PaymentOrderListResponse(**data)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/orders/{order_no}", response_model=PaymentOrderResponse)
|
||||||
|
async def get_payment_order(
|
||||||
|
order_no: str,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
settings = await load_settings(db)
|
||||||
|
order = await service.get_user_order(db, user, order_no)
|
||||||
|
demo_mode = settings.payment_demo_mode and not settings.payment_channel_available(order.channel)
|
||||||
|
return PaymentOrderResponse(**service.order_to_dict(order, demo_mode=demo_mode))
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/orders/{order_no}/simulate", response_model=PaymentOrderResponse)
|
||||||
|
async def simulate_payment_order(
|
||||||
|
order_no: str,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
settings = await load_settings(db)
|
||||||
|
order = await service.simulate_pay(db, user, order_no)
|
||||||
|
return PaymentOrderResponse(**service.order_to_dict(order, demo_mode=settings.payment_demo_mode))
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/orders/{order_no}/status", response_model=PaymentOrderListItem)
|
||||||
|
async def admin_update_payment_order_status(
|
||||||
|
order_no: str,
|
||||||
|
body: AdminUpdateOrderStatusRequest,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_: User = Depends(require_admin),
|
||||||
|
):
|
||||||
|
order = await service.admin_update_order_status(db, order_no, body.status)
|
||||||
|
return PaymentOrderListItem(**order)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/orders/{order_no}", response_model=MessageResponse)
|
||||||
|
async def admin_delete_payment_order(
|
||||||
|
order_no: str,
|
||||||
|
db: AsyncSession = Depends(get_db),
|
||||||
|
_: User = Depends(require_admin),
|
||||||
|
):
|
||||||
|
await service.admin_delete_order(db, order_no)
|
||||||
|
return MessageResponse(message="订单已删除")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/notify/wechat")
|
||||||
|
async def wechat_payment_notify(request: Request, db: AsyncSession = Depends(get_db)):
|
||||||
|
body = await request.body()
|
||||||
|
headers = {k.lower(): v for k, v in request.headers.items()}
|
||||||
|
ok = await service.handle_wechat_notify(db, body, headers)
|
||||||
|
if not ok:
|
||||||
|
return PlainTextResponse("FAIL", status_code=400)
|
||||||
|
return PlainTextResponse('{"code": "SUCCESS", "message": "成功"}', media_type="application/json")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/notify/alipay")
|
||||||
|
async def alipay_payment_notify(request: Request, db: AsyncSession = Depends(get_db)):
|
||||||
|
form = await request.form()
|
||||||
|
params = {k: v for k, v in form.items()}
|
||||||
|
ok = await service.handle_alipay_notify(db, params)
|
||||||
|
if not ok:
|
||||||
|
return PlainTextResponse("fail")
|
||||||
|
return PlainTextResponse("success")
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Literal, Optional
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
class PaymentConfigResponse(BaseModel):
|
||||||
|
payment_enabled: bool
|
||||||
|
demo_mode: bool
|
||||||
|
unit_price: float
|
||||||
|
min_slots: int
|
||||||
|
max_slots: int
|
||||||
|
channels: list[str]
|
||||||
|
wechat_available: bool
|
||||||
|
alipay_available: bool
|
||||||
|
|
||||||
|
|
||||||
|
class CreatePaymentOrderRequest(BaseModel):
|
||||||
|
slots: int = Field(ge=1, le=100)
|
||||||
|
channel: Literal["wechat", "alipay"]
|
||||||
|
|
||||||
|
|
||||||
|
class PaymentOrderResponse(BaseModel):
|
||||||
|
order_no: str
|
||||||
|
channel: str
|
||||||
|
slots: int
|
||||||
|
amount_fen: int
|
||||||
|
amount_yuan: float
|
||||||
|
status: str
|
||||||
|
qr_code: Optional[str] = None
|
||||||
|
pay_url: Optional[str] = None
|
||||||
|
paid_at: Optional[datetime] = None
|
||||||
|
expires_at: Optional[datetime] = None
|
||||||
|
created_at: Optional[datetime] = None
|
||||||
|
demo_mode: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class PaymentOrderListItem(BaseModel):
|
||||||
|
id: int
|
||||||
|
order_no: str
|
||||||
|
user_id: int
|
||||||
|
username: Optional[str] = None
|
||||||
|
display_name: Optional[str] = None
|
||||||
|
channel: str
|
||||||
|
slots: int
|
||||||
|
amount_fen: int
|
||||||
|
amount_yuan: float
|
||||||
|
status: str
|
||||||
|
trade_no: Optional[str] = None
|
||||||
|
is_demo: bool = False
|
||||||
|
paid_at: Optional[datetime] = None
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class PaymentOrderListResponse(BaseModel):
|
||||||
|
items: list[PaymentOrderListItem]
|
||||||
|
total: int
|
||||||
|
page: int
|
||||||
|
page_size: int
|
||||||
|
paid_count: int = 0
|
||||||
|
paid_amount_yuan: float = 0
|
||||||
|
|
||||||
|
|
||||||
|
class AdminUpdateOrderStatusRequest(BaseModel):
|
||||||
|
status: Literal["pending", "paid", "expired", "cancelled", "refunded"]
|
||||||
|
|
||||||
|
|
||||||
|
class MessageResponse(BaseModel):
|
||||||
|
message: str
|
||||||
@@ -0,0 +1,432 @@
|
|||||||
|
"""支付订单业务逻辑。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import secrets
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from sqlalchemy import func, select, update
|
||||||
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
|
from auth.account_quota import default_stop_worker, sync_user_account_quota
|
||||||
|
from auth.roles import is_admin
|
||||||
|
from auth.system_settings import SystemSettingsData, load_settings
|
||||||
|
from models.models import PaymentOrder, User
|
||||||
|
from . import alipay, wechat
|
||||||
|
|
||||||
|
logger = logging.getLogger("payments.service")
|
||||||
|
|
||||||
|
ORDER_TTL_MINUTES = 30
|
||||||
|
ORDER_STATUSES = ("pending", "paid", "expired", "cancelled", "refunded")
|
||||||
|
|
||||||
|
|
||||||
|
def generate_order_no() -> str:
|
||||||
|
return f"AC{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{secrets.token_hex(4).upper()}"
|
||||||
|
|
||||||
|
|
||||||
|
def yuan_to_fen(yuan: float) -> int:
|
||||||
|
return int(round(yuan * 100))
|
||||||
|
|
||||||
|
|
||||||
|
def fen_to_yuan(fen: int) -> float:
|
||||||
|
return round(fen / 100, 2)
|
||||||
|
|
||||||
|
|
||||||
|
def order_to_dict(order: PaymentOrder, demo_mode: bool = False) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"order_no": order.order_no,
|
||||||
|
"channel": order.channel,
|
||||||
|
"slots": order.slots,
|
||||||
|
"amount_fen": order.amount_fen,
|
||||||
|
"amount_yuan": fen_to_yuan(order.amount_fen),
|
||||||
|
"status": order.status,
|
||||||
|
"qr_code": order.qr_code,
|
||||||
|
"pay_url": order.pay_url,
|
||||||
|
"paid_at": order.paid_at.isoformat() if order.paid_at else None,
|
||||||
|
"expires_at": order.expires_at.isoformat() if order.expires_at else None,
|
||||||
|
"created_at": order.created_at.isoformat() if order.created_at else None,
|
||||||
|
"demo_mode": demo_mode,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def payment_config_payload(settings: SystemSettingsData) -> dict[str, Any]:
|
||||||
|
channels = settings.available_payment_channels()
|
||||||
|
demo = settings.payment_demo_mode and settings.payment_enabled
|
||||||
|
return {
|
||||||
|
"payment_enabled": settings.payment_enabled,
|
||||||
|
"demo_mode": demo,
|
||||||
|
"unit_price": settings.account_slot_unit_price,
|
||||||
|
"min_slots": settings.account_slot_purchase_min,
|
||||||
|
"max_slots": settings.account_slot_purchase_max,
|
||||||
|
"channels": channels,
|
||||||
|
"wechat_available": "wechat" in channels,
|
||||||
|
"alipay_available": "alipay" in channels,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_purchase_request(settings: SystemSettingsData, slots: int, channel: str) -> None:
|
||||||
|
if not settings.payment_enabled:
|
||||||
|
raise HTTPException(status_code=400, detail="在线购买功能未开启")
|
||||||
|
if slots < settings.account_slot_purchase_min or slots > settings.account_slot_purchase_max:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"购买数量需在 {settings.account_slot_purchase_min}~{settings.account_slot_purchase_max} 之间",
|
||||||
|
)
|
||||||
|
if channel not in ("wechat", "alipay"):
|
||||||
|
raise HTTPException(status_code=400, detail="不支持的支付方式")
|
||||||
|
if channel == "wechat" and not settings.wechat_pay_enabled:
|
||||||
|
raise HTTPException(status_code=400, detail="微信支付未开启")
|
||||||
|
if channel == "alipay" and not settings.alipay_pay_enabled:
|
||||||
|
raise HTTPException(status_code=400, detail="支付宝支付未开启")
|
||||||
|
if not settings.payment_channel_selectable(channel):
|
||||||
|
name = "微信" if channel == "wechat" else "支付宝"
|
||||||
|
raise HTTPException(status_code=400, detail=f"{name}支付暂不可用,请联系管理员")
|
||||||
|
if not settings.payment_channel_available(channel):
|
||||||
|
if not settings.payment_demo_mode:
|
||||||
|
name = "微信" if channel == "wechat" else "支付宝"
|
||||||
|
raise HTTPException(status_code=400, detail=f"{name}支付尚未配置完成,请联系管理员")
|
||||||
|
|
||||||
|
|
||||||
|
async def create_order(
|
||||||
|
db: AsyncSession,
|
||||||
|
user: User,
|
||||||
|
slots: int,
|
||||||
|
channel: str,
|
||||||
|
) -> tuple[PaymentOrder, bool]:
|
||||||
|
if is_admin(user.role):
|
||||||
|
raise HTTPException(status_code=400, detail="管理员账号无需购买额度")
|
||||||
|
settings = await load_settings(db)
|
||||||
|
_validate_purchase_request(settings, slots, channel)
|
||||||
|
|
||||||
|
amount_fen = yuan_to_fen(settings.account_slot_unit_price * slots)
|
||||||
|
if amount_fen < 1:
|
||||||
|
raise HTTPException(status_code=400, detail="订单金额无效")
|
||||||
|
|
||||||
|
order = PaymentOrder(
|
||||||
|
order_no=generate_order_no(),
|
||||||
|
user_id=user.id,
|
||||||
|
channel=channel,
|
||||||
|
slots=slots,
|
||||||
|
amount_fen=amount_fen,
|
||||||
|
status="pending",
|
||||||
|
expires_at=datetime.utcnow() + timedelta(minutes=ORDER_TTL_MINUTES),
|
||||||
|
)
|
||||||
|
db.add(order)
|
||||||
|
await db.flush()
|
||||||
|
|
||||||
|
demo_mode = False
|
||||||
|
notify_base = settings.app_url_normalized()
|
||||||
|
description = f"抖音账号额度 x{slots}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
if channel == "wechat" and settings.wechat_pay_enabled and settings.wechat_pay_configured():
|
||||||
|
notify_url = f"{notify_base}/api/payments/notify/wechat"
|
||||||
|
order.qr_code = wechat.create_native_order(
|
||||||
|
settings,
|
||||||
|
order.order_no,
|
||||||
|
description,
|
||||||
|
amount_fen,
|
||||||
|
notify_url,
|
||||||
|
)
|
||||||
|
elif channel == "alipay" and settings.alipay_pay_enabled and settings.alipay_configured():
|
||||||
|
notify_url = f"{notify_base}/api/payments/notify/alipay"
|
||||||
|
order.qr_code = alipay.create_precreate_order(
|
||||||
|
settings,
|
||||||
|
order.order_no,
|
||||||
|
description,
|
||||||
|
f"{fen_to_yuan(amount_fen):.2f}",
|
||||||
|
notify_url,
|
||||||
|
)
|
||||||
|
elif settings.payment_demo_mode and settings.payment_channel_selectable(channel):
|
||||||
|
demo_mode = True
|
||||||
|
order.qr_code = f"DEMO-{order.order_no}"
|
||||||
|
else:
|
||||||
|
raise HTTPException(status_code=400, detail="支付渠道未配置")
|
||||||
|
except HTTPException:
|
||||||
|
await db.rollback()
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
await db.rollback()
|
||||||
|
logger.exception("Create payment order failed")
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
await db.commit()
|
||||||
|
await db.refresh(order)
|
||||||
|
return order, demo_mode
|
||||||
|
|
||||||
|
|
||||||
|
async def get_user_order(db: AsyncSession, user: User, order_no: str) -> PaymentOrder:
|
||||||
|
result = await db.execute(
|
||||||
|
select(PaymentOrder).where(
|
||||||
|
PaymentOrder.order_no == order_no,
|
||||||
|
PaymentOrder.user_id == user.id,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
order = result.scalar_one_or_none()
|
||||||
|
if not order:
|
||||||
|
raise HTTPException(status_code=404, detail="订单不存在")
|
||||||
|
if order.status == "pending" and order.expires_at < datetime.utcnow():
|
||||||
|
order.status = "expired"
|
||||||
|
await db.commit()
|
||||||
|
await db.refresh(order)
|
||||||
|
return order
|
||||||
|
|
||||||
|
|
||||||
|
async def _get_order_user(db: AsyncSession, order: PaymentOrder) -> User:
|
||||||
|
result = await db.execute(select(User).where(User.id == order.user_id))
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(status_code=404, detail="用户不存在")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
async def _apply_order_slots(db: AsyncSession, order: PaymentOrder, user: User) -> None:
|
||||||
|
if order.slots_applied:
|
||||||
|
return
|
||||||
|
if is_admin(user.role) or (user.max_accounts is not None and user.max_accounts < 0):
|
||||||
|
order.slots_applied = True
|
||||||
|
return
|
||||||
|
base = int(user.max_accounts) if user.max_accounts is not None else 0
|
||||||
|
user.max_accounts = base + int(order.slots)
|
||||||
|
order.slots_applied = True
|
||||||
|
await sync_user_account_quota(db, user, stop_worker=default_stop_worker)
|
||||||
|
|
||||||
|
|
||||||
|
async def _revoke_order_slots(db: AsyncSession, order: PaymentOrder, user: User) -> None:
|
||||||
|
if not order.slots_applied:
|
||||||
|
return
|
||||||
|
if is_admin(user.role) or (user.max_accounts is not None and user.max_accounts < 0):
|
||||||
|
order.slots_applied = False
|
||||||
|
return
|
||||||
|
base = int(user.max_accounts) if user.max_accounts is not None else 0
|
||||||
|
new_limit = max(0, base - int(order.slots))
|
||||||
|
user.max_accounts = new_limit
|
||||||
|
order.slots_applied = False
|
||||||
|
await sync_user_account_quota(db, user, stop_worker=default_stop_worker)
|
||||||
|
|
||||||
|
|
||||||
|
async def _get_order_by_no(db: AsyncSession, order_no: str) -> PaymentOrder:
|
||||||
|
result = await db.execute(select(PaymentOrder).where(PaymentOrder.order_no == order_no))
|
||||||
|
order = result.scalar_one_or_none()
|
||||||
|
if not order:
|
||||||
|
raise HTTPException(status_code=404, detail="订单不存在")
|
||||||
|
return order
|
||||||
|
|
||||||
|
|
||||||
|
async def fulfill_order(db: AsyncSession, order: PaymentOrder, trade_no: str | None = None) -> None:
|
||||||
|
if order.status == "paid" and order.slots_applied:
|
||||||
|
return
|
||||||
|
if order.status != "pending":
|
||||||
|
raise HTTPException(status_code=400, detail="订单状态不可支付")
|
||||||
|
|
||||||
|
user = await _get_order_user(db, order)
|
||||||
|
await _apply_order_slots(db, order, user)
|
||||||
|
|
||||||
|
order.status = "paid"
|
||||||
|
order.paid_at = datetime.utcnow()
|
||||||
|
if trade_no:
|
||||||
|
order.trade_no = trade_no
|
||||||
|
await db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
async def simulate_pay(db: AsyncSession, user: User, order_no: str) -> PaymentOrder:
|
||||||
|
settings = await load_settings(db)
|
||||||
|
if not settings.payment_demo_mode:
|
||||||
|
raise HTTPException(status_code=403, detail="演示支付未开启")
|
||||||
|
order = await get_user_order(db, user, order_no)
|
||||||
|
if order.status != "pending":
|
||||||
|
raise HTTPException(status_code=400, detail="订单不可支付")
|
||||||
|
await fulfill_order(db, order, trade_no=f"DEMO-{order.order_no}")
|
||||||
|
await db.refresh(order)
|
||||||
|
return order
|
||||||
|
|
||||||
|
|
||||||
|
async def handle_wechat_notify(db: AsyncSession, body: bytes, headers: dict[str, str]) -> bool:
|
||||||
|
settings = await load_settings(db)
|
||||||
|
if not settings.wechat_pay_configured():
|
||||||
|
return False
|
||||||
|
if not wechat.verify_notify_signature(
|
||||||
|
settings,
|
||||||
|
body,
|
||||||
|
headers.get("wechatpay-timestamp", ""),
|
||||||
|
headers.get("wechatpay-nonce", ""),
|
||||||
|
headers.get("wechatpay-signature", ""),
|
||||||
|
headers.get("wechatpay-serial", ""),
|
||||||
|
):
|
||||||
|
return False
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
payload = json.loads(body.decode("utf-8"))
|
||||||
|
resource = payload.get("resource") or {}
|
||||||
|
data = wechat.decrypt_notify_resource(settings.wechat_api_v3_key.strip(), resource)
|
||||||
|
if data.get("trade_state") != "SUCCESS":
|
||||||
|
return True
|
||||||
|
|
||||||
|
order_no = data.get("out_trade_no")
|
||||||
|
trade_no = data.get("transaction_id")
|
||||||
|
result = await db.execute(select(PaymentOrder).where(PaymentOrder.order_no == order_no))
|
||||||
|
order = result.scalar_one_or_none()
|
||||||
|
if not order:
|
||||||
|
return False
|
||||||
|
order.notify_payload = body.decode("utf-8", errors="replace")
|
||||||
|
await fulfill_order(db, order, trade_no=trade_no)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def handle_alipay_notify(db: AsyncSession, params: dict[str, Any]) -> bool:
|
||||||
|
settings = await load_settings(db)
|
||||||
|
if not settings.alipay_configured():
|
||||||
|
return False
|
||||||
|
if not alipay.verify_notify(params, settings):
|
||||||
|
return False
|
||||||
|
if params.get("trade_status") not in ("TRADE_SUCCESS", "TRADE_FINISHED"):
|
||||||
|
return True
|
||||||
|
|
||||||
|
order_no = params.get("out_trade_no")
|
||||||
|
trade_no = params.get("trade_no")
|
||||||
|
result = await db.execute(select(PaymentOrder).where(PaymentOrder.order_no == order_no))
|
||||||
|
order = result.scalar_one_or_none()
|
||||||
|
if not order:
|
||||||
|
return False
|
||||||
|
order.notify_payload = str(params)
|
||||||
|
await fulfill_order(db, order, trade_no=trade_no)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def refresh_expired_orders(db: AsyncSession) -> None:
|
||||||
|
now = datetime.utcnow()
|
||||||
|
await db.execute(
|
||||||
|
update(PaymentOrder)
|
||||||
|
.where(PaymentOrder.status == "pending", PaymentOrder.expires_at < now)
|
||||||
|
.values(status="expired")
|
||||||
|
)
|
||||||
|
await db.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def _order_is_demo(order: PaymentOrder) -> bool:
|
||||||
|
trade_no = (order.trade_no or "").strip()
|
||||||
|
return trade_no.startswith("DEMO-")
|
||||||
|
|
||||||
|
|
||||||
|
def order_list_item(order: PaymentOrder, user: User | None = None) -> dict[str, Any]:
|
||||||
|
payload = {
|
||||||
|
"id": order.id,
|
||||||
|
"order_no": order.order_no,
|
||||||
|
"user_id": order.user_id,
|
||||||
|
"username": user.username if user else None,
|
||||||
|
"display_name": user.display_name if user else None,
|
||||||
|
"channel": order.channel,
|
||||||
|
"slots": order.slots,
|
||||||
|
"amount_fen": order.amount_fen,
|
||||||
|
"amount_yuan": fen_to_yuan(order.amount_fen),
|
||||||
|
"status": order.status,
|
||||||
|
"trade_no": order.trade_no,
|
||||||
|
"is_demo": _order_is_demo(order),
|
||||||
|
"paid_at": order.paid_at,
|
||||||
|
"created_at": order.created_at,
|
||||||
|
}
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
async def list_orders(
|
||||||
|
db: AsyncSession,
|
||||||
|
current_user: User,
|
||||||
|
*,
|
||||||
|
status: str | None = None,
|
||||||
|
channel: str | None = None,
|
||||||
|
page: int = 1,
|
||||||
|
page_size: int = 20,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
await refresh_expired_orders(db)
|
||||||
|
|
||||||
|
page = max(1, page)
|
||||||
|
page_size = max(1, min(100, page_size))
|
||||||
|
|
||||||
|
filters = []
|
||||||
|
if not is_admin(current_user.role):
|
||||||
|
filters.append(PaymentOrder.user_id == current_user.id)
|
||||||
|
if status:
|
||||||
|
filters.append(PaymentOrder.status == status)
|
||||||
|
if channel in ("wechat", "alipay"):
|
||||||
|
filters.append(PaymentOrder.channel == channel)
|
||||||
|
|
||||||
|
count_stmt = select(func.count()).select_from(PaymentOrder)
|
||||||
|
for clause in filters:
|
||||||
|
count_stmt = count_stmt.where(clause)
|
||||||
|
total = int((await db.execute(count_stmt)).scalar() or 0)
|
||||||
|
|
||||||
|
paid_filters = list(filters) + [PaymentOrder.status == "paid"]
|
||||||
|
paid_count_stmt = select(func.count()).select_from(PaymentOrder)
|
||||||
|
for clause in paid_filters:
|
||||||
|
paid_count_stmt = paid_count_stmt.where(clause)
|
||||||
|
paid_count = int((await db.execute(paid_count_stmt)).scalar() or 0)
|
||||||
|
|
||||||
|
paid_amount_stmt = select(func.coalesce(func.sum(PaymentOrder.amount_fen), 0)).select_from(PaymentOrder)
|
||||||
|
for clause in paid_filters:
|
||||||
|
paid_amount_stmt = paid_amount_stmt.where(clause)
|
||||||
|
paid_amount_fen = int((await db.execute(paid_amount_stmt)).scalar() or 0)
|
||||||
|
|
||||||
|
stmt = select(PaymentOrder, User).join(User, User.id == PaymentOrder.user_id)
|
||||||
|
for clause in filters:
|
||||||
|
stmt = stmt.where(clause)
|
||||||
|
stmt = (
|
||||||
|
stmt.order_by(PaymentOrder.created_at.desc())
|
||||||
|
.offset((page - 1) * page_size)
|
||||||
|
.limit(page_size)
|
||||||
|
)
|
||||||
|
rows = (await db.execute(stmt)).all()
|
||||||
|
|
||||||
|
items = [order_list_item(order, user) for order, user in rows]
|
||||||
|
return {
|
||||||
|
"items": items,
|
||||||
|
"total": total,
|
||||||
|
"page": page,
|
||||||
|
"page_size": page_size,
|
||||||
|
"paid_count": paid_count,
|
||||||
|
"paid_amount_yuan": fen_to_yuan(paid_amount_fen),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def admin_update_order_status(
|
||||||
|
db: AsyncSession,
|
||||||
|
order_no: str,
|
||||||
|
new_status: str,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
if new_status not in ORDER_STATUSES:
|
||||||
|
raise HTTPException(status_code=400, detail="无效的订单状态")
|
||||||
|
|
||||||
|
order = await _get_order_by_no(db, order_no)
|
||||||
|
user = await _get_order_user(db, order)
|
||||||
|
old_status = order.status
|
||||||
|
|
||||||
|
if new_status == old_status:
|
||||||
|
return order_list_item(order, user)
|
||||||
|
|
||||||
|
if new_status == "paid":
|
||||||
|
await _apply_order_slots(db, order, user)
|
||||||
|
order.status = "paid"
|
||||||
|
if not order.paid_at:
|
||||||
|
order.paid_at = datetime.utcnow()
|
||||||
|
else:
|
||||||
|
if order.slots_applied:
|
||||||
|
await _revoke_order_slots(db, order, user)
|
||||||
|
order.status = new_status
|
||||||
|
if new_status not in ("paid", "refunded"):
|
||||||
|
order.paid_at = None
|
||||||
|
|
||||||
|
await db.commit()
|
||||||
|
await db.refresh(order)
|
||||||
|
return order_list_item(order, user)
|
||||||
|
|
||||||
|
|
||||||
|
async def admin_delete_order(db: AsyncSession, order_no: str) -> None:
|
||||||
|
order = await _get_order_by_no(db, order_no)
|
||||||
|
if order.slots_applied:
|
||||||
|
user = await _get_order_user(db, order)
|
||||||
|
await _revoke_order_slots(db, order, user)
|
||||||
|
await db.delete(order)
|
||||||
|
await db.commit()
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
"""微信支付 V3 Native 扫码。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from base64 import b64decode, b64encode
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from cryptography.hazmat.primitives import hashes, serialization
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import padding
|
||||||
|
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||||
|
|
||||||
|
from auth.system_settings import SystemSettingsData
|
||||||
|
|
||||||
|
logger = logging.getLogger("payments.wechat")
|
||||||
|
|
||||||
|
WECHAT_API = "https://api.mch.weixin.qq.com"
|
||||||
|
|
||||||
|
|
||||||
|
def _load_private_key(pem: str):
|
||||||
|
text = pem.strip()
|
||||||
|
if "BEGIN" not in text:
|
||||||
|
text = f"-----BEGIN PRIVATE KEY-----\n{text}\n-----END PRIVATE KEY-----"
|
||||||
|
return serialization.load_pem_private_key(text.encode("utf-8"), password=None)
|
||||||
|
|
||||||
|
|
||||||
|
def _sign_message(private_key, message: str) -> str:
|
||||||
|
signature = private_key.sign(
|
||||||
|
message.encode("utf-8"),
|
||||||
|
padding.PKCS1v15(),
|
||||||
|
hashes.SHA256(),
|
||||||
|
)
|
||||||
|
return b64encode(signature).decode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def _build_auth_header(
|
||||||
|
method: str,
|
||||||
|
url_path: str,
|
||||||
|
body: str,
|
||||||
|
mch_id: str,
|
||||||
|
serial_no: str,
|
||||||
|
private_key,
|
||||||
|
) -> str:
|
||||||
|
timestamp = str(int(time.time()))
|
||||||
|
nonce = uuid.uuid4().hex
|
||||||
|
message = f"{method}\n{url_path}\n{timestamp}\n{nonce}\n{body}\n"
|
||||||
|
sign = _sign_message(private_key, message)
|
||||||
|
return (
|
||||||
|
f'WECHATPAY2-SHA256-RSA2048 mchid="{mch_id}",'
|
||||||
|
f'nonce_str="{nonce}",signature="{sign}",'
|
||||||
|
f'timestamp="{timestamp}",serial_no="{serial_no}"'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def create_native_order(
|
||||||
|
settings: SystemSettingsData,
|
||||||
|
order_no: str,
|
||||||
|
description: str,
|
||||||
|
amount_fen: int,
|
||||||
|
notify_url: str,
|
||||||
|
) -> str:
|
||||||
|
"""创建 Native 订单,返回 code_url。"""
|
||||||
|
private_key = _load_private_key(settings.wechat_private_key)
|
||||||
|
url_path = "/v3/pay/transactions/native"
|
||||||
|
payload = {
|
||||||
|
"appid": settings.wechat_app_id.strip(),
|
||||||
|
"mchid": settings.wechat_mch_id.strip(),
|
||||||
|
"description": description[:127],
|
||||||
|
"out_trade_no": order_no,
|
||||||
|
"notify_url": notify_url,
|
||||||
|
"amount": {"total": amount_fen, "currency": "CNY"},
|
||||||
|
}
|
||||||
|
body = json.dumps(payload, ensure_ascii=False)
|
||||||
|
headers = {
|
||||||
|
"Authorization": _build_auth_header(
|
||||||
|
"POST",
|
||||||
|
url_path,
|
||||||
|
body,
|
||||||
|
settings.wechat_mch_id.strip(),
|
||||||
|
settings.wechat_cert_serial.strip(),
|
||||||
|
private_key,
|
||||||
|
),
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"Accept": "application/json",
|
||||||
|
}
|
||||||
|
with httpx.Client(timeout=30.0) as client:
|
||||||
|
resp = client.post(f"{WECHAT_API}{url_path}", content=body.encode("utf-8"), headers=headers)
|
||||||
|
if resp.status_code >= 400:
|
||||||
|
detail = resp.text
|
||||||
|
try:
|
||||||
|
detail = resp.json().get("message") or detail
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
raise RuntimeError(f"微信支付下单失败: {detail}")
|
||||||
|
data = resp.json()
|
||||||
|
code_url = data.get("code_url")
|
||||||
|
if not code_url:
|
||||||
|
raise RuntimeError("微信支付未返回 code_url")
|
||||||
|
return code_url
|
||||||
|
|
||||||
|
|
||||||
|
def decrypt_notify_resource(api_v3_key: str, resource: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
nonce = resource.get("nonce", "")
|
||||||
|
ciphertext = resource.get("ciphertext", "")
|
||||||
|
associated_data = resource.get("associated_data", "")
|
||||||
|
aesgcm = AESGCM(api_v3_key.encode("utf-8"))
|
||||||
|
plain = aesgcm.decrypt(
|
||||||
|
nonce.encode("utf-8"),
|
||||||
|
b64decode(ciphertext),
|
||||||
|
associated_data.encode("utf-8") if associated_data else None,
|
||||||
|
)
|
||||||
|
return json.loads(plain.decode("utf-8"))
|
||||||
|
|
||||||
|
|
||||||
|
def verify_notify_signature(
|
||||||
|
settings: SystemSettingsData,
|
||||||
|
body: bytes,
|
||||||
|
timestamp: str,
|
||||||
|
nonce: str,
|
||||||
|
signature: str,
|
||||||
|
serial: str,
|
||||||
|
) -> bool:
|
||||||
|
"""简化验签:使用平台证书较复杂,此处用商户私钥对应逻辑 + 回调解密校验。"""
|
||||||
|
if not signature or not timestamp or not nonce:
|
||||||
|
return False
|
||||||
|
if serial and serial != settings.wechat_cert_serial.strip():
|
||||||
|
logger.warning("WeChat notify serial mismatch: %s", serial)
|
||||||
|
try:
|
||||||
|
payload = json.loads(body.decode("utf-8"))
|
||||||
|
resource = payload.get("resource") or {}
|
||||||
|
decrypt_notify_resource(settings.wechat_api_v3_key.strip(), resource)
|
||||||
|
return True
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("WeChat notify verify failed: %s", exc)
|
||||||
|
return False
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
# =============================================================================
|
||||||
|
# 抖音多账号自动回复系统 - 完整 Python 依赖
|
||||||
|
# 安装: pip install -r requirements.txt
|
||||||
|
# 环境: Python 3.10 ~ 3.11
|
||||||
|
# =============================================================================
|
||||||
|
#
|
||||||
|
# 【推荐】一键安装与 Web 部署:
|
||||||
|
#
|
||||||
|
# Linux/宝塔(自动探测 Python,兼容 pyporject_evn / 系统 Python):
|
||||||
|
# chmod +x install.sh start_web.sh
|
||||||
|
# ./install.sh --diagnose # 查看本机哪些 Python 可用
|
||||||
|
# ./install.sh # 自动选择可用 Python 安装
|
||||||
|
# AUTO_BUILD_PYTHON=1 ./install.sh # 无可用 Python 时自动编译 3.11
|
||||||
|
# ./start_web.sh
|
||||||
|
#
|
||||||
|
# Windows:
|
||||||
|
# install.bat # 安装 + 构建前端
|
||||||
|
# start_web.bat # 单端口 Web 访问
|
||||||
|
#
|
||||||
|
# pip 安装完成后,还需在服务器执行(install.sh 已包含):
|
||||||
|
#
|
||||||
|
# 1) Playwright 浏览器(扫码登录需要)
|
||||||
|
# python -m playwright install chromium
|
||||||
|
# python -m playwright install-deps # 仅 Linux
|
||||||
|
#
|
||||||
|
# 2) IM 签名 Node 依赖(发送私信 a_bogus 必需,需系统已装 Node.js 18+)
|
||||||
|
# cd rpa_engine/douyin_im/static && npm install
|
||||||
|
#
|
||||||
|
# 3) 前端构建(生产 Web 访问)
|
||||||
|
# cd ../../frontend && npm install && npm run build
|
||||||
|
#
|
||||||
|
# 4) 环境变量(生产务必设置,见项目根 .env.example)
|
||||||
|
# KEFU_SECRET_KEY=随机长字符串
|
||||||
|
# KEFU_ADMIN_PASSWORD=强密码
|
||||||
|
# PLAYWRIGHT_BROWSERS_PATH=/path/to/playwright-browsers
|
||||||
|
#
|
||||||
|
# 宝塔 Python 项目管理器启动命令:
|
||||||
|
# /www/wwwroot/douyin/backend/.venv/bin/python -m uvicorn main:app --host 0.0.0.0 --port 8000
|
||||||
|
# 工作目录: /www/wwwroot/douyin/backend
|
||||||
|
# 运行用户: www(与 chown -R www:www 一致)
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
# --- Web 框架 / ASGI ---
|
||||||
|
fastapi==0.111.0
|
||||||
|
starlette==0.37.2
|
||||||
|
uvicorn==0.30.1
|
||||||
|
httptools==0.8.0
|
||||||
|
watchfiles==1.2.0
|
||||||
|
websockets==12.0
|
||||||
|
python-multipart==0.0.9
|
||||||
|
|
||||||
|
# --- 数据校验 / 配置 ---
|
||||||
|
pydantic==2.7.4
|
||||||
|
pydantic_core==2.18.4
|
||||||
|
annotated-types==0.7.0
|
||||||
|
typing_extensions==4.15.0
|
||||||
|
email-validator==2.3.0
|
||||||
|
dnspython==2.8.0
|
||||||
|
python-dotenv==1.2.2
|
||||||
|
|
||||||
|
# --- 数据库 ---
|
||||||
|
SQLAlchemy==2.0.30
|
||||||
|
aiosqlite==0.20.0
|
||||||
|
# MySQL / PostgreSQL 可选驱动(使用对应数据库类型时需安装)
|
||||||
|
asyncmy==0.2.9
|
||||||
|
asyncpg==0.29.0
|
||||||
|
greenlet==3.0.3
|
||||||
|
|
||||||
|
# --- HTTP 客户端 ---
|
||||||
|
httpx==0.27.0
|
||||||
|
httpcore==1.0.9
|
||||||
|
h11==0.16.0
|
||||||
|
requests==2.34.2
|
||||||
|
urllib3==2.7.0
|
||||||
|
certifi==2026.5.20
|
||||||
|
charset-normalizer==3.4.7
|
||||||
|
idna==3.18
|
||||||
|
sniffio==1.3.1
|
||||||
|
anyio==4.13.0
|
||||||
|
|
||||||
|
# --- 鉴权 / 密码 ---
|
||||||
|
python-jose==3.3.0
|
||||||
|
passlib==1.7.4
|
||||||
|
bcrypt==4.0.1
|
||||||
|
cryptography==49.0.0
|
||||||
|
cffi==2.0.0
|
||||||
|
pycparser==3.0
|
||||||
|
ecdsa==0.19.2
|
||||||
|
pyasn1==0.6.3
|
||||||
|
rsa==4.9.1
|
||||||
|
|
||||||
|
# --- 图片处理(卡片 favicon 转换 / 私信图片尺寸)---
|
||||||
|
Pillow==10.4.0
|
||||||
|
|
||||||
|
# --- 浏览器自动化(登录 / 采集凭证)---
|
||||||
|
playwright==1.44.0
|
||||||
|
pyee==11.1.0
|
||||||
|
# 无图形界面的 Linux 服务器跑有头浏览器需要虚拟显示(还需系统安装 Xvfb):
|
||||||
|
# Debian/Ubuntu: apt install -y xvfb
|
||||||
|
# CentOS/Rocky : yum install -y xorg-x11-server-Xvfb
|
||||||
|
pyvirtualdisplay==3.0
|
||||||
|
|
||||||
|
# --- 抖音 IM(Protobuf / 签名 / WebSocket)---
|
||||||
|
protobuf==5.27.1
|
||||||
|
protobuf3-to-dict==0.1.5
|
||||||
|
six==1.17.0
|
||||||
|
PyExecJS==1.5.1
|
||||||
|
websocket-client==1.9.0
|
||||||
|
|
||||||
|
# --- FastAPI CLI / 工具(随 fastapi 安装,显式锁定避免缺包)---
|
||||||
|
fastapi-cli==0.0.24
|
||||||
|
typer==0.26.7
|
||||||
|
click==8.4.1
|
||||||
|
shellingham==1.5.4
|
||||||
|
rich==15.0.0
|
||||||
|
rich-toolkit==0.20.1
|
||||||
|
Pygments==2.20.0
|
||||||
|
markdown-it-py==4.2.0
|
||||||
|
mdurl==0.1.2
|
||||||
|
Jinja2==3.1.6
|
||||||
|
MarkupSafe==3.0.3
|
||||||
|
annotated-doc==0.0.4
|
||||||
|
orjson==3.11.9
|
||||||
|
ujson==5.12.1
|
||||||
|
PyYAML==6.0.3
|
||||||
|
colorama==0.4.6
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# [npm] IM 签名 jsrsasign(在 rpa_engine/douyin_im/static/package.json)
|
||||||
|
# jsrsasign@^11.1.0
|
||||||
|
#
|
||||||
|
# [npm] 前端(在 frontend/package.json)
|
||||||
|
# vue, ant-design-vue, axios, pinia, vue-router, vite
|
||||||
|
# =============================================================================
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,318 @@
|
|||||||
|
"""Bounded, deduplicated background queue for bulk account starts."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any, Awaitable, Callable
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger("rpa.batch_start")
|
||||||
|
|
||||||
|
StartHandler = Callable[[int], Awaitable[dict[str, Any]]]
|
||||||
|
JobToken = tuple[str, int]
|
||||||
|
|
||||||
|
|
||||||
|
def _configured_concurrency() -> int:
|
||||||
|
try:
|
||||||
|
return max(1, min(8, int(os.getenv("KEFU_BATCH_START_CONCURRENCY", "2"))))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return 2
|
||||||
|
|
||||||
|
|
||||||
|
def _utc_now() -> str:
|
||||||
|
return datetime.now(timezone.utc).isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class _BatchRecord:
|
||||||
|
batch_id: str
|
||||||
|
owner_id: int | None = None
|
||||||
|
metadata: dict[str, Any] = field(default_factory=dict)
|
||||||
|
items: dict[int, dict[str, Any]] = field(default_factory=dict)
|
||||||
|
created_at: str = field(default_factory=_utc_now)
|
||||||
|
updated_at: str = field(default_factory=_utc_now)
|
||||||
|
|
||||||
|
|
||||||
|
class BatchStartQueue:
|
||||||
|
"""Run account preparation with a small process-wide concurrency cap.
|
||||||
|
|
||||||
|
The HTTP endpoint only enqueues account ids. Long credential checks then
|
||||||
|
run in these workers, so a batch of many accounts cannot block the request
|
||||||
|
that submitted it. ``_pending_accounts`` makes overlapping clicks and
|
||||||
|
overlapping batches idempotent for each account. Pending and active
|
||||||
|
ownership is tied to a concrete job token so cleanup from a cancelled old
|
||||||
|
job cannot release a newer submission for the same account.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
handler: StartHandler,
|
||||||
|
concurrency: int | None = None,
|
||||||
|
max_batches: int = 100,
|
||||||
|
) -> None:
|
||||||
|
self._handler = handler
|
||||||
|
self.concurrency = max(1, int(concurrency or _configured_concurrency()))
|
||||||
|
self.max_batches = max(10, int(max_batches or 100))
|
||||||
|
self._queue: asyncio.Queue[JobToken] = asyncio.Queue()
|
||||||
|
self._pending_jobs: dict[int, JobToken] = {}
|
||||||
|
self._active_tasks: dict[int, tuple[JobToken, asyncio.Task]] = {}
|
||||||
|
self._batches: dict[str, _BatchRecord] = {}
|
||||||
|
self._workers: list[asyncio.Task] = []
|
||||||
|
self._lock = asyncio.Lock()
|
||||||
|
self._stopping = False
|
||||||
|
|
||||||
|
async def _ensure_workers(self) -> None:
|
||||||
|
async with self._lock:
|
||||||
|
self._workers = [task for task in self._workers if not task.done()]
|
||||||
|
if self._workers or self._stopping:
|
||||||
|
return
|
||||||
|
for index in range(self.concurrency):
|
||||||
|
self._workers.append(
|
||||||
|
asyncio.create_task(
|
||||||
|
self._worker(index + 1),
|
||||||
|
name=f"account-batch-start-{index + 1}",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
async def submit(
|
||||||
|
self,
|
||||||
|
account_ids: list[int],
|
||||||
|
owner_id: int | None = None,
|
||||||
|
metadata: dict[str, Any] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
await self._ensure_workers()
|
||||||
|
unique_ids = list(dict.fromkeys(int(value) for value in account_ids if int(value) > 0))
|
||||||
|
batch_id = uuid.uuid4().hex
|
||||||
|
record = _BatchRecord(
|
||||||
|
batch_id=batch_id,
|
||||||
|
owner_id=owner_id,
|
||||||
|
metadata=dict(metadata or {}),
|
||||||
|
)
|
||||||
|
|
||||||
|
async with self._lock:
|
||||||
|
if self._stopping:
|
||||||
|
raise RuntimeError("账号启动队列正在停止")
|
||||||
|
self._prune_locked()
|
||||||
|
self._batches[batch_id] = record
|
||||||
|
for account_id in unique_ids:
|
||||||
|
if account_id in self._pending_jobs:
|
||||||
|
record.items[account_id] = {
|
||||||
|
"account_id": account_id,
|
||||||
|
"status": "already_queued",
|
||||||
|
"message": "账号已在启动队列中",
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
job_token = (batch_id, account_id)
|
||||||
|
self._pending_jobs[account_id] = job_token
|
||||||
|
record.items[account_id] = {
|
||||||
|
"account_id": account_id,
|
||||||
|
"status": "queued",
|
||||||
|
"message": "等待启动",
|
||||||
|
}
|
||||||
|
self._queue.put_nowait(job_token)
|
||||||
|
record.updated_at = _utc_now()
|
||||||
|
return self._snapshot_locked(record)
|
||||||
|
|
||||||
|
async def get_batch(
|
||||||
|
self,
|
||||||
|
batch_id: str,
|
||||||
|
owner_id: int | None = None,
|
||||||
|
include_items: bool = False,
|
||||||
|
) -> dict[str, Any] | None:
|
||||||
|
async with self._lock:
|
||||||
|
record = self._batches.get(str(batch_id or ""))
|
||||||
|
if record and owner_id is not None and record.owner_id != int(owner_id):
|
||||||
|
return None
|
||||||
|
return self._snapshot_locked(record, include_items=include_items) if record else None
|
||||||
|
|
||||||
|
async def _worker(self, worker_number: int) -> None:
|
||||||
|
while True:
|
||||||
|
batch_id, account_id = await self._queue.get()
|
||||||
|
job_token = (batch_id, account_id)
|
||||||
|
started_at = time.monotonic()
|
||||||
|
handler_task: asyncio.Task | None = None
|
||||||
|
try:
|
||||||
|
async with self._lock:
|
||||||
|
record = self._batches.get(batch_id)
|
||||||
|
if not record:
|
||||||
|
if self._pending_jobs.get(account_id) == job_token:
|
||||||
|
self._pending_jobs.pop(account_id, None)
|
||||||
|
continue
|
||||||
|
item = record.items[account_id]
|
||||||
|
if item.get("status") == "cancelled":
|
||||||
|
if self._pending_jobs.get(account_id) == job_token:
|
||||||
|
self._pending_jobs.pop(account_id, None)
|
||||||
|
continue
|
||||||
|
item.update(status="processing", message="正在校验并启动")
|
||||||
|
record.updated_at = _utc_now()
|
||||||
|
handler_task = asyncio.create_task(
|
||||||
|
self._handler(account_id),
|
||||||
|
name=f"account-start-{account_id}",
|
||||||
|
)
|
||||||
|
self._active_tasks[account_id] = (job_token, handler_task)
|
||||||
|
|
||||||
|
result = await handler_task
|
||||||
|
async with self._lock:
|
||||||
|
record = self._batches.get(batch_id)
|
||||||
|
if record:
|
||||||
|
item = record.items[account_id]
|
||||||
|
if item.get("status") != "cancelled":
|
||||||
|
item.update(
|
||||||
|
status="submitted",
|
||||||
|
message=str(result.get("message") or "已提交启动"),
|
||||||
|
login_mode=result.get("login_mode"),
|
||||||
|
skip_browser=bool(result.get("skip_browser", False)),
|
||||||
|
elapsed_seconds=round(time.monotonic() - started_at, 3),
|
||||||
|
)
|
||||||
|
record.updated_at = _utc_now()
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
async with self._lock:
|
||||||
|
record = self._batches.get(batch_id)
|
||||||
|
if record:
|
||||||
|
record.items[account_id].update(
|
||||||
|
status="cancelled",
|
||||||
|
message="服务停止,启动任务已取消",
|
||||||
|
)
|
||||||
|
record.updated_at = _utc_now()
|
||||||
|
# Cancelling one account must not kill a long-lived queue
|
||||||
|
# worker. Re-raise only when stop() cancelled the worker.
|
||||||
|
if asyncio.current_task().cancelling():
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception(
|
||||||
|
"Batch start failed account=%s worker=%s: %s",
|
||||||
|
account_id,
|
||||||
|
worker_number,
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
async with self._lock:
|
||||||
|
record = self._batches.get(batch_id)
|
||||||
|
if record:
|
||||||
|
detail = getattr(exc, "detail", None) or str(exc) or "启动失败"
|
||||||
|
item = record.items[account_id]
|
||||||
|
if item.get("status") != "cancelled":
|
||||||
|
item.update(
|
||||||
|
status="failed",
|
||||||
|
message=str(detail),
|
||||||
|
elapsed_seconds=round(time.monotonic() - started_at, 3),
|
||||||
|
)
|
||||||
|
record.updated_at = _utc_now()
|
||||||
|
finally:
|
||||||
|
async with self._lock:
|
||||||
|
active_entry = self._active_tasks.get(account_id)
|
||||||
|
if active_entry == (job_token, handler_task):
|
||||||
|
self._active_tasks.pop(account_id, None)
|
||||||
|
if self._pending_jobs.get(account_id) == job_token:
|
||||||
|
self._pending_jobs.pop(account_id, None)
|
||||||
|
self._queue.task_done()
|
||||||
|
|
||||||
|
async def cancel_account(self, account_id: int) -> int:
|
||||||
|
"""Cancel queued/processing work so stop/delete cannot restart it."""
|
||||||
|
account_key = int(account_id)
|
||||||
|
cancelled = 0
|
||||||
|
active_task: asyncio.Task | None = None
|
||||||
|
async with self._lock:
|
||||||
|
for record in self._batches.values():
|
||||||
|
item = record.items.get(account_key)
|
||||||
|
if not item or item.get("status") not in ("queued", "processing"):
|
||||||
|
continue
|
||||||
|
item.update(status="cancelled", message="启动任务已取消")
|
||||||
|
record.updated_at = _utc_now()
|
||||||
|
cancelled += 1
|
||||||
|
self._pending_jobs.pop(account_key, None)
|
||||||
|
active_entry = self._active_tasks.get(account_key)
|
||||||
|
active_task = active_entry[1] if active_entry else None
|
||||||
|
if active_task and not active_task.done():
|
||||||
|
active_task.cancel()
|
||||||
|
if active_task and not active_task.done():
|
||||||
|
await asyncio.gather(active_task, return_exceptions=True)
|
||||||
|
return cancelled
|
||||||
|
|
||||||
|
def _snapshot_locked(
|
||||||
|
self,
|
||||||
|
record: _BatchRecord,
|
||||||
|
*,
|
||||||
|
include_items: bool = True,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
counts = {
|
||||||
|
"queued": 0,
|
||||||
|
"processing": 0,
|
||||||
|
"submitted": 0,
|
||||||
|
"failed": 0,
|
||||||
|
"skipped": 0,
|
||||||
|
"cancelled": 0,
|
||||||
|
}
|
||||||
|
browser_required = 0
|
||||||
|
for item in record.items.values():
|
||||||
|
status = item.get("status")
|
||||||
|
if status == "submitted" and item.get("skip_browser") is False:
|
||||||
|
browser_required += 1
|
||||||
|
if status == "already_queued":
|
||||||
|
counts["skipped"] += 1
|
||||||
|
elif status in counts:
|
||||||
|
counts[status] += 1
|
||||||
|
active = counts["queued"] + counts["processing"]
|
||||||
|
snapshot = {
|
||||||
|
"batch_id": record.batch_id,
|
||||||
|
"total_count": len(record.items),
|
||||||
|
"accepted_count": len(record.items) - counts["skipped"],
|
||||||
|
"queued_count": counts["queued"],
|
||||||
|
"processing_count": counts["processing"],
|
||||||
|
"submitted_count": counts["submitted"],
|
||||||
|
"failed_count": counts["failed"],
|
||||||
|
"skipped_count": counts["skipped"],
|
||||||
|
"cancelled_count": counts["cancelled"],
|
||||||
|
"browser_required_count": browser_required,
|
||||||
|
"complete": active == 0,
|
||||||
|
"created_at": record.created_at,
|
||||||
|
"updated_at": record.updated_at,
|
||||||
|
}
|
||||||
|
snapshot.update(record.metadata)
|
||||||
|
if include_items:
|
||||||
|
snapshot["items"] = [dict(item) for item in record.items.values()]
|
||||||
|
return snapshot
|
||||||
|
|
||||||
|
def _prune_locked(self) -> None:
|
||||||
|
if len(self._batches) < self.max_batches:
|
||||||
|
return
|
||||||
|
removable = [
|
||||||
|
batch_id
|
||||||
|
for batch_id, record in self._batches.items()
|
||||||
|
if self._snapshot_locked(record, include_items=False)["complete"]
|
||||||
|
]
|
||||||
|
for batch_id in removable[: max(1, len(self._batches) - self.max_batches + 1)]:
|
||||||
|
self._batches.pop(batch_id, None)
|
||||||
|
|
||||||
|
async def stop(self) -> None:
|
||||||
|
async with self._lock:
|
||||||
|
self._stopping = True
|
||||||
|
workers = list(self._workers)
|
||||||
|
self._workers.clear()
|
||||||
|
for task in workers:
|
||||||
|
task.cancel()
|
||||||
|
if workers:
|
||||||
|
await asyncio.gather(*workers, return_exceptions=True)
|
||||||
|
async with self._lock:
|
||||||
|
self._active_tasks.clear()
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
batch_id, account_id = self._queue.get_nowait()
|
||||||
|
except asyncio.QueueEmpty:
|
||||||
|
break
|
||||||
|
record = self._batches.get(batch_id)
|
||||||
|
if record:
|
||||||
|
record.items[account_id].update(
|
||||||
|
status="cancelled",
|
||||||
|
message="服务停止,启动任务已取消",
|
||||||
|
)
|
||||||
|
record.updated_at = _utc_now()
|
||||||
|
job_token = (batch_id, account_id)
|
||||||
|
if self._pending_jobs.get(account_id) == job_token:
|
||||||
|
self._pending_jobs.pop(account_id, None)
|
||||||
|
self._queue.task_done()
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
"""账号凭证检测:静态 Cookie 分析 + IM 运行时校验"""
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from rpa_engine.douyin_im.auth import DouyinAuth
|
||||||
|
from rpa_engine.douyin_im.frontier import ensure_frontier_ws
|
||||||
|
from rpa_engine.douyin_im.http_client import DouyinImHttpClient
|
||||||
|
from rpa_engine.douyin_im.session import DouyinImSession
|
||||||
|
from utils.cookie_store import analyze_cookie
|
||||||
|
|
||||||
|
logger = logging.getLogger("credential")
|
||||||
|
|
||||||
|
|
||||||
|
def _should_reset_credentials(assessment: dict) -> bool:
|
||||||
|
"""凭证全面失效时需清空 Cookie/IM 数据并重新登录。"""
|
||||||
|
if not assessment.get("has_cookie"):
|
||||||
|
return False
|
||||||
|
if not assessment.get("cookie_valid"):
|
||||||
|
return True
|
||||||
|
message = assessment.get("message") or ""
|
||||||
|
# 仅缺 ticket/签名/浏览器采集 — 保留 Cookie,走浏览器补全即可
|
||||||
|
if any(
|
||||||
|
token in message
|
||||||
|
for token in ("ticket", "签名密钥", "浏览器模式", "web_protect")
|
||||||
|
):
|
||||||
|
return False
|
||||||
|
if (
|
||||||
|
not assessment.get("im_ready")
|
||||||
|
and not assessment.get("can_skip_browser")
|
||||||
|
and assessment.get("has_sessionid")
|
||||||
|
):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def build_im_session_from_storage(
|
||||||
|
storage: dict,
|
||||||
|
saved_im_data: Optional[str] = None,
|
||||||
|
) -> DouyinImSession:
|
||||||
|
session = DouyinImSession.from_storage_state(storage or {})
|
||||||
|
if saved_im_data:
|
||||||
|
try:
|
||||||
|
saved = DouyinImSession.from_dict(json.loads(saved_im_data))
|
||||||
|
# 新粘贴的 storage_state(含真实 frontier_ws_url)优先;只有它没带时才用缓存的。
|
||||||
|
if saved.ws_urls and not session.ws_urls:
|
||||||
|
session.ws_urls = saved.ws_urls
|
||||||
|
if saved.sdk_cert and not session.sdk_cert:
|
||||||
|
session.sdk_cert = saved.sdk_cert
|
||||||
|
if saved.frontier_ts_sign and not session.frontier_ts_sign:
|
||||||
|
session.frontier_ts_sign = saved.frontier_ts_sign
|
||||||
|
if saved.keys_str and not session.keys_str:
|
||||||
|
session.keys_str = saved.keys_str
|
||||||
|
if saved.web_protect_str and not session.web_protect_str:
|
||||||
|
session.web_protect_str = saved.web_protect_str
|
||||||
|
if saved.my_uid and not session.my_uid:
|
||||||
|
session.my_uid = saved.my_uid
|
||||||
|
if saved.device_id and not session.device_id:
|
||||||
|
session.device_id = saved.device_id
|
||||||
|
if saved.web_id and not session.web_id:
|
||||||
|
session.web_id = saved.web_id
|
||||||
|
if saved.conv_meta:
|
||||||
|
session.conv_meta = {**saved.conv_meta, **session.conv_meta}
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
session.sanitize_ws_urls()
|
||||||
|
# Keep this builder pure and non-blocking. Frontier discovery can perform
|
||||||
|
# a synchronous network request (up to 15 seconds); callers that need it
|
||||||
|
# already do so from validate_im_session() through asyncio.to_thread() and
|
||||||
|
# the shared background-traffic limiter. Running it here made a large
|
||||||
|
# batch freeze the FastAPI event loop before any limiter was acquired.
|
||||||
|
return session
|
||||||
|
|
||||||
|
|
||||||
|
def has_im_session_token(session: DouyinImSession) -> bool:
|
||||||
|
return bool(session.cookies.get("sessionid") or session.cookies.get("sessionid_ss"))
|
||||||
|
|
||||||
|
|
||||||
|
def extract_sessionid_info(session: DouyinImSession) -> dict:
|
||||||
|
sessionid = session.cookies.get("sessionid") or ""
|
||||||
|
sessionid_ss = session.cookies.get("sessionid_ss") or ""
|
||||||
|
return {
|
||||||
|
"has_sessionid": bool(sessionid or sessionid_ss),
|
||||||
|
"sessionid": sessionid,
|
||||||
|
"sessionid_ss": sessionid_ss,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def build_cookie_credential_detail(
|
||||||
|
cookie_data: Optional[str],
|
||||||
|
im_session_data: Optional[str] = None,
|
||||||
|
runtime_check: bool = True,
|
||||||
|
) -> dict:
|
||||||
|
"""供编辑账号页展示 IM 凭证与 sessionid 信息"""
|
||||||
|
sessionid_info = {
|
||||||
|
"has_sessionid": False,
|
||||||
|
"sessionid": "",
|
||||||
|
"sessionid_ss": "",
|
||||||
|
"im_ready": False,
|
||||||
|
"im_status": "未保存 Cookie",
|
||||||
|
"can_skip_browser": False,
|
||||||
|
"should_reset": False,
|
||||||
|
}
|
||||||
|
if not cookie_data:
|
||||||
|
return sessionid_info
|
||||||
|
|
||||||
|
try:
|
||||||
|
storage = json.loads(cookie_data)
|
||||||
|
session = build_im_session_from_storage(storage, im_session_data)
|
||||||
|
sessionid_info.update(extract_sessionid_info(session))
|
||||||
|
except Exception:
|
||||||
|
sessionid_info["im_status"] = "Cookie 格式错误"
|
||||||
|
return sessionid_info
|
||||||
|
|
||||||
|
if not runtime_check:
|
||||||
|
if sessionid_info["has_sessionid"]:
|
||||||
|
sessionid_info["im_status"] = "已检测到 sessionid(未做运行时验证)"
|
||||||
|
else:
|
||||||
|
sessionid_info["im_status"] = "缺少 sessionid,无法 IM 直连"
|
||||||
|
return sessionid_info
|
||||||
|
|
||||||
|
assessment = await assess_account_credential(cookie_data, im_session_data)
|
||||||
|
sessionid_info["im_ready"] = assessment["im_ready"]
|
||||||
|
sessionid_info["im_status"] = assessment["message"]
|
||||||
|
sessionid_info["can_skip_browser"] = assessment["can_skip_browser"]
|
||||||
|
sessionid_info["should_reset"] = assessment["should_reset"]
|
||||||
|
return sessionid_info
|
||||||
|
|
||||||
|
|
||||||
|
async def validate_im_session(
|
||||||
|
session: DouyinImSession,
|
||||||
|
_bypass_global_limit: bool = False,
|
||||||
|
) -> tuple[bool, str]:
|
||||||
|
if not _bypass_global_limit:
|
||||||
|
from rpa_engine.douyin_im.traffic_control import get_traffic_controller
|
||||||
|
|
||||||
|
controller = get_traffic_controller()
|
||||||
|
async with controller.background_slot(0, "credential validation"):
|
||||||
|
return await validate_im_session(session, _bypass_global_limit=True)
|
||||||
|
|
||||||
|
if not session.can_direct_im():
|
||||||
|
if not has_im_session_token(session):
|
||||||
|
return False, "缺少 sessionid,无法直连 IM"
|
||||||
|
return False, "Cookie 不满足 IM 直连条件"
|
||||||
|
|
||||||
|
await asyncio.to_thread(ensure_frontier_ws, session)
|
||||||
|
try:
|
||||||
|
auth = DouyinAuth.from_im_session(session)
|
||||||
|
# 优先用已持久化的 my_uid,避免每次都发起网络 query_my_uid(uid_tt 是加密串,
|
||||||
|
# int() 解析必然失败而回退到网络请求;该请求偶发失败会误判为“未就绪”)。
|
||||||
|
uid = session.my_uid or auth.get_uid()
|
||||||
|
if not uid:
|
||||||
|
return False, "服务端未认可当前 Cookie(无法获取用户 UID)"
|
||||||
|
if not auth.is_sign_ready():
|
||||||
|
return False, "缺少 IM 签名密钥(web_protect/keys),请用浏览器登录补全"
|
||||||
|
session.my_uid = int(uid)
|
||||||
|
async with DouyinImHttpClient(session) as http:
|
||||||
|
await http.get_unread_count()
|
||||||
|
# 若已缓存到会话票据,优先校验其是否仍新鲜(最理想)。
|
||||||
|
if session.conv_meta:
|
||||||
|
ok, reason = await http.verify_messaging_capability(auth, session.my_uid)
|
||||||
|
if ok:
|
||||||
|
return True, reason
|
||||||
|
# 没有缓存会话票据是首次登录的正常情况:会话 ticket 会在发送时即时
|
||||||
|
# 创建/获取(resolve_conversation_meta),因此只要 Cookie + sessionid +
|
||||||
|
# 签名密钥(web_protect/keys) + UID 齐全,就视为可 IM 直连托管,不必再开浏览器。
|
||||||
|
return True, "IM 凭证就绪(Cookie 与签名密钥齐全,可直连托管)"
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"IM session validation failed: {e}")
|
||||||
|
return False, f"IM 运行时验证失败: {e}"
|
||||||
|
|
||||||
|
|
||||||
|
async def assess_account_credential(
|
||||||
|
cookie_data: Optional[str],
|
||||||
|
im_session_data: Optional[str] = None,
|
||||||
|
) -> dict:
|
||||||
|
cookie_info = analyze_cookie(cookie_data)
|
||||||
|
result = {
|
||||||
|
"has_cookie": cookie_info.get("has_cookie", False),
|
||||||
|
"cookie_valid": cookie_info.get("cookie_valid", False),
|
||||||
|
"cookie_status": cookie_info.get("reason", ""),
|
||||||
|
"has_sessionid": False,
|
||||||
|
"im_ready": False,
|
||||||
|
"can_skip_browser": False,
|
||||||
|
"login_mode": "browser",
|
||||||
|
"message": "未保存 Cookie,需浏览器扫码登录",
|
||||||
|
"should_reset": False,
|
||||||
|
}
|
||||||
|
|
||||||
|
if not cookie_data:
|
||||||
|
return result
|
||||||
|
|
||||||
|
try:
|
||||||
|
storage = json.loads(cookie_data)
|
||||||
|
except Exception:
|
||||||
|
result["message"] = "Cookie 格式错误"
|
||||||
|
result["should_reset"] = _should_reset_credentials(result)
|
||||||
|
return result
|
||||||
|
|
||||||
|
session = build_im_session_from_storage(storage, im_session_data)
|
||||||
|
result["has_sessionid"] = has_im_session_token(session)
|
||||||
|
|
||||||
|
if not cookie_info.get("cookie_valid"):
|
||||||
|
result["message"] = cookie_info.get("reason") or "Cookie 无效,需重新登录"
|
||||||
|
result["should_reset"] = _should_reset_credentials(result)
|
||||||
|
return result
|
||||||
|
|
||||||
|
if not result["has_sessionid"]:
|
||||||
|
result["login_mode"] = "browser"
|
||||||
|
result["message"] = "Cookie 已保存但缺少 sessionid,需浏览器刷新登录态"
|
||||||
|
result["should_reset"] = _should_reset_credentials(result)
|
||||||
|
return result
|
||||||
|
|
||||||
|
im_ok, im_reason = await validate_im_session(session)
|
||||||
|
result["im_ready"] = im_ok
|
||||||
|
if im_ok:
|
||||||
|
result["can_skip_browser"] = True
|
||||||
|
result["login_mode"] = "im_direct"
|
||||||
|
result["message"] = im_reason
|
||||||
|
else:
|
||||||
|
result["login_mode"] = "browser"
|
||||||
|
result["message"] = im_reason
|
||||||
|
|
||||||
|
result["should_reset"] = _should_reset_credentials(result)
|
||||||
|
return result
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
"""浏览器 / IM 伪装设备头(User-Agent)预设。
|
||||||
|
|
||||||
|
a_bogus 签名、Playwright 浏览器上下文、IM HTTP 请求头、Protobuf body 必须使用同一 UA,
|
||||||
|
否则抖音会返回 7911 安全校验失败。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from rpa_engine.douyin_im.dy_util import DEFAULT_USER_AGENT
|
||||||
|
|
||||||
|
# id 用于前端下拉;user_agent 为完整字符串
|
||||||
|
DEVICE_PROFILES: list[dict[str, str]] = [
|
||||||
|
{
|
||||||
|
"id": "chrome_win120",
|
||||||
|
"label": "Chrome 120 · Windows(默认,推荐)",
|
||||||
|
"platform": "Windows",
|
||||||
|
"user_agent": DEFAULT_USER_AGENT,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "chrome_win131",
|
||||||
|
"label": "Chrome 131 · Windows",
|
||||||
|
"platform": "Windows",
|
||||||
|
"user_agent": (
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||||
|
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "edge_win125",
|
||||||
|
"label": "Edge 125 · Windows",
|
||||||
|
"platform": "Windows",
|
||||||
|
"user_agent": (
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||||
|
"(KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0"
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "firefox_win117",
|
||||||
|
"label": "Firefox 117 · Windows",
|
||||||
|
"platform": "Windows",
|
||||||
|
"user_agent": (
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) "
|
||||||
|
"Gecko/20100101 Firefox/117.0"
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "chrome_mac120",
|
||||||
|
"label": "Chrome 120 · macOS",
|
||||||
|
"platform": "macOS",
|
||||||
|
"user_agent": (
|
||||||
|
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
|
||||||
|
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "safari_mac17",
|
||||||
|
"label": "Safari 17 · macOS",
|
||||||
|
"platform": "macOS",
|
||||||
|
"user_agent": (
|
||||||
|
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 "
|
||||||
|
"(KHTML, like Gecko) Version/17.0 Safari/605.1.15"
|
||||||
|
),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
_PROFILE_BY_UA = {p["user_agent"]: p for p in DEVICE_PROFILES}
|
||||||
|
|
||||||
|
|
||||||
|
def list_device_profiles() -> list[dict[str, str]]:
|
||||||
|
return [
|
||||||
|
{"id": p["id"], "label": p["label"], "platform": p["platform"], "user_agent": p["user_agent"]}
|
||||||
|
for p in DEVICE_PROFILES
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_user_agent(stored: str | None) -> str:
|
||||||
|
"""账号保存的 UA;空则使用默认 Chrome 120。"""
|
||||||
|
text = (stored or "").strip()
|
||||||
|
return text or DEFAULT_USER_AGENT
|
||||||
|
|
||||||
|
|
||||||
|
def profile_label_for_ua(ua: str | None) -> str:
|
||||||
|
text = (ua or "").strip()
|
||||||
|
if not text:
|
||||||
|
return "Chrome 120 · Windows(默认)"
|
||||||
|
hit = _PROFILE_BY_UA.get(text)
|
||||||
|
if hit:
|
||||||
|
return hit["label"]
|
||||||
|
if len(text) > 48:
|
||||||
|
return text[:48] + "…"
|
||||||
|
return text
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
from .service import DouyinImService
|
||||||
|
|
||||||
|
__all__ = ["DouyinImService"]
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import requests
|
||||||
|
from .dy_util import (
|
||||||
|
trans_cookies,
|
||||||
|
generate_msToken,
|
||||||
|
generate_a_bogus,
|
||||||
|
splice_url,
|
||||||
|
generate_webid,
|
||||||
|
normalize_client_cert,
|
||||||
|
resolve_proto_device_id,
|
||||||
|
DEFAULT_USER_AGENT,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger("douyin_im.auth")
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_storage_json(raw) -> dict | None:
|
||||||
|
"""Parse localStorage JSON (supports nested data wrapper)."""
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
if isinstance(raw, dict):
|
||||||
|
data = raw
|
||||||
|
else:
|
||||||
|
text = str(raw).strip()
|
||||||
|
data = None
|
||||||
|
for _ in range(4):
|
||||||
|
try:
|
||||||
|
parsed = json.loads(text)
|
||||||
|
except Exception:
|
||||||
|
break
|
||||||
|
if isinstance(parsed, str):
|
||||||
|
text = parsed
|
||||||
|
continue
|
||||||
|
if isinstance(parsed, dict):
|
||||||
|
data = parsed
|
||||||
|
break
|
||||||
|
break
|
||||||
|
if not data:
|
||||||
|
return None
|
||||||
|
|
||||||
|
inner = data.get("data")
|
||||||
|
if isinstance(inner, str):
|
||||||
|
try:
|
||||||
|
inner = json.loads(inner)
|
||||||
|
except Exception:
|
||||||
|
inner = None
|
||||||
|
if isinstance(inner, dict):
|
||||||
|
return inner
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
class DouyinAuth:
|
||||||
|
def __init__(self):
|
||||||
|
self.cookie = None
|
||||||
|
self.cookie_str = None
|
||||||
|
self.private_key = None
|
||||||
|
self.ticket = None
|
||||||
|
self.ts_sign = None
|
||||||
|
self.client_cert = None
|
||||||
|
self.ree_public_key = None
|
||||||
|
self.uid = None
|
||||||
|
self.msToken = None
|
||||||
|
self.web_id = None
|
||||||
|
|
||||||
|
def perepare_auth(self, cookieStr: str, web_protect_: str = "", keys_: str = ""):
|
||||||
|
self.cookie = trans_cookies(cookieStr)
|
||||||
|
self.cookie_str = cookieStr
|
||||||
|
self.msToken = self.cookie["msToken"] if "msToken" in self.cookie else generate_msToken()
|
||||||
|
self.cookie["msToken"] = self.msToken
|
||||||
|
self.cookie_str = "; ".join([f"{k}={v}" for k, v in self.cookie.items()])
|
||||||
|
web_data = _parse_storage_json(web_protect_)
|
||||||
|
if web_data:
|
||||||
|
try:
|
||||||
|
self.ticket = web_data.get("ticket") or ""
|
||||||
|
self.ts_sign = web_data.get("ts_sign") or ""
|
||||||
|
self.client_cert = web_data.get("client_cert") or ""
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"web_protect parse failed: {e}")
|
||||||
|
|
||||||
|
keys_data = _parse_storage_json(keys_)
|
||||||
|
if keys_data:
|
||||||
|
try:
|
||||||
|
self.private_key = keys_data.get("ec_privateKey") or keys_data.get("privateKey") or ""
|
||||||
|
if self.private_key:
|
||||||
|
self.ree_public_key = base64.b64encode(self.private_key.encode()).decode()
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"keys parse failed: {e}")
|
||||||
|
|
||||||
|
def is_sign_ready(self) -> bool:
|
||||||
|
return bool(
|
||||||
|
self.private_key
|
||||||
|
and self.ticket
|
||||||
|
and self.ts_sign
|
||||||
|
and self.client_cert
|
||||||
|
)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_im_session(cls, session) -> "DouyinAuth":
|
||||||
|
"""从 DouyinImSession 构建 HTTP 发送/拉会话用的签名上下文。
|
||||||
|
|
||||||
|
注意:frontier WS 的 sdk_cert/ts_sign 只用于长连接,不能覆盖 web_protect,
|
||||||
|
否则 bd-ticket-guard 与 protobuf 签名会与 ticket 失配 -> 7911。
|
||||||
|
"""
|
||||||
|
auth = cls()
|
||||||
|
auth.perepare_auth(
|
||||||
|
session.cookie_header(),
|
||||||
|
session.web_protect_str,
|
||||||
|
session.keys_str,
|
||||||
|
)
|
||||||
|
auth.web_id = session.web_id or session.device_id or None
|
||||||
|
auth.user_agent = session.user_agent or DEFAULT_USER_AGENT
|
||||||
|
auth.device_id = resolve_proto_device_id(
|
||||||
|
session.device_id, session.web_id, session.my_uid
|
||||||
|
)
|
||||||
|
# web_protect 缺 client_cert 时,才用 frontier 抓包证书兜底(不覆盖 ts_sign)
|
||||||
|
if not auth.client_cert and getattr(session, "sdk_cert", ""):
|
||||||
|
auth.client_cert = normalize_client_cert(session.sdk_cert)
|
||||||
|
elif auth.client_cert:
|
||||||
|
auth.client_cert = normalize_client_cert(auth.client_cert)
|
||||||
|
return auth
|
||||||
|
|
||||||
|
def get_uid(self):
|
||||||
|
if self.uid is None:
|
||||||
|
# 优先从 cookie 尝试提取,否则请求接口
|
||||||
|
for k in ("uid_tt", "uid_tt_ss"):
|
||||||
|
if self.cookie and self.cookie.get(k):
|
||||||
|
try:
|
||||||
|
self.uid = int(self.cookie.get(k))
|
||||||
|
return self.uid
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
self.uid = self.query_my_uid()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return self.uid
|
||||||
|
|
||||||
|
def query_my_uid(self) -> int:
|
||||||
|
url = 'https://www.douyin.com/aweme/v1/web/query/user/'
|
||||||
|
headers = {
|
||||||
|
"User-Agent": DEFAULT_USER_AGENT,
|
||||||
|
"Referer": "https://www.douyin.com/",
|
||||||
|
"Accept": "application/json, text/plain, */*",
|
||||||
|
}
|
||||||
|
params = {
|
||||||
|
"device_platform": "webapp",
|
||||||
|
"aid": "6383",
|
||||||
|
"channel": "channel_pc_web",
|
||||||
|
"publish_video_strategy_type": "2",
|
||||||
|
"verifyFp": self.cookie.get('s_v_web_id', ''),
|
||||||
|
"fp": self.cookie.get('s_v_web_id', ''),
|
||||||
|
"webid": generate_webid(self, "https://www.douyin.com/"),
|
||||||
|
"msToken": self.msToken
|
||||||
|
}
|
||||||
|
query = splice_url(params)
|
||||||
|
abogus = generate_a_bogus(query, user_agent=DEFAULT_USER_AGENT)
|
||||||
|
params['a_bogus'] = abogus
|
||||||
|
|
||||||
|
resp = requests.get(url, params=params, headers=headers, cookies=self.cookie, verify=False, timeout=10)
|
||||||
|
resp_json = resp.json()
|
||||||
|
return int(resp_json['user_uid'])
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
"""Conversation id helpers for Douyin IM."""
|
||||||
|
|
||||||
|
|
||||||
|
def parse_conversation_parts(conversation_id: str) -> tuple[int, int] | None:
|
||||||
|
parts = (conversation_id or "").split(":")
|
||||||
|
if len(parts) >= 4 and parts[0] == "0" and parts[1] == "1":
|
||||||
|
try:
|
||||||
|
return int(parts[2]), int(parts[3])
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_peer_uid(conversation_id: str, my_uid: int) -> int | None:
|
||||||
|
"""Resolve peer user id from conversation id or bare numeric id."""
|
||||||
|
raw = (conversation_id or "").strip()
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
|
||||||
|
parts = parse_conversation_parts(raw)
|
||||||
|
if parts:
|
||||||
|
uid1, uid2 = parts
|
||||||
|
if my_uid and uid1 == my_uid:
|
||||||
|
return uid2
|
||||||
|
if my_uid and uid2 == my_uid:
|
||||||
|
return uid1
|
||||||
|
# 0:1:{my}:{peer} — 若 my_uid 与首段不一致,仍取末段为对方
|
||||||
|
return uid2
|
||||||
|
|
||||||
|
if raw.isdigit():
|
||||||
|
peer = int(raw)
|
||||||
|
if my_uid and peer == my_uid:
|
||||||
|
return None
|
||||||
|
return peer
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def build_conversation_id(my_uid: int, peer_uid: int) -> str:
|
||||||
|
return f"0:1:{int(my_uid)}:{int(peer_uid)}"
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_conversation_id(conversation_id: str, my_uid: int) -> str:
|
||||||
|
"""Ensure conversation id uses current account uid as first participant."""
|
||||||
|
peer_uid = resolve_peer_uid(conversation_id, my_uid)
|
||||||
|
if peer_uid and my_uid:
|
||||||
|
return build_conversation_id(my_uid, peer_uid)
|
||||||
|
return (conversation_id or "").strip()
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
import hashlib
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
import json
|
||||||
|
import random
|
||||||
|
import base64
|
||||||
|
import urllib.parse
|
||||||
|
from os import path
|
||||||
|
import subprocess
|
||||||
|
original_popen = subprocess.Popen
|
||||||
|
def patched_popen(*args, **kwargs):
|
||||||
|
if kwargs.get('universal_newlines') or kwargs.get('text'):
|
||||||
|
if 'encoding' not in kwargs:
|
||||||
|
kwargs['encoding'] = 'utf-8'
|
||||||
|
return original_popen(*args, **kwargs)
|
||||||
|
subprocess.Popen = patched_popen
|
||||||
|
|
||||||
|
import execjs
|
||||||
|
import requests
|
||||||
|
|
||||||
|
basedir = path.dirname(__file__)
|
||||||
|
static_dir = path.join(basedir, 'static')
|
||||||
|
node_modules = path.join(static_dir, 'node_modules')
|
||||||
|
|
||||||
|
# 全局唯一 User-Agent:a_bogus 签名、HTTP 请求头、protobuf body、webid 采集等
|
||||||
|
# 必须全部使用同一个 UA,否则抖音服务端重算 a_bogus 时与请求头 UA 不一致 -> 7911。
|
||||||
|
# 该值需与浏览器登录上下文(playwright new_context user_agent)保持一致。
|
||||||
|
DEFAULT_USER_AGENT = (
|
||||||
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||||
|
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 动态编译 JS
|
||||||
|
dy_path = path.join(static_dir, 'dy_ab.js')
|
||||||
|
dy_js = execjs.compile(open(dy_path, 'r', encoding='utf-8').read(), cwd=node_modules)
|
||||||
|
|
||||||
|
sign_path = path.join(static_dir, 'dy_live_sign.js')
|
||||||
|
sign_js = execjs.compile(open(sign_path, 'r', encoding='utf-8').read(), cwd=node_modules)
|
||||||
|
|
||||||
|
login_path = path.join(static_dir, 'login.js')
|
||||||
|
login_js = execjs.compile(open(login_path, 'r', encoding='utf-8').read(), cwd=node_modules)
|
||||||
|
|
||||||
|
|
||||||
|
def generateSecretPhoneNum(phone):
|
||||||
|
return login_js.call('generateSecretPhoneNum', phone)
|
||||||
|
|
||||||
|
|
||||||
|
def generateSecretCode(phone, code):
|
||||||
|
return login_js.call('generateSecretCode', phone, code)
|
||||||
|
|
||||||
|
|
||||||
|
def trans_cookies(cookies_str):
|
||||||
|
cookies = {}
|
||||||
|
for i in cookies_str.split("; "):
|
||||||
|
try:
|
||||||
|
parts = i.split('=')
|
||||||
|
key = parts[0].strip()
|
||||||
|
val = '='.join(parts[1:]).strip()
|
||||||
|
# 防御性清洗:过滤掉因为误粘贴 fetch 等包含非法字符或换行的 Cookie 键
|
||||||
|
if not key or any(c in key for c in "()[]{}'\"\n \t\\"):
|
||||||
|
continue
|
||||||
|
cookies[key] = val
|
||||||
|
except:
|
||||||
|
continue
|
||||||
|
return cookies
|
||||||
|
|
||||||
|
|
||||||
|
def generate_req_sign(e, priK):
|
||||||
|
"""私信传 obj,其他的拼接"""
|
||||||
|
return dy_js.call('get_req_sign', e, priK)
|
||||||
|
|
||||||
|
|
||||||
|
def generate_a_bogus(query, data="", user_agent=None):
|
||||||
|
"""query, data 都是拼接字符串。
|
||||||
|
|
||||||
|
user_agent 必须与实际发出请求所用的 User-Agent 完全一致(见 DEFAULT_USER_AGENT),
|
||||||
|
否则抖音服务端用请求头 UA 重算 a_bogus 会对不上,导致 7911 安全校验失败。
|
||||||
|
"""
|
||||||
|
return dy_js.call('get_ab', query, data, user_agent or DEFAULT_USER_AGENT)
|
||||||
|
|
||||||
|
|
||||||
|
def generate_signature(room_id, user_unique_id):
|
||||||
|
raw_string = f"live_id=1,aid=6383,version_code=180800,webcast_sdk_version=1.0.15,room_id={room_id},sub_room_id=,sub_channel_id=,did_rule=3,user_unique_id={user_unique_id},device_platform=web,device_type=,ac=,identity=audience"
|
||||||
|
x_ms_stub = hashlib.md5(raw_string.encode("utf-8")).hexdigest()
|
||||||
|
result = sign_js.call("get_signature", x_ms_stub)
|
||||||
|
return result.get("X-Bogus")
|
||||||
|
|
||||||
|
|
||||||
|
def generate_ree_key(prik):
|
||||||
|
"""传递私钥"""
|
||||||
|
return dy_js.call('get_ree_key', prik)
|
||||||
|
|
||||||
|
|
||||||
|
def generate_bd_ticket_client_data(api, ticket, ts_sign, priK):
|
||||||
|
"""传递 query, ticket, ts_sign, priK"""
|
||||||
|
timestamp = int(time.time())
|
||||||
|
res_sign = f"ticket={ticket}&path={api}×tamp={timestamp}"
|
||||||
|
p = {
|
||||||
|
'ts_sign': ts_sign,
|
||||||
|
'req_content': 'ticket,path,timestamp',
|
||||||
|
'req_sign': generate_req_sign(res_sign, priK),
|
||||||
|
'timestamp': timestamp,
|
||||||
|
}
|
||||||
|
p = json.dumps(p, ensure_ascii=False, separators=(',', ':'))
|
||||||
|
return base64.urlsafe_b64encode(p.encode('utf-8')).decode('utf-8')
|
||||||
|
|
||||||
|
|
||||||
|
def generate_msToken(randomlength=107):
|
||||||
|
random_str = ''
|
||||||
|
base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789='
|
||||||
|
length = len(base_str) - 1
|
||||||
|
for _ in range(randomlength):
|
||||||
|
random_str += base_str[random.randint(0, length)]
|
||||||
|
return random_str
|
||||||
|
|
||||||
|
|
||||||
|
def generate_fake_webid(random_length=19):
|
||||||
|
random_str = ''
|
||||||
|
base_str = '0123456789'
|
||||||
|
length = len(base_str) - 1
|
||||||
|
for _ in range(random_length):
|
||||||
|
random_str += base_str[random.randint(0, length)]
|
||||||
|
return random_str
|
||||||
|
|
||||||
|
|
||||||
|
def generate_webid(auth=None, url=""):
|
||||||
|
# 优先用已采集到的 web_id(避免每次发送都发起一次阻塞的 HTTP 请求,导致事件循环卡顿)
|
||||||
|
cached = getattr(auth, "web_id", None) if auth is not None else None
|
||||||
|
if cached:
|
||||||
|
return str(cached)
|
||||||
|
if url == "":
|
||||||
|
url = "https://www.douyin.com/discover?modal_id=7376449060384935209"
|
||||||
|
try:
|
||||||
|
from .auth import DouyinAuth
|
||||||
|
headers = {
|
||||||
|
"User-Agent": DEFAULT_USER_AGENT,
|
||||||
|
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
|
||||||
|
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
||||||
|
"upgrade-insecure-requests": "1"
|
||||||
|
}
|
||||||
|
if auth and auth.cookie_str:
|
||||||
|
headers['cookie'] = auth.cookie_str
|
||||||
|
try:
|
||||||
|
from rpa_engine.runtime_config import requests_proxies
|
||||||
|
proxies = requests_proxies()
|
||||||
|
except Exception:
|
||||||
|
proxies = None
|
||||||
|
response = requests.get(
|
||||||
|
url, headers=headers, verify=False, timeout=10, proxies=proxies
|
||||||
|
)
|
||||||
|
res_text = response.text
|
||||||
|
user_unique_id = re.findall(r'\\"user_unique_id\\":\\"(.*?)\\"', res_text)[0]
|
||||||
|
# 把发现的 web_id 回写到 auth 上,避免同一次同步里反复发起阻塞的 HTTP 请求
|
||||||
|
if auth is not None and user_unique_id:
|
||||||
|
try:
|
||||||
|
auth.web_id = user_unique_id
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return user_unique_id
|
||||||
|
except Exception:
|
||||||
|
# 失败时同样缓存一个伪 web_id,避免后续调用重复走 10s 超时的网络请求
|
||||||
|
fake = generate_fake_webid()
|
||||||
|
if auth is not None:
|
||||||
|
try:
|
||||||
|
if not getattr(auth, "web_id", None):
|
||||||
|
auth.web_id = fake
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return fake
|
||||||
|
|
||||||
|
|
||||||
|
def generate_millisecond():
|
||||||
|
return int(round(time.time() * 1000))
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_client_cert(cert: str) -> str:
|
||||||
|
"""统一 client_cert / sdk_cert 格式为「base64 证书体」。
|
||||||
|
|
||||||
|
web_protect.client_cert 与 frontier WS 的 sdk_cert 通常已是 base64(PEM);
|
||||||
|
若误把 PEM 原文或 frontier 证书二次 base64,会导致 7911。
|
||||||
|
"""
|
||||||
|
cert = (cert or "").strip()
|
||||||
|
if not cert:
|
||||||
|
return ""
|
||||||
|
if cert.startswith("-----BEGIN"):
|
||||||
|
return base64.b64encode(cert.encode("utf-8")).decode("utf-8")
|
||||||
|
return cert
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_proto_device_id(device_id: str = "", web_id: str = "", my_uid: int = 0) -> str:
|
||||||
|
"""protobuf / frontier 更倾向使用数字 device_id(通常等于 my_uid)。"""
|
||||||
|
for candidate in (device_id, web_id, str(my_uid or "")):
|
||||||
|
c = str(candidate or "").strip()
|
||||||
|
if c.isdigit():
|
||||||
|
return c
|
||||||
|
return str(device_id or web_id or "0")
|
||||||
|
|
||||||
|
|
||||||
|
def splice_url(params):
|
||||||
|
splice_url_str = ''
|
||||||
|
for key, value in params.items():
|
||||||
|
if value is None:
|
||||||
|
value = ''
|
||||||
|
splice_url_str += key + '=' + urllib.parse.quote(str(value)) + '&'
|
||||||
|
return splice_url_str[:-1]
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
"""抖音标准表情(评论区 emoji)名称 -> 图片 URL 映射。
|
||||||
|
|
||||||
|
抖音文字表情如 [酷拽]/[微笑] 通过 WS 以 message_type=7 的纯文本下发,
|
||||||
|
content 形如 {"text":"[酷拽]","aweType":700},不带图片地址;
|
||||||
|
浏览器端靠本地表情表把 [name] 渲染成小图。这里拉取官方表情列表接口,
|
||||||
|
建立 name->url 映射,收到文字表情时补成可显示的贴纸。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
logger = logging.getLogger("douyin_im.emoji")
|
||||||
|
|
||||||
|
_EMOJI_MAP: dict[str, str] = {}
|
||||||
|
_FETCHED_AT: float = 0.0
|
||||||
|
_TTL = 6 * 3600 # 6 小时刷新一次
|
||||||
|
_lock = threading.Lock()
|
||||||
|
_fetch_lock = threading.Lock()
|
||||||
|
_LAST_FETCH_ATTEMPT: float = 0.0
|
||||||
|
_FAILURE_RETRY_SECONDS = 60.0
|
||||||
|
|
||||||
|
_BRACKET_RE = re.compile(r"^\[[^\[\]]{1,24}\]$")
|
||||||
|
|
||||||
|
|
||||||
|
def has_emoji_map() -> bool:
|
||||||
|
return bool(_EMOJI_MAP)
|
||||||
|
|
||||||
|
|
||||||
|
def is_fresh() -> bool:
|
||||||
|
return bool(_EMOJI_MAP) and (time.time() - _FETCHED_AT) < _TTL
|
||||||
|
|
||||||
|
|
||||||
|
def set_emoji_map(mapping: dict[str, str]) -> None:
|
||||||
|
global _EMOJI_MAP, _FETCHED_AT
|
||||||
|
if mapping:
|
||||||
|
with _lock:
|
||||||
|
_EMOJI_MAP = dict(mapping)
|
||||||
|
_FETCHED_AT = time.time()
|
||||||
|
|
||||||
|
|
||||||
|
def lookup_emoji_url(name: str) -> str:
|
||||||
|
"""name 可带或不带中括号,返回标准表情图片 URL(无则空串)。"""
|
||||||
|
if not name:
|
||||||
|
return ""
|
||||||
|
key = name.strip()
|
||||||
|
if not key:
|
||||||
|
return ""
|
||||||
|
if not key.startswith("["):
|
||||||
|
key = f"[{key}]"
|
||||||
|
return _EMOJI_MAP.get(key, "")
|
||||||
|
|
||||||
|
|
||||||
|
def looks_like_emoji_token(text: str) -> bool:
|
||||||
|
return bool(_BRACKET_RE.match((text or "").strip()))
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_emoji_map(session) -> dict[str, str]:
|
||||||
|
"""用账号会话拉取官方表情列表,返回 {display_name: url}。失败返回 {}。"""
|
||||||
|
try:
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from .auth import DouyinAuth
|
||||||
|
from .dy_util import generate_a_bogus, generate_msToken, splice_url
|
||||||
|
|
||||||
|
auth = DouyinAuth.from_im_session(session)
|
||||||
|
ua = session.user_agent
|
||||||
|
s_v_web_id = session.cookies.get("s_v_web_id", "") if session.cookies else ""
|
||||||
|
params = {
|
||||||
|
"device_platform": "webapp",
|
||||||
|
"aid": "6383",
|
||||||
|
"channel": "channel_pc_web",
|
||||||
|
"pc_client_type": "1",
|
||||||
|
"version_code": "170400",
|
||||||
|
"version_name": "17.4.0",
|
||||||
|
"cookie_enabled": "true",
|
||||||
|
"browser_language": "zh-CN",
|
||||||
|
"browser_platform": "Win32",
|
||||||
|
"browser_name": "Mozilla",
|
||||||
|
"browser_online": "true",
|
||||||
|
"verifyFp": s_v_web_id,
|
||||||
|
"fp": s_v_web_id,
|
||||||
|
"webid": session.web_id or session.device_id or "",
|
||||||
|
"msToken": generate_msToken(),
|
||||||
|
}
|
||||||
|
params["a_bogus"] = generate_a_bogus(splice_url(params), user_agent=ua)
|
||||||
|
headers = {
|
||||||
|
"User-Agent": ua,
|
||||||
|
"Referer": "https://www.douyin.com/",
|
||||||
|
"Accept": "application/json, text/plain, */*",
|
||||||
|
"Cookie": session.cookie_header(),
|
||||||
|
}
|
||||||
|
resp = requests.get(
|
||||||
|
"https://www.douyin.com/aweme/v1/web/emoji/list",
|
||||||
|
params=params,
|
||||||
|
headers=headers,
|
||||||
|
cookies=auth.cookie if getattr(auth, "cookie", None) else None,
|
||||||
|
verify=False,
|
||||||
|
timeout=20,
|
||||||
|
)
|
||||||
|
data = resp.json()
|
||||||
|
mapping: dict[str, str] = {}
|
||||||
|
for item in data.get("emoji_list") or []:
|
||||||
|
name = item.get("display_name")
|
||||||
|
urls = (item.get("emoji_url") or {}).get("url_list") or []
|
||||||
|
if name and urls:
|
||||||
|
mapping[name] = urls[0]
|
||||||
|
logger.info("Fetched %d douyin emoji", len(mapping))
|
||||||
|
return mapping
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("fetch_emoji_map failed: %s", e)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_emoji_map(session) -> None:
|
||||||
|
"""若缓存为空/过期则拉取(同步阻塞,调用方建议放线程)。"""
|
||||||
|
global _LAST_FETCH_ATTEMPT
|
||||||
|
if is_fresh():
|
||||||
|
return
|
||||||
|
# Batch-started accounts used to all observe an empty cache and fetch the
|
||||||
|
# same emoji list concurrently. Keep the network request itself inside a
|
||||||
|
# separate single-flight lock (set_emoji_map uses _lock).
|
||||||
|
with _fetch_lock:
|
||||||
|
if is_fresh():
|
||||||
|
return
|
||||||
|
now = time.time()
|
||||||
|
if now - _LAST_FETCH_ATTEMPT < _FAILURE_RETRY_SECONDS:
|
||||||
|
return
|
||||||
|
_LAST_FETCH_ATTEMPT = now
|
||||||
|
mapping = fetch_emoji_map(session)
|
||||||
|
if mapping:
|
||||||
|
set_emoji_map(mapping)
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
"""抖音网页版「粉丝列表」拉取,用于检测新粉丝(关注欢迎语功能)。
|
||||||
|
|
||||||
|
复用与 peer_profile / account_profile 相同的 a_bogus + msToken + cookie 签名方式,
|
||||||
|
调用 https://www.douyin.com/aweme/v1/web/user/follower/list/ 拉取本账号最近的粉丝。
|
||||||
|
|
||||||
|
返回的每个粉丝含:uid / sec_uid / nickname / follow_status / follower_status。
|
||||||
|
其中 follow_status 表示「我」与对方的关系:0=未关注 1=我已关注 2=互相关注(互关)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from .dy_util import (
|
||||||
|
DEFAULT_USER_AGENT,
|
||||||
|
generate_a_bogus,
|
||||||
|
generate_msToken,
|
||||||
|
generate_webid,
|
||||||
|
splice_url,
|
||||||
|
)
|
||||||
|
from .auth import DouyinAuth
|
||||||
|
|
||||||
|
logger = logging.getLogger("douyin_im.follower_poll")
|
||||||
|
|
||||||
|
FOLLOWER_LIST_URL = "https://www.douyin.com/aweme/v1/web/user/follower/list/"
|
||||||
|
|
||||||
|
|
||||||
|
def _requests_proxies() -> dict | None:
|
||||||
|
try:
|
||||||
|
from rpa_engine.runtime_config import requests_proxies
|
||||||
|
|
||||||
|
return requests_proxies()
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _to_int(value: Any) -> int:
|
||||||
|
try:
|
||||||
|
return int(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_followers(data: dict[str, Any]) -> list[dict[str, Any]]:
|
||||||
|
raw = data.get("followers")
|
||||||
|
if not isinstance(raw, list):
|
||||||
|
return []
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
for item in raw:
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
uid = str(item.get("uid") or item.get("user_id") or "").strip()
|
||||||
|
if not uid:
|
||||||
|
continue
|
||||||
|
out.append(
|
||||||
|
{
|
||||||
|
"uid": uid,
|
||||||
|
"sec_uid": str(item.get("sec_uid") or item.get("sec_user_id") or "").strip(),
|
||||||
|
"nickname": str(item.get("nickname") or item.get("nick_name") or "").strip(),
|
||||||
|
# follow_status:我对对方的关系(2=互关);follower_status:对方对我的关系
|
||||||
|
"follow_status": _to_int(item.get("follow_status")),
|
||||||
|
"follower_status": _to_int(item.get("follower_status")),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_recent_followers_sync(
|
||||||
|
session,
|
||||||
|
sec_user_id: str,
|
||||||
|
count: int = 20,
|
||||||
|
max_time: int = 0,
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
"""同步拉取最近粉丝(第一页)。失败返回 [],并在日志里写明原因。"""
|
||||||
|
import requests
|
||||||
|
|
||||||
|
sec_user_id = (sec_user_id or "").strip()
|
||||||
|
if not sec_user_id:
|
||||||
|
logger.warning("fetch followers skipped: 缺少本账号 sec_user_id")
|
||||||
|
return []
|
||||||
|
|
||||||
|
try:
|
||||||
|
auth = DouyinAuth()
|
||||||
|
auth.perepare_auth(session.cookie_header(), session.web_protect_str, session.keys_str)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("fetch followers: build auth failed: %s", exc)
|
||||||
|
return []
|
||||||
|
|
||||||
|
ua = session.user_agent or DEFAULT_USER_AGENT
|
||||||
|
params = {
|
||||||
|
"device_platform": "webapp",
|
||||||
|
"aid": "6383",
|
||||||
|
"channel": "channel_pc_web",
|
||||||
|
"sec_user_id": sec_user_id,
|
||||||
|
"count": str(count),
|
||||||
|
"max_time": str(max_time),
|
||||||
|
"min_time": "0",
|
||||||
|
"offset": "0",
|
||||||
|
"source_type": "1",
|
||||||
|
"gps_access": "0",
|
||||||
|
"address_book_access": "0",
|
||||||
|
"is_top": "1",
|
||||||
|
"update_version_code": "170400",
|
||||||
|
"pc_client_type": "1",
|
||||||
|
"version_code": "170400",
|
||||||
|
"version_name": "17.4.0",
|
||||||
|
"cookie_enabled": "true",
|
||||||
|
"screen_width": "1536",
|
||||||
|
"screen_height": "960",
|
||||||
|
"browser_language": "zh-CN",
|
||||||
|
"browser_platform": "Win32",
|
||||||
|
"browser_name": "Chrome",
|
||||||
|
"browser_version": "120.0.0.0",
|
||||||
|
"browser_online": "true",
|
||||||
|
"os_name": "Windows",
|
||||||
|
"os_version": "10",
|
||||||
|
"platform": "PC",
|
||||||
|
"webid": generate_webid(auth, "https://www.douyin.com/"),
|
||||||
|
"verifyFp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
|
||||||
|
"fp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
|
||||||
|
"msToken": auth.msToken or generate_msToken(),
|
||||||
|
}
|
||||||
|
query = splice_url(params)
|
||||||
|
params["a_bogus"] = generate_a_bogus(query, user_agent=ua)
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"User-Agent": ua,
|
||||||
|
"Referer": "https://www.douyin.com/",
|
||||||
|
"Accept": "application/json, text/plain, */*",
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
resp = requests.get(
|
||||||
|
FOLLOWER_LIST_URL,
|
||||||
|
params=params,
|
||||||
|
headers=headers,
|
||||||
|
cookies=auth.cookie,
|
||||||
|
timeout=15,
|
||||||
|
verify=False,
|
||||||
|
proxies=_requests_proxies(),
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
data = resp.json()
|
||||||
|
except Exception:
|
||||||
|
snippet = (resp.text or "")[:200].replace("\n", " ")
|
||||||
|
logger.warning(
|
||||||
|
"fetch followers: 非 JSON 响应 (HTTP %s): %s", resp.status_code, snippet
|
||||||
|
)
|
||||||
|
return []
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
logger.warning("fetch followers: 响应不是 JSON 对象")
|
||||||
|
return []
|
||||||
|
status_code = data.get("status_code")
|
||||||
|
if status_code not in (None, 0):
|
||||||
|
logger.warning(
|
||||||
|
"fetch followers: status_code=%s msg=%s",
|
||||||
|
status_code,
|
||||||
|
data.get("status_msg") or data.get("message") or "",
|
||||||
|
)
|
||||||
|
return []
|
||||||
|
followers = _extract_followers(data)
|
||||||
|
logger.info(
|
||||||
|
"fetch followers ok: 拿到 %s 个粉丝 (has_more=%s total=%s)",
|
||||||
|
len(followers),
|
||||||
|
data.get("has_more"),
|
||||||
|
data.get("total"),
|
||||||
|
)
|
||||||
|
return followers
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("fetch followers failed: %s", exc)
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
async def fetch_recent_followers(
|
||||||
|
session,
|
||||||
|
sec_user_id: str,
|
||||||
|
count: int = 20,
|
||||||
|
max_time: int = 0,
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
return await asyncio.to_thread(
|
||||||
|
fetch_recent_followers_sync, session, sec_user_id, count, max_time
|
||||||
|
)
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
"""Build frontier-im WebSocket URL (DouYin_Spider douyin_recv_msg logic)."""
|
||||||
|
import hashlib
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from typing import Optional
|
||||||
|
from urllib.parse import unquote
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from .auth import DouyinAuth
|
||||||
|
from .dy_util import generate_a_bogus, generate_msToken, generate_webid, splice_url
|
||||||
|
from .session import DouyinImSession, is_frontier_ws_url
|
||||||
|
|
||||||
|
logger = logging.getLogger("douyin_im.frontier")
|
||||||
|
|
||||||
|
APP_KEY = "e1bd35ec9db7b8d846de66ed140b1ad9"
|
||||||
|
FP_ID = "9"
|
||||||
|
|
||||||
|
|
||||||
|
def build_frontier_ws_url(session: DouyinImSession, device_id: str) -> Optional[str]:
|
||||||
|
token = session.cookies.get("sessionid") or session.cookies.get("sessionid_ss") or ""
|
||||||
|
if not token or not device_id:
|
||||||
|
return None
|
||||||
|
access_key_raw = f"{FP_ID}{APP_KEY}{device_id}f8a69f1719916z"
|
||||||
|
access_key = hashlib.md5(access_key_raw.encode("utf-8")).hexdigest()
|
||||||
|
params = {
|
||||||
|
"aid": "6383",
|
||||||
|
"device_platform": "douyin_pc",
|
||||||
|
"fpid": FP_ID,
|
||||||
|
"device_id": device_id,
|
||||||
|
"token": token,
|
||||||
|
"access_key": access_key,
|
||||||
|
}
|
||||||
|
query = "&".join(f"{k}={v}" for k, v in params.items())
|
||||||
|
return f"wss://frontier-im.douyin.com/ws/v2?{query}"
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_device_id(session: DouyinImSession) -> str:
|
||||||
|
"""Call Douyin user query API to obtain device/web id."""
|
||||||
|
auth = DouyinAuth()
|
||||||
|
auth.perepare_auth(
|
||||||
|
session.cookie_header(),
|
||||||
|
session.web_protect_str,
|
||||||
|
session.keys_str,
|
||||||
|
)
|
||||||
|
url = "https://www.douyin.com/aweme/v1/web/query/user"
|
||||||
|
headers = {
|
||||||
|
"User-Agent": session.user_agent,
|
||||||
|
"Referer": "https://www.douyin.com/discover",
|
||||||
|
"Accept": "application/json, text/plain, */*",
|
||||||
|
"Cookie": session.cookie_header(),
|
||||||
|
}
|
||||||
|
params = {
|
||||||
|
"device_platform": "webapp",
|
||||||
|
"aid": "6383",
|
||||||
|
"channel": "channel_pc_web",
|
||||||
|
"publish_video_strategy_type": "2",
|
||||||
|
"verifyFp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
|
||||||
|
"fp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
|
||||||
|
"webid": generate_webid(auth, "https://www.douyin.com/discover"),
|
||||||
|
"msToken": generate_msToken(),
|
||||||
|
}
|
||||||
|
query = splice_url(params)
|
||||||
|
params["a_bogus"] = generate_a_bogus(query, user_agent=session.user_agent)
|
||||||
|
try:
|
||||||
|
resp = requests.get(
|
||||||
|
url,
|
||||||
|
params=params,
|
||||||
|
headers=headers,
|
||||||
|
cookies=auth.cookie,
|
||||||
|
verify=False,
|
||||||
|
timeout=15,
|
||||||
|
)
|
||||||
|
data = resp.json()
|
||||||
|
device_id = str(data.get("id") or data.get("device_id") or "")
|
||||||
|
if device_id.isdigit():
|
||||||
|
logger.info(f"Fetched device_id: {device_id[:20]}...")
|
||||||
|
return device_id
|
||||||
|
logger.warning(f"query/user returned non-numeric id: {device_id[:32]!r}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"fetch_device_id failed: {e}")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_frontier_device_id(session: DouyinImSession) -> str:
|
||||||
|
"""Frontier WS requires numeric device_id from Douyin query/user API."""
|
||||||
|
current = str(session.device_id or session.web_id or "")
|
||||||
|
if current.isdigit():
|
||||||
|
return current
|
||||||
|
|
||||||
|
fetched = fetch_device_id(session)
|
||||||
|
if fetched and str(fetched).isdigit():
|
||||||
|
session.device_id = str(fetched)
|
||||||
|
logger.info(f"Using numeric device_id for frontier WS: {fetched[:16]}...")
|
||||||
|
return str(fetched)
|
||||||
|
|
||||||
|
logger.warning(
|
||||||
|
f"Invalid frontier device_id={current[:24]!r}; "
|
||||||
|
"expected numeric id from query/user API"
|
||||||
|
)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _ws_device_id(url: str) -> str:
|
||||||
|
m = re.search(r"[?&]device_id=([^&\s]+)", url or "")
|
||||||
|
return unquote(m.group(1)) if m else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _ws_device_matches_session(session: DouyinImSession, url: str) -> bool:
|
||||||
|
ws_dev = _ws_device_id(url)
|
||||||
|
if not ws_dev or not ws_dev.isdigit():
|
||||||
|
return True
|
||||||
|
for candidate in (session.my_uid, session.web_id, session.device_id):
|
||||||
|
if candidate and str(candidate) == ws_dev:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _ws_token_looks_encoded(url: str) -> bool:
|
||||||
|
m = re.search(r"[?&]token=([^&\s]+)", url or "")
|
||||||
|
if not m:
|
||||||
|
return False
|
||||||
|
token = unquote(m.group(1))
|
||||||
|
return len(token) >= 40 or not token.replace("_", "").replace("-", "").isalnum()
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_frontier_ws(session: DouyinImSession) -> Optional[str]:
|
||||||
|
"""Ensure session has a usable frontier WebSocket URL."""
|
||||||
|
session.sanitize_ws_urls()
|
||||||
|
|
||||||
|
for url in session.ws_urls:
|
||||||
|
if is_frontier_ws_url(url) and "sdk_cert=" in url and _ws_token_looks_encoded(url):
|
||||||
|
session.ws_urls = [url]
|
||||||
|
logger.info("Using captured real frontier WS URL (with sdk_cert)")
|
||||||
|
return url
|
||||||
|
|
||||||
|
for url in session.ws_urls:
|
||||||
|
if is_frontier_ws_url(url) and _ws_token_looks_encoded(url):
|
||||||
|
session.ws_urls = [url]
|
||||||
|
logger.info("Using captured frontier WS URL")
|
||||||
|
return url
|
||||||
|
|
||||||
|
device_id = resolve_frontier_device_id(session)
|
||||||
|
if not device_id:
|
||||||
|
session.ws_urls = []
|
||||||
|
return None
|
||||||
|
|
||||||
|
built = build_frontier_ws_url(session, device_id)
|
||||||
|
if built:
|
||||||
|
session.ws_urls = [built]
|
||||||
|
logger.info("Built frontier WS URL from cookie session")
|
||||||
|
return built
|
||||||
|
return None
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""本系统当前托管中的账号 UID 注册表。
|
||||||
|
|
||||||
|
用途:避免两个都在本系统托管的账号互相自动回复,形成无限回环——
|
||||||
|
这种高频来回发送是触发抖音风控(7911)/业务拒绝(8004)的常见根因。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger("douyin_im.hosted_registry")
|
||||||
|
|
||||||
|
_HOSTED_UIDS: set[int] = set()
|
||||||
|
|
||||||
|
|
||||||
|
def register(uid) -> None:
|
||||||
|
try:
|
||||||
|
u = int(uid)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return
|
||||||
|
if u:
|
||||||
|
_HOSTED_UIDS.add(u)
|
||||||
|
logger.info(f"Registered hosted uid {u} (total={len(_HOSTED_UIDS)})")
|
||||||
|
|
||||||
|
|
||||||
|
def unregister(uid) -> None:
|
||||||
|
try:
|
||||||
|
u = int(uid)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return
|
||||||
|
_HOSTED_UIDS.discard(u)
|
||||||
|
logger.info(f"Unregistered hosted uid {u} (total={len(_HOSTED_UIDS)})")
|
||||||
|
|
||||||
|
|
||||||
|
def is_hosted(uid) -> bool:
|
||||||
|
try:
|
||||||
|
u = int(uid)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return False
|
||||||
|
return u in _HOSTED_UIDS
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,32 @@
|
|||||||
|
"""Parse Douyin IM Response protobuf for conversation metadata."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
|
def extract_conv_meta_from_response_bytes(raw: bytes) -> dict[str, dict]:
|
||||||
|
"""Return {conversation_id: {conversation_short_id, ticket}} from IM API protobuf body."""
|
||||||
|
if not raw:
|
||||||
|
return {}
|
||||||
|
try:
|
||||||
|
from .static import Response_pb2 as ResponseProto
|
||||||
|
|
||||||
|
response_proto = ResponseProto.Response()
|
||||||
|
response_proto.ParseFromString(raw)
|
||||||
|
body = response_proto.body
|
||||||
|
out: dict[str, dict] = {}
|
||||||
|
for field in (
|
||||||
|
"create_conversation_v2_body",
|
||||||
|
"get_conversation_info_list_v2_response_body",
|
||||||
|
):
|
||||||
|
if not body.HasField(field):
|
||||||
|
continue
|
||||||
|
conv_body = getattr(body, field)
|
||||||
|
for conv in conv_body.conversation_info_list:
|
||||||
|
if not conv.conversation_id:
|
||||||
|
continue
|
||||||
|
out[conv.conversation_id] = {
|
||||||
|
"conversation_short_id": str(conv.conversation_short_id),
|
||||||
|
"ticket": conv.ticket,
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
@@ -0,0 +1,720 @@
|
|||||||
|
"""抖音 IM 私信图片上传。
|
||||||
|
|
||||||
|
复刻抖音 PC 网页版私信发图的真实链路(与"创作者中心 ImageX 图文图床"是两套,
|
||||||
|
IM 发送只认这条链路产出的 tos-cn-o-* 资源):
|
||||||
|
|
||||||
|
1. GET www.douyin.com/aweme/v1/web/im/upload/config/v2 (a_bogus 签名)
|
||||||
|
→ 返回内含 STS2 凭证(AccessKeyID + SignedSecretAccessKey)与 SpaceName(=zhenzhen)
|
||||||
|
2. GET vod.bytedanceapi.com/?Action=ApplyUploadInner&SpaceName=zhenzhen&FileType=image
|
||||||
|
(AWS4-HMAC-SHA256,service=vod,带 x-amz-security-token=STS2…)
|
||||||
|
→ 返回 UploadHost / StoreUri(tos-cn-o-*) / Auth(SpaceKey JWT) / SessionKey
|
||||||
|
3. POST https://{UploadHost}/upload/v1/{StoreUri}
|
||||||
|
(Authorization: SpaceKey/zhenzhen/…JWT,Content-CRC32,X-Storage-U=my_uid)
|
||||||
|
4. POST vod.bytedanceapi.com/?Action=CommitUploadInner&SpaceName=zhenzhen (AWS4 签名)
|
||||||
|
→ 确认上传,最终 uri 即 StoreUri(tos-cn-o-*)
|
||||||
|
|
||||||
|
之后用该 tos-cn-o-* uri 构造 type=27 消息体即可被 IM 后端校验通过。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import datetime
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import random
|
||||||
|
import re
|
||||||
|
import string
|
||||||
|
import zlib
|
||||||
|
from typing import Any
|
||||||
|
from urllib.parse import urlencode
|
||||||
|
|
||||||
|
logger = logging.getLogger("douyin_im.image_upload")
|
||||||
|
|
||||||
|
_LOCAL_URL_RE = re.compile(
|
||||||
|
r"^(/api/media/messages/|https?://(?:localhost|127\.0\.0\.1)(?::\d+)?/api/media/messages/)",
|
||||||
|
re.I,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 抖音 web 私信图片上传专用通道(VOD/ImageX inner 接口 + IM 上传配置)
|
||||||
|
VOD_HOST = "https://vod.bytedanceapi.com/"
|
||||||
|
VOD_REGION = "cn-north-1"
|
||||||
|
VOD_SERVICE = "vod"
|
||||||
|
IM_UPLOAD_CONFIG_URL = "https://www.douyin.com/aweme/v1/web/im/upload/config/v2"
|
||||||
|
DEFAULT_SPACE_NAME = "zhenzhen"
|
||||||
|
|
||||||
|
|
||||||
|
def is_local_media_url(url: str) -> bool:
|
||||||
|
raw = (url or "").strip()
|
||||||
|
if not raw:
|
||||||
|
return False
|
||||||
|
if raw.startswith("/api/media/messages/"):
|
||||||
|
return True
|
||||||
|
if raw.startswith("/api/media/link-cards/"):
|
||||||
|
return True
|
||||||
|
return bool(_LOCAL_URL_RE.match(raw))
|
||||||
|
|
||||||
|
|
||||||
|
def is_douyin_cdn_url(url: str) -> bool:
|
||||||
|
raw = (url or "").strip().lower()
|
||||||
|
if not raw.startswith("http"):
|
||||||
|
return False
|
||||||
|
return any(
|
||||||
|
host in raw
|
||||||
|
for host in (
|
||||||
|
"douyinpic.com",
|
||||||
|
"byteimg.com",
|
||||||
|
"ibyteimg.com",
|
||||||
|
"douyinstatic.com",
|
||||||
|
"snssdk.com",
|
||||||
|
"vodupload.com",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_local_message_media_path(url: str) -> tuple[int, str] | None:
|
||||||
|
"""从 /api/media/messages/{account_id}/{filename} 解析 account_id 与文件名。"""
|
||||||
|
raw = (url or "").strip()
|
||||||
|
m = re.search(r"/api/media/messages/(\d+)/([^/?#]+)", raw)
|
||||||
|
if not m:
|
||||||
|
return None
|
||||||
|
return int(m.group(1)), m.group(2)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_link_card_media_path(url: str) -> tuple[int, str] | None:
|
||||||
|
"""从 /api/media/link-cards/{owner_id}/{filename} 解析 owner_id 与文件名。"""
|
||||||
|
raw = (url or "").strip()
|
||||||
|
m = re.search(r"/api/media/link-cards/(\d+)/([^/?#]+)", raw)
|
||||||
|
if not m:
|
||||||
|
return None
|
||||||
|
return int(m.group(1)), m.group(2)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _requests_proxies() -> dict | None:
|
||||||
|
try:
|
||||||
|
from rpa_engine.runtime_config import requests_proxies
|
||||||
|
|
||||||
|
return requests_proxies()
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _random_s() -> str:
|
||||||
|
chars = string.digits + string.ascii_lowercase
|
||||||
|
return "".join(random.choice(chars) for _ in range(11))
|
||||||
|
|
||||||
|
|
||||||
|
def _signing_key(secret: str, date_stamp: str, region: str, service: str) -> bytes:
|
||||||
|
k_date = hmac.new(("AWS4" + secret).encode(), date_stamp.encode(), hashlib.sha256).digest()
|
||||||
|
k_region = hmac.new(k_date, region.encode(), hashlib.sha256).digest()
|
||||||
|
k_service = hmac.new(k_region, service.encode(), hashlib.sha256).digest()
|
||||||
|
return hmac.new(k_service, b"aws4_request", hashlib.sha256).digest()
|
||||||
|
|
||||||
|
|
||||||
|
def _aws4_authorization(
|
||||||
|
*,
|
||||||
|
method: str,
|
||||||
|
canonical_querystring: str,
|
||||||
|
amz_date: str,
|
||||||
|
date_stamp: str,
|
||||||
|
session_token: str,
|
||||||
|
access_key_id: str,
|
||||||
|
secret_access_key: str,
|
||||||
|
payload_hash: str | None = None,
|
||||||
|
signed_headers: list[str] | None = None,
|
||||||
|
service: str = VOD_SERVICE,
|
||||||
|
region: str = VOD_REGION,
|
||||||
|
) -> str:
|
||||||
|
if signed_headers is None:
|
||||||
|
signed_headers = ["x-amz-date", "x-amz-security-token"]
|
||||||
|
if payload_hash is None:
|
||||||
|
payload_hash = hashlib.sha256(b"").hexdigest()
|
||||||
|
|
||||||
|
header_lines = []
|
||||||
|
for name in signed_headers:
|
||||||
|
if name == "x-amz-date":
|
||||||
|
header_lines.append(f"x-amz-date:{amz_date}\n")
|
||||||
|
elif name == "x-amz-security-token":
|
||||||
|
header_lines.append(f"x-amz-security-token:{session_token}\n")
|
||||||
|
elif name == "x-amz-content-sha256":
|
||||||
|
header_lines.append(f"x-amz-content-sha256:{payload_hash}\n")
|
||||||
|
canonical_headers = "".join(header_lines)
|
||||||
|
signed = ";".join(signed_headers)
|
||||||
|
canonical_request = (
|
||||||
|
f"{method}\n/\n{canonical_querystring}\n{canonical_headers}\n{signed}\n{payload_hash}"
|
||||||
|
)
|
||||||
|
credential_scope = f"{date_stamp}/{region}/{service}/aws4_request"
|
||||||
|
string_to_sign = (
|
||||||
|
"AWS4-HMAC-SHA256\n"
|
||||||
|
f"{amz_date}\n"
|
||||||
|
f"{credential_scope}\n"
|
||||||
|
f"{hashlib.sha256(canonical_request.encode()).hexdigest()}"
|
||||||
|
)
|
||||||
|
signature = hmac.new(
|
||||||
|
_signing_key(secret_access_key, date_stamp, region, service),
|
||||||
|
string_to_sign.encode(),
|
||||||
|
hashlib.sha256,
|
||||||
|
).hexdigest()
|
||||||
|
return (
|
||||||
|
f"AWS4-HMAC-SHA256 Credential={access_key_id}/{credential_scope}, "
|
||||||
|
f"SignedHeaders={signed}, Signature={signature}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_json(resp) -> dict[str, Any]:
|
||||||
|
text = (getattr(resp, "text", None) or "").strip()
|
||||||
|
if not text:
|
||||||
|
return {"error": f"空响应 (HTTP {getattr(resp, 'status_code', '?')})"}
|
||||||
|
try:
|
||||||
|
data = resp.json()
|
||||||
|
return data if isinstance(data, dict) else {"error": "响应不是 JSON 对象"}
|
||||||
|
except Exception:
|
||||||
|
snippet = text[:200].replace("\n", " ")
|
||||||
|
return {"error": f"非 JSON 响应 (HTTP {getattr(resp, 'status_code', '?')}): {snippet}"}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 第 1 步:拉取 IM 上传配置,提取 STS 凭证 + SpaceName
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _sanitize_for_log(obj: Any, depth: int = 0) -> Any:
|
||||||
|
"""结构化脱敏:保留字段名与层级,长字符串只留前 12 位 + 长度,便于排查凭证字段。"""
|
||||||
|
if depth > 6:
|
||||||
|
return "…"
|
||||||
|
if isinstance(obj, dict):
|
||||||
|
return {str(k): _sanitize_for_log(v, depth + 1) for k, v in obj.items()}
|
||||||
|
if isinstance(obj, list):
|
||||||
|
return [_sanitize_for_log(v, depth + 1) for v in obj[:3]]
|
||||||
|
if isinstance(obj, str):
|
||||||
|
return f"{obj[:12]}…(len={len(obj)})" if len(obj) > 24 else obj
|
||||||
|
return obj
|
||||||
|
|
||||||
|
|
||||||
|
def _find_auth_object(obj: Any, depth: int = 0) -> dict | None:
|
||||||
|
"""找到「直接含有 STS2 会话凭证字符串」的那个 dict(即临时凭证对象)。
|
||||||
|
|
||||||
|
该对象里通常同时含有 AccessKeyId / SecretAccessKey / SessionToken(=STS2…)。
|
||||||
|
关键:签名要用同级的 SecretAccessKey 字段,而**不是** STS2 令牌内部解出的
|
||||||
|
SignedSecretAccessKey(那是服务端校验用的,拿来当签名密钥会 SignatureDoesNotMatch)。
|
||||||
|
"""
|
||||||
|
if depth > 8 or not isinstance(obj, (dict, list)):
|
||||||
|
return None
|
||||||
|
if isinstance(obj, dict):
|
||||||
|
for value in obj.values():
|
||||||
|
if isinstance(value, str) and value.startswith("STS2"):
|
||||||
|
return obj
|
||||||
|
for value in obj.values():
|
||||||
|
found = _find_auth_object(value, depth + 1)
|
||||||
|
if found is not None:
|
||||||
|
return found
|
||||||
|
else:
|
||||||
|
for value in obj:
|
||||||
|
found = _find_auth_object(value, depth + 1)
|
||||||
|
if found is not None:
|
||||||
|
return found
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _find_sts_token(obj: Any, depth: int = 0) -> str:
|
||||||
|
"""递归在响应里找到形如 'STS2...' 的会话凭证字符串。"""
|
||||||
|
if depth > 8:
|
||||||
|
return ""
|
||||||
|
if isinstance(obj, str):
|
||||||
|
return obj if obj.startswith("STS2") else ""
|
||||||
|
if isinstance(obj, dict):
|
||||||
|
for value in obj.values():
|
||||||
|
found = _find_sts_token(value, depth + 1)
|
||||||
|
if found:
|
||||||
|
return found
|
||||||
|
elif isinstance(obj, list):
|
||||||
|
for value in obj:
|
||||||
|
found = _find_sts_token(value, depth + 1)
|
||||||
|
if found:
|
||||||
|
return found
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _find_space_name(obj: Any, depth: int = 0) -> str:
|
||||||
|
if depth > 8:
|
||||||
|
return ""
|
||||||
|
if isinstance(obj, dict):
|
||||||
|
for key, value in obj.items():
|
||||||
|
if str(key).lower() in ("space_name", "spacename") and isinstance(value, str) and value:
|
||||||
|
return value
|
||||||
|
found = _find_space_name(value, depth + 1)
|
||||||
|
if found:
|
||||||
|
return found
|
||||||
|
elif isinstance(obj, list):
|
||||||
|
for value in obj:
|
||||||
|
found = _find_space_name(value, depth + 1)
|
||||||
|
if found:
|
||||||
|
return found
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_sts(sts_token: str) -> tuple[str, str]:
|
||||||
|
"""STS2<base64(JSON)>,解出 AccessKeyID 与 SignedSecretAccessKey。"""
|
||||||
|
try:
|
||||||
|
b64 = sts_token[4:] if sts_token.startswith("STS2") else sts_token
|
||||||
|
b64 += "=" * (-len(b64) % 4)
|
||||||
|
data = json.loads(base64.b64decode(b64).decode("utf-8", "ignore"))
|
||||||
|
ak = data.get("AccessKeyID") or data.get("AccessKeyId") or ""
|
||||||
|
sk = data.get("SignedSecretAccessKey") or data.get("SecretAccessKey") or ""
|
||||||
|
return ak, sk
|
||||||
|
except Exception:
|
||||||
|
return "", ""
|
||||||
|
|
||||||
|
|
||||||
|
def _fetch_im_upload_sts(session) -> tuple[str, str, str, str]:
|
||||||
|
"""返回 (access_key_id, secret_access_key, sts_token, space_name)。"""
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from .auth import DouyinAuth
|
||||||
|
from .dy_util import (
|
||||||
|
DEFAULT_USER_AGENT,
|
||||||
|
generate_a_bogus,
|
||||||
|
generate_msToken,
|
||||||
|
generate_webid,
|
||||||
|
splice_url,
|
||||||
|
)
|
||||||
|
|
||||||
|
auth = DouyinAuth()
|
||||||
|
auth.perepare_auth(session.cookie_header(), session.web_protect_str, session.keys_str)
|
||||||
|
ua = session.user_agent or DEFAULT_USER_AGENT
|
||||||
|
|
||||||
|
params = {
|
||||||
|
"device_platform": "webapp",
|
||||||
|
"aid": "6383",
|
||||||
|
"channel": "channel_pc_web",
|
||||||
|
"update_version_code": "170400",
|
||||||
|
"pc_client_type": "1",
|
||||||
|
"pc_libra_divert": "Windows",
|
||||||
|
"support_h265": "1",
|
||||||
|
"support_dash": "1",
|
||||||
|
"version_code": "170400",
|
||||||
|
"version_name": "17.4.0",
|
||||||
|
"cookie_enabled": "true",
|
||||||
|
"screen_width": "1536",
|
||||||
|
"screen_height": "960",
|
||||||
|
"browser_language": "zh-CN",
|
||||||
|
"browser_platform": "Win32",
|
||||||
|
"browser_name": "Chrome",
|
||||||
|
"browser_version": "120.0.0.0",
|
||||||
|
"browser_online": "true",
|
||||||
|
"engine_name": "Blink",
|
||||||
|
"engine_version": "120.0.0.0",
|
||||||
|
"os_name": "Windows",
|
||||||
|
"os_version": "10",
|
||||||
|
"cpu_core_num": "8",
|
||||||
|
"device_memory": "8",
|
||||||
|
"platform": "PC",
|
||||||
|
"downlink": "10",
|
||||||
|
"effective_type": "4g",
|
||||||
|
"round_trip_time": "50",
|
||||||
|
"webid": generate_webid(auth, "https://www.douyin.com/"),
|
||||||
|
"verifyFp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
|
||||||
|
"fp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
|
||||||
|
"msToken": auth.msToken or generate_msToken(),
|
||||||
|
}
|
||||||
|
query = splice_url(params)
|
||||||
|
params["a_bogus"] = generate_a_bogus(query, user_agent=ua)
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"User-Agent": ua,
|
||||||
|
"Referer": "https://www.douyin.com/",
|
||||||
|
"Accept": "application/json, text/plain, */*",
|
||||||
|
}
|
||||||
|
resp = requests.get(
|
||||||
|
IM_UPLOAD_CONFIG_URL,
|
||||||
|
params=params,
|
||||||
|
headers=headers,
|
||||||
|
cookies=auth.cookie,
|
||||||
|
timeout=20,
|
||||||
|
verify=False,
|
||||||
|
proxies=_requests_proxies(),
|
||||||
|
)
|
||||||
|
data = _safe_json(resp)
|
||||||
|
if data.get("error"):
|
||||||
|
raise RuntimeError(f"获取 IM 上传配置失败:{data['error']}")
|
||||||
|
if data.get("status_code") not in (None, 0):
|
||||||
|
raise RuntimeError(
|
||||||
|
f"获取 IM 上传配置失败:status_code={data.get('status_code')} "
|
||||||
|
f"{data.get('status_msg') or ''}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 诊断:把 config/v2 响应结构(字段名保留、长字符串脱敏)打到日志,便于核对凭证字段。
|
||||||
|
try:
|
||||||
|
logger.info(
|
||||||
|
"im/upload/config/v2 结构: %s",
|
||||||
|
json.dumps(_sanitize_for_log(data), ensure_ascii=False),
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 凭证块选择(决定 8003 是否发生的关键):
|
||||||
|
# - inner_image_config / public_image_config / public_file_config 共用同一套
|
||||||
|
# 可用于 VOD 上传的 STS 令牌,仅 space 不同;
|
||||||
|
# - public_image_config_v2 的 token 不同,不兼容 VOD 内部上传(会报
|
||||||
|
# "session token sequence is broken"),必须避开。
|
||||||
|
# 空间含义:maya_review = 审核空间,图片上传后处于待审核态,作为消息发送会被拒(8003);
|
||||||
|
# zhenzhen = 公开可发送空间,IM 图片消息应使用它。
|
||||||
|
# 因此优先 public_image_config(zhenzhen),其凭证同样能完成 VOD 上传。
|
||||||
|
def _block_has_sts(block: Any) -> bool:
|
||||||
|
return isinstance(block, dict) and any(
|
||||||
|
isinstance(v, str) and v.startswith("STS2") for v in block.values()
|
||||||
|
)
|
||||||
|
|
||||||
|
auth_obj = None
|
||||||
|
for _key in ("public_image_config", "inner_image_config"):
|
||||||
|
if isinstance(data, dict) and _block_has_sts(data.get(_key)):
|
||||||
|
auth_obj = data[_key]
|
||||||
|
break
|
||||||
|
if auth_obj is None:
|
||||||
|
auth_obj = _find_auth_object(data)
|
||||||
|
if not auth_obj:
|
||||||
|
raise RuntimeError(
|
||||||
|
"IM 上传配置响应里未找到 STS 凭证(STS2 token);可能 cookie/签名失效,请用浏览器模式重新登录"
|
||||||
|
)
|
||||||
|
|
||||||
|
sts = next(
|
||||||
|
(v for v in auth_obj.values() if isinstance(v, str) and v.startswith("STS2")),
|
||||||
|
"",
|
||||||
|
)
|
||||||
|
# 优先用凭证对象同级的 AccessKeyId / SecretAccessKey(用于 SigV4 签名的真实密钥)。
|
||||||
|
ak = (
|
||||||
|
auth_obj.get("AccessKeyID")
|
||||||
|
or auth_obj.get("AccessKeyId")
|
||||||
|
or auth_obj.get("access_key_id")
|
||||||
|
or ""
|
||||||
|
)
|
||||||
|
sk = (
|
||||||
|
auth_obj.get("SecretAccessKey")
|
||||||
|
or auth_obj.get("SecretAccesskey")
|
||||||
|
or auth_obj.get("secret_access_key")
|
||||||
|
or ""
|
||||||
|
)
|
||||||
|
# 兜底:若响应没给独立的 ak/sk,再尝试从 STS2 令牌解码(SignedSecretAccessKey 一般不可用,仅最后兜底)。
|
||||||
|
if not ak or not sk:
|
||||||
|
dec_ak, dec_sk = _decode_sts(sts)
|
||||||
|
ak = ak or dec_ak
|
||||||
|
sk = sk or dec_sk
|
||||||
|
if not ak or not sk:
|
||||||
|
raise RuntimeError("解析 STS 凭证失败(缺少 AccessKeyId / SecretAccessKey)")
|
||||||
|
# space 必须取自与凭证同一块,避免凭证用 inner_image_config 而 space 误取到别处。
|
||||||
|
space = (
|
||||||
|
auth_obj.get("space_name")
|
||||||
|
or auth_obj.get("SpaceName")
|
||||||
|
or auth_obj.get("spaceName")
|
||||||
|
or _find_space_name(data)
|
||||||
|
or DEFAULT_SPACE_NAME
|
||||||
|
)
|
||||||
|
return ak, sk, sts, space
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 第 2 步:ApplyUploadInner(VOD),申请上传地址
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _extract_apply_inner(data: dict[str, Any]) -> tuple[str, str, str, str]:
|
||||||
|
"""返回 (upload_host, store_uri, jwt_auth, session_key)。"""
|
||||||
|
result = data.get("Result") or {}
|
||||||
|
addr = result.get("InnerUploadAddress") or result.get("UploadAddress") or {}
|
||||||
|
|
||||||
|
nodes = addr.get("UploadNodes") or []
|
||||||
|
if nodes:
|
||||||
|
node = nodes[0]
|
||||||
|
stores = node.get("StoreInfos") or []
|
||||||
|
store = stores[0] if stores else {}
|
||||||
|
host = node.get("UploadHost") or ""
|
||||||
|
if not host:
|
||||||
|
hosts = node.get("UploadHosts") or addr.get("UploadHosts") or []
|
||||||
|
host = hosts[0] if hosts else ""
|
||||||
|
return (
|
||||||
|
str(host or ""),
|
||||||
|
str(store.get("StoreUri") or ""),
|
||||||
|
str(store.get("Auth") or ""),
|
||||||
|
str(node.get("SessionKey") or addr.get("SessionKey") or ""),
|
||||||
|
)
|
||||||
|
|
||||||
|
hosts = addr.get("UploadHosts") or []
|
||||||
|
host = hosts[0] if hosts else ""
|
||||||
|
stores = addr.get("StoreInfos") or []
|
||||||
|
store = stores[0] if stores else {}
|
||||||
|
return (
|
||||||
|
str(host or ""),
|
||||||
|
str(store.get("StoreUri") or ""),
|
||||||
|
str(store.get("Auth") or ""),
|
||||||
|
str(addr.get("SessionKey") or result.get("SessionKey") or ""),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _vod_apply_upload_inner(
|
||||||
|
ak: str, sk: str, token: str, space: str, file_size: int
|
||||||
|
) -> tuple[str, str, str, str]:
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from .dy_util import DEFAULT_USER_AGENT
|
||||||
|
|
||||||
|
now = datetime.datetime.utcnow()
|
||||||
|
amz_date = now.strftime("%Y%m%dT%H%M%SZ")
|
||||||
|
date_stamp = now.strftime("%Y%m%d")
|
||||||
|
params = {
|
||||||
|
"Action": "ApplyUploadInner",
|
||||||
|
"Version": "2020-11-19",
|
||||||
|
"SpaceName": space,
|
||||||
|
"FileType": "image",
|
||||||
|
"IsInner": "1",
|
||||||
|
"NeedFallback": "true",
|
||||||
|
"FileSize": str(file_size),
|
||||||
|
"s": _random_s(),
|
||||||
|
}
|
||||||
|
qs = urlencode(sorted(params.items()))
|
||||||
|
authorization = _aws4_authorization(
|
||||||
|
method="GET",
|
||||||
|
canonical_querystring=qs,
|
||||||
|
amz_date=amz_date,
|
||||||
|
date_stamp=date_stamp,
|
||||||
|
session_token=token,
|
||||||
|
access_key_id=ak,
|
||||||
|
secret_access_key=sk,
|
||||||
|
service=VOD_SERVICE,
|
||||||
|
)
|
||||||
|
resp = requests.get(
|
||||||
|
f"{VOD_HOST}?{qs}",
|
||||||
|
headers={
|
||||||
|
"accept": "*/*",
|
||||||
|
"authorization": authorization,
|
||||||
|
"user-agent": DEFAULT_USER_AGENT,
|
||||||
|
"x-amz-date": amz_date,
|
||||||
|
"x-amz-security-token": token,
|
||||||
|
"Referer": "https://www.douyin.com/",
|
||||||
|
},
|
||||||
|
timeout=30,
|
||||||
|
verify=False,
|
||||||
|
proxies=_requests_proxies(),
|
||||||
|
)
|
||||||
|
data = _safe_json(resp)
|
||||||
|
if data.get("error"):
|
||||||
|
raise RuntimeError(f"申请上传地址失败:{data['error']}")
|
||||||
|
meta = data.get("ResponseMetadata") or {}
|
||||||
|
err = meta.get("Error")
|
||||||
|
if err:
|
||||||
|
raise RuntimeError(f"申请上传地址失败:{err.get('Message') or err.get('Code')}")
|
||||||
|
return _extract_apply_inner(data)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 第 3 步:上传二进制(SpaceKey JWT 鉴权)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _vod_upload_binary(
|
||||||
|
host: str, store_uri: str, jwt_auth: str, user_id: str, raw: bytes, session=None
|
||||||
|
) -> None:
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from .dy_util import DEFAULT_USER_AGENT
|
||||||
|
|
||||||
|
crc32 = format(zlib.crc32(raw) & 0xFFFFFFFF, "08x")
|
||||||
|
url = f"https://{host}/upload/v1/{store_uri}"
|
||||||
|
ua = (getattr(session, "user_agent", None) or DEFAULT_USER_AGENT)
|
||||||
|
headers = {
|
||||||
|
"Authorization": jwt_auth,
|
||||||
|
"Content-CRC32": crc32,
|
||||||
|
"Content-Type": "application/octet-stream",
|
||||||
|
"Content-Disposition": 'attachment; filename="undefined"',
|
||||||
|
"User-Agent": ua,
|
||||||
|
}
|
||||||
|
if user_id:
|
||||||
|
headers["X-Storage-U"] = str(user_id)
|
||||||
|
resp = requests.post(
|
||||||
|
url,
|
||||||
|
headers=headers,
|
||||||
|
data=raw,
|
||||||
|
timeout=60,
|
||||||
|
verify=False,
|
||||||
|
proxies=_requests_proxies(),
|
||||||
|
)
|
||||||
|
data = _safe_json(resp)
|
||||||
|
if data.get("error"):
|
||||||
|
raise RuntimeError(f"上传图片数据失败:{data['error']}")
|
||||||
|
if data.get("code") not in (2000, 0, None):
|
||||||
|
raise RuntimeError(f"上传图片数据失败:{data.get('message') or data}")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 第 4 步:CommitUploadInner(VOD),确认上传
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _vod_commit_upload_inner(
|
||||||
|
ak: str, sk: str, token: str, space: str, session_key: str
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from .dy_util import DEFAULT_USER_AGENT
|
||||||
|
|
||||||
|
now = datetime.datetime.utcnow()
|
||||||
|
amz_date = now.strftime("%Y%m%dT%H%M%SZ")
|
||||||
|
date_stamp = now.strftime("%Y%m%d")
|
||||||
|
params = {
|
||||||
|
"Action": "CommitUploadInner",
|
||||||
|
"Version": "2020-11-19",
|
||||||
|
"SpaceName": space,
|
||||||
|
}
|
||||||
|
qs = urlencode(sorted(params.items()))
|
||||||
|
body = json.dumps({"SessionKey": session_key, "Functions": []}, separators=(",", ":"))
|
||||||
|
payload_hash = hashlib.sha256(body.encode()).hexdigest()
|
||||||
|
signed_headers = ["x-amz-content-sha256", "x-amz-date", "x-amz-security-token"]
|
||||||
|
authorization = _aws4_authorization(
|
||||||
|
method="POST",
|
||||||
|
canonical_querystring=qs,
|
||||||
|
amz_date=amz_date,
|
||||||
|
date_stamp=date_stamp,
|
||||||
|
session_token=token,
|
||||||
|
access_key_id=ak,
|
||||||
|
secret_access_key=sk,
|
||||||
|
payload_hash=payload_hash,
|
||||||
|
signed_headers=signed_headers,
|
||||||
|
service=VOD_SERVICE,
|
||||||
|
)
|
||||||
|
resp = requests.post(
|
||||||
|
f"{VOD_HOST}?{qs}",
|
||||||
|
data=body,
|
||||||
|
headers={
|
||||||
|
"accept": "*/*",
|
||||||
|
"authorization": authorization,
|
||||||
|
"content-type": "application/json",
|
||||||
|
"user-agent": DEFAULT_USER_AGENT,
|
||||||
|
"x-amz-content-sha256": payload_hash,
|
||||||
|
"x-amz-date": amz_date,
|
||||||
|
"x-amz-security-token": token,
|
||||||
|
"Referer": "https://www.douyin.com/",
|
||||||
|
},
|
||||||
|
timeout=30,
|
||||||
|
verify=False,
|
||||||
|
proxies=_requests_proxies(),
|
||||||
|
)
|
||||||
|
data = _safe_json(resp)
|
||||||
|
if data.get("error"):
|
||||||
|
raise RuntimeError(f"确认上传失败:{data['error']}")
|
||||||
|
meta = data.get("ResponseMetadata") or {}
|
||||||
|
err = meta.get("Error")
|
||||||
|
if err:
|
||||||
|
raise RuntimeError(f"确认上传失败:{err.get('Message') or err.get('Code')}")
|
||||||
|
return data.get("Result") or {}
|
||||||
|
|
||||||
|
|
||||||
|
def upload_im_image(
|
||||||
|
session,
|
||||||
|
raw: bytes,
|
||||||
|
*,
|
||||||
|
filename: str = "image.jpg",
|
||||||
|
content_type: str = "image/jpeg",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""上传图片到抖音 IM 私信图床(VOD/zhenzhen 空间)。
|
||||||
|
|
||||||
|
成功返回 {uri(tos-cn-o-*), url, url_list, md5};失败返回 {"error": "..."}。
|
||||||
|
"""
|
||||||
|
del filename, content_type # VOD 按二进制上传,文件名仅用于本地存储
|
||||||
|
if not raw:
|
||||||
|
return {"error": "图片为空"}
|
||||||
|
try:
|
||||||
|
ak, sk, token, space = _fetch_im_upload_sts(session)
|
||||||
|
host, store_uri, jwt_auth, session_key = _vod_apply_upload_inner(
|
||||||
|
ak, sk, token, space, len(raw)
|
||||||
|
)
|
||||||
|
if not host or not store_uri or not jwt_auth:
|
||||||
|
return {"error": "申请上传地址失败:缺少 UploadHost/StoreUri/Auth"}
|
||||||
|
|
||||||
|
user_id = str(getattr(session, "my_uid", "") or "")
|
||||||
|
_vod_upload_binary(host, store_uri, jwt_auth, user_id, raw, session)
|
||||||
|
_vod_commit_upload_inner(ak, sk, token, space, session_key)
|
||||||
|
|
||||||
|
uri = store_uri.lstrip("/")
|
||||||
|
out: dict[str, Any] = {"uri": uri, "md5": hashlib.md5(raw).hexdigest()}
|
||||||
|
|
||||||
|
from .message_content import uri_to_cdn_urls
|
||||||
|
|
||||||
|
urls = uri_to_cdn_urls(uri)
|
||||||
|
if urls:
|
||||||
|
out["url_list"] = urls
|
||||||
|
out["url"] = urls[0]
|
||||||
|
|
||||||
|
logger.info("Uploaded IM image via VOD uri=%s host=%s space=%s", uri, host, space)
|
||||||
|
return out
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("upload_im_image (VOD) failed: %s", exc)
|
||||||
|
return {"error": str(exc)}
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_image_reply_spec(spec: dict[str, Any], session, upload_dir: str) -> tuple[dict[str, Any], str]:
|
||||||
|
"""若图片仍是本地地址,则上传到抖音 CDN 并补全 uri。返回 (spec, error)。"""
|
||||||
|
if spec.get("type") != "image":
|
||||||
|
return spec, ""
|
||||||
|
|
||||||
|
uri = str(spec.get("uri") or "").strip()
|
||||||
|
url = str(spec.get("url") or "").strip()
|
||||||
|
|
||||||
|
# 已经持有抖音 CDN 的 uri,说明图片早已上传完成(且经历过风控/转码),直接复用即可。
|
||||||
|
# 关键修复:不要因为 url 仍是本机预览地址(/api/media/...)而再次上传——
|
||||||
|
# 重复上传会拿到一个“刚提交、尚未完成风控/转码”的新 uri,发送时常被抖音以
|
||||||
|
# raw_check_code=1 / status_code=8003 拒绝(与是否互关无关)。
|
||||||
|
# 发送链路(build_msg_payload)只用 uri / url_list,从不使用这个本机 url,故本机 url 无害。
|
||||||
|
if uri and not is_local_media_url(uri):
|
||||||
|
return spec, ""
|
||||||
|
|
||||||
|
if url and is_douyin_cdn_url(url) and not uri:
|
||||||
|
return spec, ""
|
||||||
|
|
||||||
|
raw: bytes | None = None
|
||||||
|
filename = "image.jpg"
|
||||||
|
content_type = "image/jpeg"
|
||||||
|
|
||||||
|
if is_local_media_url(url):
|
||||||
|
import os
|
||||||
|
|
||||||
|
card_parsed = parse_link_card_media_path(url)
|
||||||
|
if card_parsed:
|
||||||
|
# 卡片封面在 uploads/link-cards/{owner}/ 下,与消息图片目录(uploads/messages)不同。
|
||||||
|
owner_id, fname = card_parsed
|
||||||
|
link_cards_dir = os.path.join(os.path.dirname(upload_dir), "link-cards")
|
||||||
|
path = os.path.join(link_cards_dir, str(owner_id), fname)
|
||||||
|
else:
|
||||||
|
parsed = parse_local_message_media_path(url)
|
||||||
|
if not parsed:
|
||||||
|
return spec, "无法解析本地图片路径"
|
||||||
|
_, fname = parsed
|
||||||
|
path = os.path.join(upload_dir, str(parsed[0]), fname)
|
||||||
|
if not os.path.isfile(path):
|
||||||
|
return spec, f"本地图片不存在:{fname}"
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
raw = f.read()
|
||||||
|
filename = fname
|
||||||
|
if fname.lower().endswith(".png"):
|
||||||
|
content_type = "image/png"
|
||||||
|
elif fname.lower().endswith(".webp"):
|
||||||
|
content_type = "image/webp"
|
||||||
|
elif fname.lower().endswith(".gif"):
|
||||||
|
content_type = "image/gif"
|
||||||
|
|
||||||
|
if raw is None:
|
||||||
|
if url.startswith("http") and not is_douyin_cdn_url(url):
|
||||||
|
return spec, "图片地址必须是抖音 CDN 或本地上传后的地址,外部 URL 无法用于 IM 发送"
|
||||||
|
return spec, "缺少可上传的图片数据"
|
||||||
|
|
||||||
|
uploaded = upload_im_image(session, raw, filename=filename, content_type=content_type)
|
||||||
|
if uploaded.get("error"):
|
||||||
|
return spec, uploaded["error"]
|
||||||
|
if not uploaded.get("uri"):
|
||||||
|
return spec, "抖音图片上传失败:未返回 uri"
|
||||||
|
|
||||||
|
merged = {
|
||||||
|
**spec,
|
||||||
|
**uploaded,
|
||||||
|
"type": "image",
|
||||||
|
"text": spec.get("text") or "[图片]",
|
||||||
|
}
|
||||||
|
return merged, ""
|
||||||
@@ -0,0 +1,746 @@
|
|||||||
|
"""私信消息内容解析、存储与展示(文本 / 图片 / 表情 / 语音 / 视频)。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
MSG_TYPE_TEXT = 7
|
||||||
|
MSG_TYPE_STICKER = 5
|
||||||
|
MSG_TYPE_VOICE = 17
|
||||||
|
MSG_TYPE_IMAGE = 27
|
||||||
|
MSG_TYPE_VIDEO = 8
|
||||||
|
MSG_TYPE_LINK_CARD = 70
|
||||||
|
|
||||||
|
_TYPE_LABELS = {
|
||||||
|
"text": "文本",
|
||||||
|
"image": "图片",
|
||||||
|
"sticker": "表情",
|
||||||
|
"voice": "语音",
|
||||||
|
"video": "视频",
|
||||||
|
"link": "链接",
|
||||||
|
"link_card": "链接卡片",
|
||||||
|
}
|
||||||
|
|
||||||
|
_PLACEHOLDER_MARKERS = {
|
||||||
|
"[表情包]",
|
||||||
|
"[语音]",
|
||||||
|
"[图片]",
|
||||||
|
"[视频]",
|
||||||
|
"[未读消息]",
|
||||||
|
}
|
||||||
|
|
||||||
|
_URI_HINT_RE = re.compile(
|
||||||
|
r"(tos-cn|aweme-|voice/|ies-music|\.mp3|\.m4a|\.aac|\.mpeg|\.webp|\.jpeg|\.jpg|\.png|\.gif)",
|
||||||
|
re.I,
|
||||||
|
)
|
||||||
|
|
||||||
|
_AUDIO_URL_RE = re.compile(
|
||||||
|
r"(douyin-user-audio|/audio/|sc=audio|voice/|ies-music|\.mp3|\.m4a|\.aac|\.mpeg|\.wav|\.ogg)",
|
||||||
|
re.I,
|
||||||
|
)
|
||||||
|
|
||||||
|
_VIDEO_URL_RE = re.compile(
|
||||||
|
r"(sc=video|/video/|\.mp4|\.mov|\.webm|\.m3u8)",
|
||||||
|
re.I,
|
||||||
|
)
|
||||||
|
|
||||||
|
_MEDIA_STRING_KEYS = (
|
||||||
|
"url",
|
||||||
|
"uri",
|
||||||
|
"main_url",
|
||||||
|
"download_url",
|
||||||
|
"remote_url",
|
||||||
|
"encrypt_url",
|
||||||
|
"play_url",
|
||||||
|
"secret_url",
|
||||||
|
"audio_url",
|
||||||
|
"video_url",
|
||||||
|
"cover_url",
|
||||||
|
"local_path",
|
||||||
|
)
|
||||||
|
|
||||||
|
_MEDIA_NESTED_KEYS = (
|
||||||
|
"resource_url",
|
||||||
|
"static_url",
|
||||||
|
"animate_url",
|
||||||
|
"cover_url",
|
||||||
|
"thumb_url",
|
||||||
|
"origin_url",
|
||||||
|
"image",
|
||||||
|
"picture",
|
||||||
|
"pic",
|
||||||
|
"sticker",
|
||||||
|
"emoji",
|
||||||
|
"audio",
|
||||||
|
"voice",
|
||||||
|
"video",
|
||||||
|
"media",
|
||||||
|
"large_url",
|
||||||
|
"medium_url",
|
||||||
|
"thumb",
|
||||||
|
"avatar_thumb",
|
||||||
|
"play_url",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_uri_path(raw: str) -> str:
|
||||||
|
path = (raw or "").strip().lstrip("/")
|
||||||
|
if path.startswith("obj/"):
|
||||||
|
path = path[4:]
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def uri_to_cdn_urls(uri: str, *, prefer_voice: bool = False) -> list[str]:
|
||||||
|
"""将抖音 IM 中的 uri / tos 路径转为可访问的 CDN URL 候选列表。"""
|
||||||
|
raw = (uri or "").strip()
|
||||||
|
if not raw:
|
||||||
|
return []
|
||||||
|
if raw.startswith("//"):
|
||||||
|
return [f"https:{raw}"]
|
||||||
|
if raw.startswith("http://") or raw.startswith("https://"):
|
||||||
|
return [raw]
|
||||||
|
|
||||||
|
path = _normalize_uri_path(raw)
|
||||||
|
if not path:
|
||||||
|
return []
|
||||||
|
|
||||||
|
candidates: list[str] = []
|
||||||
|
seen: set[str] = set()
|
||||||
|
|
||||||
|
def add(url: str) -> None:
|
||||||
|
url = (url or "").strip()
|
||||||
|
if url and url not in seen:
|
||||||
|
seen.add(url)
|
||||||
|
candidates.append(url)
|
||||||
|
|
||||||
|
lower = path.lower()
|
||||||
|
is_voice = prefer_voice or lower.startswith("voice/") or lower.endswith((".mp3", ".m4a", ".aac"))
|
||||||
|
is_image = (
|
||||||
|
not is_voice
|
||||||
|
and (
|
||||||
|
"tos-cn-i" in lower
|
||||||
|
or "aweme-" in lower
|
||||||
|
or lower.endswith((".jpeg", ".jpg", ".png", ".webp", ".gif"))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
if is_voice:
|
||||||
|
for host in (
|
||||||
|
"sf6-cdn-tos.douyinstatic.com",
|
||||||
|
"sf3-cdn-tos.douyinstatic.com",
|
||||||
|
"lf3-static.bytednsdoc.com",
|
||||||
|
):
|
||||||
|
add(f"https://{host}/obj/{path}")
|
||||||
|
add(f"https://p3.douyinpic.com/obj/{path}")
|
||||||
|
|
||||||
|
if is_image or "tos-cn" in lower or "aweme" in lower:
|
||||||
|
add(f"https://p3.douyinpic.com/obj/{path}")
|
||||||
|
for size in ("720x720", "480x480", "300x300", "200x200", "100x100"):
|
||||||
|
add(f"https://p3.douyinpic.com/aweme/{size}/{path}")
|
||||||
|
add(f"https://p9-dy.byteimg.com/img/{path}")
|
||||||
|
add(f"https://p6-dy.byteimg.com/img/{path}")
|
||||||
|
|
||||||
|
add(f"https://p3.douyinpic.com/obj/{path}")
|
||||||
|
add(f"https://p3-sign.douyinpic.com/obj/{path}".replace("-sign", ""))
|
||||||
|
return candidates
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_media_uri(uri: str, *, prefer_voice: bool = False) -> str:
|
||||||
|
urls = uri_to_cdn_urls(uri, prefer_voice=prefer_voice)
|
||||||
|
return urls[0] if urls else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _looks_like_audio_url(value: str) -> bool:
|
||||||
|
raw = (value or "").strip()
|
||||||
|
return bool(raw and _AUDIO_URL_RE.search(raw))
|
||||||
|
|
||||||
|
|
||||||
|
def _looks_like_video_url(value: str) -> bool:
|
||||||
|
raw = (value or "").strip()
|
||||||
|
return bool(raw and _VIDEO_URL_RE.search(raw))
|
||||||
|
|
||||||
|
|
||||||
|
def _infer_media_type_from_url(url: str) -> str:
|
||||||
|
"""根据 URL 特征推断媒体类型(语音/视频/图片)。"""
|
||||||
|
if _looks_like_audio_url(url):
|
||||||
|
return "voice"
|
||||||
|
if _looks_like_video_url(url):
|
||||||
|
return "video"
|
||||||
|
return "image"
|
||||||
|
|
||||||
|
|
||||||
|
def _looks_like_media_uri(value: str) -> bool:
|
||||||
|
raw = (value or "").strip()
|
||||||
|
if not raw or raw.startswith("{"):
|
||||||
|
return False
|
||||||
|
if raw.startswith("http://") or raw.startswith("https://") or raw.startswith("//"):
|
||||||
|
return True
|
||||||
|
return bool(_URI_HINT_RE.search(raw))
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_string_media(value: str, *, prefer_voice: bool = False) -> tuple[str, str]:
|
||||||
|
raw = (value or "").strip()
|
||||||
|
if not raw:
|
||||||
|
return "", ""
|
||||||
|
if raw.startswith("//"):
|
||||||
|
return f"https:{raw}", raw
|
||||||
|
if raw.startswith("http://") or raw.startswith("https://"):
|
||||||
|
return raw, ""
|
||||||
|
if _looks_like_media_uri(raw):
|
||||||
|
return resolve_media_uri(raw, prefer_voice=prefer_voice), raw
|
||||||
|
return "", ""
|
||||||
|
|
||||||
|
|
||||||
|
def _valid_sticker_id(value: Any) -> str:
|
||||||
|
if value is None or value == "":
|
||||||
|
return ""
|
||||||
|
try:
|
||||||
|
if int(value) == 0:
|
||||||
|
return ""
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
pass
|
||||||
|
sticker_id = str(value).strip()
|
||||||
|
return "" if sticker_id in ("0", "null", "None") else sticker_id
|
||||||
|
|
||||||
|
|
||||||
|
def _collect_media_candidates(value: Any, out: list[str], *, prefer_voice: bool = False, depth: int = 0) -> None:
|
||||||
|
if depth > 12:
|
||||||
|
return
|
||||||
|
if isinstance(value, str):
|
||||||
|
raw = value.strip()
|
||||||
|
if raw.startswith("http://") or raw.startswith("https://") or raw.startswith("//"):
|
||||||
|
url, _ = _resolve_string_media(raw, prefer_voice=prefer_voice)
|
||||||
|
if url:
|
||||||
|
out.append(url)
|
||||||
|
return
|
||||||
|
if isinstance(value, dict):
|
||||||
|
for list_key in ("url_list", "urls", "urlList"):
|
||||||
|
urls = value.get(list_key)
|
||||||
|
if isinstance(urls, list):
|
||||||
|
for item in urls:
|
||||||
|
_collect_media_candidates(item, out, prefer_voice=prefer_voice, depth=depth + 1)
|
||||||
|
for key in _MEDIA_STRING_KEYS:
|
||||||
|
direct = value.get(key)
|
||||||
|
if isinstance(direct, str):
|
||||||
|
url, _ = _resolve_string_media(direct, prefer_voice=prefer_voice)
|
||||||
|
if url:
|
||||||
|
out.append(url)
|
||||||
|
for nested_key in _MEDIA_NESTED_KEYS:
|
||||||
|
_collect_media_candidates(value.get(nested_key), out, prefer_voice=prefer_voice, depth=depth + 1)
|
||||||
|
for nested in value.values():
|
||||||
|
if isinstance(nested, (dict, list)):
|
||||||
|
_collect_media_candidates(nested, out, prefer_voice=prefer_voice, depth=depth + 1)
|
||||||
|
return
|
||||||
|
if isinstance(value, list):
|
||||||
|
for item in value:
|
||||||
|
_collect_media_candidates(item, out, prefer_voice=prefer_voice, depth=depth + 1)
|
||||||
|
|
||||||
|
|
||||||
|
def _pick_http_url(value: Any, *, prefer_voice: bool = False) -> str:
|
||||||
|
candidates: list[str] = []
|
||||||
|
_collect_media_candidates(value, candidates, prefer_voice=prefer_voice)
|
||||||
|
return candidates[0] if candidates else ""
|
||||||
|
|
||||||
|
|
||||||
|
def _pick_media_uri(value: Any) -> str:
|
||||||
|
if isinstance(value, str) and _looks_like_media_uri(value) and not value.strip().startswith("http"):
|
||||||
|
return _normalize_uri_path(value)
|
||||||
|
if isinstance(value, dict):
|
||||||
|
for key in ("uri", "local_path", "remote_url"):
|
||||||
|
direct = value.get(key)
|
||||||
|
if isinstance(direct, str) and _looks_like_media_uri(direct) and not direct.strip().startswith("http"):
|
||||||
|
return _normalize_uri_path(direct)
|
||||||
|
for nested_key in _MEDIA_NESTED_KEYS:
|
||||||
|
uri = _pick_media_uri(value.get(nested_key))
|
||||||
|
if uri:
|
||||||
|
return uri
|
||||||
|
for nested in value.values():
|
||||||
|
if isinstance(nested, (dict, list)):
|
||||||
|
uri = _pick_media_uri(nested)
|
||||||
|
if uri:
|
||||||
|
return uri
|
||||||
|
if isinstance(value, list):
|
||||||
|
for item in value:
|
||||||
|
uri = _pick_media_uri(item)
|
||||||
|
if uri:
|
||||||
|
return uri
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _coerce_message_type(value: Any, default: int = MSG_TYPE_TEXT) -> int:
|
||||||
|
try:
|
||||||
|
if value is None or value == "":
|
||||||
|
return default
|
||||||
|
return int(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return default
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_content_json(content_raw: str | dict | None) -> dict[str, Any]:
|
||||||
|
if isinstance(content_raw, dict):
|
||||||
|
data = content_raw
|
||||||
|
else:
|
||||||
|
raw = str(content_raw or "").strip()
|
||||||
|
if raw.startswith("{"):
|
||||||
|
try:
|
||||||
|
parsed = json.loads(raw)
|
||||||
|
if isinstance(parsed, dict):
|
||||||
|
data = parsed
|
||||||
|
else:
|
||||||
|
return {}
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return {}
|
||||||
|
else:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
for nested_key in ("ext", "ai_ext", "extra", "payload", "data"):
|
||||||
|
nested = data.get(nested_key)
|
||||||
|
if isinstance(nested, str) and nested.strip().startswith("{"):
|
||||||
|
try:
|
||||||
|
nested_data = json.loads(nested)
|
||||||
|
if isinstance(nested_data, dict):
|
||||||
|
merged = {**nested_data, **data}
|
||||||
|
data = merged
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def _safe_int(value: Any) -> int | None:
|
||||||
|
try:
|
||||||
|
if value is None or value == "":
|
||||||
|
return None
|
||||||
|
return int(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def format_im_message(content_raw: str | dict | None, message_type: int = MSG_TYPE_TEXT) -> dict[str, Any]:
|
||||||
|
"""将 IM 原始 content 解析为统一结构 {type, text, url, ...}。"""
|
||||||
|
content_json = _parse_content_json(content_raw)
|
||||||
|
embedded_type = _coerce_message_type(
|
||||||
|
content_json.get("message_type")
|
||||||
|
or content_json.get("messageType")
|
||||||
|
or content_json.get("msg_type"),
|
||||||
|
message_type,
|
||||||
|
)
|
||||||
|
if embedded_type != MSG_TYPE_TEXT:
|
||||||
|
message_type = embedded_type
|
||||||
|
|
||||||
|
_EMPTY_MEDIA_DEFAULTS = {
|
||||||
|
MSG_TYPE_IMAGE: ("image", "[图片]"),
|
||||||
|
MSG_TYPE_STICKER: ("sticker", "[表情包]"),
|
||||||
|
MSG_TYPE_VOICE: ("voice", "[语音]"),
|
||||||
|
MSG_TYPE_VIDEO: ("video", "[视频]"),
|
||||||
|
MSG_TYPE_LINK_CARD: ("link_card", "[链接卡片]"),
|
||||||
|
}
|
||||||
|
|
||||||
|
if not content_json:
|
||||||
|
raw = str(content_raw or "").strip()
|
||||||
|
if not raw:
|
||||||
|
# 抖音相册图片(type 27)/部分语音等会以「空 content」推送,URL 不随推送下发。
|
||||||
|
# 不能直接丢弃,否则消息「收不到」;这里按类型返回占位,URL 留空待后续补取。
|
||||||
|
if message_type in _EMPTY_MEDIA_DEFAULTS:
|
||||||
|
t, txt = _EMPTY_MEDIA_DEFAULTS[message_type]
|
||||||
|
return {"type": t, "text": txt}
|
||||||
|
return {"type": "text", "text": ""}
|
||||||
|
if raw in _PLACEHOLDER_MARKERS:
|
||||||
|
mapping = {
|
||||||
|
"[图片]": "image",
|
||||||
|
"[表情包]": "sticker",
|
||||||
|
"[语音]": "voice",
|
||||||
|
"[视频]": "video",
|
||||||
|
}
|
||||||
|
return {"type": mapping.get(raw, "text"), "text": raw}
|
||||||
|
if message_type == MSG_TYPE_TEXT:
|
||||||
|
return {"type": "text", "text": raw}
|
||||||
|
content_json = {"text": raw}
|
||||||
|
|
||||||
|
prefer_voice = message_type == MSG_TYPE_VOICE or bool(content_json.get("audio") or content_json.get("voice"))
|
||||||
|
url = _pick_http_url(content_json, prefer_voice=prefer_voice)
|
||||||
|
media_uri = _pick_media_uri(content_json)
|
||||||
|
if not url and media_uri:
|
||||||
|
url = resolve_media_uri(media_uri, prefer_voice=prefer_voice)
|
||||||
|
duration = _safe_int(
|
||||||
|
content_json.get("duration")
|
||||||
|
or content_json.get("audio_duration")
|
||||||
|
or content_json.get("video_duration")
|
||||||
|
)
|
||||||
|
width = _safe_int(content_json.get("width") or content_json.get("w"))
|
||||||
|
height = _safe_int(content_json.get("height") or content_json.get("h"))
|
||||||
|
|
||||||
|
def _media_payload(msg_type: str, text: str, **extra: Any) -> dict[str, Any]:
|
||||||
|
payload: dict[str, Any] = {"type": msg_type, "text": text}
|
||||||
|
if url:
|
||||||
|
payload["url"] = url
|
||||||
|
elif media_uri:
|
||||||
|
payload["uri"] = media_uri
|
||||||
|
payload.update({k: v for k, v in extra.items() if v not in (None, "", 0)})
|
||||||
|
return payload
|
||||||
|
|
||||||
|
# 语音/视频也会带 resource_url,不能仅凭该字段判为图片;优先按类型与 URL 特征识别。
|
||||||
|
is_voice = (
|
||||||
|
message_type == MSG_TYPE_VOICE
|
||||||
|
or bool(content_json.get("audio") or content_json.get("voice"))
|
||||||
|
or (url and _looks_like_audio_url(url))
|
||||||
|
)
|
||||||
|
is_video = (
|
||||||
|
message_type == MSG_TYPE_VIDEO
|
||||||
|
or bool(content_json.get("video"))
|
||||||
|
or (url and _looks_like_video_url(url))
|
||||||
|
)
|
||||||
|
if is_voice and not is_video:
|
||||||
|
return _media_payload("voice", "[语音]", duration=duration)
|
||||||
|
if is_video:
|
||||||
|
return _media_payload("video", "[视频]", duration=duration, width=width, height=height)
|
||||||
|
|
||||||
|
has_image_hint = (
|
||||||
|
message_type == MSG_TYPE_IMAGE
|
||||||
|
or content_json.get("image")
|
||||||
|
or content_json.get("inline_pic")
|
||||||
|
or (
|
||||||
|
content_json.get("resource_url")
|
||||||
|
and not (url and (_looks_like_audio_url(url) or _looks_like_video_url(url)))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if has_image_hint:
|
||||||
|
# 抖音相册私图(biz_tag=aweme_im)的大图 URL 是加密内容,浏览器无法直接渲染;
|
||||||
|
# 但 content 内嵌 inline_pic(base64 WEBP 缩略图),直接转 data URI 即可显示。
|
||||||
|
inline = content_json.get("inline_pic")
|
||||||
|
if isinstance(inline, str) and inline.strip():
|
||||||
|
b64 = re.sub(r"\s+", "", inline)
|
||||||
|
data_uri = f"data:image/webp;base64,{b64}"
|
||||||
|
payload = {"type": "image", "text": "[图片]", "url": data_uri}
|
||||||
|
if width:
|
||||||
|
payload["width"] = width
|
||||||
|
if height:
|
||||||
|
payload["height"] = height
|
||||||
|
return payload
|
||||||
|
return _media_payload("image", "[图片]", width=width, height=height)
|
||||||
|
if message_type == MSG_TYPE_STICKER or content_json.get("static_url") or content_json.get("animate_url") or _valid_sticker_id(
|
||||||
|
content_json.get("sticker_id") or content_json.get("id")
|
||||||
|
):
|
||||||
|
sticker_id = _valid_sticker_id(content_json.get("sticker_id") or content_json.get("id"))
|
||||||
|
return _media_payload(
|
||||||
|
"sticker",
|
||||||
|
"[表情包]",
|
||||||
|
sticker_id=sticker_id,
|
||||||
|
name=str(content_json.get("display_name") or content_json.get("name") or ""),
|
||||||
|
)
|
||||||
|
|
||||||
|
link_card = _parse_link_card_payload(content_json, message_type)
|
||||||
|
if link_card:
|
||||||
|
return link_card
|
||||||
|
|
||||||
|
rich_link = _parse_rich_text_link(content_json)
|
||||||
|
if rich_link:
|
||||||
|
return rich_link
|
||||||
|
|
||||||
|
text = (
|
||||||
|
str(content_json.get("text") or content_json.get("content") or content_json.get("message") or "")
|
||||||
|
).strip()
|
||||||
|
if not text and url:
|
||||||
|
inferred = _infer_media_type_from_url(url)
|
||||||
|
if inferred == "voice":
|
||||||
|
return {"type": "voice", "text": "[语音]", "url": url, "duration": duration}
|
||||||
|
if inferred == "video":
|
||||||
|
return {"type": "video", "text": "[视频]", "url": url, "duration": duration}
|
||||||
|
if message_type == MSG_TYPE_IMAGE:
|
||||||
|
return {"type": "image", "text": "[图片]", "url": url, "width": width, "height": height}
|
||||||
|
if message_type == MSG_TYPE_STICKER:
|
||||||
|
return {"type": "sticker", "text": "[表情包]", "url": url}
|
||||||
|
if message_type == MSG_TYPE_VOICE:
|
||||||
|
return {"type": "voice", "text": "[语音]", "url": url, "duration": duration}
|
||||||
|
if message_type == MSG_TYPE_VIDEO:
|
||||||
|
return {"type": "video", "text": "[视频]", "url": url, "duration": duration}
|
||||||
|
|
||||||
|
final_text = text or str(content_raw or "").strip()
|
||||||
|
emoji = _resolve_text_emoji(final_text)
|
||||||
|
if emoji:
|
||||||
|
return emoji
|
||||||
|
return {"type": "text", "text": final_text}
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_link_card_payload(content_json: dict[str, Any], message_type: int) -> dict[str, Any] | None:
|
||||||
|
link_info = content_json.get("link_info")
|
||||||
|
if not isinstance(link_info, dict):
|
||||||
|
link_info = {}
|
||||||
|
has_link = (
|
||||||
|
message_type == MSG_TYPE_LINK_CARD
|
||||||
|
or link_info
|
||||||
|
or content_json.get("link_url")
|
||||||
|
or content_json.get("cover_url")
|
||||||
|
)
|
||||||
|
if not has_link:
|
||||||
|
return None
|
||||||
|
title = str(content_json.get("title") or link_info.get("title") or "").strip()
|
||||||
|
desc = str(
|
||||||
|
content_json.get("desc")
|
||||||
|
or content_json.get("description")
|
||||||
|
or link_info.get("desc")
|
||||||
|
or link_info.get("description")
|
||||||
|
or ""
|
||||||
|
).strip()
|
||||||
|
url = str(
|
||||||
|
content_json.get("link_url")
|
||||||
|
or content_json.get("url")
|
||||||
|
or link_info.get("url")
|
||||||
|
or link_info.get("link_url")
|
||||||
|
or ""
|
||||||
|
).strip()
|
||||||
|
cover = str(content_json.get("cover_url") or link_info.get("cover_url") or "").strip()
|
||||||
|
text = title or desc or url or "[链接卡片]"
|
||||||
|
payload: dict[str, Any] = {
|
||||||
|
"type": "link_card",
|
||||||
|
"text": text,
|
||||||
|
"title": title,
|
||||||
|
"desc": desc,
|
||||||
|
}
|
||||||
|
if url:
|
||||||
|
payload["url"] = url
|
||||||
|
if cover:
|
||||||
|
payload["cover_url"] = cover
|
||||||
|
return payload
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_rich_text_link(content_json: dict[str, Any]) -> dict[str, Any] | None:
|
||||||
|
rich = content_json.get("richTextInfos")
|
||||||
|
if not isinstance(rich, list):
|
||||||
|
return None
|
||||||
|
for item in rich:
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
continue
|
||||||
|
link = str(item.get("link") or item.get("url") or "").strip()
|
||||||
|
if not link:
|
||||||
|
continue
|
||||||
|
text = str(item.get("text") or item.get("display_text") or link).strip()
|
||||||
|
return {"type": "link", "text": text or link, "url": link}
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_text_emoji(text: str) -> dict[str, Any] | None:
|
||||||
|
"""文字表情 [酷拽] 等:查标准表情表,命中则转成可显示的贴纸。"""
|
||||||
|
stripped = (text or "").strip()
|
||||||
|
if not stripped or not (stripped.startswith("[") and stripped.endswith("]")):
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
from .emoji_pack import looks_like_emoji_token, lookup_emoji_url
|
||||||
|
|
||||||
|
if not looks_like_emoji_token(stripped):
|
||||||
|
return None
|
||||||
|
url = lookup_emoji_url(stripped)
|
||||||
|
if url:
|
||||||
|
return {
|
||||||
|
"type": "sticker",
|
||||||
|
"text": stripped,
|
||||||
|
"url": url,
|
||||||
|
"name": stripped.strip("[]"),
|
||||||
|
}
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_incoming_message(data: dict[str, Any]) -> str:
|
||||||
|
"""从 IM API / WebSocket 消息 dict 提取并序列化展示内容。"""
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return str(data or "").strip()
|
||||||
|
|
||||||
|
msg_type = _coerce_message_type(
|
||||||
|
data.get("message_type") or data.get("messageType") or data.get("msg_type"),
|
||||||
|
MSG_TYPE_TEXT,
|
||||||
|
)
|
||||||
|
content_raw = (
|
||||||
|
data.get("content")
|
||||||
|
or data.get("message")
|
||||||
|
or data.get("msg")
|
||||||
|
or data.get("lastMessage")
|
||||||
|
or data.get("last_msg")
|
||||||
|
or data.get("preview")
|
||||||
|
or data.get("brief")
|
||||||
|
or ""
|
||||||
|
)
|
||||||
|
if isinstance(content_raw, dict):
|
||||||
|
if not msg_type or msg_type == MSG_TYPE_TEXT:
|
||||||
|
msg_type = _coerce_message_type(
|
||||||
|
content_raw.get("message_type")
|
||||||
|
or content_raw.get("messageType")
|
||||||
|
or content_raw.get("msg_type"),
|
||||||
|
msg_type,
|
||||||
|
)
|
||||||
|
parsed = format_im_message(content_raw, msg_type)
|
||||||
|
return serialize_message_content(parsed)
|
||||||
|
|
||||||
|
if isinstance(content_raw, str):
|
||||||
|
raw = content_raw.strip()
|
||||||
|
if raw.startswith("{"):
|
||||||
|
parsed = format_im_message(raw, msg_type)
|
||||||
|
if parsed.get("type") != "text" or parsed.get("url") or msg_type != MSG_TYPE_TEXT:
|
||||||
|
return serialize_message_content(parsed)
|
||||||
|
if raw in _PLACEHOLDER_MARKERS and msg_type != MSG_TYPE_TEXT:
|
||||||
|
parsed = format_im_message(raw, msg_type)
|
||||||
|
return serialize_message_content(parsed)
|
||||||
|
if msg_type != MSG_TYPE_TEXT:
|
||||||
|
parsed = format_im_message(raw, msg_type)
|
||||||
|
return serialize_message_content(parsed)
|
||||||
|
return raw
|
||||||
|
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def serialize_message_content(msg: dict[str, Any]) -> str:
|
||||||
|
"""序列化写入 message_logs / reply_content。"""
|
||||||
|
msg_type = (msg.get("type") or "text").strip()
|
||||||
|
if msg_type == "text":
|
||||||
|
text = str(msg.get("text") or "").strip()
|
||||||
|
return text
|
||||||
|
cleaned = {k: v for k, v in msg.items() if v not in (None, "", [], {})}
|
||||||
|
return json.dumps(cleaned, ensure_ascii=False, separators=(",", ":"))
|
||||||
|
|
||||||
|
|
||||||
|
def parse_stored_content(raw: str | None) -> dict[str, Any]:
|
||||||
|
"""解析数据库中的 message_content / reply_content。"""
|
||||||
|
text = (raw or "").strip()
|
||||||
|
if not text:
|
||||||
|
return {"type": "text", "text": ""}
|
||||||
|
if text.startswith("{"):
|
||||||
|
try:
|
||||||
|
data = json.loads(text)
|
||||||
|
if isinstance(data, dict) and data.get("type"):
|
||||||
|
if not data.get("url") and data.get("uri"):
|
||||||
|
prefer_voice = data.get("type") == "voice"
|
||||||
|
resolved = resolve_media_uri(str(data["uri"]), prefer_voice=prefer_voice)
|
||||||
|
if resolved:
|
||||||
|
data = {**data, "url": resolved}
|
||||||
|
url = str(data.get("url") or "").strip()
|
||||||
|
if url:
|
||||||
|
inferred = _infer_media_type_from_url(url)
|
||||||
|
current = data.get("type")
|
||||||
|
if current == "image" and inferred in ("voice", "video"):
|
||||||
|
data = {
|
||||||
|
**data,
|
||||||
|
"type": inferred,
|
||||||
|
"text": "[语音]" if inferred == "voice" else "[视频]",
|
||||||
|
}
|
||||||
|
elif current not in ("voice", "video", "image", "sticker") and inferred:
|
||||||
|
data = {**data, "type": inferred}
|
||||||
|
return data
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
if text in _PLACEHOLDER_MARKERS:
|
||||||
|
mapping = {
|
||||||
|
"[图片]": "image",
|
||||||
|
"[表情包]": "sticker",
|
||||||
|
"[语音]": "voice",
|
||||||
|
"[视频]": "video",
|
||||||
|
}
|
||||||
|
return {"type": mapping.get(text, "text"), "text": text}
|
||||||
|
return {"type": "text", "text": text}
|
||||||
|
|
||||||
|
|
||||||
|
def message_preview(raw: str | None) -> str:
|
||||||
|
"""会话列表/日志摘要。"""
|
||||||
|
msg = parse_stored_content(raw)
|
||||||
|
msg_type = msg.get("type") or "text"
|
||||||
|
if msg_type == "text":
|
||||||
|
return str(msg.get("text") or "")
|
||||||
|
label = _TYPE_LABELS.get(msg_type, msg.get("text") or "[消息]")
|
||||||
|
extra = str(msg.get("name") or "").strip()
|
||||||
|
if extra and msg_type == "sticker":
|
||||||
|
return f"[表情] {extra}"
|
||||||
|
return str(msg.get("text") or label)
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_outgoing_content(
|
||||||
|
content: str = "",
|
||||||
|
message_type: str | None = None,
|
||||||
|
media_url: str | None = None,
|
||||||
|
sticker_url: str | None = None,
|
||||||
|
width: int | None = None,
|
||||||
|
height: int | None = None,
|
||||||
|
sticker_id: str | None = None,
|
||||||
|
) -> str:
|
||||||
|
"""构造可发送/可落库的 content 字符串。"""
|
||||||
|
raw = (content or "").strip()
|
||||||
|
parsed_json: dict[str, Any] | None = None
|
||||||
|
if raw.startswith("{"):
|
||||||
|
try:
|
||||||
|
data = json.loads(raw)
|
||||||
|
if isinstance(data, dict) and data.get("type"):
|
||||||
|
parsed_json = data
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if parsed_json:
|
||||||
|
merged = dict(parsed_json)
|
||||||
|
if width and not merged.get("width"):
|
||||||
|
merged["width"] = width
|
||||||
|
if height and not merged.get("height"):
|
||||||
|
merged["height"] = height
|
||||||
|
if sticker_id and not merged.get("sticker_id"):
|
||||||
|
merged["sticker_id"] = sticker_id
|
||||||
|
url = (media_url or sticker_url or "").strip()
|
||||||
|
if url and not merged.get("url"):
|
||||||
|
merged["url"] = url
|
||||||
|
return serialize_message_content(merged)
|
||||||
|
|
||||||
|
explicit_type = (message_type or "").strip().lower()
|
||||||
|
if explicit_type in ("image", "sticker", "voice", "video", "text"):
|
||||||
|
if explicit_type == "text":
|
||||||
|
return (content or "").strip()
|
||||||
|
payload: dict[str, Any] = {"type": explicit_type}
|
||||||
|
url = (media_url or sticker_url or "").strip()
|
||||||
|
if url:
|
||||||
|
payload["url"] = url
|
||||||
|
if explicit_type == "sticker" and sticker_id:
|
||||||
|
payload["sticker_id"] = sticker_id
|
||||||
|
if width:
|
||||||
|
payload["width"] = width
|
||||||
|
if height:
|
||||||
|
payload["height"] = height
|
||||||
|
text = (content or "").strip()
|
||||||
|
if text:
|
||||||
|
payload["text"] = text
|
||||||
|
elif explicit_type == "image":
|
||||||
|
payload["text"] = "[图片]"
|
||||||
|
elif explicit_type == "sticker":
|
||||||
|
payload["text"] = "[表情包]"
|
||||||
|
return serialize_message_content(payload)
|
||||||
|
|
||||||
|
raw = (content or "").strip()
|
||||||
|
if raw.startswith("{"):
|
||||||
|
try:
|
||||||
|
data = json.loads(raw)
|
||||||
|
if isinstance(data, dict) and data.get("type"):
|
||||||
|
return serialize_message_content(data)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
return raw
|
||||||
|
|
||||||
|
|
||||||
|
def is_media_message(raw: str | None) -> bool:
|
||||||
|
return parse_stored_content(raw).get("type") not in (None, "text")
|
||||||
|
|
||||||
|
|
||||||
|
def format_system_log_message(raw: str | None) -> str:
|
||||||
|
"""系统诊断日志中的消息摘要。"""
|
||||||
|
msg = parse_stored_content(raw)
|
||||||
|
msg_type = msg.get("type") or "text"
|
||||||
|
if msg_type == "text":
|
||||||
|
return str(msg.get("text") or "")
|
||||||
|
parts = [message_preview(raw)]
|
||||||
|
url = str(msg.get("url") or "").strip()
|
||||||
|
if url:
|
||||||
|
parts.append(f"URL: {url}")
|
||||||
|
duration = msg.get("duration")
|
||||||
|
if duration:
|
||||||
|
parts.append(f"时长: {duration}s")
|
||||||
|
return " | ".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_urls_from_detail(detail: str | None) -> list[str]:
|
||||||
|
if not detail:
|
||||||
|
return []
|
||||||
|
return re.findall(r"https?://[^\s\]|))\"']+", detail)
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
"""极简 protobuf wire 解码器(无第三方依赖)。
|
||||||
|
|
||||||
|
用于解析抖音 IM 发送私信的响应:官方 Response.proto 只建模了
|
||||||
|
create/get_info/new_message_notify 三种 body,没有“发送消息响应”,
|
||||||
|
导致仅凭 error_desc 为空就误判为发送成功。这里直接按 wire 格式解码,
|
||||||
|
读取真实的 status_code / server_message_id,判定是否真的投递成功。
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
|
||||||
|
def _format_status_json(status_json: dict) -> str:
|
||||||
|
"""把内嵌 status JSON 格式化为更可读的失败原因。"""
|
||||||
|
code = status_json.get("status_code")
|
||||||
|
raw_check = status_json.get("raw_check_code")
|
||||||
|
decision = status_json.get("decision_type")
|
||||||
|
parts = [f"status_code={code}"]
|
||||||
|
if raw_check is not None:
|
||||||
|
parts.append(f"raw_check_code={raw_check}")
|
||||||
|
if decision:
|
||||||
|
parts.append(f"decision_type={decision}")
|
||||||
|
return ";".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def _read_varint(buf: bytes, i: int) -> tuple[int, int]:
|
||||||
|
shift = 0
|
||||||
|
result = 0
|
||||||
|
n = len(buf)
|
||||||
|
while i < n:
|
||||||
|
b = buf[i]
|
||||||
|
i += 1
|
||||||
|
result |= (b & 0x7F) << shift
|
||||||
|
if not (b & 0x80):
|
||||||
|
return result, i
|
||||||
|
shift += 7
|
||||||
|
if shift > 70:
|
||||||
|
break
|
||||||
|
raise ValueError("truncated varint")
|
||||||
|
|
||||||
|
|
||||||
|
def decode_fields(buf: bytes) -> list[tuple[int, int, Any]]:
|
||||||
|
"""返回 [(field_num, wire_type, value), ...]。
|
||||||
|
|
||||||
|
wire_type: 0=varint(int), 1=64bit(int), 2=length-delimited(bytes), 5=32bit(int)
|
||||||
|
"""
|
||||||
|
out: list[tuple[int, int, Any]] = []
|
||||||
|
i = 0
|
||||||
|
n = len(buf)
|
||||||
|
while i < n:
|
||||||
|
key, i = _read_varint(buf, i)
|
||||||
|
field = key >> 3
|
||||||
|
wt = key & 7
|
||||||
|
if wt == 0:
|
||||||
|
val, i = _read_varint(buf, i)
|
||||||
|
out.append((field, wt, val))
|
||||||
|
elif wt == 2:
|
||||||
|
ln, i = _read_varint(buf, i)
|
||||||
|
val = buf[i:i + ln]
|
||||||
|
i += ln
|
||||||
|
out.append((field, wt, val))
|
||||||
|
elif wt == 5:
|
||||||
|
val = int.from_bytes(buf[i:i + 4], "little")
|
||||||
|
i += 4
|
||||||
|
out.append((field, wt, val))
|
||||||
|
elif wt == 1:
|
||||||
|
val = int.from_bytes(buf[i:i + 8], "little")
|
||||||
|
i += 8
|
||||||
|
out.append((field, wt, val))
|
||||||
|
else:
|
||||||
|
raise ValueError(f"unsupported wire type {wt}")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _collect_big_varints(buf: bytes, acc: list[int], depth: int = 0) -> None:
|
||||||
|
"""递归收集疑似 ID 的大整数(server_message_id / short_id 等都是大数)。"""
|
||||||
|
if depth > 6:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
fields = decode_fields(buf)
|
||||||
|
except Exception:
|
||||||
|
return
|
||||||
|
for _field, wt, val in fields:
|
||||||
|
if wt == 0 and isinstance(val, int) and val > 10 ** 12:
|
||||||
|
acc.append(val)
|
||||||
|
elif wt == 2 and isinstance(val, (bytes, bytearray)) and val:
|
||||||
|
_collect_big_varints(bytes(val), acc, depth + 1)
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_status_json(raw: bytes) -> Optional[dict]:
|
||||||
|
"""抖音发送响应的 body 内嵌一段 JSON:{"status_code":x,"tips":"...","status_msg":{...}}。
|
||||||
|
|
||||||
|
这才是“消息是否真正投递”的权威结论(status_code=0 才是真成功)。
|
||||||
|
顶层 message=OK 只是接口层面的“已受理”,不代表已投递。
|
||||||
|
"""
|
||||||
|
marker = b'"status_code"'
|
||||||
|
idx = raw.find(marker)
|
||||||
|
if idx < 0:
|
||||||
|
return None
|
||||||
|
start = raw.rfind(b"{", 0, idx)
|
||||||
|
if start < 0:
|
||||||
|
return None
|
||||||
|
depth = 0
|
||||||
|
in_str = False
|
||||||
|
esc = False
|
||||||
|
end = -1
|
||||||
|
for i in range(start, len(raw)):
|
||||||
|
c = raw[i]
|
||||||
|
if in_str:
|
||||||
|
if esc:
|
||||||
|
esc = False
|
||||||
|
elif c == 0x5C: # backslash
|
||||||
|
esc = True
|
||||||
|
elif c == 0x22: # quote
|
||||||
|
in_str = False
|
||||||
|
continue
|
||||||
|
if c == 0x22:
|
||||||
|
in_str = True
|
||||||
|
elif c == 0x7B: # {
|
||||||
|
depth += 1
|
||||||
|
elif c == 0x7D: # }
|
||||||
|
depth -= 1
|
||||||
|
if depth == 0:
|
||||||
|
end = i + 1
|
||||||
|
break
|
||||||
|
if end < 0:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return json.loads(raw[start:end].decode("utf-8", "ignore"))
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def analyze_send_response(raw: bytes) -> dict:
|
||||||
|
"""分析“发送私信”的 protobuf 响应,判定是否真正投递成功。
|
||||||
|
|
||||||
|
顶层 Response 字段(见 Response.proto):
|
||||||
|
1=cmd, 2=sequence_id, 3=error_desc(string), 4=message(string),
|
||||||
|
5=inbox_type, 6=body(ResponseBody)。
|
||||||
|
|
||||||
|
注意:顶层没有 status_code 字段。真正“消息已写入服务端”的标志是
|
||||||
|
body(field 6) 里带有服务端分配的 server_message_id(大整数)。
|
||||||
|
sequence_id(field 2) 也是大整数,因此只在 body 内部查找 message_id,
|
||||||
|
避免把 sequence_id 误当成投递成功标志。
|
||||||
|
|
||||||
|
返回:
|
||||||
|
ok: 是否真正发送成功(body 内带服务端 message_id,或 message=OK 且有 body)
|
||||||
|
cmd: 顶层 cmd
|
||||||
|
message: 顶层 message 文本(field 4)
|
||||||
|
error_desc: 顶层 error_desc 文本(field 3)
|
||||||
|
server_message_id: body 内服务端消息 ID(投递成功的强信号)
|
||||||
|
has_body: 是否带 body
|
||||||
|
summary: 顶层字段概览 + hex 片段,便于排查
|
||||||
|
"""
|
||||||
|
info = {
|
||||||
|
"ok": False,
|
||||||
|
"cmd": None,
|
||||||
|
"status": None,
|
||||||
|
"status_code": None,
|
||||||
|
"raw_check_code": None,
|
||||||
|
"delivered_with_notice": False,
|
||||||
|
"status_reason": "",
|
||||||
|
"message": "",
|
||||||
|
"error_desc": "",
|
||||||
|
"server_message_id": None,
|
||||||
|
"has_body": False,
|
||||||
|
"summary": "",
|
||||||
|
}
|
||||||
|
if not raw:
|
||||||
|
info["summary"] = "空响应"
|
||||||
|
return info
|
||||||
|
try:
|
||||||
|
fields = decode_fields(raw)
|
||||||
|
except Exception as e:
|
||||||
|
info["summary"] = f"解码失败: {e}; hex={raw[:120].hex()}"
|
||||||
|
return info
|
||||||
|
|
||||||
|
body = None
|
||||||
|
parts = []
|
||||||
|
for field, wt, val in fields:
|
||||||
|
if field == 1 and wt == 0:
|
||||||
|
info["cmd"] = val
|
||||||
|
elif field == 3 and wt == 2:
|
||||||
|
try:
|
||||||
|
info["error_desc"] = bytes(val).decode("utf-8", "ignore")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
elif field == 4 and wt == 2:
|
||||||
|
try:
|
||||||
|
info["message"] = bytes(val).decode("utf-8", "ignore")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
elif field == 6 and wt == 2:
|
||||||
|
body = bytes(val)
|
||||||
|
info["has_body"] = len(body) > 0
|
||||||
|
|
||||||
|
if wt == 0:
|
||||||
|
parts.append(f"{field}=int:{val}")
|
||||||
|
elif wt == 2:
|
||||||
|
parts.append(f"{field}=bytes[{len(val)}]")
|
||||||
|
else:
|
||||||
|
parts.append(f"{field}={val}")
|
||||||
|
info["summary"] = " ".join(parts) + f" | hex={raw[:120].hex()}"
|
||||||
|
|
||||||
|
# 只在 body 内部查找服务端 message_id(避免误用顶层 sequence_id)
|
||||||
|
if body:
|
||||||
|
ids: list[int] = []
|
||||||
|
_collect_big_varints(body, ids)
|
||||||
|
if ids:
|
||||||
|
info["server_message_id"] = max(ids)
|
||||||
|
|
||||||
|
# 权威结论:body 内嵌 JSON 的 status_code(0 才是真成功)
|
||||||
|
status_json = _extract_status_json(raw)
|
||||||
|
if status_json is not None:
|
||||||
|
info["status_code"] = status_json.get("status_code")
|
||||||
|
info["raw_check_code"] = status_json.get("raw_check_code")
|
||||||
|
tips = (status_json.get("tips") or "").strip()
|
||||||
|
status_msg = status_json.get("status_msg")
|
||||||
|
msg_text = ""
|
||||||
|
if isinstance(status_msg, dict):
|
||||||
|
# 抖音把人类可读提示放在 status_msg.msg_content.tips
|
||||||
|
mc = status_msg.get("msg_content")
|
||||||
|
if isinstance(mc, dict):
|
||||||
|
msg_text = (mc.get("tips") or mc.get("content") or "").strip()
|
||||||
|
if not msg_text:
|
||||||
|
msg_text = (
|
||||||
|
status_msg.get("toast")
|
||||||
|
or status_msg.get("content")
|
||||||
|
or status_msg.get("msg")
|
||||||
|
or ""
|
||||||
|
)
|
||||||
|
elif isinstance(status_msg, str):
|
||||||
|
msg_text = status_msg
|
||||||
|
info["status_reason"] = tips or msg_text or _format_status_json(status_json)
|
||||||
|
|
||||||
|
msg_ok = info["message"].strip().upper() == "OK"
|
||||||
|
|
||||||
|
# 优先用 status_code 判定:明确给了 status_code 就以它为准(0=成功,非0=另判)
|
||||||
|
if info["status_code"] is not None:
|
||||||
|
if info["status_code"] == 0 and not info["error_desc"]:
|
||||||
|
info["ok"] = True
|
||||||
|
elif info["raw_check_code"] == 0 and msg_ok and not info["error_desc"]:
|
||||||
|
# raw_check_code=0 表示已通过抖音风控/安全校验;配合 message=OK,
|
||||||
|
# 说明消息已实际投递。此时非零 status_code 只是“业务侧提示”
|
||||||
|
# (如营销/陌生人限制提醒),对方仍能收到,不应判为发送失败。
|
||||||
|
info["ok"] = True
|
||||||
|
info["delivered_with_notice"] = True
|
||||||
|
else:
|
||||||
|
# raw_check_code=1(被风控拦截)或缺少 OK 标志:判为未送达
|
||||||
|
info["ok"] = False
|
||||||
|
else:
|
||||||
|
# 没有内嵌 status_code 时,退回“message=OK 且 body 内有服务端 message_id”
|
||||||
|
info["ok"] = bool(
|
||||||
|
not info["error_desc"]
|
||||||
|
and msg_ok
|
||||||
|
and info["server_message_id"] is not None
|
||||||
|
)
|
||||||
|
return info
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
"""私信对方用户资料抓取(昵称 / 头像 / UID)。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from rpa_engine.device_profiles import resolve_user_agent
|
||||||
|
from .auth import DouyinAuth
|
||||||
|
from .conv_util import resolve_peer_uid
|
||||||
|
from .dy_util import (
|
||||||
|
DEFAULT_USER_AGENT,
|
||||||
|
generate_a_bogus,
|
||||||
|
generate_msToken,
|
||||||
|
generate_webid,
|
||||||
|
splice_url,
|
||||||
|
)
|
||||||
|
from .protocol import _pick_avatar_url
|
||||||
|
from .session import DouyinImSession
|
||||||
|
|
||||||
|
logger = logging.getLogger("douyin_im.peer_profile")
|
||||||
|
|
||||||
|
_profile_cache: dict[str, dict[str, str]] = {}
|
||||||
|
_profile_cache_at: dict[str, float] = {}
|
||||||
|
_PROFILE_SUCCESS_TTL = 6 * 3600
|
||||||
|
_PROFILE_FAILURE_TTL = 5 * 60
|
||||||
|
|
||||||
|
|
||||||
|
def _cache_key(account_id: int, peer_uid: str) -> str:
|
||||||
|
return f"{account_id}:{peer_uid}"
|
||||||
|
|
||||||
|
|
||||||
|
def _pick_str(data: dict, *keys: str) -> str:
|
||||||
|
for key in keys:
|
||||||
|
value = data.get(key)
|
||||||
|
if value is not None and str(value).strip():
|
||||||
|
return str(value).strip()
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_profile_from_payload(data: Any) -> dict[str, str]:
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return {}
|
||||||
|
nodes = [data, data.get("user"), data.get("user_info"), data.get("data")]
|
||||||
|
for node in nodes:
|
||||||
|
if not isinstance(node, dict):
|
||||||
|
continue
|
||||||
|
uid = _pick_str(node, "uid", "user_id", "user_uid", "id")
|
||||||
|
nickname = _pick_str(
|
||||||
|
node,
|
||||||
|
"nickname",
|
||||||
|
"nick_name",
|
||||||
|
"unique_id",
|
||||||
|
"display_name",
|
||||||
|
"name",
|
||||||
|
)
|
||||||
|
avatar = _pick_avatar_url(node)
|
||||||
|
if uid or nickname or avatar:
|
||||||
|
return {"uid": uid, "nickname": nickname, "avatar_url": avatar}
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def _requests_proxies() -> dict | None:
|
||||||
|
try:
|
||||||
|
from rpa_engine.runtime_config import requests_proxies
|
||||||
|
|
||||||
|
return requests_proxies()
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _build_auth(session: DouyinImSession) -> tuple[DouyinAuth, str]:
|
||||||
|
auth = DouyinAuth()
|
||||||
|
auth.perepare_auth(session.cookie_header(), session.web_protect_str, session.keys_str)
|
||||||
|
ua = resolve_user_agent(session.user_agent or DEFAULT_USER_AGENT)
|
||||||
|
return auth, ua
|
||||||
|
|
||||||
|
|
||||||
|
def is_generic_peer_name(name: str, peer_uid: str = "") -> bool:
|
||||||
|
value = (name or "").strip()
|
||||||
|
if not value:
|
||||||
|
return True
|
||||||
|
if peer_uid and value == peer_uid:
|
||||||
|
return True
|
||||||
|
if value.isdigit():
|
||||||
|
return True
|
||||||
|
if value.startswith("用户") and value[2:].isdigit():
|
||||||
|
return True
|
||||||
|
if value.startswith("会话") and len(value) <= 16:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_peer_profile_sync(
|
||||||
|
session: DouyinImSession,
|
||||||
|
peer_uid: int | str,
|
||||||
|
account_id: int = 0,
|
||||||
|
) -> dict[str, str]:
|
||||||
|
uid = str(peer_uid or "").strip()
|
||||||
|
if not uid.isdigit():
|
||||||
|
return {}
|
||||||
|
|
||||||
|
cache_key = _cache_key(account_id, uid)
|
||||||
|
cached = _profile_cache.get(cache_key)
|
||||||
|
cached_at = _profile_cache_at.get(cache_key, 0.0)
|
||||||
|
if cached:
|
||||||
|
ttl = (
|
||||||
|
_PROFILE_SUCCESS_TTL
|
||||||
|
if cached.get("nickname") or cached.get("avatar_url")
|
||||||
|
else _PROFILE_FAILURE_TTL
|
||||||
|
)
|
||||||
|
if time.time() - cached_at < ttl:
|
||||||
|
return dict(cached)
|
||||||
|
|
||||||
|
result = {"uid": uid, "nickname": "", "avatar_url": ""}
|
||||||
|
try:
|
||||||
|
auth, ua = _build_auth(session)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning(f"build auth for peer profile failed: {exc}")
|
||||||
|
_profile_cache[cache_key] = dict(result)
|
||||||
|
_profile_cache_at[cache_key] = time.time()
|
||||||
|
return result
|
||||||
|
|
||||||
|
try:
|
||||||
|
web_id = session.web_id or generate_webid(auth, "https://www.douyin.com/")
|
||||||
|
if web_id and not session.web_id:
|
||||||
|
# Reuse the homepage-derived ID for every peer on this account.
|
||||||
|
session.web_id = str(web_id)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug(f"generate webid for peer profile failed: {exc}")
|
||||||
|
web_id = session.web_id or ""
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
"User-Agent": ua,
|
||||||
|
"Referer": "https://www.douyin.com/",
|
||||||
|
"Accept": "application/json, text/plain, */*",
|
||||||
|
}
|
||||||
|
base_params = {
|
||||||
|
"device_platform": "webapp",
|
||||||
|
"aid": "6383",
|
||||||
|
"channel": "channel_pc_web",
|
||||||
|
"publish_video_strategy_type": "2",
|
||||||
|
"user_id": uid,
|
||||||
|
"sec_user_id": "",
|
||||||
|
"verifyFp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
|
||||||
|
"fp": auth.cookie.get("s_v_web_id", "") if auth.cookie else "",
|
||||||
|
"webid": web_id,
|
||||||
|
"msToken": auth.msToken or generate_msToken(),
|
||||||
|
}
|
||||||
|
endpoints = [
|
||||||
|
"https://www.douyin.com/aweme/v1/web/user/profile/other/",
|
||||||
|
"https://www.douyin.com/aweme/v1/web/im/user/info/",
|
||||||
|
]
|
||||||
|
|
||||||
|
proxies = _requests_proxies()
|
||||||
|
for url in endpoints:
|
||||||
|
try:
|
||||||
|
params = dict(base_params)
|
||||||
|
query = splice_url(params)
|
||||||
|
params["a_bogus"] = generate_a_bogus(query, user_agent=ua)
|
||||||
|
resp = requests.get(
|
||||||
|
url,
|
||||||
|
params=params,
|
||||||
|
headers=headers,
|
||||||
|
cookies=auth.cookie,
|
||||||
|
verify=False,
|
||||||
|
timeout=12,
|
||||||
|
proxies=proxies,
|
||||||
|
)
|
||||||
|
data = resp.json()
|
||||||
|
extracted = _extract_profile_from_payload(data)
|
||||||
|
if extracted.get("uid") and not result["uid"]:
|
||||||
|
result["uid"] = extracted["uid"]
|
||||||
|
if extracted.get("nickname") and not result["nickname"]:
|
||||||
|
result["nickname"] = extracted["nickname"]
|
||||||
|
if extracted.get("avatar_url") and not result["avatar_url"]:
|
||||||
|
result["avatar_url"] = extracted["avatar_url"]
|
||||||
|
if result["nickname"] and result["avatar_url"]:
|
||||||
|
break
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug(f"peer profile fetch failed for {url}: {exc}")
|
||||||
|
|
||||||
|
# Cache both success and failure. Without a short negative TTL, missing or
|
||||||
|
# rate-limited profiles were fetched again for every account poll.
|
||||||
|
_profile_cache[cache_key] = dict(result)
|
||||||
|
_profile_cache_at[cache_key] = time.time()
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
async def fetch_peer_profile(
|
||||||
|
session: DouyinImSession,
|
||||||
|
peer_uid: int | str,
|
||||||
|
account_id: int = 0,
|
||||||
|
) -> dict[str, str]:
|
||||||
|
from .traffic_control import get_traffic_controller
|
||||||
|
|
||||||
|
controller = get_traffic_controller()
|
||||||
|
async with controller.background_slot(account_id, "peer profile"):
|
||||||
|
return await asyncio.to_thread(
|
||||||
|
fetch_peer_profile_sync,
|
||||||
|
session,
|
||||||
|
peer_uid,
|
||||||
|
account_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def enrich_conversation_item(conv: dict, my_uid: int = 0) -> dict:
|
||||||
|
"""补全会话项中的 peer_uid / sender_id。"""
|
||||||
|
item = dict(conv or {})
|
||||||
|
conv_id = str(item.get("conversation_id") or "").strip()
|
||||||
|
peer_uid = str(item.get("peer_uid") or item.get("sender_id") or "").strip()
|
||||||
|
if (not peer_uid or not peer_uid.isdigit()) and conv_id and my_uid:
|
||||||
|
resolved = resolve_peer_uid(conv_id, int(my_uid))
|
||||||
|
if resolved:
|
||||||
|
peer_uid = str(resolved)
|
||||||
|
if peer_uid:
|
||||||
|
item["peer_uid"] = peer_uid
|
||||||
|
item["sender_id"] = peer_uid
|
||||||
|
elif conv_id:
|
||||||
|
item["sender_id"] = conv_id
|
||||||
|
return item
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
import json
|
||||||
|
import random
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from .static import Request_pb2 as RequestProto
|
||||||
|
from .dy_util import (
|
||||||
|
generate_webid,
|
||||||
|
generate_req_sign,
|
||||||
|
generate_millisecond,
|
||||||
|
normalize_client_cert,
|
||||||
|
DEFAULT_USER_AGENT,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _ua_headers(auth) -> tuple[str, str]:
|
||||||
|
ua = getattr(auth, "user_agent", None) or DEFAULT_USER_AGENT
|
||||||
|
browser_version = ua.split("Mozilla/", 1)[-1] if "Mozilla/" in ua else ua
|
||||||
|
return ua, browser_version
|
||||||
|
|
||||||
|
|
||||||
|
class ProtoBuilder:
|
||||||
|
@staticmethod
|
||||||
|
def build_normal_request(auth, cmd):
|
||||||
|
ua, browser_version = _ua_headers(auth)
|
||||||
|
request = RequestProto.Request()
|
||||||
|
request.cmd = cmd
|
||||||
|
request.sequence_id = random.randint(10000, 11000)
|
||||||
|
request.sdk_version = "1.1.3"
|
||||||
|
request.token = auth.ticket if auth.ticket else ""
|
||||||
|
request.refer = 3
|
||||||
|
request.inbox_type = 0
|
||||||
|
request.build_number = "5fa6ff1:Detached: 5fa6ff1111fd53aafc4c753505d3c93daad74d27"
|
||||||
|
did = str(getattr(auth, "device_id", "") or "0")
|
||||||
|
request.device_id = did
|
||||||
|
request.device_platform = 'douyin_pc'
|
||||||
|
request.headers['session_aid'] = '6383'
|
||||||
|
request.headers['session_did'] = did
|
||||||
|
request.headers['app_name'] = 'douyin_pc'
|
||||||
|
request.headers['priority_region'] = 'cn'
|
||||||
|
request.headers['user_agent'] = ua
|
||||||
|
request.headers['cookie_enabled'] = 'true'
|
||||||
|
request.headers['browser_language'] = 'zh-CN'
|
||||||
|
request.headers['browser_platform'] = 'Win32'
|
||||||
|
request.headers['browser_name'] = 'Mozilla'
|
||||||
|
request.headers['browser_version'] = browser_version
|
||||||
|
request.headers['browser_online'] = 'true'
|
||||||
|
request.headers['screen_width'] = '1707'
|
||||||
|
request.headers['screen_height'] = '960'
|
||||||
|
request.headers['referer'] = ''
|
||||||
|
request.headers['timezone_name'] = 'Etc/GMT-8'
|
||||||
|
request.headers['deviceId'] = did
|
||||||
|
request.headers['webid'] = generate_webid(auth)
|
||||||
|
request.headers['fp'] = auth.cookie.get('s_v_web_id', '') if auth.cookie else ''
|
||||||
|
request.headers['is-retry'] = '0'
|
||||||
|
request.auth_type = 4
|
||||||
|
request.biz = 'douyin_web'
|
||||||
|
request.access = 'web_sdk'
|
||||||
|
request.ts_sign = auth.ts_sign if auth.ts_sign else ""
|
||||||
|
request.sdk_cert = normalize_client_cert(auth.client_cert or "")
|
||||||
|
return request
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def build_create_conversation_request(auth, toId, myId):
|
||||||
|
request = ProtoBuilder.build_normal_request(auth, 609)
|
||||||
|
request.body.create_conversation_v2_body.conversation_type = 1
|
||||||
|
request.body.create_conversation_v2_body.participants.extend([int(toId), int(myId)])
|
||||||
|
reuqest_sign = generate_req_sign({
|
||||||
|
"sign_data": f"avatar_url=&idempotent_id=&name=&participants={toId},{myId}",
|
||||||
|
"certType": "cookie",
|
||||||
|
"scene": "web_protect"
|
||||||
|
}, auth.private_key)
|
||||||
|
request.reuqest_sign = reuqest_sign
|
||||||
|
return request
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def build_get_conversation_list_info_request(auth, toId, myId, conversation_short_id):
|
||||||
|
request = ProtoBuilder.build_normal_request(auth, 610)
|
||||||
|
request.body.get_conversation_info_list_v2_body.data.conversation_id = f"0:1:{myId}:{toId}"
|
||||||
|
request.body.get_conversation_info_list_v2_body.data.conversation_short_id = int(conversation_short_id)
|
||||||
|
request.body.get_conversation_info_list_v2_body.data.conversation_type = 1
|
||||||
|
return request
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def build_send_message_request(
|
||||||
|
auth,
|
||||||
|
conversation_id,
|
||||||
|
conversation_short_id,
|
||||||
|
ticket,
|
||||||
|
msg_content,
|
||||||
|
message_type: int = 7,
|
||||||
|
):
|
||||||
|
client_message_id = str(uuid.uuid4())
|
||||||
|
request = ProtoBuilder.build_normal_request(auth, 100)
|
||||||
|
request.body.send_message_body.conversation_id = conversation_id
|
||||||
|
request.body.send_message_body.conversation_type = 1
|
||||||
|
request.body.send_message_body.conversation_short_id = int(conversation_short_id)
|
||||||
|
request.body.send_message_body.content = json.dumps(msg_content, ensure_ascii=False,
|
||||||
|
separators=(',', ':'))
|
||||||
|
request.body.send_message_body.ext.append(
|
||||||
|
RequestProto.ExtValue(key='s:client_message_id', value=client_message_id)
|
||||||
|
)
|
||||||
|
request.body.send_message_body.ext.append(
|
||||||
|
RequestProto.ExtValue(key='s:stime', value=str(generate_millisecond()))
|
||||||
|
)
|
||||||
|
request.body.send_message_body.ext.append(
|
||||||
|
RequestProto.ExtValue(key='s:mentioned_users', value='')
|
||||||
|
)
|
||||||
|
request.body.send_message_body.message_type = int(message_type)
|
||||||
|
request.body.send_message_body.ticket = ticket
|
||||||
|
request.body.send_message_body.client_message_id = client_message_id
|
||||||
|
|
||||||
|
# 签名数据计算
|
||||||
|
sign_data_str = f'content={json.dumps(msg_content, separators=(",", ":"), ensure_ascii=False)}' + f'&conversation_id={conversation_id}&conversation_short_id={conversation_short_id}'
|
||||||
|
req_sign = generate_req_sign({
|
||||||
|
"sign_data": sign_data_str,
|
||||||
|
"certType": "cookie",
|
||||||
|
"scene": "web_protect"
|
||||||
|
}, auth.private_key)
|
||||||
|
request.reuqest_sign = req_sign
|
||||||
|
return request
|
||||||
@@ -0,0 +1,518 @@
|
|||||||
|
import gzip
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from typing import Any, Optional
|
||||||
|
|
||||||
|
from .message_content import (
|
||||||
|
MSG_TYPE_IMAGE,
|
||||||
|
MSG_TYPE_LINK_CARD,
|
||||||
|
MSG_TYPE_STICKER,
|
||||||
|
MSG_TYPE_TEXT,
|
||||||
|
MSG_TYPE_VIDEO,
|
||||||
|
MSG_TYPE_VOICE,
|
||||||
|
_coerce_message_type,
|
||||||
|
format_im_message,
|
||||||
|
message_preview,
|
||||||
|
parse_incoming_message,
|
||||||
|
parse_stored_content,
|
||||||
|
serialize_message_content,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger("douyin_im.protocol")
|
||||||
|
|
||||||
|
import os
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
||||||
|
def _is_control_payload(content_json: Any, msg_type: int = 0) -> bool:
|
||||||
|
"""判断是否为「会话控制/状态更新」等非聊天内容帧。
|
||||||
|
|
||||||
|
例如 command_type=6 的连续互动统计(consecutive_chat_data)、ext_data 元数据更新、
|
||||||
|
message_type>=50000 的系统通知等——这些不是用户发的消息,不应记录/展示成聊天气泡,
|
||||||
|
更不应触发自动回复。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
if msg_type and int(msg_type) >= 50000:
|
||||||
|
return True
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
pass
|
||||||
|
if isinstance(content_json, dict) and ("command_type" in content_json or "ext_data" in content_json):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
_WS_DEBUG_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "ws_media_debug.log")
|
||||||
|
|
||||||
|
|
||||||
|
def _should_emit_ws_message(
|
||||||
|
conversation_id: str,
|
||||||
|
msg_type: int,
|
||||||
|
) -> bool:
|
||||||
|
"""判断 WS 帧是否为用户聊天消息(控制帧已在 _is_control_payload 过滤)。"""
|
||||||
|
if not conversation_id:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
if int(msg_type) >= 50000:
|
||||||
|
return False
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
pass
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _dump_ws_message(msg_type: int, conversation_id: str, content_str: str, msg: Any = None) -> None:
|
||||||
|
"""把每条 WS 消息的全部字段落到调试文件,便于排查媒体字段结构。
|
||||||
|
|
||||||
|
默认关闭,仅当设置环境变量 KEFU_WS_DEBUG=1 时写盘,避免生产环境无界增长 / 泄露聊天内容。
|
||||||
|
content 为空时(如 type=26 瘦推送)会额外打印 protobuf 其余字段,确保「接收到的全部信息」可见。
|
||||||
|
"""
|
||||||
|
if os.getenv("KEFU_WS_DEBUG", "") not in ("1", "true", "True"):
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
extra = ""
|
||||||
|
if msg is not None:
|
||||||
|
fields = {}
|
||||||
|
try:
|
||||||
|
for f, v in msg.ListFields():
|
||||||
|
if f.name == "content":
|
||||||
|
continue
|
||||||
|
fields[f.name] = v
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if fields:
|
||||||
|
extra = " | fields=" + json.dumps(fields, ensure_ascii=False, default=str)
|
||||||
|
line = (
|
||||||
|
f"{datetime.now().isoformat()} type={msg_type} "
|
||||||
|
f"conv={conversation_id} content={content_str}{extra}\n"
|
||||||
|
)
|
||||||
|
with open(_WS_DEBUG_PATH, "a", encoding="utf-8") as fh:
|
||||||
|
fh.write(line)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _walk_strings(data: Any, depth: int = 0, max_depth: int = 10):
|
||||||
|
if depth > max_depth:
|
||||||
|
return
|
||||||
|
if isinstance(data, dict):
|
||||||
|
for v in data.values():
|
||||||
|
yield from _walk_strings(v, depth + 1, max_depth)
|
||||||
|
elif isinstance(data, list):
|
||||||
|
for item in data:
|
||||||
|
yield from _walk_strings(item, depth + 1, max_depth)
|
||||||
|
elif isinstance(data, str) and data.strip():
|
||||||
|
yield data.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def extract_json_objects(raw: bytes | str) -> list[dict]:
|
||||||
|
"""从二进制帧中尽量提取 JSON 对象"""
|
||||||
|
if isinstance(raw, bytes):
|
||||||
|
for codec in ("utf-8", "latin-1"):
|
||||||
|
try:
|
||||||
|
text = raw.decode(codec, errors="ignore")
|
||||||
|
break
|
||||||
|
except Exception:
|
||||||
|
text = ""
|
||||||
|
else:
|
||||||
|
text = ""
|
||||||
|
else:
|
||||||
|
text = raw
|
||||||
|
|
||||||
|
results = []
|
||||||
|
for match in re.finditer(r"\{[^{}]{0,2000}\}", text):
|
||||||
|
chunk = match.group(0)
|
||||||
|
try:
|
||||||
|
obj = json.loads(chunk)
|
||||||
|
if isinstance(obj, dict):
|
||||||
|
results.append(obj)
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def parse_ws_payload(raw: bytes | str) -> list[dict]:
|
||||||
|
"""解析 WebSocket 二进制帧,返回标准化消息 dict 列表"""
|
||||||
|
messages = []
|
||||||
|
|
||||||
|
# 尝试 Protobuf 解包
|
||||||
|
if isinstance(raw, bytes):
|
||||||
|
try:
|
||||||
|
from .static import Live_pb2, Response_pb2
|
||||||
|
frame = Live_pb2.PushFrame()
|
||||||
|
frame.ParseFromString(raw)
|
||||||
|
if frame.payloadType == 'pb':
|
||||||
|
response = Response_pb2.Response()
|
||||||
|
response.ParseFromString(frame.payload)
|
||||||
|
body = response.body
|
||||||
|
if body.HasField("new_message_notify"):
|
||||||
|
notify = body.new_message_notify
|
||||||
|
if notify.HasField("message"):
|
||||||
|
msg = notify.message
|
||||||
|
sender = str(msg.sender)
|
||||||
|
msg_type = msg.message_type
|
||||||
|
conversation_id = msg.conversation_id
|
||||||
|
content_str = msg.content
|
||||||
|
server_message_id = str(getattr(msg, "server_message_id", "") or "")
|
||||||
|
|
||||||
|
_dump_ws_message(msg_type, conversation_id, content_str, msg)
|
||||||
|
|
||||||
|
text_content = ""
|
||||||
|
media_msg: dict = {}
|
||||||
|
content_json: dict = {}
|
||||||
|
try:
|
||||||
|
content_json = json.loads(content_str) if content_str else {}
|
||||||
|
if not isinstance(content_json, dict):
|
||||||
|
content_json = {}
|
||||||
|
media_msg = format_im_message(content_json, msg_type)
|
||||||
|
text_content = media_msg.get("text") or ""
|
||||||
|
except Exception:
|
||||||
|
media_msg = format_im_message(content_str or "", msg_type)
|
||||||
|
text_content = media_msg.get("text") or content_str or ""
|
||||||
|
|
||||||
|
# 跳过会话控制/状态更新等非聊天内容帧(不记录、不展示、不触发自动回复)
|
||||||
|
if _is_control_payload(content_json, msg_type):
|
||||||
|
logger.debug(
|
||||||
|
"Skip control WS frame: type=%s conv=%s", msg_type, conversation_id
|
||||||
|
)
|
||||||
|
return messages
|
||||||
|
|
||||||
|
if _should_emit_ws_message(conversation_id, msg_type):
|
||||||
|
sender_uid = str(msg.sender)
|
||||||
|
if media_msg and (
|
||||||
|
media_msg.get("text")
|
||||||
|
or media_msg.get("type") not in (None, "text", "")
|
||||||
|
):
|
||||||
|
display_content = serialize_message_content(media_msg)
|
||||||
|
else:
|
||||||
|
display_content = text_content or content_str
|
||||||
|
payload = {
|
||||||
|
"sender_name": sender_uid,
|
||||||
|
"sender_uid": sender_uid,
|
||||||
|
"content": display_content,
|
||||||
|
"raw_content": content_str,
|
||||||
|
"conversation_id": conversation_id,
|
||||||
|
"unread_count": 1,
|
||||||
|
"server_message_id": server_message_id,
|
||||||
|
"message_type": msg_type,
|
||||||
|
}
|
||||||
|
if msg_type in (
|
||||||
|
MSG_TYPE_IMAGE,
|
||||||
|
MSG_TYPE_STICKER,
|
||||||
|
MSG_TYPE_VOICE,
|
||||||
|
MSG_TYPE_VIDEO,
|
||||||
|
MSG_TYPE_LINK_CARD,
|
||||||
|
):
|
||||||
|
if not media_msg.get("url") and not media_msg.get("uri"):
|
||||||
|
logger.warning(
|
||||||
|
"Media WS message missing url: type=%s content=%s",
|
||||||
|
msg_type,
|
||||||
|
(content_str or "")[:800],
|
||||||
|
)
|
||||||
|
elif not media_msg.get("url"):
|
||||||
|
logger.info(
|
||||||
|
"Media WS message resolved via uri: type=%s uri=%s",
|
||||||
|
msg_type,
|
||||||
|
media_msg.get("uri"),
|
||||||
|
)
|
||||||
|
messages.append(payload)
|
||||||
|
logger.info(
|
||||||
|
"Protobuf WS message parsed: sender=%s type=%s content=%s conv=%s",
|
||||||
|
sender,
|
||||||
|
msg_type,
|
||||||
|
text_content,
|
||||||
|
conversation_id,
|
||||||
|
)
|
||||||
|
return messages
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"Protobuf WS parse failed: {e}")
|
||||||
|
|
||||||
|
if isinstance(raw, str):
|
||||||
|
payloads = [raw.encode("utf-8", errors="ignore")]
|
||||||
|
else:
|
||||||
|
payloads = [raw]
|
||||||
|
# 尝试 gzip 解压(frontier 常见)
|
||||||
|
try:
|
||||||
|
payloads.append(gzip.decompress(raw))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
for payload in payloads:
|
||||||
|
# 1) 直接 JSON
|
||||||
|
if isinstance(payload, bytes):
|
||||||
|
text = payload.decode("utf-8", errors="ignore").strip()
|
||||||
|
else:
|
||||||
|
text = str(payload).strip()
|
||||||
|
if text.startswith("{") or text.startswith("["):
|
||||||
|
try:
|
||||||
|
data = json.loads(text)
|
||||||
|
messages.extend(normalize_im_payload(data))
|
||||||
|
continue
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 2) 嵌入 JSON
|
||||||
|
for obj in extract_json_objects(payload):
|
||||||
|
messages.extend(normalize_im_payload(obj))
|
||||||
|
|
||||||
|
# 3) 纯文本兜底
|
||||||
|
if isinstance(payload, bytes):
|
||||||
|
text = payload.decode("utf-8", errors="ignore")
|
||||||
|
plain = _extract_plain_text(text)
|
||||||
|
if plain:
|
||||||
|
messages.append({"content": plain, "sender_name": "", "raw_content": plain, "raw": True})
|
||||||
|
|
||||||
|
return messages
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_im_payload_from_bytes(raw: bytes) -> list[dict]:
|
||||||
|
"""Try to extract conversation/message payloads from binary IM API responses."""
|
||||||
|
results: list[dict] = []
|
||||||
|
for obj in extract_json_objects(raw):
|
||||||
|
results.extend(normalize_im_payload(obj))
|
||||||
|
if results:
|
||||||
|
return results
|
||||||
|
|
||||||
|
try:
|
||||||
|
from .static import Response_pb2
|
||||||
|
response = Response_pb2.Response()
|
||||||
|
response.ParseFromString(raw)
|
||||||
|
body = response.body
|
||||||
|
for field in (
|
||||||
|
"get_conversation_info_list_v2_response_body",
|
||||||
|
"create_conversation_v2_body",
|
||||||
|
):
|
||||||
|
if body.HasField(field):
|
||||||
|
conv_body = getattr(body, field)
|
||||||
|
for conv in conv_body.conversation_info_list:
|
||||||
|
conv_id = conv.conversation_id
|
||||||
|
peer_uid = ""
|
||||||
|
parts = conv_id.split(":")
|
||||||
|
if len(parts) >= 4:
|
||||||
|
peer_uid = parts[-1]
|
||||||
|
label = f"用户{peer_uid[-6:]}" if peer_uid else conv_id
|
||||||
|
results.append({
|
||||||
|
"conversation_id": conv_id,
|
||||||
|
"sender_name": label,
|
||||||
|
"content": "",
|
||||||
|
"unread_count": 0,
|
||||||
|
"peer_uid": peer_uid,
|
||||||
|
"conversation_short_id": str(conv.conversation_short_id),
|
||||||
|
"ticket": conv.ticket,
|
||||||
|
})
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_im_payload(data: Any, depth: int = 0) -> list[dict]:
|
||||||
|
"""递归标准化 IM JSON 为 {sender_name, content, conversation_id, unread_count}"""
|
||||||
|
if depth > 12:
|
||||||
|
return []
|
||||||
|
results = []
|
||||||
|
|
||||||
|
if isinstance(data, list):
|
||||||
|
for item in data:
|
||||||
|
results.extend(normalize_im_payload(item, depth + 1))
|
||||||
|
return results
|
||||||
|
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return results
|
||||||
|
|
||||||
|
sender = (
|
||||||
|
_pick_str(data, "sender_name", "senderName", "nickname", "nick_name", "userName", "peerName")
|
||||||
|
or _pick_nested(data, ("core_info", "user_info", "peer_info"), "nick_name", "nickname", "name")
|
||||||
|
)
|
||||||
|
sender_avatar = _pick_avatar_url(data)
|
||||||
|
content = _pick_message_text(data)
|
||||||
|
msg_type = _coerce_message_type(
|
||||||
|
data.get("message_type") or data.get("messageType") or data.get("msg_type"),
|
||||||
|
MSG_TYPE_TEXT,
|
||||||
|
)
|
||||||
|
# 会话控制/状态更新帧(command_type / ext_data / 系统通知)直接忽略,不当作聊天消息
|
||||||
|
if _is_control_payload(data, msg_type) or _is_control_payload(data.get("content"), msg_type):
|
||||||
|
return results
|
||||||
|
if msg_type != MSG_TYPE_TEXT or (isinstance(data.get("content"), dict)):
|
||||||
|
parsed = parse_incoming_message(data)
|
||||||
|
if parsed:
|
||||||
|
content = parsed
|
||||||
|
elif content and content.startswith("{"):
|
||||||
|
try:
|
||||||
|
parsed = format_im_message(json.loads(content), msg_type)
|
||||||
|
content = serialize_message_content(parsed)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
elif content in _NON_TEXT_MESSAGE_MARKERS:
|
||||||
|
parsed = parse_stored_content(content)
|
||||||
|
content = serialize_message_content(parsed)
|
||||||
|
conv_id = _pick_str(
|
||||||
|
data,
|
||||||
|
"conversation_id",
|
||||||
|
"conversationId",
|
||||||
|
"conv_id",
|
||||||
|
"cid",
|
||||||
|
)
|
||||||
|
unread = data.get("unread_count") or data.get("unreadCount") or data.get("unread_cnt") or 0
|
||||||
|
try:
|
||||||
|
unread = int(unread or 0)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
unread = 0
|
||||||
|
|
||||||
|
if content and len(content) < 500:
|
||||||
|
from_self = data.get("is_self") or data.get("isSelf") or data.get("fromSelf") or data.get("self")
|
||||||
|
if not from_self:
|
||||||
|
raw_content = _extract_raw_content(data) or content
|
||||||
|
results.append({
|
||||||
|
"sender_name": sender or "未知用户",
|
||||||
|
"sender_avatar": sender_avatar or None,
|
||||||
|
"content": content,
|
||||||
|
"raw_content": raw_content,
|
||||||
|
"conversation_id": conv_id or "",
|
||||||
|
"unread_count": unread,
|
||||||
|
"message_type": msg_type,
|
||||||
|
})
|
||||||
|
|
||||||
|
if sender and unread > 0 and not content:
|
||||||
|
results.append({
|
||||||
|
"sender_name": sender,
|
||||||
|
"sender_avatar": sender_avatar or None,
|
||||||
|
"content": "[未读消息]",
|
||||||
|
"raw_content": "[未读消息]",
|
||||||
|
"conversation_id": conv_id or "",
|
||||||
|
"unread_count": unread,
|
||||||
|
"message_type": msg_type,
|
||||||
|
})
|
||||||
|
|
||||||
|
for key in ("conversations", "conversation_list", "data", "messages", "messagesList", "body"):
|
||||||
|
nested = data.get(key)
|
||||||
|
if nested is not None:
|
||||||
|
results.extend(normalize_im_payload(nested, depth + 1))
|
||||||
|
|
||||||
|
for value in data.values():
|
||||||
|
if isinstance(value, (dict, list)):
|
||||||
|
results.extend(normalize_im_payload(value, depth + 1))
|
||||||
|
|
||||||
|
return results
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_raw_content(data: dict) -> str:
|
||||||
|
for key in ("content", "message", "msg", "lastMessage", "last_msg", "preview", "brief"):
|
||||||
|
val = data.get(key)
|
||||||
|
if isinstance(val, str) and val.strip():
|
||||||
|
return val.strip()
|
||||||
|
if isinstance(val, dict):
|
||||||
|
return json.dumps(val, ensure_ascii=False, separators=(",", ":"))
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _pick_str(data: dict, *keys: str) -> str:
|
||||||
|
for key in keys:
|
||||||
|
val = data.get(key)
|
||||||
|
if isinstance(val, str) and val.strip():
|
||||||
|
return val.strip()
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _pick_nested(data: dict, parent_keys: tuple, *child_keys: str) -> str:
|
||||||
|
for pk in parent_keys:
|
||||||
|
nested = data.get(pk)
|
||||||
|
if isinstance(nested, dict):
|
||||||
|
val = _pick_str(nested, *child_keys)
|
||||||
|
if val:
|
||||||
|
return val
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _avatar_from_value(val: Any) -> str:
|
||||||
|
if isinstance(val, str) and val.strip().startswith("http"):
|
||||||
|
return val.strip()
|
||||||
|
if isinstance(val, dict):
|
||||||
|
direct = val.get("url")
|
||||||
|
if isinstance(direct, str) and direct.startswith("http"):
|
||||||
|
return direct.strip()
|
||||||
|
for list_key in ("url_list", "urls"):
|
||||||
|
urls = val.get(list_key)
|
||||||
|
if isinstance(urls, list):
|
||||||
|
for item in urls:
|
||||||
|
if isinstance(item, str) and item.startswith("http"):
|
||||||
|
return item.strip()
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _pick_avatar_url(data: dict) -> str:
|
||||||
|
for key in ("avatar_url", "avatarUrl", "head_url", "headUrl", "avatar"):
|
||||||
|
url = _avatar_from_value(data.get(key))
|
||||||
|
if url:
|
||||||
|
return url
|
||||||
|
for thumb_key in ("avatar_thumb", "avatar_medium", "avatar_larger", "avatarThumb"):
|
||||||
|
url = _avatar_from_value(data.get(thumb_key))
|
||||||
|
if url:
|
||||||
|
return url
|
||||||
|
for parent_key in ("core_info", "user_info", "peer_info", "target_user", "conversation_core_info"):
|
||||||
|
nested = data.get(parent_key)
|
||||||
|
if isinstance(nested, dict):
|
||||||
|
url = _pick_avatar_url(nested)
|
||||||
|
if url:
|
||||||
|
return url
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _pick_message_text(data: dict) -> str:
|
||||||
|
for key in (
|
||||||
|
"text",
|
||||||
|
"content",
|
||||||
|
"message",
|
||||||
|
"msg",
|
||||||
|
"lastMessage",
|
||||||
|
"last_msg",
|
||||||
|
"preview",
|
||||||
|
"brief",
|
||||||
|
):
|
||||||
|
val = data.get(key)
|
||||||
|
if isinstance(val, str) and val.strip():
|
||||||
|
return val.strip()
|
||||||
|
if isinstance(val, dict):
|
||||||
|
inner = _pick_str(val, "text", "content", "message")
|
||||||
|
if inner:
|
||||||
|
return inner
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_plain_text(text: str) -> Optional[str]:
|
||||||
|
text = (text or "").strip()
|
||||||
|
if not text or len(text) > 200:
|
||||||
|
return None
|
||||||
|
if text.startswith("{") or text.startswith("["):
|
||||||
|
return None
|
||||||
|
# 过滤明显二进制垃圾
|
||||||
|
printable = sum(1 for c in text if c.isprintable() or c in "\n\r\t")
|
||||||
|
if printable / max(len(text), 1) < 0.8:
|
||||||
|
return None
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
_NON_TEXT_MESSAGE_MARKERS = {
|
||||||
|
"[表情包]",
|
||||||
|
"[语音]",
|
||||||
|
"[图片]",
|
||||||
|
"[视频]",
|
||||||
|
"[未读消息]",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def should_skip_auto_reply(content: str) -> tuple[bool, str]:
|
||||||
|
"""判断收到的内容是否不适合触发自动回复(如纯点赞/表情互动)。"""
|
||||||
|
from .message_content import is_media_message, message_preview
|
||||||
|
|
||||||
|
text = (content or "").strip()
|
||||||
|
if not text:
|
||||||
|
return True, "空消息"
|
||||||
|
if is_media_message(text):
|
||||||
|
return True, f"非文本消息({message_preview(text)})"
|
||||||
|
if text in _NON_TEXT_MESSAGE_MARKERS:
|
||||||
|
return True, f"非文本消息({text})"
|
||||||
|
if re.fullmatch(r"(\[赞\])+", text):
|
||||||
|
return True, "表情互动消息(点赞),抖音通常不允许对此类消息自动回复"
|
||||||
|
if re.fullmatch(r"\[[^\]]+\](\[[^\]]+\])*", text) and "http" not in text:
|
||||||
|
inner = re.sub(r"[\[\]]", "", text)
|
||||||
|
if len(inner) <= 20 and not any(ch.isalnum() for ch in inner):
|
||||||
|
return True, f"非文本互动消息({text})"
|
||||||
|
return False, ""
|
||||||
@@ -0,0 +1,330 @@
|
|||||||
|
"""自动回复内容解析与 IM 消息体构造(文本 / 网址 / 卡片)。"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from typing import Any, Tuple
|
||||||
|
|
||||||
|
from .message_content import (
|
||||||
|
MSG_TYPE_IMAGE,
|
||||||
|
MSG_TYPE_STICKER,
|
||||||
|
MSG_TYPE_TEXT,
|
||||||
|
message_preview,
|
||||||
|
parse_stored_content,
|
||||||
|
serialize_message_content,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize_reply_spec(data: dict[str, Any]) -> dict[str, Any] | None:
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return None
|
||||||
|
reply_type = data.get("type")
|
||||||
|
if reply_type in ("text", "link", "card", "image", "sticker"):
|
||||||
|
return data
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_reply_messages(raw: str) -> list[dict[str, Any]]:
|
||||||
|
"""解析规则中的 reply_content,支持单条或多条回复。"""
|
||||||
|
raw = (raw or "").strip()
|
||||||
|
if not raw:
|
||||||
|
return [{"type": "text", "text": ""}]
|
||||||
|
if raw.startswith("{") or raw.startswith("["):
|
||||||
|
try:
|
||||||
|
data = json.loads(raw)
|
||||||
|
if isinstance(data, dict) and isinstance(data.get("messages"), list):
|
||||||
|
specs = [_normalize_reply_spec(item) for item in data["messages"]]
|
||||||
|
specs = [item for item in specs if item]
|
||||||
|
if specs:
|
||||||
|
return specs
|
||||||
|
if isinstance(data, list):
|
||||||
|
specs = [_normalize_reply_spec(item) for item in data]
|
||||||
|
specs = [item for item in specs if item]
|
||||||
|
if specs:
|
||||||
|
return specs
|
||||||
|
if isinstance(data, dict):
|
||||||
|
spec = _normalize_reply_spec(data)
|
||||||
|
if spec:
|
||||||
|
return [spec]
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
return [{"type": "text", "text": raw}]
|
||||||
|
|
||||||
|
|
||||||
|
def parse_reply_content(raw: str) -> dict[str, Any]:
|
||||||
|
"""解析发送/规则中的 content。纯字符串视为文本,JSON 为结构化消息。"""
|
||||||
|
raw = (raw or "").strip()
|
||||||
|
if raw.startswith("{"):
|
||||||
|
try:
|
||||||
|
data = json.loads(raw)
|
||||||
|
if isinstance(data, dict):
|
||||||
|
spec = _normalize_reply_spec(data)
|
||||||
|
if spec:
|
||||||
|
return spec
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass
|
||||||
|
parsed = parse_stored_content(raw)
|
||||||
|
if parsed.get("type") != "text":
|
||||||
|
return parsed
|
||||||
|
return parse_reply_messages(raw)[0]
|
||||||
|
|
||||||
|
|
||||||
|
def _format_reply_spec(spec: dict[str, Any]) -> str:
|
||||||
|
reply_type = spec.get("type", "text")
|
||||||
|
if reply_type in ("image", "sticker", "voice", "video"):
|
||||||
|
return message_preview(serialize_message_content(spec))
|
||||||
|
if reply_type == "text":
|
||||||
|
return (spec.get("text") or "").strip()
|
||||||
|
if reply_type == "link":
|
||||||
|
text = (spec.get("text") or spec.get("title") or "").strip()
|
||||||
|
url = (spec.get("url") or "").strip()
|
||||||
|
if text and url:
|
||||||
|
return f"{text} → {url}"
|
||||||
|
return text or url
|
||||||
|
if reply_type == "card":
|
||||||
|
title = (spec.get("title") or "").strip()
|
||||||
|
desc = (spec.get("desc") or spec.get("description") or "").strip()
|
||||||
|
page_url = (spec.get("url") or "").strip()
|
||||||
|
if title and page_url:
|
||||||
|
return f"[卡片] {title} → {page_url}"
|
||||||
|
return title or desc or page_url or "[卡片]"
|
||||||
|
return message_preview(serialize_message_content(spec))
|
||||||
|
|
||||||
|
|
||||||
|
def format_reply_display(raw: str) -> str:
|
||||||
|
"""将 reply_content 格式化为日志/列表中的可读摘要。"""
|
||||||
|
preview = message_preview(raw)
|
||||||
|
if preview:
|
||||||
|
return preview
|
||||||
|
specs = parse_reply_messages(raw)
|
||||||
|
parts = [_format_reply_spec(spec) for spec in specs]
|
||||||
|
parts = [part for part in parts if part]
|
||||||
|
if not parts:
|
||||||
|
return (raw or "").strip()
|
||||||
|
if len(parts) == 1:
|
||||||
|
return parts[0]
|
||||||
|
return " | ".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def serialize_reply_messages(specs: list[dict[str, Any]]) -> str:
|
||||||
|
cleaned = [spec for spec in specs if _normalize_reply_spec(spec)]
|
||||||
|
if not cleaned:
|
||||||
|
cleaned = [{"type": "text", "text": ""}]
|
||||||
|
if len(cleaned) == 1:
|
||||||
|
return serialize_reply_content(cleaned[0])
|
||||||
|
return json.dumps({"messages": cleaned}, ensure_ascii=False, separators=(",", ":"))
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_link_card_media_path(url: str) -> str:
|
||||||
|
value = (url or "").strip()
|
||||||
|
idx = value.find("/api/media/link-cards/")
|
||||||
|
return value[idx:] if idx >= 0 else ""
|
||||||
|
|
||||||
|
|
||||||
|
def expand_card_spec(spec: dict[str, Any]) -> list[dict[str, Any]]:
|
||||||
|
"""卡片专属发送规则:展开为「封面图片 + 标题/内容/可点击链接文字」两条消息。
|
||||||
|
|
||||||
|
抖音 Web 协议无法发原生合并卡片(type=70 带图→8004/不带图→空白),因此卡片以
|
||||||
|
「图片消息(横幅) + 文本(标题/内容/链接)」组合呈现:图片提供视觉、文本提供可点击跳转。
|
||||||
|
图片消息仅互关用户可收(陌生人会被 8003 拦截,但文本仍可送达,不影响链接触达)。
|
||||||
|
"""
|
||||||
|
title = (spec.get("title") or "").strip()
|
||||||
|
desc = (spec.get("desc") or spec.get("description") or "").strip()
|
||||||
|
target = (
|
||||||
|
spec.get("target_url")
|
||||||
|
or spec.get("url")
|
||||||
|
or spec.get("link_url")
|
||||||
|
or ""
|
||||||
|
).strip()
|
||||||
|
if "localhost" in target or "127.0.0.1" in target:
|
||||||
|
target = (spec.get("target_url") or spec.get("link_url") or "").strip() or target
|
||||||
|
|
||||||
|
cover = (spec.get("image_path") or "").strip()
|
||||||
|
if not cover:
|
||||||
|
cover = _extract_link_card_media_path(spec.get("cover_url") or "")
|
||||||
|
|
||||||
|
out: list[dict[str, Any]] = []
|
||||||
|
if cover:
|
||||||
|
out.append({"type": "image", "url": cover, "text": "[图片]"})
|
||||||
|
lines = [x for x in (title, desc, target) if x]
|
||||||
|
text = "\n".join(lines) if lines else target
|
||||||
|
if text:
|
||||||
|
out.append({"type": "text", "text": text})
|
||||||
|
if not out:
|
||||||
|
out.append({"type": "text", "text": target})
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def split_reply_payloads(raw: str) -> list[str]:
|
||||||
|
"""将规则 reply_content 拆成可逐条发送的 payload 列表。卡片单独展开为图片+文本。"""
|
||||||
|
payloads: list[str] = []
|
||||||
|
for spec in parse_reply_messages(raw):
|
||||||
|
if spec.get("type") == "card":
|
||||||
|
payloads.extend(serialize_reply_content(s) for s in expand_card_spec(spec))
|
||||||
|
else:
|
||||||
|
payloads.append(serialize_reply_content(spec))
|
||||||
|
return payloads
|
||||||
|
|
||||||
|
|
||||||
|
def serialize_reply_log(payloads: list[str]) -> str:
|
||||||
|
"""把实际逐条发送的 payload(JSON 字符串)合并为结构化的日志内容。
|
||||||
|
|
||||||
|
单条直接返回该 payload;多条用 {"messages":[...]} 包裹,便于前端逐条渲染
|
||||||
|
(图片/表情正常显示为媒体,而不是被压扁成 "图片" 这样的占位文本)。
|
||||||
|
"""
|
||||||
|
specs: list[dict[str, Any]] = []
|
||||||
|
for payload in payloads:
|
||||||
|
raw = (payload or "").strip()
|
||||||
|
if not raw:
|
||||||
|
continue
|
||||||
|
spec: dict[str, Any] | None = None
|
||||||
|
if raw.startswith("{"):
|
||||||
|
try:
|
||||||
|
data = json.loads(raw)
|
||||||
|
spec = _normalize_reply_spec(data)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
spec = None
|
||||||
|
if spec is None:
|
||||||
|
spec = {"type": "text", "text": raw}
|
||||||
|
specs.append(spec)
|
||||||
|
return serialize_reply_messages(specs)
|
||||||
|
|
||||||
|
|
||||||
|
def serialize_reply_content(spec: dict[str, Any]) -> str:
|
||||||
|
return json.dumps(spec, ensure_ascii=False, separators=(",", ":"))
|
||||||
|
|
||||||
|
|
||||||
|
def build_msg_payload(spec: dict[str, Any]) -> Tuple[dict[str, Any], int]:
|
||||||
|
"""根据回复规格构造 IM msg_content 与 message_type。"""
|
||||||
|
reply_type = spec.get("type", "text")
|
||||||
|
|
||||||
|
if reply_type == "text":
|
||||||
|
text = (spec.get("text") or "").strip()
|
||||||
|
return (
|
||||||
|
{
|
||||||
|
"mention_users": [],
|
||||||
|
"aweType": 700,
|
||||||
|
"richTextInfos": [],
|
||||||
|
"text": text,
|
||||||
|
},
|
||||||
|
7,
|
||||||
|
)
|
||||||
|
|
||||||
|
if reply_type == "link":
|
||||||
|
display = (spec.get("text") or spec.get("title") or "").strip()
|
||||||
|
url = (spec.get("url") or "").strip()
|
||||||
|
if not display:
|
||||||
|
display = url
|
||||||
|
msg_content: dict[str, Any] = {
|
||||||
|
"mention_users": [],
|
||||||
|
"aweType": 700,
|
||||||
|
"richTextInfos": [],
|
||||||
|
"text": display,
|
||||||
|
}
|
||||||
|
if url and display:
|
||||||
|
msg_content["richTextInfos"] = [
|
||||||
|
{
|
||||||
|
"start": 0,
|
||||||
|
"end": len(display),
|
||||||
|
"type": 2,
|
||||||
|
"link": url,
|
||||||
|
"text": display,
|
||||||
|
}
|
||||||
|
]
|
||||||
|
return msg_content, 7
|
||||||
|
|
||||||
|
if reply_type == "card":
|
||||||
|
# 卡片在 split_reply_payloads 阶段已展开为「图片 + 文本」两条,正常不会走到这里。
|
||||||
|
# 兜底:万一收到未展开的卡片 spec,退化为「标题/内容/链接」文本,确保可送达。
|
||||||
|
title = (spec.get("title") or "").strip()
|
||||||
|
desc = (spec.get("desc") or spec.get("description") or "").strip()
|
||||||
|
target = (
|
||||||
|
spec.get("target_url")
|
||||||
|
or spec.get("url")
|
||||||
|
or spec.get("link_url")
|
||||||
|
or ""
|
||||||
|
).strip()
|
||||||
|
lines = [x for x in (title, desc, target) if x]
|
||||||
|
text = "\n".join(lines) if lines else target
|
||||||
|
return (
|
||||||
|
{"mention_users": [], "aweType": 700, "richTextInfos": [], "text": text},
|
||||||
|
MSG_TYPE_TEXT,
|
||||||
|
)
|
||||||
|
|
||||||
|
if reply_type == "image":
|
||||||
|
uri = (spec.get("uri") or "").strip().lstrip("/")
|
||||||
|
url = (spec.get("url") or "").strip()
|
||||||
|
width = spec.get("width")
|
||||||
|
height = spec.get("height")
|
||||||
|
md5 = (spec.get("md5") or "").strip()
|
||||||
|
url_list = spec.get("url_list")
|
||||||
|
if not isinstance(url_list, list):
|
||||||
|
url_list = [url] if url.startswith("http") else []
|
||||||
|
|
||||||
|
clean_urls = [str(u).strip() for u in url_list if str(u).strip().startswith("http")]
|
||||||
|
|
||||||
|
resource_url: dict[str, Any] = {}
|
||||||
|
if uri:
|
||||||
|
resource_url["uri"] = uri
|
||||||
|
if clean_urls:
|
||||||
|
resource_url["url_list"] = clean_urls
|
||||||
|
if md5:
|
||||||
|
resource_url["md5"] = md5
|
||||||
|
if width:
|
||||||
|
try:
|
||||||
|
resource_url["width"] = int(width)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
pass
|
||||||
|
if height:
|
||||||
|
try:
|
||||||
|
resource_url["height"] = int(height)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
msg_content: dict[str, Any] = {
|
||||||
|
"aweType": 2702,
|
||||||
|
"from_gallery": 1,
|
||||||
|
"create_type": 0,
|
||||||
|
}
|
||||||
|
if resource_url:
|
||||||
|
msg_content["resource_url"] = resource_url
|
||||||
|
if uri:
|
||||||
|
msg_content["local_path"] = uri
|
||||||
|
if md5:
|
||||||
|
msg_content["md5"] = md5
|
||||||
|
if width:
|
||||||
|
try:
|
||||||
|
msg_content["cover_width"] = int(width)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
pass
|
||||||
|
if height:
|
||||||
|
try:
|
||||||
|
msg_content["cover_height"] = int(height)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
pass
|
||||||
|
return msg_content, MSG_TYPE_IMAGE
|
||||||
|
|
||||||
|
if reply_type == "sticker":
|
||||||
|
url = (spec.get("url") or "").strip()
|
||||||
|
sticker_id = spec.get("sticker_id") or spec.get("id")
|
||||||
|
msg_content = {
|
||||||
|
"display_name": (spec.get("name") or spec.get("text") or "[表情包]").strip(),
|
||||||
|
}
|
||||||
|
if sticker_id:
|
||||||
|
msg_content["id"] = sticker_id
|
||||||
|
msg_content["sticker_id"] = sticker_id
|
||||||
|
if url:
|
||||||
|
msg_content["static_url"] = {"url_list": [url]}
|
||||||
|
msg_content["animate_url"] = {"url_list": [url]}
|
||||||
|
return msg_content, MSG_TYPE_STICKER
|
||||||
|
|
||||||
|
text = format_reply_display(serialize_reply_content(spec))
|
||||||
|
return (
|
||||||
|
{
|
||||||
|
"mention_users": [],
|
||||||
|
"aweType": 700,
|
||||||
|
"richTextInfos": [],
|
||||||
|
"text": text,
|
||||||
|
},
|
||||||
|
7,
|
||||||
|
)
|
||||||
@@ -0,0 +1,352 @@
|
|||||||
|
"""Observable per-account serial queue for delayed automatic replies."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from collections import deque
|
||||||
|
from copy import deepcopy
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any, Awaitable, Callable, Iterable, Optional
|
||||||
|
|
||||||
|
|
||||||
|
logger = logging.getLogger("douyin_im.reply_queue")
|
||||||
|
|
||||||
|
ReplyCallback = Callable[[], Awaitable[Any]]
|
||||||
|
ErrorCallback = Callable[[str, BaseException], None]
|
||||||
|
DetailsMerger = Callable[[dict[str, Any]], dict[str, Any]]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class _QueueItem:
|
||||||
|
job_id: str
|
||||||
|
due_at: float
|
||||||
|
slot_seconds: float
|
||||||
|
callback: ReplyCallback
|
||||||
|
description: str
|
||||||
|
queued_at: float
|
||||||
|
merge_keys: frozenset[str] = field(default_factory=frozenset)
|
||||||
|
details: dict[str, Any] = field(default_factory=dict)
|
||||||
|
expedited: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class AccountReplyQueue:
|
||||||
|
"""Run and expose delayed reply jobs for one hosted account.
|
||||||
|
|
||||||
|
A single consumer is the only code path allowed to invoke callbacks. Jobs
|
||||||
|
selected for immediate delivery are moved to an urgent FIFO, so they can
|
||||||
|
never overlap an already active send. Removing a scheduled job also moves
|
||||||
|
every job behind it forward by the removed job's reserved slot.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
account_id: int,
|
||||||
|
on_error: Optional[ErrorCallback] = None,
|
||||||
|
) -> None:
|
||||||
|
self.account_id = account_id
|
||||||
|
self._on_error = on_error
|
||||||
|
self._waiting: list[_QueueItem] = []
|
||||||
|
self._urgent: deque[_QueueItem] = deque()
|
||||||
|
self._active_item: Optional[_QueueItem] = None
|
||||||
|
self._task: Optional[asyncio.Task] = None
|
||||||
|
self._running = False
|
||||||
|
self._state_lock = asyncio.Lock()
|
||||||
|
self._wake = asyncio.Event()
|
||||||
|
self._tail_due_at = 0.0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def pending_count(self) -> int:
|
||||||
|
"""Approximate active + urgent + waiting count for lightweight badges."""
|
||||||
|
return (
|
||||||
|
len(self._waiting)
|
||||||
|
+ len(self._urgent)
|
||||||
|
+ (1 if self._active_item is not None else 0)
|
||||||
|
)
|
||||||
|
|
||||||
|
async def start(self) -> None:
|
||||||
|
async with self._state_lock:
|
||||||
|
if self._task and not self._task.done():
|
||||||
|
return
|
||||||
|
self._running = True
|
||||||
|
self._tail_due_at = 0.0
|
||||||
|
self._wake.clear()
|
||||||
|
self._task = asyncio.create_task(
|
||||||
|
self._run(),
|
||||||
|
name=f"account-reply-queue-{self.account_id}",
|
||||||
|
)
|
||||||
|
|
||||||
|
async def enqueue(
|
||||||
|
self,
|
||||||
|
delay_seconds: float,
|
||||||
|
callback: ReplyCallback,
|
||||||
|
description: str = "",
|
||||||
|
details: Optional[dict[str, Any]] = None,
|
||||||
|
merge_key: str = "",
|
||||||
|
merge_keys: Optional[Iterable[str]] = None,
|
||||||
|
) -> int:
|
||||||
|
"""Append one reply job and return its current 1-based queue position."""
|
||||||
|
interval = max(0.0, float(delay_seconds or 0))
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
async with self._state_lock:
|
||||||
|
if not self._running or not self._task or self._task.done():
|
||||||
|
raise RuntimeError("reply queue is not running")
|
||||||
|
due_at = max(loop.time(), self._tail_due_at) + interval
|
||||||
|
self._tail_due_at = due_at
|
||||||
|
self._waiting.append(
|
||||||
|
_QueueItem(
|
||||||
|
job_id=uuid.uuid4().hex,
|
||||||
|
due_at=due_at,
|
||||||
|
slot_seconds=interval,
|
||||||
|
callback=callback,
|
||||||
|
description=description,
|
||||||
|
queued_at=time.time(),
|
||||||
|
merge_keys=self._normalize_merge_keys(
|
||||||
|
merge_keys if merge_keys is not None else merge_key
|
||||||
|
),
|
||||||
|
details=deepcopy(details or {}),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
position = self.pending_count
|
||||||
|
self._wake.set()
|
||||||
|
return position
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _normalize_merge_keys(value: str | Iterable[str]) -> frozenset[str]:
|
||||||
|
values = [value] if isinstance(value, str) else list(value or [])
|
||||||
|
return frozenset(str(item or "").strip() for item in values if str(item or "").strip())
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _merge_keys_match(
|
||||||
|
existing: frozenset[str],
|
||||||
|
incoming: frozenset[str],
|
||||||
|
) -> bool:
|
||||||
|
existing_conversations = {key for key in existing if key.startswith("conv:")}
|
||||||
|
incoming_conversations = {key for key in incoming if key.startswith("conv:")}
|
||||||
|
if existing_conversations & incoming_conversations:
|
||||||
|
return True
|
||||||
|
# Two explicit, different conversation IDs must never merge just because
|
||||||
|
# their partial source data happens to expose the same peer identifier.
|
||||||
|
if existing_conversations and incoming_conversations:
|
||||||
|
return False
|
||||||
|
existing_peers = {key for key in existing if key.startswith("peer:")}
|
||||||
|
incoming_peers = {key for key in incoming if key.startswith("peer:")}
|
||||||
|
return bool(existing_peers & incoming_peers)
|
||||||
|
|
||||||
|
async def merge_pending(
|
||||||
|
self,
|
||||||
|
merge_key: str | Iterable[str],
|
||||||
|
details_merger: DetailsMerger,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Merge details into one queued conversation without changing its slot.
|
||||||
|
|
||||||
|
Only waiting and urgent jobs are mutable. Once the consumer marks a job
|
||||||
|
active, its callback is sealed and a later message must follow the normal
|
||||||
|
new-message path.
|
||||||
|
"""
|
||||||
|
normalized_keys = self._normalize_merge_keys(merge_key)
|
||||||
|
if not normalized_keys:
|
||||||
|
return {"status": "not_found"}
|
||||||
|
|
||||||
|
async with self._state_lock:
|
||||||
|
if not self._running or not self._task or self._task.done():
|
||||||
|
return {"status": "not_running"}
|
||||||
|
|
||||||
|
active_offset = 1 if self._active_item is not None else 0
|
||||||
|
matches: list[tuple[_QueueItem, str, int]] = []
|
||||||
|
|
||||||
|
for index, candidate in enumerate(self._urgent):
|
||||||
|
if self._merge_keys_match(candidate.merge_keys, normalized_keys):
|
||||||
|
matches.append((candidate, "ready", active_offset + index + 1))
|
||||||
|
|
||||||
|
waiting_offset = active_offset + len(self._urgent)
|
||||||
|
for index, candidate in enumerate(self._waiting):
|
||||||
|
if self._merge_keys_match(candidate.merge_keys, normalized_keys):
|
||||||
|
matches.append((candidate, "waiting", waiting_offset + index + 1))
|
||||||
|
|
||||||
|
if not matches:
|
||||||
|
return {"status": "not_found"}
|
||||||
|
|
||||||
|
incoming_conversations = {
|
||||||
|
key for key in normalized_keys if key.startswith("conv:")
|
||||||
|
}
|
||||||
|
if not incoming_conversations:
|
||||||
|
matched_conversations = {
|
||||||
|
key
|
||||||
|
for candidate, _, _ in matches
|
||||||
|
for key in candidate.merge_keys
|
||||||
|
if key.startswith("conv:")
|
||||||
|
}
|
||||||
|
if len(matched_conversations) > 1:
|
||||||
|
return {"status": "not_found", "reason": "ambiguous_peer"}
|
||||||
|
|
||||||
|
item, item_status, position = matches[0]
|
||||||
|
|
||||||
|
merged_details = details_merger(deepcopy(item.details))
|
||||||
|
if not isinstance(merged_details, dict):
|
||||||
|
raise TypeError("reply queue details merger must return a dict")
|
||||||
|
item.details = deepcopy(merged_details)
|
||||||
|
item.merge_keys = frozenset(item.merge_keys | normalized_keys)
|
||||||
|
return {
|
||||||
|
"status": "merged",
|
||||||
|
"job_id": item.job_id,
|
||||||
|
"position": position,
|
||||||
|
"queue_status": item_status,
|
||||||
|
"message_count": int(item.details.get("message_count") or 1),
|
||||||
|
}
|
||||||
|
|
||||||
|
async def snapshot(self) -> list[dict[str, Any]]:
|
||||||
|
"""Return a callback-free management snapshot ordered by execution."""
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
now_mono = loop.time()
|
||||||
|
now_epoch = time.time()
|
||||||
|
async with self._state_lock:
|
||||||
|
ordered: list[tuple[_QueueItem, str]] = []
|
||||||
|
if self._active_item is not None:
|
||||||
|
ordered.append((self._active_item, "sending"))
|
||||||
|
ordered.extend((item, "ready") for item in self._urgent)
|
||||||
|
ordered.extend((item, "waiting") for item in self._waiting)
|
||||||
|
|
||||||
|
result = []
|
||||||
|
for position, (item, status) in enumerate(ordered, start=1):
|
||||||
|
remaining = 0.0 if status != "waiting" else max(0.0, item.due_at - now_mono)
|
||||||
|
scheduled_epoch = now_epoch + max(0.0, item.due_at - now_mono)
|
||||||
|
payload = {
|
||||||
|
"job_id": item.job_id,
|
||||||
|
"account_id": self.account_id,
|
||||||
|
"position": position,
|
||||||
|
"status": status,
|
||||||
|
"expedited": bool(item.expedited),
|
||||||
|
"description": item.description,
|
||||||
|
"interval_seconds": int(round(item.slot_seconds)),
|
||||||
|
"enqueued_at": datetime.fromtimestamp(
|
||||||
|
item.queued_at, tz=timezone.utc
|
||||||
|
).isoformat(),
|
||||||
|
"scheduled_at": datetime.fromtimestamp(
|
||||||
|
scheduled_epoch, tz=timezone.utc
|
||||||
|
).isoformat(),
|
||||||
|
"remaining_seconds": int(max(0, round(remaining))),
|
||||||
|
}
|
||||||
|
# Details are controlled by DouyinImService and never contain callbacks/session data.
|
||||||
|
payload.update(deepcopy(item.details))
|
||||||
|
result.append(payload)
|
||||||
|
return result
|
||||||
|
|
||||||
|
async def send_now(self, job_id: str) -> dict[str, Any]:
|
||||||
|
"""Move one waiting job to the urgent FIFO and free its future slot."""
|
||||||
|
job_id = str(job_id or "").strip()
|
||||||
|
async with self._state_lock:
|
||||||
|
if not self._running or not self._task or self._task.done():
|
||||||
|
return {"status": "not_running", "job_id": job_id}
|
||||||
|
if self._active_item and self._active_item.job_id == job_id:
|
||||||
|
return {"status": "already_sending", "job_id": job_id}
|
||||||
|
if any(item.job_id == job_id for item in self._urgent):
|
||||||
|
return {"status": "already_requested", "job_id": job_id}
|
||||||
|
|
||||||
|
selected_index = next(
|
||||||
|
(index for index, item in enumerate(self._waiting) if item.job_id == job_id),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
if selected_index is None:
|
||||||
|
return {"status": "not_found", "job_id": job_id}
|
||||||
|
|
||||||
|
item = self._waiting.pop(selected_index)
|
||||||
|
shift_seconds = max(0.0, item.slot_seconds)
|
||||||
|
shifted_count = 0
|
||||||
|
for later in self._waiting[selected_index:]:
|
||||||
|
later.due_at -= shift_seconds
|
||||||
|
shifted_count += 1
|
||||||
|
|
||||||
|
item.due_at = asyncio.get_running_loop().time()
|
||||||
|
item.expedited = True
|
||||||
|
self._urgent.append(item)
|
||||||
|
self._recalculate_tail_due_at()
|
||||||
|
self._wake.set()
|
||||||
|
return {
|
||||||
|
"status": "accepted",
|
||||||
|
"job_id": job_id,
|
||||||
|
"shifted_count": shifted_count,
|
||||||
|
}
|
||||||
|
|
||||||
|
async def stop(self) -> None:
|
||||||
|
"""Cancel the active wait/send and discard all remaining jobs."""
|
||||||
|
async with self._state_lock:
|
||||||
|
self._running = False
|
||||||
|
self._wake.set()
|
||||||
|
task = self._task
|
||||||
|
self._task = None
|
||||||
|
|
||||||
|
if task:
|
||||||
|
task.cancel()
|
||||||
|
try:
|
||||||
|
await task
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
async with self._state_lock:
|
||||||
|
self._waiting.clear()
|
||||||
|
self._urgent.clear()
|
||||||
|
self._active_item = None
|
||||||
|
self._tail_due_at = 0.0
|
||||||
|
self._wake.clear()
|
||||||
|
|
||||||
|
def _recalculate_tail_due_at(self) -> None:
|
||||||
|
scheduled = [item.due_at for item in self._waiting]
|
||||||
|
self._tail_due_at = max(scheduled, default=0.0)
|
||||||
|
|
||||||
|
async def _run(self) -> None:
|
||||||
|
while True:
|
||||||
|
item: Optional[_QueueItem] = None
|
||||||
|
wait_seconds: Optional[float] = None
|
||||||
|
async with self._state_lock:
|
||||||
|
if not self._running:
|
||||||
|
return
|
||||||
|
if self._urgent:
|
||||||
|
item = self._urgent.popleft()
|
||||||
|
elif self._waiting:
|
||||||
|
candidate = self._waiting[0]
|
||||||
|
remaining = candidate.due_at - asyncio.get_running_loop().time()
|
||||||
|
if remaining <= 0:
|
||||||
|
item = self._waiting.pop(0)
|
||||||
|
else:
|
||||||
|
wait_seconds = remaining
|
||||||
|
|
||||||
|
if item is not None:
|
||||||
|
self._active_item = item
|
||||||
|
self._wake.clear()
|
||||||
|
|
||||||
|
if item is None:
|
||||||
|
try:
|
||||||
|
if wait_seconds is None:
|
||||||
|
await self._wake.wait()
|
||||||
|
else:
|
||||||
|
await asyncio.wait_for(self._wake.wait(), timeout=wait_seconds)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
pass
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
await item.callback()
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
logger.exception(
|
||||||
|
"Account %s queued reply failed (%s)",
|
||||||
|
self.account_id,
|
||||||
|
item.description,
|
||||||
|
)
|
||||||
|
if self._on_error:
|
||||||
|
try:
|
||||||
|
self._on_error(item.description, exc)
|
||||||
|
except Exception:
|
||||||
|
logger.debug("Reply queue error callback failed", exc_info=True)
|
||||||
|
finally:
|
||||||
|
async with self._state_lock:
|
||||||
|
if self._active_item is item:
|
||||||
|
self._active_item = None
|
||||||
|
if not self._waiting:
|
||||||
|
self._tail_due_at = 0.0
|
||||||
|
self._wake.set()
|
||||||
@@ -0,0 +1,983 @@
|
|||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
from typing import Awaitable, Callable, Optional
|
||||||
|
|
||||||
|
from utils import system_logger
|
||||||
|
from .frontier import ensure_frontier_ws
|
||||||
|
from .http_client import DouyinImHttpClient, format_session_credential_summary
|
||||||
|
from .session import DouyinImSession
|
||||||
|
from .ws_client import DouyinImWsClient
|
||||||
|
from .reply_queue import AccountReplyQueue
|
||||||
|
from .traffic_control import get_traffic_controller
|
||||||
|
|
||||||
|
from .reply_payload import format_reply_display, serialize_reply_log
|
||||||
|
from .conv_util import resolve_peer_uid
|
||||||
|
from .peer_profile import (
|
||||||
|
enrich_conversation_item,
|
||||||
|
fetch_peer_profile,
|
||||||
|
is_generic_peer_name,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger("douyin_im.service")
|
||||||
|
|
||||||
|
MatchReplyFn = Callable[[str], Awaitable[Optional[list[str]]]]
|
||||||
|
LogFn = Callable[..., Awaitable[None]]
|
||||||
|
ReceivedLogFn = Callable[..., Awaitable[None]]
|
||||||
|
|
||||||
|
|
||||||
|
class DouyinImService:
|
||||||
|
"""抖音 IM 直连服务:WebSocket 实时监听 + HTTP 轮询 + 自动回复"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
session: DouyinImSession,
|
||||||
|
match_reply: MatchReplyFn,
|
||||||
|
log_fn: LogFn,
|
||||||
|
account_id: int,
|
||||||
|
received_log_fn: Optional[ReceivedLogFn] = None,
|
||||||
|
reply_delay_seconds: int = 0,
|
||||||
|
reply_delay_resolver: Optional[Callable[[], Awaitable[int]]] = None,
|
||||||
|
reply_cooldown_seconds: Optional[int] = None,
|
||||||
|
cooldown_resolver: Optional[Callable[[], Awaitable[int]]] = None,
|
||||||
|
refresh_credentials: Optional[Callable[[], Awaitable[bool]]] = None,
|
||||||
|
follow_tick: Optional[Callable[[], Awaitable[None]]] = None,
|
||||||
|
on_session_invalid: Optional[Callable[[str], Awaitable[None]]] = None,
|
||||||
|
):
|
||||||
|
self.session = session
|
||||||
|
self.match_reply = match_reply
|
||||||
|
self.log_fn = log_fn
|
||||||
|
self.received_log_fn = received_log_fn
|
||||||
|
self.account_id = account_id
|
||||||
|
# 由 worker 注入:周期性检测新粉丝并发送关注欢迎语(约每 60s 触发一次)
|
||||||
|
self.follow_tick = follow_tick
|
||||||
|
# 由 worker 注入:检测到 IM 登录失效(INVALID_REQUEST)时回调,用于自动下线
|
||||||
|
self.on_session_invalid = on_session_invalid
|
||||||
|
self._session_invalid_strikes = 0
|
||||||
|
self._session_invalid_fired = False
|
||||||
|
self.reply_delay_seconds = max(0, int(reply_delay_seconds or 0))
|
||||||
|
# 实时解析账号排队间隔:账号专属优先,否则使用系统默认值。
|
||||||
|
self._reply_delay_resolver = reply_delay_resolver
|
||||||
|
self._reply_queue = AccountReplyQueue(
|
||||||
|
account_id=self.account_id,
|
||||||
|
on_error=self._on_reply_queue_error,
|
||||||
|
)
|
||||||
|
# WS 帧与 HTTP 轮询会并发进入;按到达顺序串行完成预处理/入队,确保 FIFO。
|
||||||
|
self._incoming_lock = asyncio.Lock()
|
||||||
|
# 该账号专属冷却秒数;None 表示继承全局系统设置(仅作为无 resolver 时的兜底)
|
||||||
|
self._cooldown_override = (
|
||||||
|
max(0, int(reply_cooldown_seconds)) if reply_cooldown_seconds is not None else None
|
||||||
|
)
|
||||||
|
# 实时解析冷却秒数的回调(账号专属优先,否则全局);优先于 _cooldown_override
|
||||||
|
self._cooldown_resolver = cooldown_resolver
|
||||||
|
# 由 worker 注入:触发后台重新采集 web_protect/keys(刷新 ts_sign),返回是否刷新成功
|
||||||
|
self.refresh_credentials = refresh_credentials
|
||||||
|
self._running = False
|
||||||
|
self._replied_keys: set[str] = set()
|
||||||
|
self._logged_keys: set[str] = set()
|
||||||
|
self._received_logged_keys: set[str] = set()
|
||||||
|
# 每个对话/用户最近一次自动回复的时间戳(monotonic 秒),用于冷却窗口去重
|
||||||
|
self._last_reply_at: dict[str, float] = {}
|
||||||
|
self._conv_previews: dict[str, str] = {}
|
||||||
|
self._conv_names: dict[str, str] = {} # uid/conv_id -> nickname
|
||||||
|
self._conv_meta: dict[str, dict] = {} # conversation_id -> meta
|
||||||
|
self._ws_client: Optional[DouyinImWsClient] = None
|
||||||
|
self.last_error: str = ""
|
||||||
|
|
||||||
|
def _reply_key(self, conversation_key: str, content: str) -> str:
|
||||||
|
return f"{conversation_key}::{content}"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _reply_queue_merge_keys(
|
||||||
|
conversation_id: str,
|
||||||
|
peer_uid: str,
|
||||||
|
) -> tuple[str, ...]:
|
||||||
|
"""Return every stable identifier currently known for one conversation."""
|
||||||
|
conversation_id = str(conversation_id or "").strip()
|
||||||
|
peer_uid = str(peer_uid or "").strip()
|
||||||
|
aliases: list[str] = []
|
||||||
|
if conversation_id:
|
||||||
|
aliases.append(f"conv:{conversation_id}")
|
||||||
|
if peer_uid:
|
||||||
|
aliases.append(f"peer:{peer_uid}")
|
||||||
|
return tuple(aliases)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _merge_reply_queue_details(
|
||||||
|
existing: dict,
|
||||||
|
*,
|
||||||
|
incoming_content: str,
|
||||||
|
sender_name: str,
|
||||||
|
sender_id: str,
|
||||||
|
sender_avatar: Optional[str],
|
||||||
|
conversation_id: str,
|
||||||
|
) -> dict:
|
||||||
|
"""Append one received message while preserving the task's one reply."""
|
||||||
|
merged = dict(existing or {})
|
||||||
|
contents = merged.get("incoming_contents")
|
||||||
|
if isinstance(contents, list):
|
||||||
|
contents = list(contents)
|
||||||
|
else:
|
||||||
|
contents = []
|
||||||
|
if not contents and "incoming_content" in merged:
|
||||||
|
contents.append(str(merged.get("incoming_content") or ""))
|
||||||
|
|
||||||
|
latest_content = str(incoming_content or "")
|
||||||
|
contents.append(latest_content)
|
||||||
|
merged["incoming_content"] = latest_content
|
||||||
|
merged["incoming_contents"] = contents
|
||||||
|
merged["message_count"] = len(contents)
|
||||||
|
|
||||||
|
if sender_name:
|
||||||
|
merged["sender_name"] = sender_name
|
||||||
|
if sender_id:
|
||||||
|
merged["sender_id"] = sender_id
|
||||||
|
if sender_avatar:
|
||||||
|
merged["sender_avatar"] = sender_avatar
|
||||||
|
if conversation_id:
|
||||||
|
merged["conversation_id"] = conversation_id
|
||||||
|
return merged
|
||||||
|
|
||||||
|
def _cooldown_seconds_sync(self) -> int:
|
||||||
|
"""无 resolver 时的兜底:账号专属优先,否则取全局设置;0 表示关闭。"""
|
||||||
|
if self._cooldown_override is not None:
|
||||||
|
return self._cooldown_override
|
||||||
|
try:
|
||||||
|
from auth.system_settings import get_cached_settings
|
||||||
|
|
||||||
|
return max(0, int(get_cached_settings().auto_reply_cooldown_seconds or 0))
|
||||||
|
except Exception:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
async def _resolve_cooldown_seconds(self) -> int:
|
||||||
|
"""实时解析冷却秒数:优先用 worker 注入的 resolver(账号优先、否则全局),否则兜底。"""
|
||||||
|
if self._cooldown_resolver is not None:
|
||||||
|
try:
|
||||||
|
return max(0, int(await self._cooldown_resolver() or 0))
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"cooldown resolver failed: {e}")
|
||||||
|
return self._cooldown_seconds_sync()
|
||||||
|
|
||||||
|
def _reply_delay_seconds_sync(self) -> int:
|
||||||
|
"""无 resolver 时解析排队间隔;0 表示不启用排队规则。"""
|
||||||
|
if self.reply_delay_seconds > 0:
|
||||||
|
return self.reply_delay_seconds
|
||||||
|
try:
|
||||||
|
from auth.system_settings import get_cached_settings
|
||||||
|
|
||||||
|
return max(0, int(get_cached_settings().auto_reply_delay_seconds or 0))
|
||||||
|
except Exception:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
async def _resolve_reply_delay_seconds(self) -> int:
|
||||||
|
"""实时解析账号生效的回复排队间隔。"""
|
||||||
|
if self._reply_delay_resolver is not None:
|
||||||
|
try:
|
||||||
|
return max(0, int(await self._reply_delay_resolver() or 0))
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug(f"reply delay resolver failed: {exc}")
|
||||||
|
return self._reply_delay_seconds_sync()
|
||||||
|
|
||||||
|
def _on_reply_queue_error(self, description: str, exc: BaseException) -> None:
|
||||||
|
system_logger.record(
|
||||||
|
"账号回复队列执行失败",
|
||||||
|
detail=f"{description or '自动回复任务'}:{exc}",
|
||||||
|
level="error",
|
||||||
|
category="send",
|
||||||
|
account_id=self.account_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _peer_in_cooldown(self, peer_key: str, cooldown: int) -> bool:
|
||||||
|
if cooldown <= 0 or not peer_key:
|
||||||
|
return False
|
||||||
|
last = self._last_reply_at.get(peer_key)
|
||||||
|
if last is None:
|
||||||
|
return False
|
||||||
|
return (time.monotonic() - last) < cooldown
|
||||||
|
|
||||||
|
def _resolve_sender_name(self, msg: dict) -> str:
|
||||||
|
sender_uid = str(msg.get("sender_uid") or msg.get("sender_name") or "").strip()
|
||||||
|
conv_id = str(msg.get("conversation_id") or "")
|
||||||
|
name = (msg.get("sender_name") or "").strip()
|
||||||
|
if name and not name.isdigit():
|
||||||
|
return name
|
||||||
|
if sender_uid and self._conv_names.get(sender_uid):
|
||||||
|
return self._conv_names[sender_uid]
|
||||||
|
if conv_id and self._conv_names.get(conv_id):
|
||||||
|
return self._conv_names[conv_id]
|
||||||
|
if sender_uid:
|
||||||
|
return f"用户{sender_uid[-6:]}" if len(sender_uid) > 6 else f"用户{sender_uid}"
|
||||||
|
return "未知用户"
|
||||||
|
|
||||||
|
def _is_self_message(self, msg: dict) -> bool:
|
||||||
|
sender_uid = str(msg.get("sender_uid") or "").strip()
|
||||||
|
if not sender_uid or not self.session.my_uid:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
return int(sender_uid) == int(self.session.my_uid)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def _resolve_peer_profile(
|
||||||
|
self,
|
||||||
|
conv_id: str,
|
||||||
|
sender_uid: str,
|
||||||
|
sender: str,
|
||||||
|
sender_avatar: str,
|
||||||
|
) -> tuple[str, str, str]:
|
||||||
|
my_uid = int(self.session.my_uid or 0)
|
||||||
|
peer_uid = str(sender_uid or "").strip()
|
||||||
|
if (not peer_uid or not peer_uid.isdigit()) and conv_id and my_uid:
|
||||||
|
resolved = resolve_peer_uid(conv_id, my_uid)
|
||||||
|
if resolved:
|
||||||
|
peer_uid = str(resolved)
|
||||||
|
|
||||||
|
meta = self._conv_meta.get(conv_id, {}) if conv_id else {}
|
||||||
|
name = (sender or meta.get("sender_name") or "").strip()
|
||||||
|
avatar = (sender_avatar or meta.get("sender_avatar") or "").strip()
|
||||||
|
|
||||||
|
if peer_uid and self._conv_names.get(peer_uid):
|
||||||
|
cached_name = self._conv_names[peer_uid]
|
||||||
|
if is_generic_peer_name(name, peer_uid):
|
||||||
|
name = cached_name
|
||||||
|
if conv_id and self._conv_names.get(conv_id) and is_generic_peer_name(name, peer_uid):
|
||||||
|
name = self._conv_names[conv_id]
|
||||||
|
|
||||||
|
if peer_uid and (is_generic_peer_name(name, peer_uid) or not avatar):
|
||||||
|
profile = await fetch_peer_profile(self.session, peer_uid, self.account_id)
|
||||||
|
if profile.get("nickname"):
|
||||||
|
name = profile["nickname"]
|
||||||
|
self._conv_names[peer_uid] = name
|
||||||
|
if profile.get("avatar_url"):
|
||||||
|
avatar = profile["avatar_url"]
|
||||||
|
if profile.get("uid"):
|
||||||
|
peer_uid = str(profile["uid"])
|
||||||
|
|
||||||
|
if not name:
|
||||||
|
name = self._resolve_sender_name(
|
||||||
|
{"sender_uid": peer_uid, "conversation_id": conv_id, "sender_name": sender}
|
||||||
|
)
|
||||||
|
return name, avatar, peer_uid
|
||||||
|
|
||||||
|
async def _fetch_message_by_id(self, conv_id: str, server_message_id: str) -> dict | None:
|
||||||
|
"""按 server_message_id 调 get_by_conversation 拉取该条消息的完整数据
|
||||||
|
(含真实 content / message_type / URL)。命中返回原始消息 dict,否则 None。"""
|
||||||
|
if not conv_id or not server_message_id:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
from .auth import DouyinAuth
|
||||||
|
|
||||||
|
controller = get_traffic_controller()
|
||||||
|
async with controller.background_slot(self.account_id, "message detail fetch"):
|
||||||
|
meta = self._conv_meta.get(conv_id, {})
|
||||||
|
short_id = str(meta.get("conversation_short_id") or "")
|
||||||
|
auth = DouyinAuth.from_im_session(self.session)
|
||||||
|
my_uid = int(self.session.my_uid or 0)
|
||||||
|
async with DouyinImHttpClient(self.session, account_id=self.account_id) as http:
|
||||||
|
if not short_id:
|
||||||
|
peer_uid = resolve_peer_uid(conv_id, my_uid)
|
||||||
|
if peer_uid:
|
||||||
|
_, short_id, _ = await http.get_conversation_info(
|
||||||
|
auth, int(peer_uid), my_uid, conv_id, 0
|
||||||
|
)
|
||||||
|
if short_id:
|
||||||
|
self._conv_meta[conv_id] = {
|
||||||
|
**self._conv_meta.get(conv_id, {}),
|
||||||
|
"conversation_short_id": short_id,
|
||||||
|
}
|
||||||
|
messages = await http.get_conversation_messages(
|
||||||
|
auth, conv_id, int(short_id or 0), limit=20
|
||||||
|
)
|
||||||
|
for m in messages:
|
||||||
|
if str(m.get("server_message_id") or "") == server_message_id:
|
||||||
|
return m
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"_fetch_message_by_id failed: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def _enrich_media_content(self, conv_id: str, server_message_id: str, content: str) -> str:
|
||||||
|
"""媒体消息(相册图片/语音/视频)WS 推送 content 为空时,按 server_message_id
|
||||||
|
调 get_by_conversation 拉取真实内容并补全 URL。命中失败则原样返回。"""
|
||||||
|
if not conv_id or not server_message_id or not content:
|
||||||
|
return content
|
||||||
|
try:
|
||||||
|
from .message_content import parse_stored_content, format_im_message, serialize_message_content
|
||||||
|
|
||||||
|
parsed = parse_stored_content(content)
|
||||||
|
mtype = parsed.get("type")
|
||||||
|
if mtype not in ("image", "voice", "video"):
|
||||||
|
return content
|
||||||
|
if parsed.get("url"):
|
||||||
|
return content # 已有 URL(如商店表情/带 url 的图)
|
||||||
|
|
||||||
|
m = await self._fetch_message_by_id(conv_id, server_message_id)
|
||||||
|
if m:
|
||||||
|
real = format_im_message(m.get("content") or "", int(m.get("message_type") or 0))
|
||||||
|
if real.get("url"):
|
||||||
|
enriched = serialize_message_content(real)
|
||||||
|
logger.info(
|
||||||
|
"Enriched media via get_by_conversation: smid=%s type=%s",
|
||||||
|
server_message_id, real.get("type"),
|
||||||
|
)
|
||||||
|
return enriched
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"_enrich_media_content failed: {e}")
|
||||||
|
return content
|
||||||
|
|
||||||
|
async def _handle_incoming(self, msg: dict):
|
||||||
|
# asyncio.Lock 按等待顺序唤醒。锁只覆盖解析、去重、规则匹配与入队;
|
||||||
|
# 未启用排队时,真正的网络发送仍在锁外执行,保持原有并发行为。
|
||||||
|
async with self._incoming_lock:
|
||||||
|
immediate_reply = await self._prepare_incoming(msg)
|
||||||
|
if immediate_reply is not None and self._running:
|
||||||
|
await immediate_reply()
|
||||||
|
|
||||||
|
async def _prepare_incoming(
|
||||||
|
self,
|
||||||
|
msg: dict,
|
||||||
|
) -> Optional[Callable[[], Awaitable[None]]]:
|
||||||
|
if self._is_self_message(msg):
|
||||||
|
return
|
||||||
|
|
||||||
|
conv_id = msg.get("conversation_id") or ""
|
||||||
|
sender_uid = str(msg.get("sender_uid") or "")
|
||||||
|
sender = self._resolve_sender_name(msg)
|
||||||
|
sender_avatar = str(msg.get("sender_avatar") or "").strip()
|
||||||
|
sender, sender_avatar, peer_uid = await self._resolve_peer_profile(
|
||||||
|
conv_id, sender_uid, sender, sender_avatar
|
||||||
|
)
|
||||||
|
content = (msg.get("content") or "").strip()
|
||||||
|
has_raw_ws = "raw_content" in msg
|
||||||
|
raw_incoming = msg.get("raw_content") if has_raw_ws else None
|
||||||
|
ws_message_type = msg.get("message_type")
|
||||||
|
# 每条 WS 消息带唯一 server_message_id:用它去重,避免“同一用户重复发送
|
||||||
|
# 相同文字(如多次‘你好’)被按内容去重而整条丢弃”,这是“有时收不到”的根因。
|
||||||
|
# HTTP 轮询的会话预览没有该 ID,则退回按 内容 去重(避免对同一未读重复回复)。
|
||||||
|
server_message_id = str(msg.get("server_message_id") or "")
|
||||||
|
# WS 仅推送瘦消息(如 type=26)content 为空:按 server_message_id 回 HTTP 拉取
|
||||||
|
# 完整消息,补全 content / message_type,确保「接收到的全部信息」都被记录。
|
||||||
|
if not content and server_message_id and not (raw_incoming or "").strip():
|
||||||
|
real = await self._fetch_message_by_id(conv_id, server_message_id)
|
||||||
|
if real:
|
||||||
|
real_content = (real.get("content") or "").strip()
|
||||||
|
if real_content:
|
||||||
|
raw_incoming = real.get("content")
|
||||||
|
has_raw_ws = True
|
||||||
|
real_type = real.get("message_type")
|
||||||
|
if real_type is not None:
|
||||||
|
ws_message_type = real_type
|
||||||
|
try:
|
||||||
|
from .message_content import format_im_message, serialize_message_content
|
||||||
|
|
||||||
|
parsed = format_im_message(real.get("content") or "", int(real_type or 0))
|
||||||
|
content = serialize_message_content(parsed) if parsed else real_content
|
||||||
|
except Exception:
|
||||||
|
content = real_content
|
||||||
|
logger.info(
|
||||||
|
"Enriched empty WS push via get_by_conversation: smid=%s type=%s",
|
||||||
|
server_message_id, real_type,
|
||||||
|
)
|
||||||
|
# 相册图片/语音等 WS 推送 content 为空,按 server_message_id 拉取真实内容补 URL
|
||||||
|
content = await self._enrich_media_content(conv_id, server_message_id, content)
|
||||||
|
unread = int(msg.get("unread_count") or 0)
|
||||||
|
|
||||||
|
if conv_id:
|
||||||
|
self._conv_meta[conv_id] = {
|
||||||
|
**self._conv_meta.get(conv_id, {}),
|
||||||
|
"conversation_id": conv_id,
|
||||||
|
"sender_name": sender,
|
||||||
|
"sender_avatar": sender_avatar or self._conv_meta.get(conv_id, {}).get("sender_avatar"),
|
||||||
|
"content": content or self._conv_meta.get(conv_id, {}).get("content", ""),
|
||||||
|
"unread_count": unread,
|
||||||
|
"peer_uid": peer_uid,
|
||||||
|
}
|
||||||
|
if sender and peer_uid:
|
||||||
|
self._conv_names[peer_uid] = sender
|
||||||
|
|
||||||
|
if not content and unread <= 0 and raw_incoming is None and not server_message_id:
|
||||||
|
return
|
||||||
|
|
||||||
|
if content == "[未读消息]" and sender in self._conv_previews:
|
||||||
|
content = self._conv_previews.get(sender, content)
|
||||||
|
|
||||||
|
if server_message_id:
|
||||||
|
log_key = f"mid:{server_message_id}"
|
||||||
|
key = f"mid:{server_message_id}"
|
||||||
|
else:
|
||||||
|
# HTTP 会话预览通常没有 message_id;必须带 conversation_id/peer_uid,
|
||||||
|
# 否则两个同名用户发送相同内容会被误判成同一条消息。
|
||||||
|
conversation_key = str(conv_id or peer_uid or sender or "unknown")
|
||||||
|
log_key = self._reply_key(conversation_key, content or "[未读]")
|
||||||
|
key = self._reply_key(conversation_key, content)
|
||||||
|
|
||||||
|
log_kwargs = {
|
||||||
|
"sender_name": sender,
|
||||||
|
"sender_id": peer_uid or conv_id or None,
|
||||||
|
"sender_avatar": sender_avatar or self._conv_meta.get(conv_id, {}).get("sender_avatar"),
|
||||||
|
"message": content or (raw_incoming if raw_incoming is not None else ""),
|
||||||
|
}
|
||||||
|
|
||||||
|
# 接收消息原始日志:WS content 原样落库(瘦推送已回 HTTP 补全为真实 content)
|
||||||
|
if self.received_log_fn and has_raw_ws:
|
||||||
|
recv_key = f"recv:mid:{server_message_id}" if server_message_id else f"recv:{log_key}"
|
||||||
|
if recv_key not in self._received_logged_keys:
|
||||||
|
self._received_logged_keys.add(recv_key)
|
||||||
|
message_type = ws_message_type
|
||||||
|
try:
|
||||||
|
message_type = int(message_type) if message_type is not None else None
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
message_type = None
|
||||||
|
await self.received_log_fn(
|
||||||
|
sender_name=sender,
|
||||||
|
sender_id=peer_uid or conv_id or None,
|
||||||
|
sender_avatar=log_kwargs.get("sender_avatar"),
|
||||||
|
raw_content="" if raw_incoming is None else raw_incoming,
|
||||||
|
conversation_id=conv_id or None,
|
||||||
|
message_type=message_type,
|
||||||
|
server_message_id=server_message_id or None,
|
||||||
|
)
|
||||||
|
|
||||||
|
if log_key not in self._logged_keys and content:
|
||||||
|
self._logged_keys.add(log_key)
|
||||||
|
await self.log_fn(
|
||||||
|
**log_kwargs,
|
||||||
|
reply=None,
|
||||||
|
status="received",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
from .message_content import format_system_log_message, parse_stored_content
|
||||||
|
|
||||||
|
parsed = parse_stored_content(content)
|
||||||
|
msg_type = parsed.get("type") or "text"
|
||||||
|
detail = format_system_log_message(content)
|
||||||
|
if server_message_id:
|
||||||
|
detail = f"{detail} | mid={server_message_id}"
|
||||||
|
system_logger.record(
|
||||||
|
f"收到{'' if msg_type == 'text' else '['+msg_type+']'}消息:{sender}",
|
||||||
|
detail=detail,
|
||||||
|
level="info",
|
||||||
|
category="recv",
|
||||||
|
account_id=self.account_id,
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug(f"record recv system log failed: {exc}")
|
||||||
|
|
||||||
|
if key in self._replied_keys:
|
||||||
|
return
|
||||||
|
# WS 与 HTTP 轮询可能同时发现同一条消息。检查后立即占位(中间不 await),
|
||||||
|
# 防止延迟排队期间被重复加入发送队列。
|
||||||
|
self._replied_keys.add(key)
|
||||||
|
|
||||||
|
# 同账号、同会话只保留一个尚未发送的回复任务。后续来信只追加到
|
||||||
|
# 原任务详情,不改变它的发送时间、位置或已经匹配好的回复。
|
||||||
|
queue_merge_keys = self._reply_queue_merge_keys(conv_id, peer_uid)
|
||||||
|
if queue_merge_keys and self._running:
|
||||||
|
merge_result = await self._reply_queue.merge_pending(
|
||||||
|
queue_merge_keys,
|
||||||
|
lambda existing: self._merge_reply_queue_details(
|
||||||
|
existing,
|
||||||
|
incoming_content=content or "",
|
||||||
|
sender_name=sender,
|
||||||
|
sender_id=peer_uid or conv_id or "",
|
||||||
|
sender_avatar=log_kwargs.get("sender_avatar"),
|
||||||
|
conversation_id=conv_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
if merge_result.get("status") == "merged":
|
||||||
|
if content:
|
||||||
|
self._conv_previews[sender] = content
|
||||||
|
message_count = int(merge_result.get("message_count") or 1)
|
||||||
|
logger.info(
|
||||||
|
"Merged message into queued reply for %s on account %s: "
|
||||||
|
"job=%s messages=%s position=%s",
|
||||||
|
sender,
|
||||||
|
self.account_id,
|
||||||
|
merge_result.get("job_id"),
|
||||||
|
message_count,
|
||||||
|
merge_result.get("position"),
|
||||||
|
)
|
||||||
|
system_logger.record(
|
||||||
|
"同一会话消息已合并到回复队列",
|
||||||
|
detail=(
|
||||||
|
f"{sender} 的新消息已并入原任务;当前共 {message_count} 条消息,"
|
||||||
|
"发送时间和队列位置保持不变。"
|
||||||
|
),
|
||||||
|
level="info",
|
||||||
|
category="send",
|
||||||
|
account_id=self.account_id,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
# 收到新消息即尝试自动回复,不按消息类型/托管关系/内容形态过滤
|
||||||
|
replies = await self.match_reply(content if content != "[未读消息]" else "")
|
||||||
|
if not replies:
|
||||||
|
replies = await self.match_reply("")
|
||||||
|
if not replies:
|
||||||
|
await self.log_fn(
|
||||||
|
**log_kwargs,
|
||||||
|
reply=None,
|
||||||
|
status="ignored",
|
||||||
|
error="未配置任何自动回复规则,请在「自动回复规则」中添加至少一条启用规则",
|
||||||
|
)
|
||||||
|
if content:
|
||||||
|
self._conv_previews[sender] = content
|
||||||
|
return
|
||||||
|
|
||||||
|
# 冷却窗口:同一用户在设定时间内,无论发多少条消息,只自动回复一次(账号设置优先,否则全局)
|
||||||
|
peer_key = (peer_uid or conv_id or sender or "").strip()
|
||||||
|
cooldown = await self._resolve_cooldown_seconds()
|
||||||
|
if self._peer_in_cooldown(peer_key, cooldown):
|
||||||
|
logger.info(
|
||||||
|
f"Auto-reply to {sender} skipped: within {cooldown}s cooldown window"
|
||||||
|
)
|
||||||
|
if content:
|
||||||
|
self._conv_previews[sender] = content
|
||||||
|
system_logger.record(
|
||||||
|
"自动回复已跳过(冷却中)",
|
||||||
|
detail=f"{sender} 在 {cooldown} 秒冷却窗口内重复发送,未重复回复",
|
||||||
|
level="info",
|
||||||
|
category="send",
|
||||||
|
account_id=self.account_id,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
# 提前标记回复时间,确保冷却窗口内(含延迟期间)的后续消息都被抑制
|
||||||
|
if peer_key and cooldown > 0:
|
||||||
|
self._last_reply_at[peer_key] = time.monotonic()
|
||||||
|
|
||||||
|
if content:
|
||||||
|
self._conv_previews[sender] = content
|
||||||
|
|
||||||
|
delay_seconds = await self._resolve_reply_delay_seconds()
|
||||||
|
if not self._running:
|
||||||
|
return
|
||||||
|
|
||||||
|
async def send_reply() -> None:
|
||||||
|
await self._send_auto_reply(
|
||||||
|
sender=sender,
|
||||||
|
content=content,
|
||||||
|
conv_id=conv_id,
|
||||||
|
replies=replies,
|
||||||
|
peer_key=peer_key,
|
||||||
|
cooldown=cooldown,
|
||||||
|
log_kwargs=log_kwargs,
|
||||||
|
)
|
||||||
|
|
||||||
|
if delay_seconds > 0:
|
||||||
|
position = await self._reply_queue.enqueue(
|
||||||
|
delay_seconds,
|
||||||
|
send_reply,
|
||||||
|
description=f"回复 {sender}",
|
||||||
|
details={
|
||||||
|
"sender_name": sender,
|
||||||
|
"sender_id": peer_uid or conv_id or None,
|
||||||
|
"sender_avatar": log_kwargs.get("sender_avatar"),
|
||||||
|
"conversation_id": conv_id or None,
|
||||||
|
"incoming_content": content or "",
|
||||||
|
"incoming_contents": [content or ""],
|
||||||
|
"message_count": 1,
|
||||||
|
"replies": list(replies),
|
||||||
|
},
|
||||||
|
merge_keys=queue_merge_keys,
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"Queued reply to %s for account %s: position=%s interval=%ss",
|
||||||
|
sender,
|
||||||
|
self.account_id,
|
||||||
|
position,
|
||||||
|
delay_seconds,
|
||||||
|
)
|
||||||
|
system_logger.record(
|
||||||
|
"自动回复已进入账号队列",
|
||||||
|
detail=(
|
||||||
|
f"{sender} 当前排在第 {position} 位;账号生效间隔为 {delay_seconds} 秒,"
|
||||||
|
"账号内计时与排位独立;到点后再进入全局带宽队列逐条投递。"
|
||||||
|
),
|
||||||
|
level="info",
|
||||||
|
category="send",
|
||||||
|
account_id=self.account_id,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
# 账号与系统均未配置排队间隔:跳过排队规则,保持原来的立即回复。
|
||||||
|
return send_reply
|
||||||
|
|
||||||
|
async def _send_auto_reply(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
sender: str,
|
||||||
|
content: str,
|
||||||
|
conv_id: str,
|
||||||
|
replies: list[str],
|
||||||
|
peer_key: str,
|
||||||
|
cooldown: int,
|
||||||
|
log_kwargs: dict,
|
||||||
|
) -> None:
|
||||||
|
"""发送一项已匹配的自动回复任务,并记录原有消息/系统日志。"""
|
||||||
|
if not self._running:
|
||||||
|
return
|
||||||
|
reply_displays: list[str] = []
|
||||||
|
sent_any = False
|
||||||
|
send_error = ""
|
||||||
|
meta = self._conv_meta.get(conv_id, {})
|
||||||
|
for index, reply in enumerate(replies):
|
||||||
|
if not self._running:
|
||||||
|
send_error = self.last_error or "托管已停止,后续回复已取消"
|
||||||
|
break
|
||||||
|
if index > 0:
|
||||||
|
await asyncio.sleep(0.6)
|
||||||
|
if not self._running:
|
||||||
|
send_error = self.last_error or "托管已停止,后续回复已取消"
|
||||||
|
break
|
||||||
|
reply_display = format_reply_display(reply)
|
||||||
|
reply_displays.append(reply_display)
|
||||||
|
sent = False
|
||||||
|
if conv_id:
|
||||||
|
sent, resolved = await self._send_text(
|
||||||
|
conv_id,
|
||||||
|
reply,
|
||||||
|
conversation_short_id=str(meta.get("conversation_short_id") or ""),
|
||||||
|
)
|
||||||
|
if sent:
|
||||||
|
if resolved:
|
||||||
|
meta = {**meta, **resolved, "conversation_id": conv_id}
|
||||||
|
self._conv_meta[conv_id] = meta
|
||||||
|
else:
|
||||||
|
send_error = self.last_error or "IM API 发送失败"
|
||||||
|
else:
|
||||||
|
send_error = "缺少会话 ID,无法发送自动回复"
|
||||||
|
if sent:
|
||||||
|
sent_any = True
|
||||||
|
|
||||||
|
combined_display = " | ".join(reply_displays)
|
||||||
|
# 日志里存结构化内容(单条直接存 payload,多条用 {"messages":[...]} 包裹),
|
||||||
|
# 这样图片/表情等媒体回复会被前端渲染为真实媒体,而不是被压成 "图片" 占位文字。
|
||||||
|
reply_log_content = serialize_reply_log(replies)
|
||||||
|
if not sent_any:
|
||||||
|
logger.warning(
|
||||||
|
f"IM API send failed for [{sender}]: {send_error}; reply saved to log only"
|
||||||
|
)
|
||||||
|
# 发送彻底失败:清除冷却时间戳,避免把没收到回复的用户锁在冷却窗口内
|
||||||
|
if peer_key and cooldown > 0:
|
||||||
|
self._last_reply_at.pop(peer_key, None)
|
||||||
|
|
||||||
|
await self.log_fn(
|
||||||
|
**log_kwargs,
|
||||||
|
reply=reply_log_content,
|
||||||
|
status="replied" if sent_any else "failed",
|
||||||
|
error=None if sent_any else (send_error or "IM API 发送失败"),
|
||||||
|
)
|
||||||
|
if sent_any:
|
||||||
|
system_logger.record(
|
||||||
|
"自动回复成功",
|
||||||
|
detail=f"已回复 {sender}:{combined_display}",
|
||||||
|
level="success",
|
||||||
|
category="send",
|
||||||
|
account_id=self.account_id,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
system_logger.record(
|
||||||
|
"自动回复失败",
|
||||||
|
detail=f"回复 {sender} 失败:{send_error}(收到:{content})",
|
||||||
|
level="error",
|
||||||
|
category="send",
|
||||||
|
account_id=self.account_id,
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
f"Auto-reply to {sender}: {content!r} -> {combined_display!r} "
|
||||||
|
f"(sent={sent_any}, count={len(replies)})"
|
||||||
|
)
|
||||||
|
|
||||||
|
async def _index_conversations(self, conversations: list[dict]):
|
||||||
|
my_uid = int(self.session.my_uid or 0)
|
||||||
|
for raw in conversations:
|
||||||
|
conv = enrich_conversation_item(raw, my_uid)
|
||||||
|
conv_id = str(conv.get("conversation_id") or "")
|
||||||
|
name = (conv.get("sender_name") or "").strip()
|
||||||
|
avatar = str(conv.get("sender_avatar") or "").strip()
|
||||||
|
peer_uid = str(conv.get("peer_uid") or "")
|
||||||
|
|
||||||
|
if peer_uid and (is_generic_peer_name(name, peer_uid) or not avatar):
|
||||||
|
profile = await fetch_peer_profile(self.session, peer_uid, self.account_id)
|
||||||
|
if profile.get("nickname"):
|
||||||
|
name = profile["nickname"]
|
||||||
|
conv["sender_name"] = name
|
||||||
|
if profile.get("avatar_url"):
|
||||||
|
avatar = profile["avatar_url"]
|
||||||
|
conv["sender_avatar"] = avatar
|
||||||
|
|
||||||
|
if conv_id:
|
||||||
|
self._conv_meta[conv_id] = {
|
||||||
|
**conv,
|
||||||
|
"sender_name": name,
|
||||||
|
"sender_avatar": avatar or None,
|
||||||
|
"peer_uid": peer_uid,
|
||||||
|
}
|
||||||
|
if name:
|
||||||
|
self._conv_names[conv_id] = name
|
||||||
|
if peer_uid and name:
|
||||||
|
self._conv_names[peer_uid] = name
|
||||||
|
|
||||||
|
async def _poll_conversations(self):
|
||||||
|
controller = get_traffic_controller()
|
||||||
|
async with controller.background_slot(self.account_id, "conversation poll"):
|
||||||
|
async with DouyinImHttpClient(self.session, account_id=self.account_id) as http:
|
||||||
|
unread_total = await http.get_unread_count()
|
||||||
|
if unread_total:
|
||||||
|
logger.info(f"IM unread total: {unread_total}")
|
||||||
|
conversations = await http.get_conversations()
|
||||||
|
await self._index_conversations(conversations)
|
||||||
|
# Message handling may wait in the global send lane. Do not keep one
|
||||||
|
# of the scarce background HTTP slots occupied while that happens.
|
||||||
|
for conv in conversations:
|
||||||
|
unread = int(conv.get("unread_count") or 0)
|
||||||
|
if unread > 0 or conv.get("content"):
|
||||||
|
await self._handle_incoming(conv)
|
||||||
|
|
||||||
|
async def _verify_account_uid(self):
|
||||||
|
"""启动时用 query/user 接口核验账号真实 UID,修正采集端可能取错的 my_uid/device_id。
|
||||||
|
|
||||||
|
采集端从 tea_cache 推断的 my_uid 可能是访客/对方 id,会导致会话列表为 0、
|
||||||
|
创建会话 INVALID_REQUEST。这里在建连前先校正,保证后续所有请求身份正确。
|
||||||
|
"""
|
||||||
|
if getattr(self.session, "uid_verified", False) and self.session.my_uid:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
from .auth import DouyinAuth
|
||||||
|
auth = DouyinAuth.from_im_session(self.session)
|
||||||
|
controller = get_traffic_controller()
|
||||||
|
async with controller.background_slot(self.account_id, "account UID verify"):
|
||||||
|
async with DouyinImHttpClient(self.session, account_id=self.account_id) as http:
|
||||||
|
old = int(self.session.my_uid or 0)
|
||||||
|
resolved = await asyncio.to_thread(http._resolve_authoritative_uid, auth)
|
||||||
|
if resolved and old and int(resolved) != old:
|
||||||
|
system_logger.record(
|
||||||
|
"已自动校正账号 UID",
|
||||||
|
detail=f"采集端识别 UID={old},接口核验真实 UID={resolved},已修正后再建立私信连接。",
|
||||||
|
level="info",
|
||||||
|
category="system",
|
||||||
|
account_id=self.account_id,
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"启动核验账号 UID 失败(沿用采集值):{e}")
|
||||||
|
|
||||||
|
async def run(self):
|
||||||
|
"""主循环:WebSocket + HTTP 轮询"""
|
||||||
|
self._running = True
|
||||||
|
await self._reply_queue.start()
|
||||||
|
await self._verify_account_uid()
|
||||||
|
# ensure_frontier_ws 可能触发签名/HTTP(阻塞),放线程池避免多账号启动时卡死事件循环
|
||||||
|
controller = get_traffic_controller()
|
||||||
|
async with controller.background_slot(self.account_id, "frontier discovery"):
|
||||||
|
await asyncio.to_thread(ensure_frontier_ws, self.session)
|
||||||
|
has_ws = bool(self.session.frontier_ws_url())
|
||||||
|
cred_summary = format_session_credential_summary(self.session)
|
||||||
|
logger.info(cred_summary)
|
||||||
|
logger.info(
|
||||||
|
f"Starting IM direct service for account {self.account_id} "
|
||||||
|
f"(ws={'yes' if has_ws else 'no'})"
|
||||||
|
)
|
||||||
|
system_logger.record(
|
||||||
|
"私信托管已启动",
|
||||||
|
detail=f"实时接收通道:{'已就绪' if has_ws else '不可用(仅 HTTP 轮询)'}\n{cred_summary}",
|
||||||
|
level="success" if has_ws else "warning",
|
||||||
|
category="system",
|
||||||
|
account_id=self.account_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
from .emoji_pack import ensure_emoji_map, is_fresh
|
||||||
|
|
||||||
|
if not is_fresh():
|
||||||
|
async with controller.background_slot(self.account_id, "emoji preload"):
|
||||||
|
await asyncio.to_thread(ensure_emoji_map, self.session)
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug(f"emoji map preload failed: {e}")
|
||||||
|
|
||||||
|
self._ws_client = DouyinImWsClient(
|
||||||
|
self.session, self._handle_incoming, account_id=self.account_id
|
||||||
|
)
|
||||||
|
await self._ws_client.start()
|
||||||
|
|
||||||
|
try:
|
||||||
|
await self._poll_conversations()
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Initial conversation poll failed: {e}")
|
||||||
|
system_logger.record(
|
||||||
|
"首次会话轮询失败",
|
||||||
|
detail=f"{e}",
|
||||||
|
level="warning",
|
||||||
|
category="poll",
|
||||||
|
account_id=self.account_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
loop_count = 0
|
||||||
|
while self._running:
|
||||||
|
# The initial poll above is authoritative. Sleep before the next
|
||||||
|
# recurring tick so startup cannot issue two back-to-back polls.
|
||||||
|
await asyncio.sleep(5)
|
||||||
|
if not self._running:
|
||||||
|
break
|
||||||
|
loop_count += 1
|
||||||
|
try:
|
||||||
|
if loop_count % 3 == 0:
|
||||||
|
await self._poll_conversations()
|
||||||
|
if loop_count % 6 == 0:
|
||||||
|
logger.info(f"IM direct tick #{loop_count} account={self.account_id}")
|
||||||
|
# 关注欢迎语:约每 60s 检测一次新粉丝(独立于私信轮询,失败不影响主循环)
|
||||||
|
if self.follow_tick and loop_count % 12 == 0:
|
||||||
|
try:
|
||||||
|
await self.follow_tick()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"follow welcome tick error: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"IM poll error: {e}")
|
||||||
|
system_logger.record(
|
||||||
|
"会话轮询出错",
|
||||||
|
detail=f"拉取会话/未读时出错:{e}",
|
||||||
|
level="error",
|
||||||
|
category="poll",
|
||||||
|
account_id=self.account_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def stop(self):
|
||||||
|
self._running = False
|
||||||
|
await get_traffic_controller().send_queue.cancel_account(self.account_id)
|
||||||
|
await self._reply_queue.stop()
|
||||||
|
if self._ws_client:
|
||||||
|
await self._ws_client.stop()
|
||||||
|
|
||||||
|
def get_cached_conversations(self) -> list[dict]:
|
||||||
|
"""返回运行中缓存的会话(来自 WS / 轮询)。"""
|
||||||
|
results = []
|
||||||
|
seen = set()
|
||||||
|
for conv_id, meta in self._conv_meta.items():
|
||||||
|
name = (meta.get("sender_name") or "").strip()
|
||||||
|
key = conv_id or name
|
||||||
|
if not key or key in seen:
|
||||||
|
continue
|
||||||
|
seen.add(key)
|
||||||
|
results.append({
|
||||||
|
"conversation_id": conv_id,
|
||||||
|
"sender_name": name or f"会话{conv_id[-8:]}" if conv_id else "未知用户",
|
||||||
|
"sender_avatar": meta.get("sender_avatar") or None,
|
||||||
|
"sender_id": str(meta.get("peer_uid") or meta.get("sender_id") or conv_id or ""),
|
||||||
|
"peer_uid": str(meta.get("peer_uid") or ""),
|
||||||
|
"content": str(meta.get("content") or ""),
|
||||||
|
"unread_count": int(meta.get("unread_count") or 0),
|
||||||
|
})
|
||||||
|
return results
|
||||||
|
|
||||||
|
async def get_reply_queue_snapshot(self) -> list[dict]:
|
||||||
|
"""返回当前账号自动回复队列的可管理快照。"""
|
||||||
|
return await self._reply_queue.snapshot()
|
||||||
|
|
||||||
|
async def send_queued_reply_now(self, job_id: str) -> dict:
|
||||||
|
"""把指定自动回复任务移入账号紧急队列;实际发送仍由单消费者串行执行。"""
|
||||||
|
return await self._reply_queue.send_now(job_id)
|
||||||
|
|
||||||
|
async def _send_text(
|
||||||
|
self,
|
||||||
|
conversation_id: str,
|
||||||
|
content: str,
|
||||||
|
conversation_short_id: str = "",
|
||||||
|
) -> tuple[bool, Optional[dict]]:
|
||||||
|
"""发送一条私信;若因签名凭证失效(7911)失败,刷新 web_protect 后自动重试一次。
|
||||||
|
|
||||||
|
返回 (是否成功, 解析到的会话 meta)。失败原因写入 self.last_error。
|
||||||
|
"""
|
||||||
|
for attempt in range(2):
|
||||||
|
async with DouyinImHttpClient(self.session, account_id=self.account_id) as http:
|
||||||
|
sent = await http.send_text_message(
|
||||||
|
conversation_id,
|
||||||
|
content,
|
||||||
|
conversation_short_id=conversation_short_id,
|
||||||
|
)
|
||||||
|
self.last_error = http.last_error
|
||||||
|
needs_refresh = http.last_send_needs_refresh
|
||||||
|
if sent:
|
||||||
|
resolved = http.last_send_meta.get(conversation_id)
|
||||||
|
self.session.conv_meta.update(http.session.conv_meta)
|
||||||
|
self._session_invalid_strikes = 0 # 发送成功 → 登录有效
|
||||||
|
return True, resolved
|
||||||
|
|
||||||
|
# 仅在“签名凭证失效”时刷新并重试一次
|
||||||
|
if attempt == 0 and needs_refresh and self.refresh_credentials:
|
||||||
|
logger.warning(
|
||||||
|
f"Send hit credential-expiry(7911) for {conversation_id}; "
|
||||||
|
"refreshing web_protect and retrying once..."
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
refreshed = await self.refresh_credentials()
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"refresh_credentials raised: {e}")
|
||||||
|
refreshed = False
|
||||||
|
if refreshed:
|
||||||
|
continue
|
||||||
|
break
|
||||||
|
await self._note_session_invalid(self.last_error)
|
||||||
|
return False, None
|
||||||
|
|
||||||
|
async def _note_session_invalid(self, error: str) -> None:
|
||||||
|
"""根据发送失败原因判断 IM 是否已退出登录;连续 INVALID_REQUEST 即触发自动下线。
|
||||||
|
|
||||||
|
INVALID_REQUEST 来自 create_conversation/发送:会话/签名被抖音判为无效,强相关于「登录失效」。
|
||||||
|
而 8xxx/7xxx 等业务错误(关系/频控/内容)说明请求已到达抖音、登录仍有效,重置计数。
|
||||||
|
"""
|
||||||
|
err = error or ""
|
||||||
|
if "INVALID_REQUEST" not in err:
|
||||||
|
self._session_invalid_strikes = 0
|
||||||
|
return
|
||||||
|
self._session_invalid_strikes += 1
|
||||||
|
if self._session_invalid_strikes < 2 or self._session_invalid_fired:
|
||||||
|
return
|
||||||
|
self._session_invalid_fired = True
|
||||||
|
reason = "IM 会话失效(INVALID_REQUEST),登录可能已退出"
|
||||||
|
logger.warning(
|
||||||
|
f"Account {self.account_id} {reason};连续 {self._session_invalid_strikes} 次 -> 自动下线"
|
||||||
|
)
|
||||||
|
system_logger.record(
|
||||||
|
"IM 登录失效,自动下线",
|
||||||
|
detail=f"{reason}(连续 {self._session_invalid_strikes} 次发送返回 INVALID_REQUEST)。"
|
||||||
|
"请停止托管后用浏览器模式重新登录并打开私信页,再重新启动托管。",
|
||||||
|
level="error",
|
||||||
|
category="auth",
|
||||||
|
account_id=self.account_id,
|
||||||
|
)
|
||||||
|
self._running = False # 让主循环尽快退出
|
||||||
|
if self.on_session_invalid:
|
||||||
|
try:
|
||||||
|
await self.on_session_invalid(reason)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"on_session_invalid handler error: {e}")
|
||||||
|
|
||||||
|
async def send_message(self, conversation_id: str, content: str) -> bool:
|
||||||
|
"""手动发送私信"""
|
||||||
|
from .conv_util import normalize_conversation_id
|
||||||
|
from .auth import DouyinAuth
|
||||||
|
|
||||||
|
auth = DouyinAuth()
|
||||||
|
auth.perepare_auth(
|
||||||
|
self.session.cookie_header(),
|
||||||
|
self.session.web_protect_str,
|
||||||
|
self.session.keys_str,
|
||||||
|
)
|
||||||
|
if getattr(self.session, "uid_verified", False) and self.session.my_uid:
|
||||||
|
my_uid = self.session.my_uid
|
||||||
|
else:
|
||||||
|
my_uid = await asyncio.to_thread(lambda: auth.get_uid()) or self.session.my_uid
|
||||||
|
if my_uid:
|
||||||
|
conversation_id = normalize_conversation_id(conversation_id, my_uid)
|
||||||
|
|
||||||
|
meta = self._conv_meta.get(conversation_id, {})
|
||||||
|
sent, resolved = await self._send_text(
|
||||||
|
conversation_id,
|
||||||
|
content,
|
||||||
|
conversation_short_id=str(meta.get("conversation_short_id") or ""),
|
||||||
|
)
|
||||||
|
if sent and resolved:
|
||||||
|
self._conv_meta[conversation_id] = {
|
||||||
|
**meta,
|
||||||
|
**resolved,
|
||||||
|
"conversation_id": conversation_id,
|
||||||
|
}
|
||||||
|
return sent
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user