13LSR commited on
Commit
41cdf55
·
1 Parent(s): e8bc673
.spec-workflow/config.example.toml ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Spec Workflow MCP Server Configuration File
2
+ # ============================================
3
+ #
4
+ # This is an example configuration file for the Spec Workflow MCP Server.
5
+ # Copy this file to 'config.toml' in the same directory to use it.
6
+ #
7
+ # Configuration Precedence:
8
+ # 1. Command-line arguments (highest priority)
9
+ # 2. Config file settings
10
+ # 3. Built-in defaults (lowest priority)
11
+ #
12
+ # All settings are optional. Uncomment and modify as needed.
13
+ # Please note that not all MCP clients will support loading this config file due to the nature of where they are running from.
14
+
15
+ # Project directory path
16
+ # The root directory of your project where spec files are located.
17
+ # Note: You may have to use double slashes (\\) instead of single slashes (/) on Windows or for certain clients.
18
+ # Supports tilde (~) expansion for home directory.
19
+ # Default: current working directory
20
+ # projectDir = "."
21
+ # projectDir = "~/my-project"
22
+ # projectDir = "/absolute/path/to/project"
23
+
24
+ # Dashboard port
25
+ # The port number for the web dashboard.
26
+ # Must be between 1024 and 65535.
27
+ # Default: ephemeral port (automatically assigned)
28
+ # port = 3000
29
+
30
+ # Auto-start dashboard
31
+ # Automatically launch the dashboard when the MCP server starts.
32
+ # The dashboard will open in your default browser.
33
+ # Default: false
34
+ # autoStartDashboard = false
35
+
36
+ # Dashboard-only mode
37
+ # Run only the web dashboard without the MCP server.
38
+ # Useful for standalone dashboard usage.
39
+ # Default: false
40
+ # dashboardOnly = false
41
+
42
+ # Language
43
+ # Set the interface language for internationalization (i18n).
44
+ # Available languages depend on your installation.
45
+ # Common values: "en" (English), "ja" (Japanese), etc.
46
+ # Default: system language or "en"
47
+ # lang = "en"
48
+
49
+ # Example configurations:
50
+ # =====================
51
+
52
+ # Example 1: Development setup with auto-started dashboard
53
+ # ----------------------------------------------------------
54
+ # projectDir = "~/dev/my-project"
55
+ # autoStartDashboard = true
56
+ # port = 3456
57
+
58
+ # Example 2: Production MCP server without dashboard
59
+ # ---------------------------------------------------
60
+ # projectDir = "/var/projects/production"
61
+ # autoStartDashboard = false
62
+
63
+ # Example 3: Dashboard-only mode for viewing specs
64
+ # -------------------------------------------------
65
+ # projectDir = "."
66
+ # dashboardOnly = true
67
+ # port = 8080
68
+
69
+ # Example 4: Japanese language interface
70
+ # ---------------------------------------
71
+ # lang = "ja"
72
+ # autoStartDashboard = true
.spec-workflow/templates/design-template.md ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Design Document
2
+
3
+ ## Overview
4
+
5
+ [High-level description of the feature and its place in the overall system]
6
+
7
+ ## Steering Document Alignment
8
+
9
+ ### Technical Standards (tech.md)
10
+ [How the design follows documented technical patterns and standards]
11
+
12
+ ### Project Structure (structure.md)
13
+ [How the implementation will follow project organization conventions]
14
+
15
+ ## Code Reuse Analysis
16
+ [What existing code will be leveraged, extended, or integrated with this feature]
17
+
18
+ ### Existing Components to Leverage
19
+ - **[Component/Utility Name]**: [How it will be used]
20
+ - **[Service/Helper Name]**: [How it will be extended]
21
+
22
+ ### Integration Points
23
+ - **[Existing System/API]**: [How the new feature will integrate]
24
+ - **[Database/Storage]**: [How data will connect to existing schemas]
25
+
26
+ ## Architecture
27
+
28
+ [Describe the overall architecture and design patterns used]
29
+
30
+ ### Modular Design Principles
31
+ - **Single File Responsibility**: Each file should handle one specific concern or domain
32
+ - **Component Isolation**: Create small, focused components rather than large monolithic files
33
+ - **Service Layer Separation**: Separate data access, business logic, and presentation layers
34
+ - **Utility Modularity**: Break utilities into focused, single-purpose modules
35
+
36
+ ```mermaid
37
+ graph TD
38
+ A[Component A] --> B[Component B]
39
+ B --> C[Component C]
40
+ ```
41
+
42
+ ## Components and Interfaces
43
+
44
+ ### Component 1
45
+ - **Purpose:** [What this component does]
46
+ - **Interfaces:** [Public methods/APIs]
47
+ - **Dependencies:** [What it depends on]
48
+ - **Reuses:** [Existing components/utilities it builds upon]
49
+
50
+ ### Component 2
51
+ - **Purpose:** [What this component does]
52
+ - **Interfaces:** [Public methods/APIs]
53
+ - **Dependencies:** [What it depends on]
54
+ - **Reuses:** [Existing components/utilities it builds upon]
55
+
56
+ ## Data Models
57
+
58
+ ### Model 1
59
+ ```
60
+ [Define the structure of Model1 in your language]
61
+ - id: [unique identifier type]
62
+ - name: [string/text type]
63
+ - [Additional properties as needed]
64
+ ```
65
+
66
+ ### Model 2
67
+ ```
68
+ [Define the structure of Model2 in your language]
69
+ - id: [unique identifier type]
70
+ - [Additional properties as needed]
71
+ ```
72
+
73
+ ## Error Handling
74
+
75
+ ### Error Scenarios
76
+ 1. **Scenario 1:** [Description]
77
+ - **Handling:** [How to handle]
78
+ - **User Impact:** [What user sees]
79
+
80
+ 2. **Scenario 2:** [Description]
81
+ - **Handling:** [How to handle]
82
+ - **User Impact:** [What user sees]
83
+
84
+ ## Testing Strategy
85
+
86
+ ### Unit Testing
87
+ - [Unit testing approach]
88
+ - [Key components to test]
89
+
90
+ ### Integration Testing
91
+ - [Integration testing approach]
92
+ - [Key flows to test]
93
+
94
+ ### End-to-End Testing
95
+ - [E2E testing approach]
96
+ - [User scenarios to test]
.spec-workflow/templates/product-template.md ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Product Overview
2
+
3
+ ## Product Purpose
4
+ [Describe the core purpose of this product/project. What problem does it solve?]
5
+
6
+ ## Target Users
7
+ [Who are the primary users of this product? What are their needs and pain points?]
8
+
9
+ ## Key Features
10
+ [List the main features that deliver value to users]
11
+
12
+ 1. **Feature 1**: [Description]
13
+ 2. **Feature 2**: [Description]
14
+ 3. **Feature 3**: [Description]
15
+
16
+ ## Business Objectives
17
+ [What are the business goals this product aims to achieve?]
18
+
19
+ - [Objective 1]
20
+ - [Objective 2]
21
+ - [Objective 3]
22
+
23
+ ## Success Metrics
24
+ [How will we measure the success of this product?]
25
+
26
+ - [Metric 1]: [Target]
27
+ - [Metric 2]: [Target]
28
+ - [Metric 3]: [Target]
29
+
30
+ ## Product Principles
31
+ [Core principles that guide product decisions]
32
+
33
+ 1. **[Principle 1]**: [Explanation]
34
+ 2. **[Principle 2]**: [Explanation]
35
+ 3. **[Principle 3]**: [Explanation]
36
+
37
+ ## Monitoring & Visibility (if applicable)
38
+ [How do users track progress and monitor the system?]
39
+
40
+ - **Dashboard Type**: [e.g., Web-based, CLI, Desktop app]
41
+ - **Real-time Updates**: [e.g., WebSocket, polling, push notifications]
42
+ - **Key Metrics Displayed**: [What information is most important to surface]
43
+ - **Sharing Capabilities**: [e.g., read-only links, exports, reports]
44
+
45
+ ## Future Vision
46
+ [Where do we see this product evolving in the future?]
47
+
48
+ ### Potential Enhancements
49
+ - **Remote Access**: [e.g., Tunnel features for sharing dashboards with stakeholders]
50
+ - **Analytics**: [e.g., Historical trends, performance metrics]
51
+ - **Collaboration**: [e.g., Multi-user support, commenting]
.spec-workflow/templates/requirements-template.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Requirements Document
2
+
3
+ ## Introduction
4
+
5
+ [Provide a brief overview of the feature, its purpose, and its value to users]
6
+
7
+ ## Alignment with Product Vision
8
+
9
+ [Explain how this feature supports the goals outlined in product.md]
10
+
11
+ ## Requirements
12
+
13
+ ### Requirement 1
14
+
15
+ **User Story:** As a [role], I want [feature], so that [benefit]
16
+
17
+ #### Acceptance Criteria
18
+
19
+ 1. WHEN [event] THEN [system] SHALL [response]
20
+ 2. IF [precondition] THEN [system] SHALL [response]
21
+ 3. WHEN [event] AND [condition] THEN [system] SHALL [response]
22
+
23
+ ### Requirement 2
24
+
25
+ **User Story:** As a [role], I want [feature], so that [benefit]
26
+
27
+ #### Acceptance Criteria
28
+
29
+ 1. WHEN [event] THEN [system] SHALL [response]
30
+ 2. IF [precondition] THEN [system] SHALL [response]
31
+
32
+ ## Non-Functional Requirements
33
+
34
+ ### Code Architecture and Modularity
35
+ - **Single Responsibility Principle**: Each file should have a single, well-defined purpose
36
+ - **Modular Design**: Components, utilities, and services should be isolated and reusable
37
+ - **Dependency Management**: Minimize interdependencies between modules
38
+ - **Clear Interfaces**: Define clean contracts between components and layers
39
+
40
+ ### Performance
41
+ - [Performance requirements]
42
+
43
+ ### Security
44
+ - [Security requirements]
45
+
46
+ ### Reliability
47
+ - [Reliability requirements]
48
+
49
+ ### Usability
50
+ - [Usability requirements]
.spec-workflow/templates/structure-template.md ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Project Structure
2
+
3
+ ## Directory Organization
4
+
5
+ ```
6
+ [Define your project's directory structure. Examples below - adapt to your project type]
7
+
8
+ Example for a library/package:
9
+ project-root/
10
+ ├── src/ # Source code
11
+ ├── tests/ # Test files
12
+ ├── docs/ # Documentation
13
+ ├── examples/ # Usage examples
14
+ └── [build/dist/out] # Build output
15
+
16
+ Example for an application:
17
+ project-root/
18
+ ├── [src/app/lib] # Main source code
19
+ ├── [assets/resources] # Static resources
20
+ ├── [config/settings] # Configuration
21
+ ├── [scripts/tools] # Build/utility scripts
22
+ └── [tests/spec] # Test files
23
+
24
+ Common patterns:
25
+ - Group by feature/module
26
+ - Group by layer (UI, business logic, data)
27
+ - Group by type (models, controllers, views)
28
+ - Flat structure for simple projects
29
+ ```
30
+
31
+ ## Naming Conventions
32
+
33
+ ### Files
34
+ - **Components/Modules**: [e.g., `PascalCase`, `snake_case`, `kebab-case`]
35
+ - **Services/Handlers**: [e.g., `UserService`, `user_service`, `user-service`]
36
+ - **Utilities/Helpers**: [e.g., `dateUtils`, `date_utils`, `date-utils`]
37
+ - **Tests**: [e.g., `[filename]_test`, `[filename].test`, `[filename]Test`]
38
+
39
+ ### Code
40
+ - **Classes/Types**: [e.g., `PascalCase`, `CamelCase`, `snake_case`]
41
+ - **Functions/Methods**: [e.g., `camelCase`, `snake_case`, `PascalCase`]
42
+ - **Constants**: [e.g., `UPPER_SNAKE_CASE`, `SCREAMING_CASE`, `PascalCase`]
43
+ - **Variables**: [e.g., `camelCase`, `snake_case`, `lowercase`]
44
+
45
+ ## Import Patterns
46
+
47
+ ### Import Order
48
+ 1. External dependencies
49
+ 2. Internal modules
50
+ 3. Relative imports
51
+ 4. Style imports
52
+
53
+ ### Module/Package Organization
54
+ ```
55
+ [Describe your project's import/include patterns]
56
+ Examples:
57
+ - Absolute imports from project root
58
+ - Relative imports within modules
59
+ - Package/namespace organization
60
+ - Dependency management approach
61
+ ```
62
+
63
+ ## Code Structure Patterns
64
+
65
+ [Define common patterns for organizing code within files. Below are examples - choose what applies to your project]
66
+
67
+ ### Module/Class Organization
68
+ ```
69
+ Example patterns:
70
+ 1. Imports/includes/dependencies
71
+ 2. Constants and configuration
72
+ 3. Type/interface definitions
73
+ 4. Main implementation
74
+ 5. Helper/utility functions
75
+ 6. Exports/public API
76
+ ```
77
+
78
+ ### Function/Method Organization
79
+ ```
80
+ Example patterns:
81
+ - Input validation first
82
+ - Core logic in the middle
83
+ - Error handling throughout
84
+ - Clear return points
85
+ ```
86
+
87
+ ### File Organization Principles
88
+ ```
89
+ Choose what works for your project:
90
+ - One class/module per file
91
+ - Related functionality grouped together
92
+ - Public API at the top/bottom
93
+ - Implementation details hidden
94
+ ```
95
+
96
+ ## Code Organization Principles
97
+
98
+ 1. **Single Responsibility**: Each file should have one clear purpose
99
+ 2. **Modularity**: Code should be organized into reusable modules
100
+ 3. **Testability**: Structure code to be easily testable
101
+ 4. **Consistency**: Follow patterns established in the codebase
102
+
103
+ ## Module Boundaries
104
+ [Define how different parts of your project interact and maintain separation of concerns]
105
+
106
+ Examples of boundary patterns:
107
+ - **Core vs Plugins**: Core functionality vs extensible plugins
108
+ - **Public API vs Internal**: What's exposed vs implementation details
109
+ - **Platform-specific vs Cross-platform**: OS-specific code isolation
110
+ - **Stable vs Experimental**: Production code vs experimental features
111
+ - **Dependencies direction**: Which modules can depend on which
112
+
113
+ ## Code Size Guidelines
114
+ [Define your project's guidelines for file and function sizes]
115
+
116
+ Suggested guidelines:
117
+ - **File size**: [Define maximum lines per file]
118
+ - **Function/Method size**: [Define maximum lines per function]
119
+ - **Class/Module complexity**: [Define complexity limits]
120
+ - **Nesting depth**: [Maximum nesting levels]
121
+
122
+ ## Dashboard/Monitoring Structure (if applicable)
123
+ [How dashboard or monitoring components are organized]
124
+
125
+ ### Example Structure:
126
+ ```
127
+ src/
128
+ └── dashboard/ # Self-contained dashboard subsystem
129
+ ├── server/ # Backend server components
130
+ ├── client/ # Frontend assets
131
+ ├── shared/ # Shared types/utilities
132
+ └── public/ # Static assets
133
+ ```
134
+
135
+ ### Separation of Concerns
136
+ - Dashboard isolated from core business logic
137
+ - Own CLI entry point for independent operation
138
+ - Minimal dependencies on main application
139
+ - Can be disabled without affecting core functionality
140
+
141
+ ## Documentation Standards
142
+ - All public APIs must have documentation
143
+ - Complex logic should include inline comments
144
+ - README files for major modules
145
+ - Follow language-specific documentation conventions
.spec-workflow/templates/tasks-template.md ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Tasks Document
2
+
3
+ - [ ] 1. Create core interfaces in src/types/feature.ts
4
+ - File: src/types/feature.ts
5
+ - Define TypeScript interfaces for feature data structures
6
+ - Extend existing base interfaces from base.ts
7
+ - Purpose: Establish type safety for feature implementation
8
+ - _Leverage: src/types/base.ts_
9
+ - _Requirements: 1.1_
10
+ - _Prompt: Role: TypeScript Developer specializing in type systems and interfaces | Task: Create comprehensive TypeScript interfaces for the feature data structures following requirements 1.1, extending existing base interfaces from src/types/base.ts | Restrictions: Do not modify existing base interfaces, maintain backward compatibility, follow project naming conventions | Success: All interfaces compile without errors, proper inheritance from base types, full type coverage for feature requirements_
11
+
12
+ - [ ] 2. Create base model class in src/models/FeatureModel.ts
13
+ - File: src/models/FeatureModel.ts
14
+ - Implement base model extending BaseModel class
15
+ - Add validation methods using existing validation utilities
16
+ - Purpose: Provide data layer foundation for feature
17
+ - _Leverage: src/models/BaseModel.ts, src/utils/validation.ts_
18
+ - _Requirements: 2.1_
19
+ - _Prompt: Role: Backend Developer with expertise in Node.js and data modeling | Task: Create a base model class extending BaseModel and implementing validation following requirement 2.1, leveraging existing patterns from src/models/BaseModel.ts and src/utils/validation.ts | Restrictions: Must follow existing model patterns, do not bypass validation utilities, maintain consistent error handling | Success: Model extends BaseModel correctly, validation methods implemented and tested, follows project architecture patterns_
20
+
21
+ - [ ] 3. Add specific model methods to FeatureModel.ts
22
+ - File: src/models/FeatureModel.ts (continue from task 2)
23
+ - Implement create, update, delete methods
24
+ - Add relationship handling for foreign keys
25
+ - Purpose: Complete model functionality for CRUD operations
26
+ - _Leverage: src/models/BaseModel.ts_
27
+ - _Requirements: 2.2, 2.3_
28
+ - _Prompt: Role: Backend Developer with expertise in ORM and database operations | Task: Implement CRUD methods and relationship handling in FeatureModel.ts following requirements 2.2 and 2.3, extending patterns from src/models/BaseModel.ts | Restrictions: Must maintain transaction integrity, follow existing relationship patterns, do not duplicate base model functionality | Success: All CRUD operations work correctly, relationships are properly handled, database operations are atomic and efficient_
29
+
30
+ - [ ] 4. Create model unit tests in tests/models/FeatureModel.test.ts
31
+ - File: tests/models/FeatureModel.test.ts
32
+ - Write tests for model validation and CRUD methods
33
+ - Use existing test utilities and fixtures
34
+ - Purpose: Ensure model reliability and catch regressions
35
+ - _Leverage: tests/helpers/testUtils.ts, tests/fixtures/data.ts_
36
+ - _Requirements: 2.1, 2.2_
37
+ - _Prompt: Role: QA Engineer with expertise in unit testing and Jest/Mocha frameworks | Task: Create comprehensive unit tests for FeatureModel validation and CRUD methods covering requirements 2.1 and 2.2, using existing test utilities from tests/helpers/testUtils.ts and fixtures from tests/fixtures/data.ts | Restrictions: Must test both success and failure scenarios, do not test external dependencies directly, maintain test isolation | Success: All model methods are tested with good coverage, edge cases covered, tests run independently and consistently_
38
+
39
+ - [ ] 5. Create service interface in src/services/IFeatureService.ts
40
+ - File: src/services/IFeatureService.ts
41
+ - Define service contract with method signatures
42
+ - Extend base service interface patterns
43
+ - Purpose: Establish service layer contract for dependency injection
44
+ - _Leverage: src/services/IBaseService.ts_
45
+ - _Requirements: 3.1_
46
+ - _Prompt: Role: Software Architect specializing in service-oriented architecture and TypeScript interfaces | Task: Design service interface contract following requirement 3.1, extending base service patterns from src/services/IBaseService.ts for dependency injection | Restrictions: Must maintain interface segregation principle, do not expose internal implementation details, ensure contract compatibility with DI container | Success: Interface is well-defined with clear method signatures, extends base service appropriately, supports all required service operations_
47
+
48
+ - [ ] 6. Implement feature service in src/services/FeatureService.ts
49
+ - File: src/services/FeatureService.ts
50
+ - Create concrete service implementation using FeatureModel
51
+ - Add error handling with existing error utilities
52
+ - Purpose: Provide business logic layer for feature operations
53
+ - _Leverage: src/services/BaseService.ts, src/utils/errorHandler.ts, src/models/FeatureModel.ts_
54
+ - _Requirements: 3.2_
55
+ - _Prompt: Role: Backend Developer with expertise in service layer architecture and business logic | Task: Implement concrete FeatureService following requirement 3.2, using FeatureModel and extending BaseService patterns with proper error handling from src/utils/errorHandler.ts | Restrictions: Must implement interface contract exactly, do not bypass model validation, maintain separation of concerns from data layer | Success: Service implements all interface methods correctly, robust error handling implemented, business logic is well-encapsulated and testable_
56
+
57
+ - [ ] 7. Add service dependency injection in src/utils/di.ts
58
+ - File: src/utils/di.ts (modify existing)
59
+ - Register FeatureService in dependency injection container
60
+ - Configure service lifetime and dependencies
61
+ - Purpose: Enable service injection throughout application
62
+ - _Leverage: existing DI configuration in src/utils/di.ts_
63
+ - _Requirements: 3.1_
64
+ - _Prompt: Role: DevOps Engineer with expertise in dependency injection and IoC containers | Task: Register FeatureService in DI container following requirement 3.1, configuring appropriate lifetime and dependencies using existing patterns from src/utils/di.ts | Restrictions: Must follow existing DI container patterns, do not create circular dependencies, maintain service resolution efficiency | Success: FeatureService is properly registered and resolvable, dependencies are correctly configured, service lifetime is appropriate for use case_
65
+
66
+ - [ ] 8. Create service unit tests in tests/services/FeatureService.test.ts
67
+ - File: tests/services/FeatureService.test.ts
68
+ - Write tests for service methods with mocked dependencies
69
+ - Test error handling scenarios
70
+ - Purpose: Ensure service reliability and proper error handling
71
+ - _Leverage: tests/helpers/testUtils.ts, tests/mocks/modelMocks.ts_
72
+ - _Requirements: 3.2, 3.3_
73
+ - _Prompt: Role: QA Engineer with expertise in service testing and mocking frameworks | Task: Create comprehensive unit tests for FeatureService methods covering requirements 3.2 and 3.3, using mocked dependencies from tests/mocks/modelMocks.ts and test utilities | Restrictions: Must mock all external dependencies, test business logic in isolation, do not test framework code | Success: All service methods tested with proper mocking, error scenarios covered, tests verify business logic correctness and error handling_
74
+
75
+ - [ ] 4. Create API endpoints
76
+ - Design API structure
77
+ - _Leverage: src/api/baseApi.ts, src/utils/apiUtils.ts_
78
+ - _Requirements: 4.0_
79
+ - _Prompt: Role: API Architect specializing in RESTful design and Express.js | Task: Design comprehensive API structure following requirement 4.0, leveraging existing patterns from src/api/baseApi.ts and utilities from src/utils/apiUtils.ts | Restrictions: Must follow REST conventions, maintain API versioning compatibility, do not expose internal data structures directly | Success: API structure is well-designed and documented, follows existing patterns, supports all required operations with proper HTTP methods and status codes_
80
+
81
+ - [ ] 4.1 Set up routing and middleware
82
+ - Configure application routes
83
+ - Add authentication middleware
84
+ - Set up error handling middleware
85
+ - _Leverage: src/middleware/auth.ts, src/middleware/errorHandler.ts_
86
+ - _Requirements: 4.1_
87
+ - _Prompt: Role: Backend Developer with expertise in Express.js middleware and routing | Task: Configure application routes and middleware following requirement 4.1, integrating authentication from src/middleware/auth.ts and error handling from src/middleware/errorHandler.ts | Restrictions: Must maintain middleware order, do not bypass security middleware, ensure proper error propagation | Success: Routes are properly configured with correct middleware chain, authentication works correctly, errors are handled gracefully throughout the request lifecycle_
88
+
89
+ - [ ] 4.2 Implement CRUD endpoints
90
+ - Create API endpoints
91
+ - Add request validation
92
+ - Write API integration tests
93
+ - _Leverage: src/controllers/BaseController.ts, src/utils/validation.ts_
94
+ - _Requirements: 4.2, 4.3_
95
+ - _Prompt: Role: Full-stack Developer with expertise in API development and validation | Task: Implement CRUD endpoints following requirements 4.2 and 4.3, extending BaseController patterns and using validation utilities from src/utils/validation.ts | Restrictions: Must validate all inputs, follow existing controller patterns, ensure proper HTTP status codes and responses | Success: All CRUD operations work correctly, request validation prevents invalid data, integration tests pass and cover all endpoints_
96
+
97
+ - [ ] 5. Add frontend components
98
+ - Plan component architecture
99
+ - _Leverage: src/components/BaseComponent.tsx, src/styles/theme.ts_
100
+ - _Requirements: 5.0_
101
+ - _Prompt: Role: Frontend Architect with expertise in React component design and architecture | Task: Plan comprehensive component architecture following requirement 5.0, leveraging base patterns from src/components/BaseComponent.tsx and theme system from src/styles/theme.ts | Restrictions: Must follow existing component patterns, maintain design system consistency, ensure component reusability | Success: Architecture is well-planned and documented, components are properly organized, follows existing patterns and theme system_
102
+
103
+ - [ ] 5.1 Create base UI components
104
+ - Set up component structure
105
+ - Implement reusable components
106
+ - Add styling and theming
107
+ - _Leverage: src/components/BaseComponent.tsx, src/styles/theme.ts_
108
+ - _Requirements: 5.1_
109
+ - _Prompt: Role: Frontend Developer specializing in React and component architecture | Task: Create reusable UI components following requirement 5.1, extending BaseComponent patterns and using existing theme system from src/styles/theme.ts | Restrictions: Must use existing theme variables, follow component composition patterns, ensure accessibility compliance | Success: Components are reusable and properly themed, follow existing architecture, accessible and responsive_
110
+
111
+ - [ ] 5.2 Implement feature-specific components
112
+ - Create feature components
113
+ - Add state management
114
+ - Connect to API endpoints
115
+ - _Leverage: src/hooks/useApi.ts, src/components/BaseComponent.tsx_
116
+ - _Requirements: 5.2, 5.3_
117
+ - _Prompt: Role: React Developer with expertise in state management and API integration | Task: Implement feature-specific components following requirements 5.2 and 5.3, using API hooks from src/hooks/useApi.ts and extending BaseComponent patterns | Restrictions: Must use existing state management patterns, handle loading and error states properly, maintain component performance | Success: Components are fully functional with proper state management, API integration works smoothly, user experience is responsive and intuitive_
118
+
119
+ - [ ] 6. Integration and testing
120
+ - Plan integration approach
121
+ - _Leverage: src/utils/integrationUtils.ts, tests/helpers/testUtils.ts_
122
+ - _Requirements: 6.0_
123
+ - _Prompt: Role: Integration Engineer with expertise in system integration and testing strategies | Task: Plan comprehensive integration approach following requirement 6.0, leveraging integration utilities from src/utils/integrationUtils.ts and test helpers | Restrictions: Must consider all system components, ensure proper test coverage, maintain integration test reliability | Success: Integration plan is comprehensive and feasible, all system components work together correctly, integration points are well-tested_
124
+
125
+ - [ ] 6.1 Write end-to-end tests
126
+ - Set up E2E testing framework
127
+ - Write user journey tests
128
+ - Add test automation
129
+ - _Leverage: tests/helpers/testUtils.ts, tests/fixtures/data.ts_
130
+ - _Requirements: All_
131
+ - _Prompt: Role: QA Automation Engineer with expertise in E2E testing and test frameworks like Cypress or Playwright | Task: Implement comprehensive end-to-end tests covering all requirements, setting up testing framework and user journey tests using test utilities and fixtures | Restrictions: Must test real user workflows, ensure tests are maintainable and reliable, do not test implementation details | Success: E2E tests cover all critical user journeys, tests run reliably in CI/CD pipeline, user experience is validated from end-to-end_
132
+
133
+ - [ ] 6.2 Final integration and cleanup
134
+ - Integrate all components
135
+ - Fix any integration issues
136
+ - Clean up code and documentation
137
+ - _Leverage: src/utils/cleanup.ts, docs/templates/_
138
+ - _Requirements: All_
139
+ - _Prompt: Role: Senior Developer with expertise in code quality and system integration | Task: Complete final integration of all components and perform comprehensive cleanup covering all requirements, using cleanup utilities and documentation templates | Restrictions: Must not break existing functionality, ensure code quality standards are met, maintain documentation consistency | Success: All components are fully integrated and working together, code is clean and well-documented, system meets all requirements and quality standards_
.spec-workflow/templates/tech-template.md ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Technology Stack
2
+
3
+ ## Project Type
4
+ [Describe what kind of project this is: web application, CLI tool, desktop application, mobile app, library, API service, embedded system, game, etc.]
5
+
6
+ ## Core Technologies
7
+
8
+ ### Primary Language(s)
9
+ - **Language**: [e.g., Python 3.11, Go 1.21, TypeScript, Rust, C++]
10
+ - **Runtime/Compiler**: [if applicable]
11
+ - **Language-specific tools**: [package managers, build tools, etc.]
12
+
13
+ ### Key Dependencies/Libraries
14
+ [List the main libraries and frameworks your project depends on]
15
+ - **[Library/Framework name]**: [Purpose and version]
16
+ - **[Library/Framework name]**: [Purpose and version]
17
+
18
+ ### Application Architecture
19
+ [Describe how your application is structured - this could be MVC, event-driven, plugin-based, client-server, standalone, microservices, monolithic, etc.]
20
+
21
+ ### Data Storage (if applicable)
22
+ - **Primary storage**: [e.g., PostgreSQL, files, in-memory, cloud storage]
23
+ - **Caching**: [e.g., Redis, in-memory, disk cache]
24
+ - **Data formats**: [e.g., JSON, Protocol Buffers, XML, binary]
25
+
26
+ ### External Integrations (if applicable)
27
+ - **APIs**: [External services you integrate with]
28
+ - **Protocols**: [e.g., HTTP/REST, gRPC, WebSocket, TCP/IP]
29
+ - **Authentication**: [e.g., OAuth, API keys, certificates]
30
+
31
+ ### Monitoring & Dashboard Technologies (if applicable)
32
+ - **Dashboard Framework**: [e.g., React, Vue, vanilla JS, terminal UI]
33
+ - **Real-time Communication**: [e.g., WebSocket, Server-Sent Events, polling]
34
+ - **Visualization Libraries**: [e.g., Chart.js, D3, terminal graphs]
35
+ - **State Management**: [e.g., Redux, Vuex, file system as source of truth]
36
+
37
+ ## Development Environment
38
+
39
+ ### Build & Development Tools
40
+ - **Build System**: [e.g., Make, CMake, Gradle, npm scripts, cargo]
41
+ - **Package Management**: [e.g., pip, npm, cargo, go mod, apt, brew]
42
+ - **Development workflow**: [e.g., hot reload, watch mode, REPL]
43
+
44
+ ### Code Quality Tools
45
+ - **Static Analysis**: [Tools for code quality and correctness]
46
+ - **Formatting**: [Code style enforcement tools]
47
+ - **Testing Framework**: [Unit, integration, and/or end-to-end testing tools]
48
+ - **Documentation**: [Documentation generation tools]
49
+
50
+ ### Version Control & Collaboration
51
+ - **VCS**: [e.g., Git, Mercurial, SVN]
52
+ - **Branching Strategy**: [e.g., Git Flow, GitHub Flow, trunk-based]
53
+ - **Code Review Process**: [How code reviews are conducted]
54
+
55
+ ### Dashboard Development (if applicable)
56
+ - **Live Reload**: [e.g., Hot module replacement, file watchers]
57
+ - **Port Management**: [e.g., Dynamic allocation, configurable ports]
58
+ - **Multi-Instance Support**: [e.g., Running multiple dashboards simultaneously]
59
+
60
+ ## Deployment & Distribution (if applicable)
61
+ - **Target Platform(s)**: [Where/how the project runs: cloud, on-premise, desktop, mobile, embedded]
62
+ - **Distribution Method**: [How users get your software: download, package manager, app store, SaaS]
63
+ - **Installation Requirements**: [Prerequisites, system requirements]
64
+ - **Update Mechanism**: [How updates are delivered]
65
+
66
+ ## Technical Requirements & Constraints
67
+
68
+ ### Performance Requirements
69
+ - [e.g., response time, throughput, memory usage, startup time]
70
+ - [Specific benchmarks or targets]
71
+
72
+ ### Compatibility Requirements
73
+ - **Platform Support**: [Operating systems, architectures, versions]
74
+ - **Dependency Versions**: [Minimum/maximum versions of dependencies]
75
+ - **Standards Compliance**: [Industry standards, protocols, specifications]
76
+
77
+ ### Security & Compliance
78
+ - **Security Requirements**: [Authentication, encryption, data protection]
79
+ - **Compliance Standards**: [GDPR, HIPAA, SOC2, etc. if applicable]
80
+ - **Threat Model**: [Key security considerations]
81
+
82
+ ### Scalability & Reliability
83
+ - **Expected Load**: [Users, requests, data volume]
84
+ - **Availability Requirements**: [Uptime targets, disaster recovery]
85
+ - **Growth Projections**: [How the system needs to scale]
86
+
87
+ ## Technical Decisions & Rationale
88
+ [Document key architectural and technology choices]
89
+
90
+ ### Decision Log
91
+ 1. **[Technology/Pattern Choice]**: [Why this was chosen, alternatives considered]
92
+ 2. **[Architecture Decision]**: [Rationale, trade-offs accepted]
93
+ 3. **[Tool/Library Selection]**: [Reasoning, evaluation criteria]
94
+
95
+ ## Known Limitations
96
+ [Document any technical debt, limitations, or areas for improvement]
97
+
98
+ - [Limitation 1]: [Impact and potential future solutions]
99
+ - [Limitation 2]: [Why it exists and when it might be addressed]
.spec-workflow/user-templates/README.md ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # User Templates
2
+
3
+ This directory allows you to create custom templates that override the default Spec Workflow templates.
4
+
5
+ ## How to Use Custom Templates
6
+
7
+ 1. **Create your custom template file** in this directory with the exact same name as the default template you want to override:
8
+ - `requirements-template.md` - Override requirements document template
9
+ - `design-template.md` - Override design document template
10
+ - `tasks-template.md` - Override tasks document template
11
+ - `product-template.md` - Override product steering template
12
+ - `tech-template.md` - Override tech steering template
13
+ - `structure-template.md` - Override structure steering template
14
+
15
+ 2. **Template Loading Priority**:
16
+ - The system first checks this `user-templates/` directory
17
+ - If a matching template is found here, it will be used
18
+ - Otherwise, the default template from `templates/` will be used
19
+
20
+ ## Example Custom Template
21
+
22
+ To create a custom requirements template:
23
+
24
+ 1. Create a file named `requirements-template.md` in this directory
25
+ 2. Add your custom structure, for example:
26
+
27
+ ```markdown
28
+ # Requirements Document
29
+
30
+ ## Executive Summary
31
+ [Your custom section]
32
+
33
+ ## Business Requirements
34
+ [Your custom structure]
35
+
36
+ ## Technical Requirements
37
+ [Your custom fields]
38
+
39
+ ## Custom Sections
40
+ [Add any sections specific to your workflow]
41
+ ```
42
+
43
+ ## Template Variables
44
+
45
+ Templates can include placeholders that will be replaced when documents are created:
46
+ - `{{projectName}}` - The name of your project
47
+ - `{{featureName}}` - The name of the feature being specified
48
+ - `{{date}}` - The current date
49
+ - `{{author}}` - The document author
50
+
51
+ ## Best Practices
52
+
53
+ 1. **Start from defaults**: Copy a default template from `../templates/` as a starting point
54
+ 2. **Keep structure consistent**: Maintain similar section headers for tool compatibility
55
+ 3. **Document changes**: Add comments explaining why sections were added/modified
56
+ 4. **Version control**: Track your custom templates in version control
57
+ 5. **Test thoroughly**: Ensure custom templates work with the spec workflow tools
58
+
59
+ ## Notes
60
+
61
+ - Custom templates are project-specific and not included in the package distribution
62
+ - The `templates/` directory contains the default templates which are updated with each version
63
+ - Your custom templates in this directory are preserved during updates
64
+ - If a custom template has errors, the system will fall back to the default template
Dockerfile CHANGED
@@ -1,5 +1,10 @@
1
  FROM python:3.11-slim
2
 
 
 
 
 
 
3
  # 设置工作目录
4
  WORKDIR /app
5
 
@@ -12,13 +17,19 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
12
  COPY requirements.txt requirements.txt
13
  RUN pip install --no-cache-dir -r requirements.txt
14
 
15
- # 复制项目文件
16
  COPY . .
 
 
 
 
17
 
18
  # 时区与环境变量
19
  ENV TZ=Asia/Shanghai \
20
  PORT=7860 \
21
- PYTHONUNBUFFERED=1
 
 
22
 
23
  # 暴露端口(Hugging Face Spaces 默认使用 $PORT)
24
  EXPOSE 7860
 
1
  FROM python:3.11-slim
2
 
3
+ # 创建非特权用户
4
+ RUN useradd -m -u 1000 appuser && \
5
+ mkdir -p /tmp/music_downloads /tmp/music_api_logs && \
6
+ chown -R appuser:appuser /tmp/music_downloads /tmp/music_api_logs
7
+
8
  # 设置工作目录
9
  WORKDIR /app
10
 
 
17
  COPY requirements.txt requirements.txt
18
  RUN pip install --no-cache-dir -r requirements.txt
19
 
20
+ # 复制项目文件并设置权限
21
  COPY . .
22
+ RUN chown -R appuser:appuser /app
23
+
24
+ # 切换到非特权用户
25
+ USER appuser
26
 
27
  # 时区与环境变量
28
  ENV TZ=Asia/Shanghai \
29
  PORT=7860 \
30
+ PYTHONUNBUFFERED=1 \
31
+ DOWNLOADS_DIR=/tmp/music_downloads \
32
+ LOG_LEVEL=INFO
33
 
34
  # 暴露端口(Hugging Face Spaces 默认使用 $PORT)
35
  EXPOSE 7860
main.py CHANGED
@@ -83,9 +83,22 @@ class MusicAPIService:
83
  self.netease_api = NeteaseAPI()
84
  self.downloader = MusicDownloader()
85
 
86
- # 创建下载目录
87
- self.downloads_path = Path(config.downloads_dir)
88
- self.downloads_path.mkdir(exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
  self.logger.info(f" 音乐 API 服务初始化完成,下载目录: {self.downloads_path.absolute()}")
91
 
@@ -105,7 +118,13 @@ class MusicAPIService:
105
 
106
  # 文件处理器
107
  try:
108
- file_handler = logging.FileHandler('music_api.log', encoding='utf-8')
 
 
 
 
 
 
109
  file_formatter = logging.Formatter(
110
  '%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s'
111
  )
 
83
  self.netease_api = NeteaseAPI()
84
  self.downloader = MusicDownloader()
85
 
86
+ # 创建下载目录,使用临时目录避免权限问题
87
+ if config.downloads_dir == 'downloads':
88
+ import tempfile
89
+ temp_dir = Path(tempfile.gettempdir()) / "music_api_downloads"
90
+ self.downloads_path = temp_dir
91
+ else:
92
+ self.downloads_path = Path(config.downloads_dir)
93
+
94
+ try:
95
+ self.downloads_path.mkdir(parents=True, exist_ok=True)
96
+ except PermissionError:
97
+ # 如果权限不足,使用系统临时目录
98
+ import tempfile
99
+ temp_dir = Path(tempfile.gettempdir()) / "music_api_downloads"
100
+ self.downloads_path = temp_dir
101
+ self.downloads_path.mkdir(parents=True, exist_ok=True)
102
 
103
  self.logger.info(f" 音乐 API 服务初始化完成,下载目录: {self.downloads_path.absolute()}")
104
 
 
118
 
119
  # 文件处理器
120
  try:
121
+ # 使用临时目录避免权限问题
122
+ import tempfile
123
+ log_dir = Path(tempfile.gettempdir()) / "music_api_logs"
124
+ log_dir.mkdir(parents=True, exist_ok=True)
125
+ log_file = log_dir / "music_api.log"
126
+
127
+ file_handler = logging.FileHandler(str(log_file), encoding='utf-8')
128
  file_formatter = logging.Formatter(
129
  '%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s'
130
  )
music_downloader.py CHANGED
@@ -92,8 +92,21 @@ class MusicDownloader:
92
  download_dir: 下载目录
93
  max_concurrent: 最大并发下载数
94
  """
95
- self.download_dir = Path(download_dir)
96
- self.download_dir.mkdir(exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  self.max_concurrent = max_concurrent
98
 
99
  # 初始化依赖
 
92
  download_dir: 下载目录
93
  max_concurrent: 最大并发下载数
94
  """
95
+ # 使用临时目录避免权限问题
96
+ if download_dir == "downloads":
97
+ import tempfile
98
+ temp_dir = Path(tempfile.gettempdir()) / "music_downloads"
99
+ self.download_dir = temp_dir
100
+ else:
101
+ self.download_dir = Path(download_dir)
102
+ try:
103
+ self.download_dir.mkdir(parents=True, exist_ok=True)
104
+ except PermissionError:
105
+ # 如果权限不足,使用系统临时目录
106
+ import tempfile
107
+ temp_dir = Path(tempfile.gettempdir()) / "music_downloads"
108
+ self.download_dir = temp_dir
109
+ self.download_dir.mkdir(parents=True, exist_ok=True)
110
  self.max_concurrent = max_concurrent
111
 
112
  # 初始化依赖
music_downloader.py.backup ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """音乐下载器模块
2
+
3
+ 提供网易云音乐下载功能,包括:
4
+ - 音乐信息获取
5
+ - 文件下载到本地
6
+ - 内存下载
7
+ - 音乐标签写入
8
+ - 异步下载支持
9
+ """
10
+
11
+ import os
12
+ import re
13
+ import asyncio
14
+ import aiohttp
15
+ import aiofiles
16
+ from io import BytesIO
17
+ from typing import Dict, List, Optional, Tuple, Any, Union
18
+ from pathlib import Path
19
+ from dataclasses import dataclass
20
+ from enum import Enum
21
+
22
+ import requests
23
+ from mutagen.flac import FLAC
24
+ from mutagen.mp3 import MP3
25
+ from mutagen.id3 import ID3, TIT2, TPE1, TALB, TDRC, TRCK, APIC
26
+ from mutagen.mp4 import MP4
27
+
28
+ from music_api import NeteaseAPI, APIException
29
+ from cookie_manager import CookieManager
30
+
31
+
32
+ class AudioFormat(Enum):
33
+ """音频格式枚举"""
34
+ MP3 = "mp3"
35
+ FLAC = "flac"
36
+ M4A = "m4a"
37
+ UNKNOWN = "unknown"
38
+
39
+
40
+ class QualityLevel(Enum):
41
+ """音质等级枚举"""
42
+ STANDARD = "standard" # 标准
43
+ EXHIGH = "exhigh" # 极高
44
+ LOSSLESS = "lossless" # 无损
45
+ HIRES = "hires" # Hi-Res
46
+ SKY = "sky" # 沉浸环绕声
47
+ JYEFFECT = "jyeffect" # 高清环绕声
48
+ JYMASTER = "jymaster" # 超清母带
49
+
50
+
51
+ @dataclass
52
+ class MusicInfo:
53
+ """音乐信息数据类"""
54
+ id: int
55
+ name: str
56
+ artists: str
57
+ album: str
58
+ pic_url: str
59
+ duration: int
60
+ track_number: int
61
+ download_url: str
62
+ file_type: str
63
+ file_size: int
64
+ quality: str
65
+ lyric: str = ""
66
+ tlyric: str = ""
67
+
68
+
69
+ @dataclass
70
+ class DownloadResult:
71
+ """下载结果数据类"""
72
+ success: bool
73
+ file_path: Optional[str] = None
74
+ file_size: int = 0
75
+ error_message: str = ""
76
+ music_info: Optional[MusicInfo] = None
77
+
78
+
79
+ class DownloadException(Exception):
80
+ """下载异常类"""
81
+ pass
82
+
83
+
84
+ class MusicDownloader:
85
+ """音乐下载器主类"""
86
+
87
+ def __init__(self, download_dir: str = "downloads", max_concurrent: int = 3):
88
+ """
89
+ 初始化音乐下载器
90
+
91
+ Args:
92
+ download_dir: 下载目录
93
+ max_concurrent: 最大并发下载数
94
+ """
95
+ self.download_dir = Path(download_dir)
96
+ self.download_dir.mkdir(exist_ok=True)
97
+ self.max_concurrent = max_concurrent
98
+
99
+ # 初始化依赖
100
+ self.cookie_manager = CookieManager()
101
+ self.api = NeteaseAPI()
102
+
103
+ # 支持的文件格式
104
+ self.supported_formats = {
105
+ 'mp3': AudioFormat.MP3,
106
+ 'flac': AudioFormat.FLAC,
107
+ 'm4a': AudioFormat.M4A
108
+ }
109
+
110
+ def _sanitize_filename(self, filename: str) -> str:
111
+ """清理文件名,移除非法字符
112
+
113
+ Args:
114
+ filename: 原始文件名
115
+
116
+ Returns:
117
+ 清理后的安全文件名
118
+ """
119
+ # 移除或替换非法字符
120
+ illegal_chars = r'[<>:"/\\|?*]'
121
+ filename = re.sub(illegal_chars, '_', filename)
122
+
123
+ # 移除前后空格和点
124
+ filename = filename.strip(' .')
125
+
126
+ # 限制长度
127
+ if len(filename) > 200:
128
+ filename = filename[:200]
129
+
130
+ return filename or "unknown"
131
+
132
+ def _determine_file_extension(self, url: str, content_type: str = "") -> str:
133
+ """根据URL和Content-Type确定文件扩展名
134
+
135
+ Args:
136
+ url: 下载URL
137
+ content_type: HTTP Content-Type头
138
+
139
+ Returns:
140
+ 文件扩展名
141
+ """
142
+ # 首先尝试从URL获取
143
+ if '.flac' in url.lower():
144
+ return '.flac'
145
+ elif '.mp3' in url.lower():
146
+ return '.mp3'
147
+ elif '.m4a' in url.lower():
148
+ return '.m4a'
149
+
150
+ # 从Content-Type获取
151
+ content_type = content_type.lower()
152
+ if 'flac' in content_type:
153
+ return '.flac'
154
+ elif 'mpeg' in content_type or 'mp3' in content_type:
155
+ return '.mp3'
156
+ elif 'mp4' in content_type or 'm4a' in content_type:
157
+ return '.m4a'
158
+
159
+ return '.mp3' # 默认
160
+
161
+ def get_music_info(self, music_id: int, quality: str = "standard") -> MusicInfo:
162
+ """获取音乐详细信息
163
+
164
+ Args:
165
+ music_id: 音乐ID
166
+ quality: 音质等级
167
+
168
+ Returns:
169
+ 音乐信息对象
170
+
171
+ Raises:
172
+ DownloadException: 获取信息失败时抛出
173
+ """
174
+ try:
175
+ # 获取cookies
176
+ cookies = self.cookie_manager.parse_cookies()
177
+
178
+ # 获取音乐URL信息
179
+ url_result = self.api.get_song_url(music_id, quality, cookies)
180
+ if not url_result.get('data') or not url_result['data']:
181
+ raise DownloadException(f"无法获取音乐ID {music_id} 的播放链接")
182
+
183
+ song_data = url_result['data'][0]
184
+ download_url = song_data.get('url', '')
185
+ if not download_url:
186
+ raise DownloadException(f"音乐ID {music_id} 无可用的下载链接")
187
+
188
+ # 获取音乐详情
189
+ detail_result = self.api.get_song_detail(music_id)
190
+ if not detail_result.get('songs') or not detail_result['songs']:
191
+ raise DownloadException(f"无法获取音乐ID {music_id} 的详细信息")
192
+
193
+ song_detail = detail_result['songs'][0]
194
+
195
+ # 获取歌词
196
+ lyric_result = self.api.get_lyric(music_id, cookies)
197
+ lyric = lyric_result.get('lrc', {}).get('lyric', '') if lyric_result else ''
198
+ tlyric = lyric_result.get('tlyric', {}).get('lyric', '') if lyric_result else ''
199
+
200
+ # 构建艺术家字符串
201
+ artists = '/'.join(artist['name'] for artist in song_detail.get('ar', []))
202
+
203
+ # 创建MusicInfo对象
204
+ music_info = MusicInfo(
205
+ id=music_id,
206
+ name=song_detail.get('name', '未知歌曲'),
207
+ artists=artists or '未知艺术家',
208
+ album=song_detail.get('al', {}).get('name', '未知专辑'),
209
+ pic_url=song_detail.get('al', {}).get('picUrl', ''),
210
+ duration=song_detail.get('dt', 0) // 1000, # 转换为秒
211
+ track_number=song_detail.get('no', 0),
212
+ download_url=download_url,
213
+ file_type=song_data.get('type', 'mp3').lower(),
214
+ file_size=song_data.get('size', 0),
215
+ quality=quality,
216
+ lyric=lyric,
217
+ tlyric=tlyric
218
+ )
219
+
220
+ return music_info
221
+
222
+ except APIException as e:
223
+ raise DownloadException(f"API调用失败: {e}")
224
+ except Exception as e:
225
+ raise DownloadException(f"获取音乐信息时发生错误: {e}")
226
+
227
+ def download_music_file(self, music_id: int, quality: str = "standard") -> DownloadResult:
228
+ """下载音乐文件到本地
229
+
230
+ Args:
231
+ music_id: 音乐ID
232
+ quality: 音质等级
233
+
234
+ Returns:
235
+ 下载结果对象
236
+ """
237
+ try:
238
+ # 获取音乐信息
239
+ music_info = self.get_music_info(music_id, quality)
240
+
241
+ # 生成文件名
242
+ filename = f"{music_info.artists} - {music_info.name}"
243
+ safe_filename = self._sanitize_filename(filename)
244
+
245
+ # 确定文件扩展名
246
+ file_ext = self._determine_file_extension(music_info.download_url)
247
+ file_path = self.download_dir / f"{safe_filename}{file_ext}"
248
+
249
+ # 检查文件是否已存在
250
+ if file_path.exists():
251
+ return DownloadResult(
252
+ success=True,
253
+ file_path=str(file_path),
254
+ file_size=file_path.stat().st_size,
255
+ music_info=music_info
256
+ )
257
+
258
+ # 下载文件
259
+ response = requests.get(music_info.download_url, stream=True, timeout=30)
260
+ response.raise_for_status()
261
+
262
+ # 写入文件
263
+ with open(file_path, 'wb') as f:
264
+ for chunk in response.iter_content(chunk_size=8192):
265
+ if chunk:
266
+ f.write(chunk)
267
+
268
+ # 写入音乐标签
269
+ self._write_music_tags(file_path, music_info)
270
+
271
+ return DownloadResult(
272
+ success=True,
273
+ file_path=str(file_path),
274
+ file_size=file_path.stat().st_size,
275
+ music_info=music_info
276
+ )
277
+
278
+ except DownloadException:
279
+ raise
280
+ except requests.RequestException as e:
281
+ return DownloadResult(
282
+ success=False,
283
+ error_message=f"下载请求失败: {e}"
284
+ )
285
+ except Exception as e:
286
+ return DownloadResult(
287
+ success=False,
288
+ error_message=f"下载过程中发生错误: {e}"
289
+ )
290
+
291
+ async def download_music_file_async(self, music_id: int, quality: str = "standard") -> DownloadResult:
292
+ """异步下载音乐文件到本地
293
+
294
+ Args:
295
+ music_id: 音乐ID
296
+ quality: 音质等级
297
+
298
+ Returns:
299
+ 下载结果对象
300
+ """
301
+ try:
302
+ # 获取音乐信息(同步操作)
303
+ music_info = self.get_music_info(music_id, quality)
304
+
305
+ # 生成文件名
306
+ filename = f"{music_info.artists} - {music_info.name}"
307
+ safe_filename = self._sanitize_filename(filename)
308
+
309
+ # 确定文件扩展名
310
+ file_ext = self._determine_file_extension(music_info.download_url)
311
+ file_path = self.download_dir / f"{safe_filename}{file_ext}"
312
+
313
+ # 检查文件是否已存在
314
+ if file_path.exists():
315
+ return DownloadResult(
316
+ success=True,
317
+ file_path=str(file_path),
318
+ file_size=file_path.stat().st_size,
319
+ music_info=music_info
320
+ )
321
+
322
+ # 异步下载文件
323
+ async with aiohttp.ClientSession() as session:
324
+ async with session.get(music_info.download_url) as response:
325
+ response.raise_for_status()
326
+
327
+ async with aiofiles.open(file_path, 'wb') as f:
328
+ async for chunk in response.content.iter_chunked(8192):
329
+ await f.write(chunk)
330
+
331
+ # 写入音乐标签
332
+ self._write_music_tags(file_path, music_info)
333
+
334
+ return DownloadResult(
335
+ success=True,
336
+ file_path=str(file_path),
337
+ file_size=file_path.stat().st_size,
338
+ music_info=music_info
339
+ )
340
+
341
+ except DownloadException:
342
+ raise
343
+ except aiohttp.ClientError as e:
344
+ return DownloadResult(
345
+ success=False,
346
+ error_message=f"异步下载请求失败: {e}"
347
+ )
348
+ except Exception as e:
349
+ return DownloadResult(
350
+ success=False,
351
+ error_message=f"异步下载过程中发生错误: {e}"
352
+ )
353
+
354
+ def download_music_to_memory(self, music_id: int, quality: str = "standard") -> Tuple[bool, BytesIO, MusicInfo]:
355
+ """下载音乐到内存
356
+
357
+ Args:
358
+ music_id: 音乐ID
359
+ quality: 音质等级
360
+
361
+ Returns:
362
+ (是否成功, 音乐数据流, 音乐信息)
363
+
364
+ Raises:
365
+ DownloadException: 下载失败时抛出
366
+ """
367
+ try:
368
+ # 获取音乐信息
369
+ music_info = self.get_music_info(music_id, quality)
370
+
371
+ # 下载到内存
372
+ response = requests.get(music_info.download_url, timeout=30)
373
+ response.raise_for_status()
374
+
375
+ # 创建BytesIO对象
376
+ audio_data = BytesIO(response.content)
377
+
378
+ return True, audio_data, music_info
379
+
380
+ except DownloadException:
381
+ raise
382
+ except requests.RequestException as e:
383
+ raise DownloadException(f"下载到内存失败: {e}")
384
+ except Exception as e:
385
+ raise DownloadException(f"内存下载过程中发生错误: {e}")
386
+
387
+ async def download_batch_async(self, music_ids: List[int], quality: str = "standard") -> List[DownloadResult]:
388
+ """批量异步下载音乐
389
+
390
+ Args:
391
+ music_ids: 音乐ID列表
392
+ quality: 音质等级
393
+
394
+ Returns:
395
+ 下载结果列表
396
+ """
397
+ semaphore = asyncio.Semaphore(self.max_concurrent)
398
+
399
+ async def download_with_semaphore(music_id: int) -> DownloadResult:
400
+ async with semaphore:
401
+ return await self.download_music_file_async(music_id, quality)
402
+
403
+ tasks = [download_with_semaphore(music_id) for music_id in music_ids]
404
+ results = await asyncio.gather(*tasks, return_exceptions=True)
405
+
406
+ # 处理异常结果
407
+ processed_results = []
408
+ for i, result in enumerate(results):
409
+ if isinstance(result, Exception):
410
+ processed_results.append(DownloadResult(
411
+ success=False,
412
+ error_message=f"下载音乐ID {music_ids[i]} 时发生异常: {result}"
413
+ ))
414
+ else:
415
+ processed_results.append(result)
416
+
417
+ return processed_results
418
+
419
+ def _write_music_tags(self, file_path: Path, music_info: MusicInfo) -> None:
420
+ """写入音乐标签信息
421
+
422
+ Args:
423
+ file_path: 音乐文件路径
424
+ music_info: 音乐信息
425
+ """
426
+ try:
427
+ file_ext = file_path.suffix.lower()
428
+
429
+ if file_ext == '.mp3':
430
+ self._write_mp3_tags(file_path, music_info)
431
+ elif file_ext == '.flac':
432
+ self._write_flac_tags(file_path, music_info)
433
+ elif file_ext == '.m4a':
434
+ self._write_m4a_tags(file_path, music_info)
435
+
436
+ except Exception as e:
437
+ print(f"写入音乐标签失败: {e}")
438
+
439
+ def _write_mp3_tags(self, file_path: Path, music_info: MusicInfo) -> None:
440
+ """写入MP3标签"""
441
+ try:
442
+ audio = MP3(str(file_path), ID3=ID3)
443
+
444
+ # 添加ID3标签
445
+ audio.tags.add(TIT2(encoding=3, text=music_info.name))
446
+ audio.tags.add(TPE1(encoding=3, text=music_info.artists))
447
+ audio.tags.add(TALB(encoding=3, text=music_info.album))
448
+
449
+ if music_info.track_number > 0:
450
+ audio.tags.add(TRCK(encoding=3, text=str(music_info.track_number)))
451
+
452
+ # 下载并添加封面
453
+ if music_info.pic_url:
454
+ try:
455
+ pic_response = requests.get(music_info.pic_url, timeout=10)
456
+ pic_response.raise_for_status()
457
+ audio.tags.add(APIC(
458
+ encoding=3,
459
+ mime='image/jpeg',
460
+ type=3,
461
+ desc='Cover',
462
+ data=pic_response.content
463
+ ))
464
+ except:
465
+ pass # 封面下载失败不影响主流程
466
+
467
+ audio.save()
468
+ except Exception as e:
469
+ print(f"写入MP3标签失败: {e}")
470
+
471
+ def _write_flac_tags(self, file_path: Path, music_info: MusicInfo) -> None:
472
+ """写入FLAC标签"""
473
+ try:
474
+ audio = FLAC(str(file_path))
475
+
476
+ audio['TITLE'] = music_info.name
477
+ audio['ARTIST'] = music_info.artists
478
+ audio['ALBUM'] = music_info.album
479
+
480
+ if music_info.track_number > 0:
481
+ audio['TRACKNUMBER'] = str(music_info.track_number)
482
+
483
+ # 下载并添加封面
484
+ if music_info.pic_url:
485
+ try:
486
+ pic_response = requests.get(music_info.pic_url, timeout=10)
487
+ pic_response.raise_for_status()
488
+
489
+ from mutagen.flac import Picture
490
+ picture = Picture()
491
+ picture.type = 3 # Cover (front)
492
+ picture.mime = 'image/jpeg'
493
+ picture.desc = 'Cover'
494
+ picture.data = pic_response.content
495
+ audio.add_picture(picture)
496
+ except:
497
+ pass # 封面下载失败不影响主流程
498
+
499
+ audio.save()
500
+ except Exception as e:
501
+ print(f"写入FLAC标签失败: {e}")
502
+
503
+ def _write_m4a_tags(self, file_path: Path, music_info: MusicInfo) -> None:
504
+ """写入M4A标签"""
505
+ try:
506
+ audio = MP4(str(file_path))
507
+
508
+ audio['\xa9nam'] = music_info.name
509
+ audio['\xa9ART'] = music_info.artists
510
+ audio['\xa9alb'] = music_info.album
511
+
512
+ if music_info.track_number > 0:
513
+ audio['trkn'] = [(music_info.track_number, 0)]
514
+
515
+ # 下载并添加封面
516
+ if music_info.pic_url:
517
+ try:
518
+ pic_response = requests.get(music_info.pic_url, timeout=10)
519
+ pic_response.raise_for_status()
520
+ audio['covr'] = [pic_response.content]
521
+ except:
522
+ pass # 封面下载失败不影响主流程
523
+
524
+ audio.save()
525
+ except Exception as e:
526
+ print(f"写入M4A标签失败: {e}")
527
+
528
+ def get_download_progress(self, music_id: int, quality: str = "standard") -> Dict[str, Any]:
529
+ """获取下载进度信息
530
+
531
+ Args:
532
+ music_id: 音乐ID
533
+ quality: 音质等级
534
+
535
+ Returns:
536
+ 包含进度信息的字典
537
+ """
538
+ try:
539
+ music_info = self.get_music_info(music_id, quality)
540
+
541
+ filename = f"{music_info.artists} - {music_info.name}"
542
+ safe_filename = self._sanitize_filename(filename)
543
+ file_ext = self._determine_file_extension(music_info.download_url)
544
+ file_path = self.download_dir / f"{safe_filename}{file_ext}"
545
+
546
+ if file_path.exists():
547
+ current_size = file_path.stat().st_size
548
+ progress = (current_size / music_info.file_size * 100) if music_info.file_size > 0 else 0
549
+
550
+ return {
551
+ 'music_id': music_id,
552
+ 'filename': safe_filename + file_ext,
553
+ 'total_size': music_info.file_size,
554
+ 'current_size': current_size,
555
+ 'progress': min(progress, 100),
556
+ 'completed': current_size >= music_info.file_size
557
+ }
558
+ else:
559
+ return {
560
+ 'music_id': music_id,
561
+ 'filename': safe_filename + file_ext,
562
+ 'total_size': music_info.file_size,
563
+ 'current_size': 0,
564
+ 'progress': 0,
565
+ 'completed': False
566
+ }
567
+
568
+ except Exception as e:
569
+ return {
570
+ 'music_id': music_id,
571
+ 'error': str(e),
572
+ 'progress': 0,
573
+ 'completed': False
574
+ }
575
+
576
+
577
+ if __name__ == "__main__":
578
+ # 测试代码
579
+ downloader = MusicDownloader()
580
+ print("音乐下载器模块")
581
+ print("支持的功能:")
582
+ print("- 同步下载")
583
+ print("- 异步下载")
584
+ print("- 批量下载")
585
+ print("- 内存下载")
586
+ print("- 音乐标签写入")
587
+ print("- 下载进度跟踪")