added prp
This commit is contained in:
296
prp/README.md
Normal file
296
prp/README.md
Normal file
@@ -0,0 +1,296 @@
|
||||
# Project Reconstruction Plan (PRP) Collection
|
||||
|
||||
## Overview
|
||||
|
||||
This comprehensive collection of PRP (Project Reconstruction Plan) files provides detailed specifications and documentation for recreating the AI StyleGallery application using any framework or technology stack.
|
||||
|
||||
## Purpose
|
||||
|
||||
These PRP files serve as a complete blueprint for:
|
||||
- **Framework Migration**: Recreate the application in different frameworks (React, Angular, Django, etc.)
|
||||
- **Technology Modernization**: Upgrade to newer versions or different tech stacks
|
||||
- **Team Onboarding**: Help new developers understand the system architecture
|
||||
- **System Documentation**: Maintain comprehensive documentation of business logic and implementation details
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
prp/
|
||||
├── README.md # This overview file
|
||||
├── business-logic.md # High-level business requirements and workflows
|
||||
├── data-models.md # Complete data model specifications with relationships
|
||||
├── api-specification.md # All API endpoints, parameters, and responses
|
||||
├── frontend-components.md # Vue.js component specifications and interactions
|
||||
├── plugin-architecture.md # AI provider plugin system details
|
||||
├── authentication-authorization.md # User roles, permissions, and security
|
||||
├── configuration-settings.md # Application settings and configuration structure
|
||||
└── deployment-requirements.md # Dependencies, environment setup, and deployment notes
|
||||
```
|
||||
|
||||
## PRP Files Guide
|
||||
|
||||
### 1. Business Logic (`business-logic.md`)
|
||||
**Read First** - Start here to understand what the application does
|
||||
|
||||
**Contains**:
|
||||
- High-level business requirements
|
||||
- Core user workflows and journeys
|
||||
- Business rules and constraints
|
||||
- Success metrics and KPIs
|
||||
- Future enhancement opportunities
|
||||
|
||||
**Use For**:
|
||||
- Understanding the application's purpose
|
||||
- Planning framework migration strategy
|
||||
- Identifying core features to implement
|
||||
|
||||
### 2. Data Models (`data-models.md`)
|
||||
**Read Second** - Essential for database design
|
||||
|
||||
**Contains**:
|
||||
- Complete entity relationship diagram
|
||||
- Detailed model specifications with all attributes
|
||||
- Foreign key relationships and constraints
|
||||
- Data types and validation rules
|
||||
- Business logic implementation details
|
||||
|
||||
**Use For**:
|
||||
- Database schema design
|
||||
- ORM model creation
|
||||
- Understanding data relationships
|
||||
- Planning data migration strategies
|
||||
|
||||
### 3. API Specification (`api-specification.md`)
|
||||
**Read Third** - Critical for backend implementation
|
||||
|
||||
**Contains**:
|
||||
- Complete REST API endpoint documentation
|
||||
- Request/response formats and examples
|
||||
- Authentication and security requirements
|
||||
- Error handling and status codes
|
||||
- WebSocket integration details
|
||||
|
||||
**Use For**:
|
||||
- Backend API development
|
||||
- Frontend integration planning
|
||||
- API testing strategy
|
||||
- Third-party integration planning
|
||||
|
||||
### 4. Frontend Components (`frontend-components.md`)
|
||||
**Framework-Specific** - Vue.js implementation details
|
||||
|
||||
**Contains**:
|
||||
- Component hierarchy and architecture
|
||||
- State management patterns
|
||||
- User interaction flows
|
||||
- Responsive design specifications
|
||||
- Accessibility requirements
|
||||
|
||||
**Use For**:
|
||||
- Vue.js specific implementation
|
||||
- General frontend architecture planning
|
||||
- Component-based framework migration
|
||||
- UI/UX design reference
|
||||
|
||||
### 5. Plugin Architecture (`plugin-architecture.md`)
|
||||
**Technical Deep Dive** - Advanced backend patterns
|
||||
|
||||
**Contains**:
|
||||
- Strategy pattern implementation
|
||||
- Plugin interface specifications
|
||||
- AI provider integration details
|
||||
- Error handling and logging
|
||||
- Extension and customization points
|
||||
|
||||
**Use For**:
|
||||
- Implementing extensible AI provider systems
|
||||
- Understanding plugin-based architecture
|
||||
- Adding new AI service integrations
|
||||
- Advanced backend development
|
||||
|
||||
### 6. Authentication & Authorization (`authentication-authorization.md`)
|
||||
**Security Critical** - Must implement carefully
|
||||
|
||||
**Contains**:
|
||||
- User role and permission system
|
||||
- Laravel Sanctum API authentication
|
||||
- Security measures and best practices
|
||||
- Session management and protection
|
||||
- Compliance and legal considerations
|
||||
|
||||
**Use For**:
|
||||
- Security implementation planning
|
||||
- Authentication system design
|
||||
- Permission and access control
|
||||
- Security auditing and compliance
|
||||
|
||||
### 7. Configuration & Settings (`configuration-settings.md`)
|
||||
**Operational** - Runtime configuration management
|
||||
|
||||
**Contains**:
|
||||
- Settings management system
|
||||
- Environment-based configuration
|
||||
- Feature flags and dynamic settings
|
||||
- Admin configuration interface
|
||||
- Performance and monitoring settings
|
||||
|
||||
**Use For**:
|
||||
- Configuration management implementation
|
||||
- Environment setup and deployment
|
||||
- Feature flag system design
|
||||
- Admin panel development
|
||||
|
||||
### 8. Deployment Requirements (`deployment-requirements.md`)
|
||||
**DevOps & Operations** - Production deployment guide
|
||||
|
||||
**Contains**:
|
||||
- System requirements and specifications
|
||||
- Installation and setup procedures
|
||||
- Web server configuration (Nginx/Apache)
|
||||
- Security hardening and optimization
|
||||
- Monitoring and troubleshooting guides
|
||||
|
||||
**Use For**:
|
||||
- Production environment setup
|
||||
- DevOps and deployment automation
|
||||
- Performance optimization
|
||||
- Operational procedures and maintenance
|
||||
|
||||
## How to Use These PRP Files
|
||||
|
||||
### For Framework Migration
|
||||
|
||||
1. **Start with Business Logic** - Understand core requirements
|
||||
2. **Design Data Models** - Plan database schema
|
||||
3. **Implement Authentication** - Set up security first
|
||||
4. **Build API Layer** - Follow API specifications
|
||||
5. **Create Frontend** - Use component specifications as guide
|
||||
6. **Add Plugin System** - Implement extensible architecture
|
||||
7. **Configure & Deploy** - Follow deployment requirements
|
||||
|
||||
### For New Developer Onboarding
|
||||
|
||||
1. **Read Business Logic** - Understand what the app does
|
||||
2. **Study Data Models** - Learn the data structure
|
||||
3. **Review API Specification** - Understand system interfaces
|
||||
4. **Examine Frontend Components** - Learn UI interactions
|
||||
5. **Set up Development Environment** - Follow deployment guide
|
||||
|
||||
### For System Enhancement
|
||||
|
||||
1. **Identify Enhancement Area** - Choose relevant PRP file
|
||||
2. **Understand Current Implementation** - Study existing patterns
|
||||
3. **Plan Changes** - Design improvements within existing architecture
|
||||
4. **Implement & Test** - Follow established patterns and conventions
|
||||
|
||||
## Key Architecture Patterns
|
||||
|
||||
### Plugin-Based AI Integration
|
||||
- **Strategy Pattern**: Runtime selection of AI providers
|
||||
- **Interface Contract**: Consistent API across all providers
|
||||
- **Error Handling**: Graceful degradation and retry logic
|
||||
- **Logging**: Comprehensive audit trail for all operations
|
||||
|
||||
### Component-Based Frontend
|
||||
- **Single Page Application**: Vue.js with Inertia.js
|
||||
- **State Management**: Composition API with reactive data
|
||||
- **Real-time Updates**: WebSocket for live progress monitoring
|
||||
- **Responsive Design**: Mobile-first approach with touch support
|
||||
|
||||
### Role-Based Security
|
||||
- **Two-Tier Authentication**: Session-based admin, token-based API
|
||||
- **Granular Permissions**: Role-based access with ownership checks
|
||||
- **Security Headers**: Comprehensive protection against common attacks
|
||||
- **Audit Logging**: Complete trail of authentication and authorization events
|
||||
|
||||
## Technology Stack Compatibility
|
||||
|
||||
### Current Implementation
|
||||
- **Backend**: Laravel 12.21.0 with PHP 8.3
|
||||
- **Frontend**: Vue.js 3.5.18 with Inertia.js 1.3.0
|
||||
- **Database**: SQLite with Eloquent ORM
|
||||
- **Admin Panel**: Filament 3.3.34
|
||||
- **Styling**: Tailwind CSS 3.4.17
|
||||
|
||||
### Migration Opportunities
|
||||
- **React/Angular**: Use API specification for backend integration
|
||||
- **Django/FastAPI**: Implement data models and business logic
|
||||
- **Next.js/Nuxt.js**: Full-stack framework migration
|
||||
- **Spring Boot**: Java-based implementation
|
||||
- **ASP.NET Core**: .NET implementation
|
||||
|
||||
## Implementation Priorities
|
||||
|
||||
### Phase 1: Core Foundation
|
||||
1. **Database Schema** - Implement data models
|
||||
2. **Authentication System** - User roles and security
|
||||
3. **Basic API** - Core CRUD operations
|
||||
4. **Simple Frontend** - Basic gallery view
|
||||
|
||||
### Phase 2: Advanced Features
|
||||
1. **AI Plugin System** - Extensible provider architecture
|
||||
2. **Real-time Processing** - WebSocket integration
|
||||
3. **Advanced UI** - Component-based interface
|
||||
4. **Admin Panel** - Management interface
|
||||
|
||||
### Phase 3: Production Readiness
|
||||
1. **Performance Optimization** - Caching and scaling
|
||||
2. **Security Hardening** - Production security measures
|
||||
3. **Monitoring & Logging** - Operational visibility
|
||||
4. **Deployment Automation** - CI/CD and DevOps
|
||||
|
||||
## Quality Assurance
|
||||
|
||||
### Testing Strategy
|
||||
- **Unit Tests**: Individual component and function testing
|
||||
- **Integration Tests**: API and component interaction testing
|
||||
- **End-to-End Tests**: Complete user workflow testing
|
||||
- **Performance Tests**: Load testing and optimization
|
||||
|
||||
### Code Quality
|
||||
- **Standards**: Follow PSR-12 for PHP, ESLint for JavaScript
|
||||
- **Documentation**: Comprehensive code comments and API docs
|
||||
- **Security**: Regular security audits and vulnerability scanning
|
||||
- **Performance**: Monitoring and optimization based on metrics
|
||||
|
||||
## Support and Maintenance
|
||||
|
||||
### Documentation Updates
|
||||
- Keep PRP files current with code changes
|
||||
- Version control PRP files alongside code
|
||||
- Regular review and updates for accuracy
|
||||
|
||||
### Team Coordination
|
||||
- Use PRP files for architecture decision records
|
||||
- Reference PRP files in code reviews and planning
|
||||
- Maintain consistency between PRP and implementation
|
||||
|
||||
## Contributing to PRP Files
|
||||
|
||||
### Update Process
|
||||
1. **Identify Changes**: Document what needs updating
|
||||
2. **Update PRP Files**: Modify relevant sections
|
||||
3. **Review Changes**: Ensure accuracy and completeness
|
||||
4. **Version Control**: Commit PRP changes with code changes
|
||||
|
||||
### Quality Standards
|
||||
- **Accuracy**: PRP must reflect actual implementation
|
||||
- **Completeness**: Include all relevant details and examples
|
||||
- **Clarity**: Use clear language and consistent formatting
|
||||
- **Maintenance**: Regular updates to prevent drift
|
||||
|
||||
## Success Metrics
|
||||
|
||||
### Implementation Completeness
|
||||
- **Feature Parity**: All documented features implemented
|
||||
- **API Compatibility**: All endpoints match specifications
|
||||
- **Performance**: Meets or exceeds documented benchmarks
|
||||
- **Security**: Implements all security measures
|
||||
|
||||
### Development Efficiency
|
||||
- **Onboarding Time**: Reduced time for new developers
|
||||
- **Bug Reduction**: Fewer architecture-related issues
|
||||
- **Maintenance**: Easier troubleshooting and enhancements
|
||||
- **Documentation**: Single source of truth for system knowledge
|
||||
|
||||
This PRP collection provides a complete blueprint for understanding, maintaining, and recreating the AI StyleGallery application across different technologies and frameworks.
|
||||
522
prp/api-specification.md
Normal file
522
prp/api-specification.md
Normal file
@@ -0,0 +1,522 @@
|
||||
# API Specification
|
||||
|
||||
## Overview
|
||||
RESTful API built with Laravel Sanctum for authentication. Provides endpoints for image management, style application, and AI processing integration.
|
||||
|
||||
## Base URL
|
||||
```
|
||||
/api
|
||||
```
|
||||
|
||||
## Authentication
|
||||
Laravel Sanctum token-based authentication using `Authorization: Bearer <token>` header.
|
||||
|
||||
## Response Format
|
||||
All responses use JSON format with consistent structure:
|
||||
|
||||
### Success Response
|
||||
```json
|
||||
{
|
||||
"message": "Operation completed successfully",
|
||||
"data": { ... }
|
||||
}
|
||||
```
|
||||
|
||||
### Error Response
|
||||
```json
|
||||
{
|
||||
"error": "Error description",
|
||||
"message": "Detailed error message"
|
||||
}
|
||||
```
|
||||
|
||||
## Endpoints
|
||||
|
||||
### 1. Image Management
|
||||
|
||||
#### 1.1 Get Images
|
||||
**Endpoint**: `GET /api/images`
|
||||
|
||||
**Authentication**: Not required (filtered by visibility rules)
|
||||
|
||||
**Description**: Retrieves paginated list of images with automatic filesystem synchronization
|
||||
|
||||
**Query Parameters**:
|
||||
- None
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
[
|
||||
{
|
||||
"image_id": 1,
|
||||
"path": "/storage/uploads/image.jpg",
|
||||
"name": "image.jpg",
|
||||
"is_temp": false,
|
||||
"is_public": true,
|
||||
"is_new": true
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
**Business Logic**:
|
||||
- Synchronizes filesystem with database before returning results
|
||||
- Filters images based on authentication status
|
||||
- Adds `is_new` flag for recently uploaded images (within configurable timespan)
|
||||
- Returns images in descending order by `updated_at`
|
||||
|
||||
**Error Codes**:
|
||||
- `500`: Internal server error during synchronization
|
||||
|
||||
---
|
||||
|
||||
#### 1.2 Upload Image
|
||||
**Endpoint**: `POST /api/images/upload`
|
||||
|
||||
**Authentication**: Not required
|
||||
|
||||
**Description**: Uploads new image file to the gallery
|
||||
|
||||
**Request Body** (multipart/form-data):
|
||||
```json
|
||||
{
|
||||
"image": "file (JPEG, PNG, WebP, max 10MB)"
|
||||
}
|
||||
```
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
{
|
||||
"message": "Image uploaded successfully",
|
||||
"image_id": 1,
|
||||
"path": "/storage/uploads/new-image.jpg"
|
||||
}
|
||||
```
|
||||
|
||||
**Validation Rules**:
|
||||
- `image`: required, image file, mime types: jpeg,png,webp, max:10240KB
|
||||
|
||||
**Business Logic**:
|
||||
- Generates unique filename to prevent conflicts
|
||||
- Stores in `public/storage/uploads/` directory
|
||||
- Creates database record with `is_public = true`
|
||||
- Returns full URL path for immediate use
|
||||
|
||||
**Error Codes**:
|
||||
- `422`: Validation failed (invalid file type/size)
|
||||
- `500`: File storage error
|
||||
|
||||
---
|
||||
|
||||
#### 1.3 Apply Style to Image
|
||||
**Endpoint**: `POST /api/images/style-change`
|
||||
|
||||
**Authentication**: Not required (same-origin check)
|
||||
|
||||
**Description**: Initiates AI style transformation process
|
||||
|
||||
**Headers**:
|
||||
```
|
||||
Referer: https://yourdomain.com (same-origin validation)
|
||||
```
|
||||
|
||||
**Request Body**:
|
||||
```json
|
||||
{
|
||||
"image_id": 1,
|
||||
"style_id": 1
|
||||
}
|
||||
```
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
{
|
||||
"message": "Style change request sent",
|
||||
"prompt_id": "comfyui-job-123",
|
||||
"image_uuid": "550e8400-e29b-41d4-a716-446655440000",
|
||||
"plugin": "comfyui"
|
||||
}
|
||||
```
|
||||
|
||||
**Validation Rules**:
|
||||
- `image_id`: required, exists in `images` table
|
||||
- `style_id`: nullable, exists in `styles` table
|
||||
|
||||
**Business Logic**:
|
||||
- Validates same-origin request for security
|
||||
- Loads appropriate AI plugin based on style's API provider
|
||||
- Updates image record with `comfyui_prompt_id` and `style_id`
|
||||
- Returns tracking information for frontend progress monitoring
|
||||
|
||||
**Error Codes**:
|
||||
- `403`: Unauthorized origin
|
||||
- `404`: Image or style not found
|
||||
- `422`: Validation failed
|
||||
- `500`: Plugin processing error
|
||||
|
||||
---
|
||||
|
||||
#### 1.4 Fetch Styled Image Result
|
||||
**Endpoint**: `GET /api/images/fetch-styled/{promptId}`
|
||||
|
||||
**Authentication**: Not required
|
||||
|
||||
**Description**: Retrieves result of completed AI style transformation
|
||||
|
||||
**Path Parameters**:
|
||||
- `promptId`: string (ComfyUI job identifier)
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
{
|
||||
"message": "Styled image fetched successfully",
|
||||
"styled_image": {
|
||||
"id": 2,
|
||||
"path": "/storage/uploads/styled_image.png",
|
||||
"is_temp": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Business Logic**:
|
||||
- Finds image record by `comfyui_prompt_id`
|
||||
- Loads appropriate AI plugin to fetch result
|
||||
- Saves styled image to filesystem
|
||||
- Creates new database record for styled image
|
||||
- Links styled image to original via `original_image_id`
|
||||
|
||||
**Error Codes**:
|
||||
- `404`: Image not found or still processing
|
||||
- `500`: Plugin fetch error or file save error
|
||||
|
||||
---
|
||||
|
||||
#### 1.5 Keep Styled Image
|
||||
**Endpoint**: `POST /api/images/keep`
|
||||
|
||||
**Authentication**: Required (Sanctum)
|
||||
|
||||
**Description**: Converts temporary styled image to permanent
|
||||
|
||||
**Request Body**:
|
||||
```json
|
||||
{
|
||||
"image_id": 2
|
||||
}
|
||||
```
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
{
|
||||
"message": "Image kept successfully"
|
||||
}
|
||||
```
|
||||
|
||||
**Validation Rules**:
|
||||
- `image_id`: required, exists in `images` table
|
||||
|
||||
**Business Logic**:
|
||||
- Verifies user owns the image
|
||||
- Sets `is_temp = false` on image record
|
||||
- Image becomes permanent part of user's gallery
|
||||
|
||||
**Error Codes**:
|
||||
- `401`: Unauthenticated
|
||||
- `404`: Image not found
|
||||
- `403`: User doesn't own image
|
||||
|
||||
---
|
||||
|
||||
#### 1.6 Delete Image
|
||||
**Endpoint**: `DELETE /api/images/{image}`
|
||||
|
||||
**Authentication**: Required (Sanctum)
|
||||
|
||||
**Description**: Permanently removes image and file
|
||||
|
||||
**Path Parameters**:
|
||||
- `image`: integer (image ID)
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
{
|
||||
"message": "Image deleted successfully"
|
||||
}
|
||||
```
|
||||
|
||||
**Business Logic**:
|
||||
- Verifies user owns the image
|
||||
- Deletes physical file from storage
|
||||
- Removes database record
|
||||
- Cascading: styled images deleted when original is deleted
|
||||
|
||||
**Error Codes**:
|
||||
- `401`: Unauthenticated
|
||||
- `404`: Image not found
|
||||
- `403`: User doesn't own image
|
||||
- `500`: File deletion error
|
||||
|
||||
---
|
||||
|
||||
#### 1.7 Get Image Status (Deprecated)
|
||||
**Endpoint**: `GET /api/images/status`
|
||||
|
||||
**Authentication**: Not required
|
||||
|
||||
**Description**: Legacy endpoint for image processing status
|
||||
|
||||
**Query Parameters**:
|
||||
```json
|
||||
{
|
||||
"image_id": 1,
|
||||
"api_provider_name": "ComfyUI"
|
||||
}
|
||||
```
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
{
|
||||
"status": "unknown"
|
||||
}
|
||||
```
|
||||
|
||||
**Note**: Currently returns static response, replaced by WebSocket progress
|
||||
|
||||
---
|
||||
|
||||
### 2. Style Management
|
||||
|
||||
#### 2.1 Get Available Styles
|
||||
**Endpoint**: `GET /api/styles`
|
||||
|
||||
**Authentication**: Not required
|
||||
|
||||
**Description**: Retrieves all enabled styles for style selector
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"title": "Oil Painting",
|
||||
"description": "Classic oil painting style",
|
||||
"preview_image": "/storage/style_previews/oil-painting.jpg",
|
||||
"enabled": true
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
**Business Logic**:
|
||||
- Returns only enabled styles
|
||||
- Includes preview images for UI display
|
||||
- Ordered by `sort_order` field
|
||||
|
||||
**Error Codes**:
|
||||
- `500`: Database query error
|
||||
|
||||
---
|
||||
|
||||
### 3. AI Provider Management
|
||||
|
||||
#### 3.1 Get ComfyUI URL
|
||||
**Endpoint**: `GET /api/comfyui-url`
|
||||
|
||||
**Authentication**: Not required
|
||||
|
||||
**Description**: Returns WebSocket URL for real-time progress updates
|
||||
|
||||
**Query Parameters** (optional):
|
||||
```json
|
||||
{
|
||||
"style_id": 1,
|
||||
"image_uuid": "550e8400-e29b-41d4-a716-446655440000"
|
||||
}
|
||||
```
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
{
|
||||
"comfyui_url": "https://your-comfyui-server.com"
|
||||
}
|
||||
```
|
||||
|
||||
**Business Logic**:
|
||||
- Determines appropriate API provider based on style or image
|
||||
- Falls back to first available ComfyUI provider if none specified
|
||||
- Returns base URL for WebSocket connection
|
||||
|
||||
**Error Codes**:
|
||||
- `404`: No enabled ComfyUI provider found
|
||||
|
||||
---
|
||||
|
||||
### 4. User Management
|
||||
|
||||
#### 4.1 Get Authenticated User
|
||||
**Endpoint**: `GET /api/user`
|
||||
|
||||
**Authentication**: Required (Sanctum)
|
||||
|
||||
**Description**: Returns current authenticated user information
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"name": "John Doe",
|
||||
"email": "john@example.com",
|
||||
"role": "user",
|
||||
"theme_preference": "light",
|
||||
"locale": "en"
|
||||
}
|
||||
```
|
||||
|
||||
**Error Codes**:
|
||||
- `401`: Unauthenticated
|
||||
|
||||
---
|
||||
|
||||
### 5. Admin Management
|
||||
|
||||
#### 5.1 Store Navigation State
|
||||
**Endpoint**: `POST /api/admin/navigation-state`
|
||||
|
||||
**Authentication**: Required (Sanctum)
|
||||
|
||||
**Description**: Saves admin panel navigation preferences
|
||||
|
||||
**Request Body**:
|
||||
```json
|
||||
{
|
||||
"state": "collapsed",
|
||||
"active_tab": "dashboard"
|
||||
}
|
||||
```
|
||||
|
||||
**Response**:
|
||||
```json
|
||||
{
|
||||
"message": "Navigation state saved"
|
||||
}
|
||||
```
|
||||
|
||||
**Business Logic**:
|
||||
- Stores UI state preferences for admin users
|
||||
- Used by Filament admin panel for user experience
|
||||
|
||||
---
|
||||
|
||||
## WebSocket Integration
|
||||
|
||||
### ComfyUI Progress Updates
|
||||
|
||||
**Connection**:
|
||||
```
|
||||
WebSocket URL: ws://{comfyui-server-host}/ws
|
||||
```
|
||||
|
||||
**Message Format**:
|
||||
```json
|
||||
{
|
||||
"type": "progress",
|
||||
"data": {
|
||||
"prompt_id": "job-123",
|
||||
"value": 50,
|
||||
"max": 100
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Frontend Handling**:
|
||||
- Connect to WebSocket after receiving `prompt_id` from style-change endpoint
|
||||
- Monitor progress messages for matching `prompt_id`
|
||||
- Update UI progress bar based on `value/max` percentage
|
||||
- Fetch final result when progress reaches 100%
|
||||
|
||||
## Error Handling
|
||||
|
||||
### HTTP Status Codes
|
||||
- `200`: Success
|
||||
- `201`: Created
|
||||
- `400`: Bad Request
|
||||
- `401`: Unauthenticated
|
||||
- `403`: Forbidden
|
||||
- `404`: Not Found
|
||||
- `422`: Validation Error
|
||||
- `500`: Internal Server Error
|
||||
|
||||
### Error Response Structure
|
||||
```json
|
||||
{
|
||||
"error": "Human readable error message",
|
||||
"message": "Technical details for debugging",
|
||||
"errors": {
|
||||
"field_name": ["Specific field validation errors"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Rate Limiting
|
||||
|
||||
### Current Implementation
|
||||
- No explicit rate limiting configured
|
||||
- External AI services may have their own limits
|
||||
- Consider implementing for production deployment
|
||||
|
||||
### Recommended Limits
|
||||
- Image upload: 10 per minute per user
|
||||
- Style change requests: 5 per minute per user
|
||||
- API calls: 1000 per hour per user
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Authentication
|
||||
- Laravel Sanctum for API authentication
|
||||
- Bearer token in Authorization header
|
||||
- CSRF protection for web routes
|
||||
|
||||
### Input Validation
|
||||
- All inputs validated using Laravel Form Requests
|
||||
- File upload restrictions (type, size)
|
||||
- SQL injection prevention via Eloquent ORM
|
||||
|
||||
### Same-Origin Policy
|
||||
- Style change endpoint validates request origin
|
||||
- Prevents CSRF attacks from external sites
|
||||
|
||||
### File Security
|
||||
- Uploaded files stored outside web root
|
||||
- File type validation prevents malicious uploads
|
||||
- Secure file permissions on storage directories
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
### Caching
|
||||
- No explicit caching implemented
|
||||
- Consider caching for frequently accessed data:
|
||||
- Available styles list
|
||||
- User permissions
|
||||
- API provider configurations
|
||||
|
||||
### Database Optimization
|
||||
- Eager loading for relationships (styles → ai_models → api_providers)
|
||||
- Consider indexes on frequently queried fields
|
||||
- Automatic filesystem synchronization on image listing
|
||||
|
||||
### File Storage
|
||||
- Images stored on local filesystem
|
||||
- Consider CDN integration for global distribution
|
||||
- Automatic cleanup of temporary files
|
||||
|
||||
## Future API Enhancements
|
||||
|
||||
### Potential Endpoints
|
||||
- `GET /api/images/{id}/history` - Processing history for image
|
||||
- `POST /api/images/batch-style-change` - Apply style to multiple images
|
||||
- `GET /api/styles/search?q=term` - Search styles by name/description
|
||||
- `POST /api/users/preferences` - Update user preferences
|
||||
- `GET /api/admin/stats` - Application statistics for admins
|
||||
|
||||
### WebSocket Enhancements
|
||||
- Real-time notifications for all users
|
||||
- Live gallery updates when new images are processed
|
||||
- Admin monitoring of processing queue status
|
||||
552
prp/authentication-authorization.md
Normal file
552
prp/authentication-authorization.md
Normal file
@@ -0,0 +1,552 @@
|
||||
# Authentication and Authorization Specification
|
||||
|
||||
## Overview
|
||||
|
||||
Comprehensive authentication and authorization system using Laravel Sanctum for API authentication and Filament for admin panel access control, with role-based permissions and security best practices.
|
||||
|
||||
## Authentication Architecture
|
||||
|
||||
### Laravel Sanctum Integration
|
||||
|
||||
**Purpose**: Provides API authentication for SPA applications
|
||||
|
||||
**Token Management**:
|
||||
- **Token Storage**: Database storage with automatic expiration
|
||||
- **Token Types**: Personal access tokens with configurable abilities
|
||||
- **Security**: CSRF protection and secure token generation
|
||||
|
||||
**Frontend Integration**:
|
||||
```javascript
|
||||
// Login process
|
||||
axios.post('/login', credentials)
|
||||
.then(response => {
|
||||
// Store token securely
|
||||
localStorage.setItem('api_token', response.data.token);
|
||||
// Set default authorization header
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${response.data.token}`;
|
||||
});
|
||||
```
|
||||
|
||||
### Session-Based Authentication
|
||||
|
||||
**Purpose**: Traditional web session management for admin panel
|
||||
|
||||
**Implementation**:
|
||||
- Laravel Breeze scaffolding for basic auth
|
||||
- Session cookies for state management
|
||||
- CSRF protection for form submissions
|
||||
|
||||
## User Model and Roles
|
||||
|
||||
### User Model
|
||||
|
||||
**Location**: `app/Models/User.php`
|
||||
|
||||
**Key Attributes**:
|
||||
```php
|
||||
// Authentication
|
||||
email: string (unique) // Primary login identifier
|
||||
password: string (hashed) // Secure password hash
|
||||
email_verified_at: timestamp // Email verification status
|
||||
|
||||
// Authorization
|
||||
role_id: bigint unsigned (nullable) // Foreign key to roles table
|
||||
|
||||
// Two-Factor Authentication
|
||||
two_factor_secret: text (nullable) // TOTP secret key
|
||||
two_factor_recovery_codes: text (nullable) // Backup recovery codes
|
||||
two_factor_confirmed_at: timestamp (nullable) // 2FA confirmation
|
||||
|
||||
// Preferences
|
||||
email_notifications_enabled: boolean (default: true) // Notification preferences
|
||||
theme_preference: string (default: 'light') // UI theme
|
||||
locale: string (default: 'en') // Language preference
|
||||
```
|
||||
|
||||
### Role-Based Access Control
|
||||
|
||||
**Role Model**:
|
||||
```php
|
||||
// Simple role system
|
||||
id: bigint unsigned auto_increment primary key
|
||||
name: varchar(255) unique // Role identifier ('admin', 'user')
|
||||
created_at, updated_at: timestamps
|
||||
```
|
||||
|
||||
**Predefined Roles**:
|
||||
- **admin**: Full system access, user management, configuration
|
||||
- **user**: Standard user access, personal gallery management
|
||||
|
||||
**Role Assignment**:
|
||||
```php
|
||||
// Default role assignment (in migration)
|
||||
$usersTable->foreignId('role_id')->constrained()->default(2); // Defaults to 'user' role
|
||||
|
||||
// Role checking
|
||||
$user->role->name === 'admin'
|
||||
$user->role?->name === 'admin' // Safe null checking
|
||||
```
|
||||
|
||||
## Authorization Mechanisms
|
||||
|
||||
### API Authorization
|
||||
|
||||
**Protected Routes**:
|
||||
```php
|
||||
// routes/api.php
|
||||
Route::middleware('auth:sanctum')->group(function () {
|
||||
Route::post('/api/images/keep', [ImageController::class, 'keepImage']);
|
||||
Route::delete('/api/images/{image}', [ImageController::class, 'deleteImage']);
|
||||
Route::get('/api/user', function (Request $request) {
|
||||
return $request->user();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
**Middleware Stack**:
|
||||
1. **auth:sanctum**: Validates bearer token
|
||||
2. **Custom Logic**: Additional business rule validation
|
||||
|
||||
### Admin Panel Authorization
|
||||
|
||||
**Filament Integration**:
|
||||
- Built-in authentication for `/admin` routes
|
||||
- Session-based admin access
|
||||
- Automatic logout on inactivity
|
||||
|
||||
**Access Control**:
|
||||
```php
|
||||
// Filament panel configuration
|
||||
->requirePasswordResetAfterLogin(false)
|
||||
->passwordReset()
|
||||
->emailVerification()
|
||||
->twoFactorAuthentication()
|
||||
```
|
||||
|
||||
## Security Measures
|
||||
|
||||
### Password Security
|
||||
|
||||
**Hashing Algorithm**:
|
||||
- Laravel default: bcrypt with cost factor 12
|
||||
- Future migration path to Argon2
|
||||
|
||||
**Password Requirements**:
|
||||
- Minimum 8 characters
|
||||
- Mixed case letters
|
||||
- Numbers and special characters
|
||||
- Not in common password lists
|
||||
|
||||
### Two-Factor Authentication
|
||||
|
||||
**Implementation**:
|
||||
- TOTP (Time-based One-Time Password) standard
|
||||
- Google Authenticator, Authy compatibility
|
||||
- Recovery codes for account recovery
|
||||
|
||||
**Setup Flow**:
|
||||
1. User enables 2FA in profile settings
|
||||
2. QR code generated for authenticator app
|
||||
3. User confirms setup with first TOTP code
|
||||
4. Recovery codes generated and displayed once
|
||||
|
||||
**Verification**:
|
||||
```php
|
||||
// Middleware for 2FA verification
|
||||
if ($user->two_factor_secret && !$user->two_factor_confirmed_at) {
|
||||
return redirect()->route('two-factor.challenge');
|
||||
}
|
||||
```
|
||||
|
||||
### Session Security
|
||||
|
||||
**Configuration**:
|
||||
```php
|
||||
// config/session.php
|
||||
'secure' => env('SESSION_SECURE_COOKIE', true), // HTTPS only
|
||||
'http_only' => true, // Prevent XSS access
|
||||
'same_site' => 'lax', // CSRF protection
|
||||
'expire_on_close' => false, // Persistent sessions
|
||||
'lifetime' => 120, // 2 hour timeout
|
||||
```
|
||||
|
||||
**Admin Session Management**:
|
||||
- Shorter session lifetime for admin users
|
||||
- Automatic logout on suspicious activity
|
||||
- Session fixation protection
|
||||
|
||||
## Permission System
|
||||
|
||||
### Image Ownership
|
||||
|
||||
**Business Rules**:
|
||||
- Users can only modify their own images
|
||||
- Temporary images are tied to processing session
|
||||
- Public images visible to all authenticated users
|
||||
|
||||
**Implementation**:
|
||||
```php
|
||||
// ImageController@deleteImage
|
||||
public function deleteImage(Image $image)
|
||||
{
|
||||
// Implicit authorization via route model binding
|
||||
// User must own the image or be admin
|
||||
$this->authorize('delete', $image);
|
||||
// or explicit check
|
||||
if ($image->user_id !== auth()->id() && !auth()->user()->isAdmin()) {
|
||||
abort(403);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Admin Permissions
|
||||
|
||||
**Admin-Only Operations**:
|
||||
- User management (create, edit, delete users)
|
||||
- System configuration changes
|
||||
- Plugin and API provider management
|
||||
- Style and AI model configuration
|
||||
- Application settings modification
|
||||
|
||||
**Permission Checking**:
|
||||
```php
|
||||
// Policy-based authorization
|
||||
class ImagePolicy
|
||||
{
|
||||
public function delete(User $user, Image $image): bool
|
||||
{
|
||||
return $user->id === $image->user_id || $user->role->name === 'admin';
|
||||
}
|
||||
}
|
||||
|
||||
// Controller usage
|
||||
$this->authorize('delete', $image);
|
||||
```
|
||||
|
||||
## Security Headers and CSRF Protection
|
||||
|
||||
### Security Headers
|
||||
|
||||
**Content Security Policy**:
|
||||
```php
|
||||
// app/Http/Middleware/SetContentSecurityPolicy.php
|
||||
$contentSecurityPolicy = [
|
||||
'default-src' => ['self'],
|
||||
'script-src' => ['self', 'unsafe-inline', 'unsafe-eval'],
|
||||
'style-src' => ['self', 'unsafe-inline'],
|
||||
'img-src' => ['self', 'data:', 'https:'],
|
||||
'connect-src' => ['self', 'ws:', 'wss:'],
|
||||
];
|
||||
```
|
||||
|
||||
**Other Security Headers**:
|
||||
- `X-Frame-Options: SAMEORIGIN` - Prevent clickjacking
|
||||
- `X-Content-Type-Options: nosniff` - Prevent MIME sniffing
|
||||
- `Referrer-Policy: strict-origin-when-cross-origin` - Control referrer info
|
||||
- `Permissions-Policy: camera=(), microphone=(), geolocation=()` - Disable unnecessary permissions
|
||||
|
||||
### CSRF Protection
|
||||
|
||||
**Laravel CSRF**:
|
||||
- Automatic token generation for forms
|
||||
- Middleware validation on state-changing requests
|
||||
- Exception for API routes (handled by Sanctum)
|
||||
|
||||
**Custom CSRF**:
|
||||
```php
|
||||
// Verify CSRF token manually if needed
|
||||
if (!hash_equals($request->session()->token(), $request->input('_token'))) {
|
||||
abort(419, 'CSRF token mismatch');
|
||||
}
|
||||
```
|
||||
|
||||
## Authentication Flows
|
||||
|
||||
### User Registration
|
||||
|
||||
**Flow**:
|
||||
1. User submits registration form
|
||||
2. Validation (email format, password strength, uniqueness)
|
||||
3. Account creation with default 'user' role
|
||||
4. Email verification (if enabled)
|
||||
5. Welcome email sent
|
||||
|
||||
**Validation Rules**:
|
||||
```php
|
||||
'email' => 'required|email|unique:users|max:255',
|
||||
'password' => 'required|min:8|confirmed',
|
||||
'name' => 'required|string|max:255',
|
||||
```
|
||||
|
||||
### User Login
|
||||
|
||||
**Flow**:
|
||||
1. User submits credentials
|
||||
2. Rate limiting applied (5 attempts per minute)
|
||||
3. Credentials verified against database
|
||||
4. 2FA challenge if enabled
|
||||
5. Session/token created
|
||||
6. Redirect to appropriate interface
|
||||
|
||||
**Rate Limiting**:
|
||||
```php
|
||||
// Throttle login attempts
|
||||
RateLimiter::tooManyAttempts($key, 5) // 5 attempts
|
||||
RateLimiter::hit($key, 60) // Lock for 60 seconds
|
||||
```
|
||||
|
||||
### Password Reset
|
||||
|
||||
**Secure Token Flow**:
|
||||
1. User requests password reset
|
||||
2. Secure token generated and emailed
|
||||
3. Token validated on reset form
|
||||
4. Password updated with new hash
|
||||
5. Old tokens invalidated
|
||||
|
||||
**Token Security**:
|
||||
- Cryptographically secure random tokens
|
||||
- Short expiration time (1 hour)
|
||||
- Single-use tokens
|
||||
|
||||
## Admin Authentication
|
||||
|
||||
### Admin Panel Access
|
||||
|
||||
**Route Protection**:
|
||||
```php
|
||||
// Admin routes protected by Filament middleware
|
||||
Route::prefix('admin')->name('admin.')->middleware([
|
||||
'auth:sanctum', // API authentication
|
||||
// Filament middleware stack
|
||||
])->group(function () {
|
||||
// Admin routes
|
||||
});
|
||||
```
|
||||
|
||||
**Role-Based Access**:
|
||||
- Only users with 'admin' role can access admin panel
|
||||
- Automatic redirect for unauthorized users
|
||||
- Session management for admin activities
|
||||
|
||||
### Admin User Management
|
||||
|
||||
**User CRUD Operations**:
|
||||
- Create new users with role assignment
|
||||
- Edit user details and permissions
|
||||
- Disable/enable user accounts
|
||||
- Reset passwords securely
|
||||
|
||||
**Bulk Operations**:
|
||||
- Mass role assignment
|
||||
- Account activation/deactivation
|
||||
- Email notifications for status changes
|
||||
|
||||
## API Security
|
||||
|
||||
### Token Management
|
||||
|
||||
**Token Creation**:
|
||||
```php
|
||||
// Create personal access token
|
||||
$token = $user->createToken('api-token', ['read', 'write']);
|
||||
$plainTextToken = $token->plainTextToken;
|
||||
```
|
||||
|
||||
**Token Abilities**:
|
||||
- `read`: View images and styles
|
||||
- `write`: Upload images and apply styles
|
||||
- `admin`: Full administrative access
|
||||
|
||||
**Token Expiration**:
|
||||
```php
|
||||
// Create expiring token
|
||||
$token = $user->createToken('temp-token', ['read'], now()->addHour());
|
||||
```
|
||||
|
||||
### API Rate Limiting
|
||||
|
||||
**Current Implementation**: No explicit rate limiting (rely on external services)
|
||||
|
||||
**Recommended Limits**:
|
||||
```php
|
||||
// Per-user rate limits
|
||||
'api:images:upload' => '5,1', // 5 uploads per minute
|
||||
'api:images:style-change' => '3,1', // 3 style changes per minute
|
||||
'api:admin:*' => '60,1', // 60 admin actions per minute
|
||||
```
|
||||
|
||||
## Security Monitoring
|
||||
|
||||
### Audit Logging
|
||||
|
||||
**Authentication Events**:
|
||||
- Login attempts (success/failure)
|
||||
- Password changes
|
||||
- 2FA setup/removal
|
||||
- Role changes
|
||||
- Admin actions
|
||||
|
||||
**Security Events**:
|
||||
- Suspicious login attempts
|
||||
- Multiple failed authentication attempts
|
||||
- Admin privilege escalation
|
||||
- API abuse detection
|
||||
|
||||
### Intrusion Detection
|
||||
|
||||
**Failed Login Monitoring**:
|
||||
- Track failed attempts by IP/user
|
||||
- Automatic account lockout after threshold
|
||||
- Admin notification for repeated failures
|
||||
|
||||
**Session Monitoring**:
|
||||
- Concurrent session detection
|
||||
- Session hijacking prevention
|
||||
- Unusual activity flagging
|
||||
|
||||
## Data Protection
|
||||
|
||||
### Password Storage
|
||||
- **Algorithm**: bcrypt with configurable cost
|
||||
- **Salt**: Automatic per-password salt generation
|
||||
- **Upgrade Path**: Automatic rehash on successful login
|
||||
|
||||
### Sensitive Data
|
||||
- **API Tokens**: Encrypted storage in database
|
||||
- **2FA Secrets**: Encrypted TOTP secrets
|
||||
- **Configuration**: Environment variables for sensitive settings
|
||||
|
||||
### Data Backup Security
|
||||
- Encrypted database backups
|
||||
- Secure backup storage locations
|
||||
- Access logging for backup operations
|
||||
|
||||
## Compliance Considerations
|
||||
|
||||
### GDPR Compliance
|
||||
|
||||
**Data Handling**:
|
||||
- User consent for data processing
|
||||
- Right to data portability
|
||||
- Right to be forgotten (account deletion)
|
||||
- Data processing activity logs
|
||||
|
||||
**Privacy Features**:
|
||||
- Granular privacy settings
|
||||
- Data export functionality
|
||||
- Secure account deletion process
|
||||
|
||||
### Security Standards
|
||||
|
||||
**OWASP Compliance**:
|
||||
- Protection against common web vulnerabilities
|
||||
- Secure coding practices
|
||||
- Regular security assessments
|
||||
|
||||
**Industry Standards**:
|
||||
- HTTPS enforcement
|
||||
- Secure cookie handling
|
||||
- Input validation and sanitization
|
||||
|
||||
## Future Security Enhancements
|
||||
|
||||
### Advanced Authentication
|
||||
|
||||
**OAuth Integration**:
|
||||
- Social login providers (Google, GitHub)
|
||||
- Single sign-on capabilities
|
||||
- Third-party application access
|
||||
|
||||
**Biometric Authentication**:
|
||||
- WebAuthn/FIDO2 support
|
||||
- Hardware security key support
|
||||
- Mobile authenticator integration
|
||||
|
||||
### Advanced Authorization
|
||||
|
||||
**Permission-Based Access**:
|
||||
- Granular permissions beyond roles
|
||||
- Resource-based permissions
|
||||
- Dynamic permission assignment
|
||||
|
||||
**Multi-Tenancy**:
|
||||
- Organization-based access control
|
||||
- Team-based permissions
|
||||
- Resource isolation
|
||||
|
||||
### Enhanced Security
|
||||
|
||||
**Advanced Monitoring**:
|
||||
- Real-time threat detection
|
||||
- Automated security responses
|
||||
- Security information and event management (SIEM)
|
||||
|
||||
**Zero-Trust Architecture**:
|
||||
- Continuous authentication
|
||||
- Micro-segmentation
|
||||
- Least privilege access
|
||||
|
||||
## Deployment Security
|
||||
|
||||
### Environment Security
|
||||
|
||||
**Development**:
|
||||
- Debug mode disabled
|
||||
- Verbose error reporting off
|
||||
- Test credentials and data
|
||||
|
||||
**Production**:
|
||||
- HTTPS enforcement
|
||||
- Secure headers enabled
|
||||
- Production credentials only
|
||||
|
||||
### Infrastructure Security
|
||||
|
||||
**Server Hardening**:
|
||||
- Minimal attack surface
|
||||
- Regular security updates
|
||||
- Firewall configuration
|
||||
|
||||
**Database Security**:
|
||||
- Encrypted database connections
|
||||
- Minimal privilege accounts
|
||||
- Regular backup testing
|
||||
|
||||
## Testing Security Features
|
||||
|
||||
### Authentication Tests
|
||||
|
||||
**Unit Tests**:
|
||||
- Password hashing verification
|
||||
- Token generation and validation
|
||||
- Role assignment and checking
|
||||
|
||||
**Integration Tests**:
|
||||
- Complete login/logout flow
|
||||
- API authentication middleware
|
||||
- Admin panel access control
|
||||
|
||||
**Security Tests**:
|
||||
- SQL injection prevention
|
||||
- XSS vulnerability testing
|
||||
- CSRF protection validation
|
||||
|
||||
## Troubleshooting Security
|
||||
|
||||
### Common Issues
|
||||
|
||||
**Token Expiration**:
|
||||
- Automatic token refresh mechanisms
|
||||
- Graceful handling of expired sessions
|
||||
- User notification and re-authentication
|
||||
|
||||
**Permission Errors**:
|
||||
- Clear error messages for users
|
||||
- Detailed logging for administrators
|
||||
- Permission debugging tools
|
||||
|
||||
**Session Issues**:
|
||||
- Session fixation protection
|
||||
- Secure session handling
|
||||
- Cross-site request forgery prevention
|
||||
137
prp/business-logic.md
Normal file
137
prp/business-logic.md
Normal file
@@ -0,0 +1,137 @@
|
||||
# Business Logic Specification
|
||||
|
||||
## Overview
|
||||
AI StyleGallery is a web application that enables users to transform their uploaded images using various AI-generated artistic styles through integration with external AI services.
|
||||
|
||||
## Core Business Requirements
|
||||
|
||||
### Primary User Journey
|
||||
1. **Image Upload**: Users can upload personal images to their gallery
|
||||
2. **Style Selection**: Users can browse and select from available AI artistic styles
|
||||
3. **AI Processing**: Selected images are sent to external AI services for style transformation
|
||||
4. **Result Management**: Users can view styled results and choose to keep (make permanent) or discard them
|
||||
5. **Gallery Management**: Users can view their collection of original and styled images
|
||||
|
||||
### Key Business Rules
|
||||
- **Image Privacy**: Images are private by default, users control visibility
|
||||
- **Temporary Processing**: AI-styled images are initially temporary until user confirms
|
||||
- **Style Availability**: Only enabled styles from active AI models are available to users
|
||||
- **Provider Flexibility**: Support multiple AI service providers (ComfyUI, RunwareAI, etc.)
|
||||
- **Real-time Progress**: Users receive real-time updates during AI processing
|
||||
|
||||
## Core Business Workflows
|
||||
|
||||
### 1. Image Style Transformation Workflow
|
||||
|
||||
#### Process Flow
|
||||
```
|
||||
User selects image → Opens context menu → Chooses "Change Style" →
|
||||
Browses style selector → Selects style → Initiates AI processing →
|
||||
Receives real-time progress updates → Views styled result →
|
||||
Chooses to keep or discard the styled image
|
||||
```
|
||||
|
||||
#### Technical Implementation
|
||||
- Frontend captures user selection via Vue.js components
|
||||
- Backend validates request and loads appropriate AI plugin
|
||||
- Plugin handles communication with external AI service
|
||||
- Real-time progress tracked via WebSocket (ComfyUI) or polling (other providers)
|
||||
- Styled image saved to storage and database record created
|
||||
- User notified of completion and can manage result
|
||||
|
||||
#### Success Criteria
|
||||
- Processing completes within reasonable time (typically 30-180 seconds)
|
||||
- User receives clear progress feedback during processing
|
||||
- Styled image maintains acceptable quality and resolution
|
||||
- User can easily keep or discard results
|
||||
|
||||
### 2. Gallery Management Workflow
|
||||
|
||||
#### Image Synchronization
|
||||
- Automatic sync between filesystem and database
|
||||
- Missing files removed from database
|
||||
- New files added to database with metadata
|
||||
- Maintains data consistency across application restarts
|
||||
|
||||
#### Visibility Rules
|
||||
- **Public Images**: Visible to all users
|
||||
- **Private Images**: Only visible to image owner
|
||||
- **Temporary Images**: Visible to owner during processing/review period
|
||||
- **Authenticated Users**: See all their own images
|
||||
- **Unauthenticated Users**: See only public images and their temporary results
|
||||
|
||||
### 3. Admin Management Workflow
|
||||
|
||||
#### Content Management
|
||||
- **Styles**: Create, edit, enable/disable artistic styles
|
||||
- **AI Models**: Configure available AI models and their parameters
|
||||
- **API Providers**: Set up connections to external AI services
|
||||
- **Users**: Manage user accounts and assign roles
|
||||
- **Settings**: Configure application-wide settings
|
||||
|
||||
#### Quality Assurance
|
||||
- Preview images for styles before publishing
|
||||
- Test connections to AI services
|
||||
- Monitor processing success rates
|
||||
- Manage storage and cleanup old temporary files
|
||||
|
||||
## Business Entities & Relationships
|
||||
|
||||
### Primary Entities
|
||||
- **Users**: Account holders with roles and preferences
|
||||
- **Images**: Uploaded files with metadata and processing status
|
||||
- **Styles**: AI artistic styles with prompts and parameters
|
||||
- **AI Models**: Specific AI models (e.g., Stable Diffusion variants)
|
||||
- **API Providers**: External AI services (ComfyUI, RunwareAI, etc.)
|
||||
|
||||
### Key Relationships
|
||||
- **User → Images**: One-to-many (users own multiple images)
|
||||
- **Image → Style**: Many-to-one (multiple images can use same style)
|
||||
- **Style → AI Model**: Many-to-one (multiple styles can use same model)
|
||||
- **AI Model → API Provider**: Many-to-one (multiple models can use same provider)
|
||||
- **Image → Original Image**: Self-referencing (styled images reference originals)
|
||||
|
||||
## Business Constraints & Validation Rules
|
||||
|
||||
### Data Validation
|
||||
- **Image Files**: Must be valid image formats (JPEG, PNG, WebP), max 10MB
|
||||
- **Style Prompts**: Required text describing desired artistic transformation
|
||||
- **API URLs**: Must be valid, accessible endpoints
|
||||
- **User Email**: Must be unique and valid format
|
||||
|
||||
### Business Rules
|
||||
- **Temporary Image Expiry**: Styled images expire if not kept within timeframe
|
||||
- **Storage Limits**: Maximum storage per user or globally
|
||||
- **API Rate Limits**: Respect external service limitations
|
||||
- **Processing Queue**: Handle multiple simultaneous requests appropriately
|
||||
|
||||
## Success Metrics
|
||||
|
||||
### User Experience
|
||||
- **Processing Speed**: Average time under 60 seconds for style transformation
|
||||
- **Success Rate**: 95%+ successful transformations
|
||||
- **User Retention**: Users return and process multiple images
|
||||
- **Feature Adoption**: High usage of style transformation features
|
||||
|
||||
### Technical Performance
|
||||
- **System Uptime**: 99.5%+ availability
|
||||
- **Response Times**: Gallery loads under 2 seconds
|
||||
- **Error Rates**: Under 1% processing failures
|
||||
- **Storage Efficiency**: Automatic cleanup of unused temporary files
|
||||
|
||||
## Future Enhancement Opportunities
|
||||
|
||||
### Potential Features
|
||||
- **Batch Processing**: Apply styles to multiple images simultaneously
|
||||
- **Style Chaining**: Apply multiple styles in sequence
|
||||
- **Custom Styles**: User-created style presets
|
||||
- **Social Features**: Share styled images with other users
|
||||
- **Advanced Filters**: Search and filter gallery by style, date, etc.
|
||||
- **Mobile Optimization**: Enhanced mobile experience
|
||||
- **API Access**: Third-party integrations via API
|
||||
|
||||
### Scalability Considerations
|
||||
- **Multiple AI Providers**: Load balancing across providers
|
||||
- **CDN Integration**: Faster image delivery globally
|
||||
- **Database Optimization**: Handle large numbers of images efficiently
|
||||
- **Caching Strategy**: Reduce redundant AI processing
|
||||
636
prp/configuration-settings.md
Normal file
636
prp/configuration-settings.md
Normal file
@@ -0,0 +1,636 @@
|
||||
# Configuration and Settings Specification
|
||||
|
||||
## Overview
|
||||
|
||||
Comprehensive configuration management system using Laravel's settings with database storage, environment variables, and runtime configuration for flexible application behavior.
|
||||
|
||||
## Configuration Architecture
|
||||
|
||||
### Configuration Sources (Priority Order)
|
||||
|
||||
1. **Runtime Settings** (Database) - User-configurable application behavior
|
||||
2. **Environment Variables** (`.env`) - Sensitive and environment-specific settings
|
||||
3. **Configuration Files** (`config/`) - Framework and package defaults
|
||||
4. **Hardcoded Defaults** - Fallback values in code
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Runtime Settings (Database) │
|
||||
│ • User-configurable behavior │
|
||||
│ • Admin-managed settings │
|
||||
│ • Feature flags and toggles │
|
||||
└─────────────────────┬───────────────────────────────────┘
|
||||
│ Priority 1 (Highest)
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Environment Variables (.env) │
|
||||
│ • Sensitive credentials │
|
||||
│ • Environment-specific configuration │
|
||||
│ • Deployment-specific settings │
|
||||
└─────────────────────┬───────────────────────────────────┘
|
||||
│ Priority 2
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Configuration Files (config/) │
|
||||
│ • Laravel framework settings │
|
||||
│ • Package configurations │
|
||||
│ • Default application behavior │
|
||||
└─────────────────────┬───────────────────────────────────┘
|
||||
│ Priority 3
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Hardcoded Defaults │
|
||||
│ • Fallback values in code │
|
||||
│ • Emergency defaults │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Settings Model
|
||||
|
||||
### Database Structure
|
||||
|
||||
**Table**: `settings`
|
||||
|
||||
**Schema**:
|
||||
```sql
|
||||
CREATE TABLE settings (
|
||||
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
||||
key VARCHAR(255) UNIQUE NOT NULL,
|
||||
value LONGTEXT NULL,
|
||||
created_at TIMESTAMP NULL,
|
||||
updated_at TIMESTAMP NULL
|
||||
);
|
||||
```
|
||||
|
||||
**Model**: `app/Models/Setting.php`
|
||||
|
||||
**Key Features**:
|
||||
- Unique constraint on `key` field
|
||||
- `value` stored as LONGTEXT for flexibility (JSON, arrays, large strings)
|
||||
- Automatic timestamps for audit trail
|
||||
|
||||
### Setting Access Patterns
|
||||
|
||||
**Simple Value Retrieval**:
|
||||
```php
|
||||
$value = Setting::where('key', 'app_name')->first()->value ?? 'Default Name';
|
||||
```
|
||||
|
||||
**Type-Safe Access**:
|
||||
```php
|
||||
// Boolean setting
|
||||
$enabled = Setting::getBoolean('feature_enabled', false);
|
||||
|
||||
// Integer setting
|
||||
$maxImages = Setting::getInteger('max_images_per_user', 100);
|
||||
|
||||
// JSON setting
|
||||
$parameters = Setting::getJson('api_parameters', []);
|
||||
```
|
||||
|
||||
## Configuration Categories
|
||||
|
||||
### 1. Application Settings
|
||||
|
||||
**Core Application Behavior**:
|
||||
|
||||
```php
|
||||
// Application Identity
|
||||
'app_name' => 'AI StyleGallery'
|
||||
'app_description' => 'Transform images with AI styles'
|
||||
'app_url' => 'https://your-domain.com'
|
||||
|
||||
// Gallery Behavior
|
||||
'gallery_heading' => 'Meine Bildergalerie'
|
||||
'default_style_id' => 1
|
||||
'new_image_timespan_minutes' => 60
|
||||
'image_refresh_interval' => 5 // seconds
|
||||
|
||||
// Upload Configuration
|
||||
'max_upload_size' => 10 // MB
|
||||
'allowed_image_types' => 'jpeg,jpg,png,webp'
|
||||
'auto_process_uploaded_images' => false
|
||||
|
||||
// UI Configuration
|
||||
'show_print_button' => true
|
||||
'default_theme' => 'light'
|
||||
'default_locale' => 'de'
|
||||
```
|
||||
|
||||
### 2. AI Processing Settings
|
||||
|
||||
**Processing Behavior**:
|
||||
```php
|
||||
// Timeout Configuration
|
||||
'comfyui_timeout' => 180 // seconds
|
||||
'runwareai_timeout' => 60 // seconds
|
||||
'max_processing_time' => 300 // seconds
|
||||
|
||||
// Retry Configuration
|
||||
'max_retry_attempts' => 3
|
||||
'retry_delay' => 1000000 // microseconds
|
||||
|
||||
// Queue Management
|
||||
'max_concurrent_processes' => 3
|
||||
'process_queue_enabled' => true
|
||||
|
||||
// Quality Settings
|
||||
'default_output_quality' => 95 // JPEG quality
|
||||
'enable_progressive_jpeg' => true
|
||||
```
|
||||
|
||||
### 3. Storage Configuration
|
||||
|
||||
**File Management**:
|
||||
```php
|
||||
// Storage Paths
|
||||
'upload_path' => 'uploads/'
|
||||
'style_preview_path' => 'style_previews/'
|
||||
'temp_path' => 'temp/'
|
||||
|
||||
// Cleanup Settings
|
||||
'auto_cleanup_temp_files' => true
|
||||
'temp_file_retention_hours' => 24
|
||||
'max_storage_per_user_gb' => 5
|
||||
|
||||
// CDN Configuration
|
||||
'cdn_enabled' => false
|
||||
'cdn_base_url' => 'https://cdn.your-domain.com'
|
||||
```
|
||||
|
||||
### 4. Notification Settings
|
||||
|
||||
**Communication Preferences**:
|
||||
```php
|
||||
// Email Settings
|
||||
'email_notifications_enabled' => true
|
||||
'admin_notification_email' => 'admin@your-domain.com'
|
||||
'notification_from_email' => 'noreply@your-domain.com'
|
||||
|
||||
// Processing Notifications
|
||||
'notify_on_processing_start' => false
|
||||
'notify_on_processing_complete' => true
|
||||
'notify_on_processing_error' => true
|
||||
|
||||
// Admin Alerts
|
||||
'alert_on_high_error_rate' => true
|
||||
'error_rate_threshold' => 10 // percentage
|
||||
```
|
||||
|
||||
### 5. Security Settings
|
||||
|
||||
**Security Configuration**:
|
||||
```php
|
||||
// Session Security
|
||||
'session_lifetime' => 120 // minutes
|
||||
'admin_session_lifetime' => 60 // minutes
|
||||
'enable_session_fixation_protection' => true
|
||||
|
||||
// Rate Limiting
|
||||
'login_attempts_per_minute' => 5
|
||||
'api_rate_limit_per_hour' => 1000
|
||||
|
||||
// Content Security
|
||||
'enable_csp' => true
|
||||
'csp_report_only' => false
|
||||
```
|
||||
|
||||
### 6. Performance Settings
|
||||
|
||||
**Performance Optimization**:
|
||||
```php
|
||||
// Caching
|
||||
'cache_enabled' => true
|
||||
'cache_ttl' => 3600 // seconds
|
||||
'style_cache_ttl' => 7200 // seconds
|
||||
|
||||
// Image Optimization
|
||||
'enable_lazy_loading' => true
|
||||
'thumbnail_size' => 300 // pixels
|
||||
'preview_quality' => 80 // JPEG quality
|
||||
|
||||
// Database Optimization
|
||||
'query_cache_enabled' => true
|
||||
'eager_loading_enabled' => true
|
||||
```
|
||||
|
||||
## Environment Configuration
|
||||
|
||||
### Sensitive Configuration (`.env`)
|
||||
|
||||
```bash
|
||||
# Application
|
||||
APP_NAME="AI StyleGallery"
|
||||
APP_ENV=production
|
||||
APP_KEY=base64:your-app-key-here
|
||||
APP_URL=https://your-domain.com
|
||||
|
||||
# Database
|
||||
DB_CONNECTION=sqlite
|
||||
DB_DATABASE=/path/to/database.sqlite
|
||||
|
||||
# Mail Configuration
|
||||
MAIL_MAILER=smtp
|
||||
MAIL_HOST=smtp.your-provider.com
|
||||
MAIL_PORT=587
|
||||
MAIL_USERNAME=your-email@domain.com
|
||||
MAIL_PASSWORD=your-app-password
|
||||
MAIL_ENCRYPTION=tls
|
||||
|
||||
# Redis (for caching)
|
||||
REDIS_HOST=127.0.0.1
|
||||
REDIS_PASSWORD=null
|
||||
REDIS_PORT=6379
|
||||
|
||||
# Broadcasting (for real-time features)
|
||||
BROADCAST_DRIVER=pusher
|
||||
PUSHER_APP_ID=your-pusher-id
|
||||
PUSHER_APP_KEY=your-pusher-key
|
||||
PUSHER_APP_SECRET=your-pusher-secret
|
||||
PUSHER_HOST=your-pusher-host
|
||||
PUSHER_PORT=443
|
||||
PUSHER_SCHEME=https
|
||||
|
||||
# AI Service Credentials
|
||||
COMFYUI_API_URL=https://your-comfyui-server.com
|
||||
COMFYUI_API_KEY=your-comfyui-key
|
||||
|
||||
RUNWAREAI_API_URL=https://api.runwareai.com
|
||||
RUNWAREAI_API_TOKEN=your-runwareai-token
|
||||
```
|
||||
|
||||
## Configuration Files
|
||||
|
||||
### Laravel Configuration (`config/`)
|
||||
|
||||
#### `config/app.php`
|
||||
```php
|
||||
'locale' => env('APP_LOCALE', 'de'),
|
||||
'timezone' => env('APP_TIMEZONE', 'Europe/Berlin'),
|
||||
'key' => env('APP_KEY'),
|
||||
'cipher' => 'AES-256-CBC',
|
||||
```
|
||||
|
||||
#### `config/filesystems.php`
|
||||
```php
|
||||
'public' => [
|
||||
'driver' => 'local',
|
||||
'root' => public_path('storage'),
|
||||
'url' => env('APP_URL').'/storage',
|
||||
'visibility' => 'public',
|
||||
],
|
||||
```
|
||||
|
||||
#### `config/filament.php`
|
||||
```php
|
||||
'brand' => [
|
||||
'name' => env('APP_NAME', 'AI StyleGallery'),
|
||||
'logo' => '/images/logo.png',
|
||||
],
|
||||
'auth' => [
|
||||
'guard' => 'web',
|
||||
'pages' => [
|
||||
'login' => \App\Filament\Pages\Login::route('/login'),
|
||||
],
|
||||
],
|
||||
```
|
||||
|
||||
## Runtime Configuration Management
|
||||
|
||||
### Setting Access Helpers
|
||||
|
||||
**Location**: `app/Services/SettingsService.php`
|
||||
|
||||
**Core Methods**:
|
||||
|
||||
#### `get(string $key, $default = null)`
|
||||
- Retrieves setting value with optional default
|
||||
- Automatic type casting for common types
|
||||
|
||||
#### `set(string $key, $value): void`
|
||||
- Stores or updates setting value
|
||||
- Handles type conversion and validation
|
||||
|
||||
#### `getBoolean(string $key, bool $default = false): bool`
|
||||
- Retrieves boolean setting with fallback
|
||||
|
||||
#### `getInteger(string $key, int $default = 0): int`
|
||||
- Retrieves integer setting with fallback
|
||||
|
||||
#### `getJson(string $key, $default = []): array`
|
||||
- Retrieves JSON setting as associative array
|
||||
|
||||
**Usage Examples**:
|
||||
```php
|
||||
// Application settings
|
||||
$appName = Settings::get('app_name', 'AI StyleGallery');
|
||||
$maxCopies = Settings::getInteger('max_print_copies', 10);
|
||||
$features = Settings::getJson('enabled_features', []);
|
||||
|
||||
// Feature flags
|
||||
$printEnabled = Settings::getBoolean('show_print_button', true);
|
||||
$notificationsEnabled = Settings::getBoolean('email_notifications_enabled', true);
|
||||
```
|
||||
|
||||
### Configuration Caching
|
||||
|
||||
**Cache Strategy**:
|
||||
- Settings cached in Redis/memory for performance
|
||||
- Automatic cache invalidation on setting changes
|
||||
- Separate TTL for different setting categories
|
||||
|
||||
**Implementation**:
|
||||
```php
|
||||
// Cache key pattern
|
||||
'settings:' . $key => $value
|
||||
|
||||
// Cache TTL by category
|
||||
'application_settings' => 3600, // 1 hour
|
||||
'ai_settings' => 1800, // 30 minutes
|
||||
'security_settings' => 7200, // 2 hours
|
||||
```
|
||||
|
||||
## Admin Configuration Interface
|
||||
|
||||
### Filament Settings Management
|
||||
|
||||
**Settings Resource**: `app/Filament/Resources/SettingResource.php`
|
||||
|
||||
**Features**:
|
||||
- **CRUD Interface**: Create, read, update, delete settings
|
||||
- **Type Validation**: Ensure setting values match expected types
|
||||
- **Bulk Operations**: Mass update related settings
|
||||
- **Import/Export**: Backup and restore configuration
|
||||
- **Validation**: Prevent invalid configuration values
|
||||
|
||||
**Setting Types**:
|
||||
- **Text**: Simple string values
|
||||
- **Number**: Integer and float values
|
||||
- **Boolean**: True/false toggles
|
||||
- **JSON**: Complex configuration objects
|
||||
- **Select**: Predefined option lists
|
||||
|
||||
### Settings Categories
|
||||
|
||||
**Organization**:
|
||||
- **General**: Application name, description, URLs
|
||||
- **Gallery**: Image handling, display options
|
||||
- **AI Processing**: Provider settings, timeouts, quality
|
||||
- **Storage**: File paths, cleanup, CDN settings
|
||||
- **Notifications**: Email, alerts, communication
|
||||
- **Security**: Authentication, rate limiting, privacy
|
||||
- **Performance**: Caching, optimization, limits
|
||||
|
||||
## Dynamic Configuration
|
||||
|
||||
### Feature Flags
|
||||
|
||||
**Implementation**:
|
||||
```php
|
||||
// Feature flag checking
|
||||
if (Settings::getBoolean('enable_batch_processing', false)) {
|
||||
// Enable batch processing features
|
||||
}
|
||||
|
||||
// Environment-specific features
|
||||
if (app()->environment('production')) {
|
||||
$features = Settings::getJson('production_features', []);
|
||||
} else {
|
||||
$features = Settings::getJson('development_features', []);
|
||||
}
|
||||
```
|
||||
|
||||
**Common Feature Flags**:
|
||||
- `enable_printing`: Show/hide print functionality
|
||||
- `enable_batch_processing`: Allow multiple image processing
|
||||
- `enable_social_features`: User sharing capabilities
|
||||
- `enable_advanced_styles`: Premium style options
|
||||
|
||||
### Environment-Based Configuration
|
||||
|
||||
**Automatic Configuration**:
|
||||
```php
|
||||
// Different settings per environment
|
||||
$environment = app()->environment();
|
||||
|
||||
switch ($environment) {
|
||||
case 'production':
|
||||
$settings = Settings::getJson('production_overrides', []);
|
||||
break;
|
||||
case 'staging':
|
||||
$settings = Settings::getJson('staging_overrides', []);
|
||||
break;
|
||||
default:
|
||||
$settings = Settings::getJson('development_overrides', []);
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration Validation
|
||||
|
||||
### Setting Validation Rules
|
||||
|
||||
**Validation Framework**:
|
||||
```php
|
||||
$rules = [
|
||||
'app_name' => 'required|string|max:255',
|
||||
'max_upload_size' => 'required|integer|min:1|max:100',
|
||||
'allowed_image_types' => 'required|string',
|
||||
'comfyui_timeout' => 'required|integer|min:30|max:600',
|
||||
'cdn_enabled' => 'boolean',
|
||||
'api_parameters' => 'nullable|json',
|
||||
];
|
||||
```
|
||||
|
||||
**Validation Implementation**:
|
||||
```php
|
||||
// Validate before saving
|
||||
$validator = Validator::make($settings, $rules);
|
||||
if ($validator->fails()) {
|
||||
throw new ValidationException($validator->errors());
|
||||
}
|
||||
|
||||
// Type conversion
|
||||
$sanitizedValue = match($setting->type) {
|
||||
'boolean' => (bool) $value,
|
||||
'integer' => (int) $value,
|
||||
'json' => json_decode($value, true),
|
||||
default => (string) $value,
|
||||
};
|
||||
```
|
||||
|
||||
## Configuration Migration
|
||||
|
||||
### Version Management
|
||||
|
||||
**Configuration Versions**:
|
||||
- Track configuration schema versions
|
||||
- Automatic migration of configuration values
|
||||
- Backup before major configuration changes
|
||||
|
||||
**Migration Example**:
|
||||
```php
|
||||
// Configuration migration for new version
|
||||
if ($currentVersion < 2.0) {
|
||||
// Migrate old 'upload_size' to 'max_upload_size'
|
||||
$oldValue = Settings::get('upload_size');
|
||||
if ($oldValue) {
|
||||
Settings::set('max_upload_size', $oldValue * 1024 * 1024); // Convert MB to bytes
|
||||
Settings::forget('upload_size');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Backup and Restore
|
||||
|
||||
**Configuration Backup**:
|
||||
```php
|
||||
// Export all settings
|
||||
$allSettings = Settings::all();
|
||||
$backup = [
|
||||
'version' => config('app.version'),
|
||||
'timestamp' => now()->toISOString(),
|
||||
'settings' => $allSettings->pluck('value', 'key')->toArray(),
|
||||
];
|
||||
|
||||
// Save to file
|
||||
Storage::put('config-backup-' . date('Y-m-d-H-i-s') . '.json', json_encode($backup));
|
||||
```
|
||||
|
||||
## Monitoring and Analytics
|
||||
|
||||
### Configuration Monitoring
|
||||
|
||||
**Change Tracking**:
|
||||
- Log all configuration changes
|
||||
- Track who made changes and when
|
||||
- Alert on critical configuration modifications
|
||||
|
||||
**Performance Impact**:
|
||||
- Monitor configuration load times
|
||||
- Track cache hit/miss ratios
|
||||
- Alert on configuration-related errors
|
||||
|
||||
### Analytics Integration
|
||||
|
||||
**Usage Analytics**:
|
||||
```php
|
||||
// Track feature usage
|
||||
if (Settings::getBoolean('analytics_enabled', false)) {
|
||||
Analytics::track('feature_used', [
|
||||
'feature' => 'style_application',
|
||||
'style_id' => $style->id,
|
||||
'user_id' => auth()->id(),
|
||||
]);
|
||||
}
|
||||
```
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Sensitive Configuration
|
||||
|
||||
**Encryption**:
|
||||
- Encrypt sensitive setting values in database
|
||||
- Use Laravel's encryption helpers for sensitive data
|
||||
- Separate encryption keys for different environments
|
||||
|
||||
**Access Control**:
|
||||
- Restrict sensitive settings to admin users only
|
||||
- Audit trail for sensitive configuration changes
|
||||
- Automatic masking in logs and exports
|
||||
|
||||
### Configuration Injection Prevention
|
||||
|
||||
**Input Sanitization**:
|
||||
- Validate all configuration inputs
|
||||
- Prevent code injection through configuration
|
||||
- Escape special characters in configuration values
|
||||
|
||||
## Deployment Configuration
|
||||
|
||||
### Environment-Specific Settings
|
||||
|
||||
**Deployment Pipeline**:
|
||||
```php
|
||||
// Production deployment
|
||||
Settings::set('app_environment', 'production');
|
||||
Settings::set('cdn_enabled', true);
|
||||
Settings::set('debug_mode', false);
|
||||
|
||||
// Development deployment
|
||||
Settings::set('app_environment', 'development');
|
||||
Settings::set('cdn_enabled', false);
|
||||
Settings::set('debug_mode', true);
|
||||
```
|
||||
|
||||
### Configuration Synchronization
|
||||
|
||||
**Multi-Server Setup**:
|
||||
- Synchronize configuration across web servers
|
||||
- Handle configuration updates without downtime
|
||||
- Validate configuration consistency
|
||||
|
||||
## Troubleshooting Configuration
|
||||
|
||||
### Common Issues
|
||||
|
||||
**Configuration Not Loading**:
|
||||
- Check database connectivity
|
||||
- Verify settings table exists
|
||||
- Validate setting key names
|
||||
|
||||
**Performance Issues**:
|
||||
- Monitor configuration cache hit rates
|
||||
- Check for configuration-related database queries
|
||||
- Optimize frequently accessed settings
|
||||
|
||||
**Type Mismatches**:
|
||||
- Ensure proper type casting in code
|
||||
- Validate setting types in admin interface
|
||||
- Handle legacy configuration gracefully
|
||||
|
||||
### Debug Tools
|
||||
|
||||
**Configuration Inspector**:
|
||||
```php
|
||||
// Development-only configuration debugging
|
||||
if (app()->environment('local')) {
|
||||
Route::get('/admin/config-debug', function () {
|
||||
return [
|
||||
'all_settings' => Settings::all(),
|
||||
'environment' => app()->environment(),
|
||||
'cached_settings' => Cache::get('settings:*'),
|
||||
];
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
## Future Configuration Enhancements
|
||||
|
||||
### Advanced Features
|
||||
|
||||
**Configuration Templates**:
|
||||
- Predefined configuration sets for different use cases
|
||||
- One-click configuration application
|
||||
- Configuration comparison and diff tools
|
||||
|
||||
**Dynamic Configuration**:
|
||||
- Real-time configuration updates
|
||||
- Hot-reloading of configuration changes
|
||||
- A/B testing for configuration options
|
||||
|
||||
**External Configuration**:
|
||||
- Integration with external configuration management systems
|
||||
- Cloud-based configuration storage
|
||||
- Configuration sharing across projects
|
||||
|
||||
### Configuration API
|
||||
|
||||
**RESTful Configuration Management**:
|
||||
- API endpoints for configuration management
|
||||
- Version control for configuration changes
|
||||
- Configuration validation via API
|
||||
|
||||
**Webhook Integration**:
|
||||
- Notify external systems of configuration changes
|
||||
- Trigger deployments on configuration updates
|
||||
- Integrate with monitoring and alerting systems
|
||||
340
prp/data-models.md
Normal file
340
prp/data-models.md
Normal file
@@ -0,0 +1,340 @@
|
||||
# Data Models Specification
|
||||
|
||||
## Entity Relationship Diagram
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ User │
|
||||
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
|
||||
│ │ Role │ │ Setting │ │ Image │ │
|
||||
│ │ • id │ │ • id │ │ • id │ │
|
||||
│ │ • name │ │ • key │ │ • uuid │ │
|
||||
│ │ • timestamps │ │ • value │ │ • path │ │
|
||||
│ └─────────────────┘ │ • timestamps │ │ • is_temp │ │
|
||||
│ │ 1 │ └─────────────────┘ │ • is_public │ │
|
||||
│ ▼ │ │ 1 │ • timestamps │ │
|
||||
│ ┌─────────────────┐ │ ▼ └─────────────────┘ │
|
||||
│ │ • id │ │ ┌─────────────────┐ │
|
||||
│ │ • name │ │ │ ApiProvider │ │
|
||||
│ │ • email │ │ │ • id │ │
|
||||
│ │ • password │ │ │ • name │ │
|
||||
│ │ • role_id │ │ │ • api_url │ │
|
||||
│ │ • timestamps │ │ │ • username │ │
|
||||
│ │ • 2FA fields │ │ │ • password │ │
|
||||
│ └─────────────────┘ │ │ • token │ │
|
||||
│ │ │ │ • plugin │ │
|
||||
│ ▼ │ │ • enabled │ │
|
||||
│ ┌─────────────────┐ │ │ • timestamps │ │
|
||||
│ │ Style │◄─┘ └─────────────────┘ │
|
||||
│ │ • id │ │ 1 │
|
||||
│ │ • title │ ▼ │
|
||||
│ │ • prompt │ ┌─────────────────┐ │
|
||||
│ │ • description │ │ AiModel │ │
|
||||
│ │ • preview_img │ │ • id │ │
|
||||
│ │ • parameters │ │ • name │ │
|
||||
│ │ • ai_model_id │ │ • model_id │ │
|
||||
│ │ • enabled │ │ • model_type │ │
|
||||
│ │ • sort_order │ │ • api_provider │ │
|
||||
│ │ • timestamps │ │ • parameters │ │
|
||||
│ └─────────────────┘ │ • enabled │ │
|
||||
│ │ │ • timestamps │ │
|
||||
│ ▼ │ └─────────────────┘ │
|
||||
│ ┌─────────────────┐ │ │
|
||||
│ │ Original │◄┘ │
|
||||
│ │ Image │ │
|
||||
│ └─────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Model Specifications
|
||||
|
||||
### 1. User Model
|
||||
|
||||
**Purpose**: Represents authenticated users of the application
|
||||
|
||||
**Table**: `users`
|
||||
|
||||
**Attributes**:
|
||||
```php
|
||||
id: bigint unsigned auto_increment primary key
|
||||
name: varchar(255) // User's display name
|
||||
email: varchar(255) unique // Unique email address
|
||||
password: varchar(255) // Hashed password
|
||||
role_id: bigint unsigned nullable // Foreign key to roles table
|
||||
email_notifications_enabled: tinyint(1) default(1) // Email notification preference
|
||||
theme_preference: varchar(255) default('light') // UI theme preference
|
||||
locale: varchar(255) default('en') // Language preference
|
||||
two_factor_secret: text nullable // 2FA secret key
|
||||
two_factor_recovery_codes: text nullable // 2FA backup codes
|
||||
two_factor_confirmed_at: timestamp nullable // 2FA confirmation timestamp
|
||||
created_at: timestamp nullable
|
||||
updated_at: timestamp nullable
|
||||
```
|
||||
|
||||
**Relationships**:
|
||||
- **BelongsTo**: Role (one user has one role)
|
||||
- **HasMany**: Images (one user can have many images)
|
||||
|
||||
**Business Rules**:
|
||||
- Email must be unique across all users
|
||||
- Password must be hashed using secure algorithm
|
||||
- Role determines permissions and access levels
|
||||
- 2FA fields are optional but provide enhanced security
|
||||
|
||||
---
|
||||
|
||||
### 2. Role Model
|
||||
|
||||
**Purpose**: Defines user roles for access control
|
||||
|
||||
**Table**: `roles`
|
||||
|
||||
**Attributes**:
|
||||
```php
|
||||
id: bigint unsigned auto_increment primary key
|
||||
name: varchar(255) unique // Role name (e.g., 'admin', 'user')
|
||||
created_at: timestamp nullable
|
||||
updated_at: timestamp nullable
|
||||
```
|
||||
|
||||
**Relationships**:
|
||||
- **HasMany**: Users (one role can have many users)
|
||||
|
||||
**Business Rules**:
|
||||
- Role names must be unique
|
||||
- Predefined roles: 'admin', 'user'
|
||||
- Used by Filament for access control
|
||||
|
||||
---
|
||||
|
||||
### 3. Image Model
|
||||
|
||||
**Purpose**: Stores metadata for uploaded and AI-generated images
|
||||
|
||||
**Table**: `images`
|
||||
|
||||
**Attributes**:
|
||||
```php
|
||||
id: bigint unsigned auto_increment primary key
|
||||
uuid: char(36) unique nullable // Unique identifier for tracking
|
||||
path: varchar(255) // File path relative to storage disk
|
||||
original_image_id: bigint unsigned nullable // FK to original image (for styled images)
|
||||
style_id: bigint unsigned nullable // FK to applied style
|
||||
is_temp: tinyint(1) default(0) // True for temporary styled images
|
||||
is_public: tinyint(1) default(1) // True for publicly visible images
|
||||
comfyui_prompt_id: varchar(255) nullable // Tracking ID from ComfyUI
|
||||
created_at: timestamp nullable
|
||||
updated_at: timestamp nullable
|
||||
```
|
||||
|
||||
**Relationships**:
|
||||
- **BelongsTo**: Style (many images can use one style)
|
||||
- **BelongsTo**: Original Image (self-referencing, styled images reference originals)
|
||||
- **HasMany**: Styled Images (self-referencing, original images have many styled versions)
|
||||
|
||||
**Business Rules**:
|
||||
- UUID is generated for tracking and external references
|
||||
- Original images have `original_image_id` = null
|
||||
- Styled images reference original via `original_image_id`
|
||||
- Temporary images (`is_temp = true`) are pending user decision
|
||||
- Public images (`is_public = true`) are visible to all users
|
||||
- ComfyUI prompt ID tracks processing jobs
|
||||
|
||||
---
|
||||
|
||||
### 4. Style Model
|
||||
|
||||
**Purpose**: Defines AI artistic styles available for image transformation
|
||||
|
||||
**Table**: `styles`
|
||||
|
||||
**Attributes**:
|
||||
```php
|
||||
id: bigint unsigned auto_increment primary key
|
||||
title: varchar(255) // Display name of the style
|
||||
prompt: longtext // AI prompt describing the style
|
||||
description: longtext // Human-readable description
|
||||
preview_image: varchar(255) // Path to style preview image
|
||||
parameters: json nullable // Additional AI parameters (cast to array)
|
||||
ai_model_id: bigint unsigned // FK to associated AI model
|
||||
enabled: tinyint(1) default(1) // Whether style is active
|
||||
sort_order: integer default(0) // Display order in UI
|
||||
created_at: timestamp nullable
|
||||
updated_at: timestamp nullable
|
||||
```
|
||||
|
||||
**Relationships**:
|
||||
- **BelongsTo**: AiModel (many styles can use one AI model)
|
||||
- **HasMany**: Images (one style can be applied to many images)
|
||||
|
||||
**Business Rules**:
|
||||
- Only enabled styles are available to users
|
||||
- Preview images help users choose appropriate styles
|
||||
- Parameters are JSON and merged with AI model parameters
|
||||
- Sort order controls display sequence in style selector
|
||||
|
||||
---
|
||||
|
||||
### 5. AiModel Model
|
||||
|
||||
**Purpose**: Represents specific AI models available through providers
|
||||
|
||||
**Table**: `ai_models`
|
||||
|
||||
**Attributes**:
|
||||
```php
|
||||
id: bigint unsigned auto_increment primary key
|
||||
name: varchar(255) // Human-readable model name
|
||||
model_id: varchar(255) // Identifier used by AI service
|
||||
model_type: varchar(255) nullable // Type/category (e.g., 'Stable Diffusion')
|
||||
parameters: json nullable // Default parameters (cast to array)
|
||||
api_provider_id: bigint unsigned nullable // FK to primary API provider
|
||||
enabled: tinyint(1) default(1) // Whether model is active
|
||||
created_at: timestamp nullable
|
||||
updated_at: timestamp nullable
|
||||
```
|
||||
|
||||
**Relationships**:
|
||||
- **BelongsTo**: ApiProvider (many models can use one provider)
|
||||
- **HasMany**: Styles (one model can have many styles)
|
||||
|
||||
**Business Rules**:
|
||||
- Model ID must match identifier expected by AI service
|
||||
- Only enabled models are available for new styles
|
||||
- Parameters provide defaults, merged with style parameters
|
||||
- Primary API provider handles communication for this model
|
||||
|
||||
---
|
||||
|
||||
### 6. ApiProvider Model
|
||||
|
||||
**Purpose**: Configures connections to external AI services
|
||||
|
||||
**Table**: `api_providers`
|
||||
|
||||
**Attributes**:
|
||||
```php
|
||||
id: bigint unsigned auto_increment primary key
|
||||
name: varchar(255) // Provider name (e.g., 'ComfyUI Production')
|
||||
api_url: varchar(255) // Base URL of AI service
|
||||
username: varchar(255) nullable // Authentication username
|
||||
password: varchar(255) nullable // Authentication password
|
||||
token: varchar(255) nullable // API token/key
|
||||
plugin: varchar(255) // Plugin identifier (e.g., 'comfyui', 'runwareai')
|
||||
enabled: tinyint(1) default(1) // Whether provider is active
|
||||
created_at: timestamp nullable
|
||||
updated_at: timestamp nullable
|
||||
```
|
||||
|
||||
**Relationships**:
|
||||
- **HasMany**: AiModels (one provider can serve many models)
|
||||
- **HasMany**: Styles (indirectly through AI models)
|
||||
|
||||
**Business Rules**:
|
||||
- Plugin field determines which adapter to use
|
||||
- Only enabled providers are available for processing
|
||||
- Authentication credentials are encrypted/stored securely
|
||||
- API URL must be valid and accessible
|
||||
|
||||
---
|
||||
|
||||
### 7. Setting Model
|
||||
|
||||
**Purpose**: Stores application-wide configuration settings
|
||||
|
||||
**Table**: `settings`
|
||||
|
||||
**Attributes**:
|
||||
```php
|
||||
id: bigint unsigned auto_increment primary key
|
||||
key: varchar(255) unique // Setting identifier
|
||||
value: longtext nullable // Setting value (can be JSON)
|
||||
created_at: timestamp nullable
|
||||
updated_at: timestamp nullable
|
||||
```
|
||||
|
||||
**Relationships**: None (standalone configuration storage)
|
||||
|
||||
**Business Rules**:
|
||||
- Keys must be unique across application
|
||||
- Values can be simple strings or complex JSON
|
||||
- Used for various configuration needs throughout app
|
||||
|
||||
## Data Integrity Constraints
|
||||
|
||||
### Foreign Key Relationships
|
||||
- `users.role_id` → `roles.id` (nullable, defaults to user role)
|
||||
- `images.original_image_id` → `images.id` (nullable, self-referencing)
|
||||
- `images.style_id` → `styles.id` (nullable)
|
||||
- `styles.ai_model_id` → `ai_models.id` (required)
|
||||
- `ai_models.api_provider_id` → `api_providers.id` (nullable)
|
||||
|
||||
### Unique Constraints
|
||||
- `users.email` (unique)
|
||||
- `roles.name` (unique)
|
||||
- `images.uuid` (unique, nullable)
|
||||
- `settings.key` (unique)
|
||||
|
||||
### Check Constraints
|
||||
- `images.is_temp` ∈ {0, 1}
|
||||
- `images.is_public` ∈ {0, 1}
|
||||
- `styles.enabled` ∈ {0, 1}
|
||||
- `ai_models.enabled` ∈ {0, 1}
|
||||
- `api_providers.enabled` ∈ {0, 1}
|
||||
|
||||
## Data Types & Casting
|
||||
|
||||
### Automatic Casting
|
||||
- **Boolean Fields**: `enabled`, `is_temp`, `is_public` → boolean
|
||||
- **JSON Fields**: `parameters` (in styles, ai_models) → array
|
||||
- **Timestamps**: `created_at`, `updated_at` → datetime
|
||||
|
||||
### File Paths
|
||||
- All image paths are relative to storage disk
|
||||
- Preview images stored in `storage/app/public/style_previews/`
|
||||
- Uploaded images stored in `storage/app/public/uploads/`
|
||||
|
||||
## Business Logic Implementation
|
||||
|
||||
### Image Path Resolution
|
||||
- **Storage Disk**: Uses 'public' disk configuration
|
||||
- **URL Generation**: `asset('storage/' . $image->path)`
|
||||
- **File Location**: `public_path('storage/' . $image->path)`
|
||||
|
||||
### Parameter Merging
|
||||
- **Style Parameters**: Override AI model parameters
|
||||
- **Merge Strategy**: `array_replace_recursive($modelParams, $styleParams)`
|
||||
- **Placeholder Replacement**: `__PROMPT__`, `__FILENAME__`, `__MODEL_ID__`
|
||||
|
||||
### UUID Usage
|
||||
- **Image Tracking**: Unique identifier for external references
|
||||
- **Generation**: Laravel's `HasUuids` trait or manual generation
|
||||
- **Uniqueness**: Enforced by unique database constraint
|
||||
|
||||
## Data Access Patterns
|
||||
|
||||
### Common Queries
|
||||
- **User Images**: `$user->images()` - all images for a user
|
||||
- **Public Images**: `Image::where('is_public', true)`
|
||||
- **Active Styles**: `Style::where('enabled', true)->with('aiModel')`
|
||||
- **Enabled Models**: `AiModel::where('enabled', true)->with('primaryApiProvider')`
|
||||
|
||||
### Query Optimization
|
||||
- **Eager Loading**: Styles load AI models and providers
|
||||
- **Soft Deletes**: Not implemented (permanent deletion)
|
||||
- **Indexing**: Consider indexes on frequently queried fields
|
||||
|
||||
## Migration Strategy
|
||||
|
||||
### Future Enhancements
|
||||
- **Image Metadata**: EXIF data, dimensions, file size
|
||||
- **Processing History**: Track all transformations applied to images
|
||||
- **User Preferences**: Default styles, notification settings
|
||||
- **Batch Operations**: Multiple image processing, bulk style application
|
||||
- **Tagging System**: Categorize images with custom tags
|
||||
- **Sharing Features**: Public galleries, social features
|
||||
|
||||
### Schema Evolution
|
||||
- **Version Control**: Each model change requires migration
|
||||
- **Backward Compatibility**: Maintain existing data integrity
|
||||
- **Testing**: Validate schema changes against business rules
|
||||
1164
prp/deployment-requirements.md
Normal file
1164
prp/deployment-requirements.md
Normal file
File diff suppressed because it is too large
Load Diff
525
prp/frontend-components.md
Normal file
525
prp/frontend-components.md
Normal file
@@ -0,0 +1,525 @@
|
||||
# Frontend Components Specification
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
Single Page Application built with Vue.js 3 and Inertia.js, providing a responsive image gallery interface with real-time AI processing capabilities.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **Framework**: Vue.js 3.5.18 with Composition API
|
||||
- **Routing**: Inertia.js 1.3.0 (Laravel backend integration)
|
||||
- **Build Tool**: Vite 5.4.19
|
||||
- **Styling**: Tailwind CSS 3.4.17
|
||||
- **HTTP Client**: Axios 1.11.0
|
||||
- **State Management**: Vue 3 Composition API (ref, computed, reactive)
|
||||
- **Real-time**: WebSocket for ComfyUI progress, polling for other providers
|
||||
|
||||
## Component Hierarchy
|
||||
|
||||
```
|
||||
App.vue (Root)
|
||||
└── Home.vue (Main Gallery Page)
|
||||
├── GalleryGrid.vue (Image Grid Display)
|
||||
├── Navigation.vue (Pagination Controls)
|
||||
├── ImageContextMenu.vue (Image Actions Overlay)
|
||||
│ └── StyleSelector.vue (Style Selection Interface)
|
||||
├── StyledImageDisplay.vue (Result Preview)
|
||||
├── LoadingSpinner.vue (Progress Indicator)
|
||||
└── PrintQuantityModal.vue (Print Options)
|
||||
```
|
||||
|
||||
## Component Specifications
|
||||
|
||||
### 1. Home.vue (Main Gallery Page)
|
||||
|
||||
**Purpose**: Primary interface displaying user's image gallery with pagination and overlay management
|
||||
|
||||
**Location**: `resources/js/Pages/Home.vue`
|
||||
|
||||
**Props**:
|
||||
```typescript
|
||||
interface Props {
|
||||
galleryHeading: string // Page title
|
||||
translations: object // Internationalization strings
|
||||
}
|
||||
```
|
||||
|
||||
**State Management**:
|
||||
```typescript
|
||||
const images = ref([]) // Gallery images array
|
||||
const currentPage = ref(1) // Current pagination page
|
||||
const currentOverlayComponent = ref(null) // Active overlay ('contextMenu', 'styleSelector', etc.)
|
||||
const contextMenuPosition = ref({ x: 0, y: 0 }) // Context menu coordinates
|
||||
const selectedImage = ref(null) // Currently selected image
|
||||
const styledImage = ref(null) // Newly processed styled image
|
||||
const processingProgress = ref(0) // AI processing progress (0-100)
|
||||
const errorMessage = ref(null) // Error display state
|
||||
const isLoading = ref(false) // Global loading state
|
||||
const currentTheme = ref('light') // UI theme preference
|
||||
```
|
||||
|
||||
**Key Methods**:
|
||||
|
||||
#### `fetchImages()`
|
||||
- **Purpose**: Retrieves and synchronizes gallery images
|
||||
- **Implementation**: Axios GET to `/api/images`
|
||||
- **Auto-refresh**: Polls every 5 seconds (configurable interval)
|
||||
- **Error Handling**: Displays user-friendly error messages
|
||||
|
||||
#### `applyStyle(style, imageId)`
|
||||
- **Purpose**: Initiates AI style transformation process
|
||||
- **Flow**:
|
||||
1. Sends style change request to backend
|
||||
2. Receives `prompt_id` and `plugin` type
|
||||
3. Establishes appropriate progress monitoring (WebSocket vs Polling)
|
||||
4. Updates UI with real-time progress
|
||||
5. Displays result when complete
|
||||
|
||||
#### `showContextMenu(image, event)`
|
||||
- **Purpose**: Displays context menu for selected image
|
||||
- **Positioning**: Calculates optimal position based on click coordinates
|
||||
- **Responsive**: Adapts to screen boundaries
|
||||
|
||||
**UI Structure**:
|
||||
- **Header**: Title and theme toggle
|
||||
- **Gallery**: Grid layout with pagination
|
||||
- **Overlays**: Conditional rendering based on `currentOverlayComponent`
|
||||
- **Notifications**: Error messages with auto-dismiss
|
||||
|
||||
**Styling**:
|
||||
- **Layout**: Flexbox-based responsive design
|
||||
- **Theme**: Light/dark mode support with CSS variables
|
||||
- **Responsive**: Mobile-first approach with touch gestures
|
||||
|
||||
---
|
||||
|
||||
### 2. GalleryGrid.vue
|
||||
|
||||
**Purpose**: Displays images in responsive grid layout with interaction handling
|
||||
|
||||
**Props**:
|
||||
```typescript
|
||||
interface Props {
|
||||
images: Image[] // Array of image objects to display
|
||||
translations: object // UI text translations
|
||||
}
|
||||
```
|
||||
|
||||
**Events**:
|
||||
```typescript
|
||||
interface Events {
|
||||
imageTapped: [image: Image, event: MouseEvent] // Image selection
|
||||
}
|
||||
```
|
||||
|
||||
**Features**:
|
||||
- **Responsive Grid**: Adaptive columns based on screen size
|
||||
- **Lazy Loading**: Images load as they enter viewport
|
||||
- **Touch Support**: Tap gestures for mobile devices
|
||||
- **Accessibility**: Proper alt text and keyboard navigation
|
||||
|
||||
**Image Object Structure**:
|
||||
```typescript
|
||||
interface Image {
|
||||
image_id: number
|
||||
path: string // URL to image file
|
||||
name: string // Filename
|
||||
is_temp: boolean // Temporary styled image flag
|
||||
is_public: boolean // Visibility status
|
||||
is_new: boolean // Recently uploaded flag
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. ImageContextMenu.vue
|
||||
|
||||
**Purpose**: Contextual action menu displayed when user taps/clicks an image
|
||||
|
||||
**Location**: `resources/js/Components/ImageContextMenu.vue`
|
||||
|
||||
**Props**:
|
||||
```typescript
|
||||
interface Props {
|
||||
position: { x: number, y: number } // Menu position coordinates
|
||||
image: Image // Selected image object
|
||||
}
|
||||
```
|
||||
|
||||
**Events**:
|
||||
```typescript
|
||||
interface Events {
|
||||
close: [] // Close menu
|
||||
print: [image: Image] // Print image
|
||||
changeStyle: [] // Open style selector
|
||||
styleSelected: [style: Style, imageId: number] // Style applied
|
||||
}
|
||||
```
|
||||
|
||||
**Layout Structure**:
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ [X] Close [Image Preview] │
|
||||
│ │
|
||||
│ ┌─────────────────────────────────────────────┐ │
|
||||
│ │ ▲ │ │
|
||||
│ │ Image Preview │ │
|
||||
│ │ ▼ │ │
|
||||
│ │ (70% width) │ │
|
||||
│ └─────────────────────────────────────────────┘ │
|
||||
│ ┌─────────────────────────────────────────────┐ │
|
||||
│ │ [Print] [Change Style] [Close] │ │
|
||||
│ │ (30% width) │ │
|
||||
│ └─────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Features**:
|
||||
- **Dynamic Positioning**: Calculates optimal position to stay within viewport
|
||||
- **Backdrop Click**: Closes menu when clicking outside
|
||||
- **Nested Components**: Embeds StyleSelector when needed
|
||||
- **Responsive**: Adapts layout for different screen sizes
|
||||
|
||||
**Styling**:
|
||||
- **Overlay**: Semi-transparent backdrop with blur effect
|
||||
- **Menu**: Elevated card with shadow and rounded corners
|
||||
- **Responsive**: Touch-friendly button sizes on mobile
|
||||
|
||||
---
|
||||
|
||||
### 4. StyleSelector.vue
|
||||
|
||||
**Purpose**: Allows users to browse and select AI styles for image transformation
|
||||
|
||||
**Props**:
|
||||
```typescript
|
||||
interface Props {
|
||||
image_id: number // Target image for styling
|
||||
}
|
||||
```
|
||||
|
||||
**Events**:
|
||||
```typescript
|
||||
interface Events {
|
||||
styleSelected: [style: Style, imageId: number] // Style chosen
|
||||
back: [] // Return to context menu
|
||||
close: [] // Close selector
|
||||
}
|
||||
```
|
||||
|
||||
**State Management**:
|
||||
```typescript
|
||||
const styles = ref([]) // Available styles array
|
||||
// Lazy loading management
|
||||
const observer = ref(null) // IntersectionObserver instance
|
||||
```
|
||||
|
||||
**Key Methods**:
|
||||
|
||||
#### `fetchStyles()`
|
||||
- **Purpose**: Retrieves available styles from API
|
||||
- **Implementation**: Axios GET to `/api/styles`
|
||||
- **Filtering**: Only enabled styles returned
|
||||
- **Lazy Loading**: Sets up IntersectionObserver for preview images
|
||||
|
||||
#### `selectStyle(style)`
|
||||
- **Purpose**: Confirms style selection and triggers processing
|
||||
- **Implementation**: Emits `styleSelected` event with style and image ID
|
||||
|
||||
**UI Structure**:
|
||||
```
|
||||
┌─────────────────────────────────────────────────┐
|
||||
│ [<] Back Available Styles │
|
||||
├─────────────────────────────────────────────────┤
|
||||
│ ┌─────────────────────────────────────────────┐ │
|
||||
│ │ [Preview] Style Name [Description] │ │
|
||||
│ │ [Preview] Another Style [Description] │ │
|
||||
│ │ [Preview] Third Style [Description] │ │
|
||||
│ └─────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Features**:
|
||||
- **Preview Images**: Thumbnail images for each style
|
||||
- **Lazy Loading**: Images load when entering viewport
|
||||
- **Back Navigation**: Return to previous context menu
|
||||
- **Responsive**: Scrollable list on smaller screens
|
||||
|
||||
**Style Object Structure**:
|
||||
```typescript
|
||||
interface Style {
|
||||
id: number
|
||||
title: string // Display name
|
||||
description: string // Human-readable description
|
||||
preview_image: string // Thumbnail image path
|
||||
enabled: boolean // Availability status
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5. LoadingSpinner.vue
|
||||
|
||||
**Purpose**: Visual indicator for AI processing progress
|
||||
|
||||
**Props**:
|
||||
```typescript
|
||||
interface Props {
|
||||
progress: number // Progress percentage (0-100)
|
||||
}
|
||||
```
|
||||
|
||||
**Features**:
|
||||
- **Progress Bar**: Visual representation of completion status
|
||||
- **Animated**: Smooth progress updates
|
||||
- **Responsive**: Adapts to different screen sizes
|
||||
- **Accessible**: Screen reader compatible
|
||||
|
||||
**Styling**:
|
||||
- **Modern Design**: Gradient progress bar with smooth animations
|
||||
- **Centered**: Overlay positioning for full-screen processes
|
||||
- **Theme Aware**: Adapts to light/dark theme
|
||||
|
||||
---
|
||||
|
||||
### 6. StyledImageDisplay.vue
|
||||
|
||||
**Purpose**: Preview and management interface for completed AI-styled images
|
||||
|
||||
**Props**:
|
||||
```typescript
|
||||
interface Props {
|
||||
image: Image // Styled image object
|
||||
}
|
||||
```
|
||||
|
||||
**Events**:
|
||||
```typescript
|
||||
interface Events {
|
||||
keep: [image: Image] // Keep styled image permanently
|
||||
delete: [image: Image] // Discard styled image
|
||||
}
|
||||
```
|
||||
|
||||
**Features**:
|
||||
- **Full Preview**: Large display of styled result
|
||||
- **Action Buttons**: Keep/Discard options
|
||||
- **Responsive**: Mobile-optimized layout
|
||||
- **Loading State**: Handles image loading gracefully
|
||||
|
||||
---
|
||||
|
||||
### 7. Navigation.vue
|
||||
|
||||
**Purpose**: Pagination controls for gallery navigation
|
||||
|
||||
**Props**:
|
||||
```typescript
|
||||
interface Props {
|
||||
currentPage: number // Current active page
|
||||
totalPages: number // Total available pages
|
||||
}
|
||||
```
|
||||
|
||||
**Events**:
|
||||
```typescript
|
||||
interface Events {
|
||||
prevPage: [] // Navigate to previous page
|
||||
nextPage: [] // Navigate to next page
|
||||
}
|
||||
```
|
||||
|
||||
**Features**:
|
||||
- **Page Numbers**: Visual page indicators
|
||||
- **Touch Gestures**: Swipe left/right for page navigation
|
||||
- **Responsive**: Touch-friendly on mobile devices
|
||||
- **Keyboard**: Arrow key navigation support
|
||||
|
||||
---
|
||||
|
||||
### 8. PrintQuantityModal.vue
|
||||
|
||||
**Purpose**: Print options interface for physical image printing
|
||||
|
||||
**Props**:
|
||||
```typescript
|
||||
interface Props {
|
||||
maxCopies: number // Maximum allowed copies
|
||||
}
|
||||
```
|
||||
|
||||
**Events**:
|
||||
```typescript
|
||||
interface Events {
|
||||
close: [] // Close modal
|
||||
printConfirmed: [quantity: number] // Print confirmed
|
||||
}
|
||||
```
|
||||
|
||||
**Features**:
|
||||
- **Quantity Selection**: Number input for copy count
|
||||
- **Validation**: Enforces maximum copy limits
|
||||
- **Confirmation**: Clear confirmation before printing
|
||||
- **Responsive**: Modal overlay with backdrop
|
||||
|
||||
## Component Interactions
|
||||
|
||||
### Image Selection Flow
|
||||
```
|
||||
User taps image → GalleryGrid emits imageTapped →
|
||||
Home.vue shows contextMenu at tap position →
|
||||
ImageContextMenu displays with image preview and options
|
||||
```
|
||||
|
||||
### Style Application Flow
|
||||
```
|
||||
User selects "Change Style" → ImageContextMenu shows StyleSelector →
|
||||
User browses and selects style → StyleSelector emits styleSelected →
|
||||
Home.vue initiates AI processing with progress monitoring →
|
||||
Real-time updates via WebSocket/Polling → Result displayed →
|
||||
User can keep or discard styled image
|
||||
```
|
||||
|
||||
### Progress Monitoring
|
||||
|
||||
#### ComfyUI (WebSocket)
|
||||
```typescript
|
||||
// Establish WebSocket connection
|
||||
const wsUrl = `ws://${comfyUiHost}/ws`
|
||||
const ws = new WebSocket(wsUrl)
|
||||
|
||||
// Monitor progress messages
|
||||
ws.onmessage = (event) => {
|
||||
const message = JSON.parse(event.data)
|
||||
if (message.type === 'progress' && message.data.prompt_id === currentPromptId) {
|
||||
processingProgress.value = (message.data.value / message.data.max) * 100
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Other Providers (Polling)
|
||||
```typescript
|
||||
// Poll for completion every 2 seconds
|
||||
const pollForResult = () => {
|
||||
axios.get(`/api/images/fetch-styled/${promptId}`)
|
||||
.then(response => {
|
||||
// Success - display result
|
||||
styledImage.value = response.data.styled_image
|
||||
currentOverlayComponent.value = 'styledImageDisplay'
|
||||
})
|
||||
.catch(error => {
|
||||
if (error.response?.status === 404) {
|
||||
// Still processing - continue polling
|
||||
setTimeout(pollForResult, 2000)
|
||||
} else {
|
||||
// Error - display message
|
||||
showError(error.response?.data?.error)
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
## State Management Patterns
|
||||
|
||||
### Overlay Management
|
||||
- Single active overlay at a time
|
||||
- Stack-based navigation (context menu → style selector → back)
|
||||
- Proper cleanup on component unmount
|
||||
|
||||
### Error Handling
|
||||
- Centralized error display with auto-dismiss
|
||||
- User-friendly error messages
|
||||
- Graceful degradation for failed operations
|
||||
|
||||
### Theme Management
|
||||
- Persistent theme preference in localStorage
|
||||
- CSS variable-based theming
|
||||
- System preference detection
|
||||
|
||||
## Responsive Design
|
||||
|
||||
### Breakpoints
|
||||
- **Mobile**: < 768px (single column, touch-optimized)
|
||||
- **Tablet**: 768px - 1024px (2-3 columns, hybrid interaction)
|
||||
- **Desktop**: > 1024px (4+ columns, mouse-optimized)
|
||||
|
||||
### Touch Interactions
|
||||
- **Tap**: Image selection and button activation
|
||||
- **Swipe**: Gallery navigation (left/right)
|
||||
- **Long Press**: Context menu (mobile equivalent of right-click)
|
||||
- **Pinch**: Zoom functionality (future enhancement)
|
||||
|
||||
## Accessibility Features
|
||||
|
||||
### ARIA Support
|
||||
- Proper semantic HTML structure
|
||||
- ARIA labels for interactive elements
|
||||
- Screen reader announcements for dynamic content
|
||||
|
||||
### Keyboard Navigation
|
||||
- Tab order for all interactive elements
|
||||
- Enter/Space for button activation
|
||||
- Escape key for modal dismissal
|
||||
- Arrow keys for gallery navigation
|
||||
|
||||
### Visual Accessibility
|
||||
- High contrast mode support
|
||||
- Sufficient color contrast ratios
|
||||
- Scalable text and UI elements
|
||||
- Reduced motion preferences
|
||||
|
||||
## Performance Optimizations
|
||||
|
||||
### Image Loading
|
||||
- **Lazy Loading**: IntersectionObserver for viewport detection
|
||||
- **Progressive Loading**: Blur placeholder → low quality → high quality
|
||||
- **Caching**: Browser cache for static assets
|
||||
- **Compression**: Optimized image formats (WebP support)
|
||||
|
||||
### Component Optimization
|
||||
- **Conditional Rendering**: Only render active overlays
|
||||
- **Event Delegation**: Efficient event handling for large galleries
|
||||
- **Memoization**: Computed properties for expensive operations
|
||||
- **Code Splitting**: Component-based lazy loading
|
||||
|
||||
## Internationalization
|
||||
|
||||
### Translation Structure
|
||||
```typescript
|
||||
interface Translations {
|
||||
api: {
|
||||
dark_mode: string
|
||||
light_mode: string
|
||||
close: string
|
||||
print: string
|
||||
change_style: string
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Implementation
|
||||
- Laravel backend provides translations
|
||||
- Vue components use translation keys
|
||||
- Runtime language switching support
|
||||
|
||||
## Future Enhancement Opportunities
|
||||
|
||||
### Component Additions
|
||||
- **ImageEditor.vue**: Basic image editing tools
|
||||
- **BatchProcessor.vue**: Multi-image style application
|
||||
- **GalleryFilters.vue**: Search and filter functionality
|
||||
- **UserProfile.vue**: User settings and preferences
|
||||
- **AdminDashboard.vue**: Administrative controls
|
||||
|
||||
### Feature Enhancements
|
||||
- **Drag & Drop**: Upload images via drag-and-drop
|
||||
- **Keyboard Shortcuts**: Power user productivity features
|
||||
- **Offline Support**: PWA capabilities for offline viewing
|
||||
- **Social Features**: Share and discover styled images
|
||||
- **Advanced Progress**: Detailed processing stage information
|
||||
|
||||
### Technical Improvements
|
||||
- **Virtual Scrolling**: Handle very large galleries efficiently
|
||||
- **Service Workers**: Background processing and caching
|
||||
- **WebAssembly**: Client-side image processing
|
||||
- **Real-time Collaboration**: Multiple users styling same image
|
||||
651
prp/plugin-architecture.md
Normal file
651
prp/plugin-architecture.md
Normal file
@@ -0,0 +1,651 @@
|
||||
# Plugin Architecture Specification
|
||||
|
||||
## Overview
|
||||
|
||||
Extensible plugin system for integrating multiple AI service providers, enabling the application to work with different AI platforms (ComfyUI, RunwareAI, etc.) through a unified interface.
|
||||
|
||||
## Architecture Pattern
|
||||
|
||||
**Strategy Pattern Implementation** with plugin-based architecture allowing runtime selection of AI processing backends.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ ImageController │
|
||||
│ • Orchestrates image processing workflow │
|
||||
│ • Loads appropriate plugin based on ApiProvider │
|
||||
└─────────────────────┬───────────────────────────────────────────┘
|
||||
│
|
||||
┌─────────────▼─────────────────────────────────────────────┐
|
||||
│ PluginLoader │
|
||||
│ • Discovers and instantiates plugins │
|
||||
│ • Maps plugin identifiers to implementations │
|
||||
└─────────────┬───────────────────────────────────────────┘
|
||||
│
|
||||
┌─────────────▼─────────────────────────────────────────────┐
|
||||
│ ApiPluginInterface │
|
||||
│ • Defines contract for all AI plugins │
|
||||
│ • Ensures consistent behavior across providers │
|
||||
└─────┬─────────────────┬──────────────────────────────────┘
|
||||
│ │
|
||||
┌─────▼──────┐ ┌──────▼──────┐
|
||||
│ ComfyUi │ │ RunwareAi │
|
||||
│ Plugin │ │ Plugin │
|
||||
└────────────┘ └─────────────┘
|
||||
```
|
||||
|
||||
## Core Interfaces
|
||||
|
||||
### ApiPluginInterface
|
||||
|
||||
**Purpose**: Defines the contract that all AI provider plugins must implement
|
||||
|
||||
**Location**: `app/Api/Plugins/ApiPluginInterface.php`
|
||||
|
||||
**Methods**:
|
||||
|
||||
#### Core Plugin Information
|
||||
```php
|
||||
/**
|
||||
* Returns unique plugin identifier
|
||||
*/
|
||||
public function getIdentifier(): string
|
||||
|
||||
/**
|
||||
* Returns human-readable plugin name
|
||||
*/
|
||||
public function getName(): string
|
||||
|
||||
/**
|
||||
* Checks if plugin is enabled and ready for use
|
||||
*/
|
||||
public function isEnabled(): bool
|
||||
|
||||
/**
|
||||
* Enables the plugin
|
||||
*/
|
||||
public function enable(): bool
|
||||
|
||||
/**
|
||||
* Disables the plugin
|
||||
*/
|
||||
public function disable(): bool
|
||||
```
|
||||
|
||||
#### Image Processing
|
||||
```php
|
||||
/**
|
||||
* Main method for processing image style changes
|
||||
* @param Image $image Original image to transform
|
||||
* @param Style $style Style to apply
|
||||
* @return array Processing result with tracking information
|
||||
*/
|
||||
public function processImageStyleChange(Image $image, Style $style): array
|
||||
```
|
||||
|
||||
#### Progress & Status
|
||||
```php
|
||||
/**
|
||||
* Gets current processing status for image
|
||||
* @param string $imageUUID Image identifier
|
||||
* @return array Status information
|
||||
*/
|
||||
public function getStatus(string $imageUUID): array
|
||||
|
||||
/**
|
||||
* Gets processing progress for image
|
||||
* @param string $imageUUID Image identifier
|
||||
* @return array Progress information (0-100 percentage)
|
||||
*/
|
||||
public function getProgress(string $imageUUID): array
|
||||
```
|
||||
|
||||
#### Result Retrieval
|
||||
```php
|
||||
/**
|
||||
* Retrieves final styled image data
|
||||
* @param string $promptId Provider-specific job identifier
|
||||
* @return string Base64 encoded image data
|
||||
*/
|
||||
public function getStyledImage(string $promptId): string
|
||||
```
|
||||
|
||||
#### Provider-Specific Features
|
||||
```php
|
||||
/**
|
||||
* Tests connection to AI service
|
||||
* @param array $data Connection parameters
|
||||
* @return bool Connection success
|
||||
*/
|
||||
public function testConnection(array $data): bool
|
||||
|
||||
/**
|
||||
* Searches for available AI models
|
||||
* @param string $searchTerm Search query
|
||||
* @return array Available models
|
||||
*/
|
||||
public function searchModels(string $searchTerm): array
|
||||
```
|
||||
|
||||
## Plugin Implementations
|
||||
|
||||
### 1. ComfyUI Plugin
|
||||
|
||||
**Plugin Identifier**: `comfyui`
|
||||
|
||||
**Purpose**: Integration with ComfyUI web-based AI image generation platform
|
||||
|
||||
**Configuration Requirements**:
|
||||
```php
|
||||
// ApiProvider configuration
|
||||
[
|
||||
'name' => 'ComfyUI Production',
|
||||
'api_url' => 'https://your-comfyui-server.com',
|
||||
'plugin' => 'comfyui',
|
||||
'enabled' => true
|
||||
]
|
||||
```
|
||||
|
||||
#### Key Features
|
||||
|
||||
**Workflow-Based Processing**:
|
||||
- Uses JSON workflow definitions for complex AI pipelines
|
||||
- Supports custom node-based processing graphs
|
||||
- Parameter injection via placeholder replacement
|
||||
|
||||
**WebSocket Progress Updates**:
|
||||
- Real-time progress monitoring via WebSocket connection
|
||||
- Detailed progress information (current step, completion percentage)
|
||||
- Live preview of intermediate results
|
||||
|
||||
**Placeholder System**:
|
||||
```json
|
||||
{
|
||||
"prompt": "__PROMPT__",
|
||||
"filename": "__FILENAME__",
|
||||
"model_id": "__MODEL_ID__"
|
||||
}
|
||||
```
|
||||
- `__PROMPT__`: Style prompt text
|
||||
- `__FILENAME__`: Uploaded image filename
|
||||
- `__MODEL_ID__`: AI model identifier
|
||||
|
||||
#### Processing Flow
|
||||
|
||||
1. **Image Upload**
|
||||
```php
|
||||
POST {api_url}/upload/image
|
||||
Body: multipart/form-data with image file
|
||||
Response: {"name": "uploaded_filename.png"}
|
||||
```
|
||||
|
||||
2. **Workflow Construction**
|
||||
```php
|
||||
// Merge model and style parameters
|
||||
$mergedParams = array_replace_recursive($modelParams, $styleParams)
|
||||
|
||||
// Replace placeholders
|
||||
$workflow = str_replace('__PROMPT__', $prompt, $workflow)
|
||||
$workflow = str_replace('__FILENAME__', $filename, $workflow)
|
||||
$workflow = str_replace('__MODEL_ID__', $modelId, $workflow)
|
||||
```
|
||||
|
||||
3. **Prompt Queueing**
|
||||
```php
|
||||
POST {api_url}/prompt
|
||||
Body: {"prompt": $workflow}
|
||||
Response: {"prompt_id": "unique-job-id"}
|
||||
```
|
||||
|
||||
4. **Progress Monitoring**
|
||||
```php
|
||||
// WebSocket connection
|
||||
ws://{server}/ws
|
||||
|
||||
// Progress messages
|
||||
{
|
||||
"type": "progress",
|
||||
"data": {
|
||||
"prompt_id": "job-id",
|
||||
"value": 50,
|
||||
"max": 100
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
5. **Result Retrieval**
|
||||
```php
|
||||
GET {api_url}/history/{prompt_id}
|
||||
|
||||
// Extract image URL
|
||||
$imageUrl = "/view?filename={$filename}&subfolder={$subfolder}&type=output"
|
||||
|
||||
// Download final image
|
||||
GET {api_url}{$imageUrl}
|
||||
```
|
||||
|
||||
#### Error Handling
|
||||
- **Connection Failures**: Retry logic with exponential backoff
|
||||
- **Invalid Workflows**: JSON validation before submission
|
||||
- **Processing Timeouts**: Configurable timeout limits
|
||||
- **WebSocket Disconnections**: Automatic reconnection attempts
|
||||
|
||||
---
|
||||
|
||||
### 2. RunwareAI Plugin
|
||||
|
||||
**Plugin Identifier**: `runwareai`
|
||||
|
||||
**Purpose**: Integration with RunwareAI REST API for image style transformation
|
||||
|
||||
**Configuration Requirements**:
|
||||
```php
|
||||
// ApiProvider configuration
|
||||
[
|
||||
'name' => 'RunwareAI Production',
|
||||
'api_url' => 'https://api.runwareai.com',
|
||||
'token' => 'your-api-token',
|
||||
'plugin' => 'runwareai',
|
||||
'enabled' => true
|
||||
]
|
||||
```
|
||||
|
||||
#### Key Features
|
||||
|
||||
**Direct API Integration**:
|
||||
- RESTful API communication
|
||||
- Bearer token authentication
|
||||
- Synchronous processing with immediate results
|
||||
|
||||
**Model Search Capability**:
|
||||
- Search available AI models by name/type
|
||||
- Filter by model categories (base, checkpoint, etc.)
|
||||
- Real-time model availability checking
|
||||
|
||||
**Seed Image Processing**:
|
||||
- Upload original image as "seed"
|
||||
- Apply style transformation using seed as base
|
||||
- Return styled result directly
|
||||
|
||||
#### Processing Flow
|
||||
|
||||
1. **Image Upload**
|
||||
```php
|
||||
POST {api_url}
|
||||
Headers: Authorization: Bearer {token}
|
||||
Body: {
|
||||
"taskType": "imageUpload",
|
||||
"taskUUID": "unique-id",
|
||||
"image": "data:image/png;base64,{base64_data}"
|
||||
}
|
||||
Response: {
|
||||
"data": [{
|
||||
"imageUUID": "uploaded-image-uuid"
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
2. **Style Transformation**
|
||||
```php
|
||||
POST {api_url}
|
||||
Headers: Authorization: Bearer {token}
|
||||
Body: {
|
||||
"taskType": "imageInference",
|
||||
"taskUUID": "unique-id",
|
||||
"positivePrompt": "style prompt text",
|
||||
"seedImage": "uploaded-image-uuid",
|
||||
"model": "model-id",
|
||||
"outputType": "base64Data"
|
||||
}
|
||||
Response: {
|
||||
"data": [{
|
||||
"imageBase64Data": "base64-encoded-result"
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
3. **Model Search** (Optional)
|
||||
```php
|
||||
POST {api_url}
|
||||
Headers: Authorization: Bearer {token}
|
||||
Body: {
|
||||
"taskType": "modelSearch",
|
||||
"search": "search-term",
|
||||
"type": "base",
|
||||
"category": "checkpoint",
|
||||
"limit": 100
|
||||
}
|
||||
Response: {
|
||||
"data": [{
|
||||
"results": [{
|
||||
"name": "Model Name",
|
||||
"air": "model-id",
|
||||
"type": "model-type"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
#### Error Handling
|
||||
- **Authentication Failures**: Clear error messages for token issues
|
||||
- **Rate Limiting**: Respect API rate limits with proper delays
|
||||
- **Invalid Parameters**: Validation of all request parameters
|
||||
- **Network Issues**: Timeout handling with retry logic
|
||||
|
||||
## Plugin Loading Mechanism
|
||||
|
||||
### PluginLoader Class
|
||||
|
||||
**Purpose**: Discovers, loads, and manages AI provider plugins
|
||||
|
||||
**Location**: `app/Api/Plugins/PluginLoader.php`
|
||||
|
||||
**Key Methods**:
|
||||
|
||||
#### `getPlugin(string $pluginIdentifier, ApiProvider $apiProvider): ApiPluginInterface`
|
||||
- **Purpose**: Returns instantiated plugin for given identifier
|
||||
- **Implementation**: Dynamic class loading based on plugin identifier
|
||||
- **Error Handling**: Throws exception for unknown plugins
|
||||
|
||||
#### `getAvailablePlugins(): array`
|
||||
- **Purpose**: Returns list of all available plugin identifiers
|
||||
- **Implementation**: Scans plugin directory for implementations
|
||||
|
||||
**Plugin Discovery**:
|
||||
```php
|
||||
// Maps plugin identifiers to class names
|
||||
$pluginMap = [
|
||||
'comfyui' => ComfyUi::class,
|
||||
'runwareai' => RunwareAi::class,
|
||||
]
|
||||
|
||||
// Dynamic instantiation
|
||||
$pluginClass = $pluginMap[$identifier] ?? null;
|
||||
if ($pluginClass) {
|
||||
return new $pluginClass($apiProvider);
|
||||
}
|
||||
```
|
||||
|
||||
## Parameter Merging Strategy
|
||||
|
||||
### Deep Merge Algorithm
|
||||
|
||||
**Purpose**: Combines AI model parameters with style-specific overrides
|
||||
|
||||
**Implementation**:
|
||||
```php
|
||||
$modelParams = $style->aiModel->parameters ?? [];
|
||||
$styleParams = $style->parameters ?? [];
|
||||
$mergedParams = array_replace_recursive($modelParams, $styleParams);
|
||||
```
|
||||
|
||||
**Example**:
|
||||
```php
|
||||
// Model parameters (base configuration)
|
||||
$modelParams = [
|
||||
"workflow" => [
|
||||
"nodes" => [
|
||||
"1" => ["class_type" => "KSampler"],
|
||||
"2" => ["class_type" => "SaveImage"]
|
||||
]
|
||||
]
|
||||
];
|
||||
|
||||
// Style parameters (overrides and additions)
|
||||
$styleParams = [
|
||||
"workflow" => [
|
||||
"nodes" => [
|
||||
"1" => [
|
||||
"inputs" => ["seed" => 12345],
|
||||
"class_type" => "KSamplerAdvanced" // Override
|
||||
],
|
||||
"3" => ["class_type" => "PreviewImage"] // Addition
|
||||
]
|
||||
]
|
||||
];
|
||||
|
||||
// Result: Deep merged configuration
|
||||
$mergedParams = [
|
||||
"workflow" => [
|
||||
"nodes" => [
|
||||
"1" => [
|
||||
"class_type" => "KSamplerAdvanced", // Overridden
|
||||
"inputs" => ["seed" => 12345] // Added
|
||||
],
|
||||
"2" => ["class_type" => "SaveImage"], // Preserved
|
||||
"3" => ["class_type" => "PreviewImage"] // Added
|
||||
]
|
||||
]
|
||||
]
|
||||
```
|
||||
|
||||
## Logging Integration
|
||||
|
||||
### LoggablePlugin Trait
|
||||
|
||||
**Purpose**: Provides consistent logging across all plugins
|
||||
|
||||
**Location**: `app/Api/Plugins/LoggablePlugin.php`
|
||||
|
||||
**Features**:
|
||||
- **Structured Logging**: Consistent log format across plugins
|
||||
- **Log Levels**: Debug, Info, Warning, Error
|
||||
- **Context Information**: Plugin name, operation details
|
||||
- **Performance Tracking**: Execution time monitoring
|
||||
|
||||
**Usage**:
|
||||
```php
|
||||
class ComfyUi implements ApiPluginInterface
|
||||
{
|
||||
use LoggablePlugin;
|
||||
|
||||
public function processImageStyleChange(Image $image, Style $style): array
|
||||
{
|
||||
$this->logInfo('Starting ComfyUI style change process', [
|
||||
'image_id' => $image->id,
|
||||
'style_id' => $style->id
|
||||
]);
|
||||
|
||||
// Processing logic...
|
||||
|
||||
$this->logInfo('ComfyUI style change completed successfully', [
|
||||
'prompt_id' => $result['prompt_id']
|
||||
]);
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling Strategy
|
||||
|
||||
### Plugin-Specific Errors
|
||||
|
||||
**ComfyUI Errors**:
|
||||
- **Workflow Validation**: Invalid JSON structure in workflow
|
||||
- **Node Connection**: Missing or invalid node connections
|
||||
- **Resource Limits**: GPU memory or processing queue full
|
||||
- **Network Timeout**: Server unreachable or slow response
|
||||
|
||||
**RunwareAI Errors**:
|
||||
- **Authentication**: Invalid or expired API token
|
||||
- **Rate Limiting**: Too many requests per minute/hour
|
||||
- **Model Availability**: Requested model not available
|
||||
- **Image Processing**: Invalid image format or corrupted data
|
||||
|
||||
### Error Recovery
|
||||
|
||||
**Retry Logic**:
|
||||
```php
|
||||
$maxRetries = 3;
|
||||
$retryDelay = 1000000; // 1 second in microseconds
|
||||
|
||||
for ($attempt = 1; $attempt <= $maxRetries; $attempt++) {
|
||||
try {
|
||||
return $this->processImageStyleChange($image, $style);
|
||||
} catch (RetryableException $e) {
|
||||
if ($attempt === $maxRetries) {
|
||||
throw new MaxRetriesExceededException('Processing failed after ' . $maxRetries . ' attempts');
|
||||
}
|
||||
usleep($retryDelay * $attempt); // Exponential backoff
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Circuit Breaker Pattern**:
|
||||
- Track failure rates per provider
|
||||
- Temporarily disable failing providers
|
||||
- Automatic recovery testing
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests
|
||||
- **Plugin Interface**: Verify all plugins implement required methods
|
||||
- **Parameter Merging**: Test deep merge algorithm with various inputs
|
||||
- **Error Handling**: Verify proper exception throwing and recovery
|
||||
|
||||
### Integration Tests
|
||||
- **End-to-End Processing**: Test complete workflow with mock AI services
|
||||
- **Provider Switching**: Verify seamless transition between providers
|
||||
- **Error Scenarios**: Test behavior with network failures and invalid responses
|
||||
|
||||
### Mock Services
|
||||
- **ComfyUI Mock**: Simulated WebSocket and HTTP responses
|
||||
- **RunwareAI Mock**: Mock API responses for all endpoints
|
||||
- **Network Simulation**: Latency and failure injection
|
||||
|
||||
## Future Plugin Development
|
||||
|
||||
### Adding New Providers
|
||||
|
||||
1. **Implement Interface**:
|
||||
```php
|
||||
class NewProvider implements ApiPluginInterface
|
||||
{
|
||||
use LoggablePlugin;
|
||||
|
||||
public function getIdentifier(): string { return 'newprovider'; }
|
||||
public function getName(): string { return 'New AI Provider'; }
|
||||
// ... implement all required methods
|
||||
}
|
||||
```
|
||||
|
||||
2. **Register Plugin**:
|
||||
```php
|
||||
// In PluginLoader
|
||||
$pluginMap['newprovider'] = NewProvider::class;
|
||||
```
|
||||
|
||||
3. **Add Configuration**:
|
||||
- Create ApiProvider record with appropriate settings
|
||||
- Configure authentication and endpoint details
|
||||
|
||||
### Plugin Enhancement Opportunities
|
||||
|
||||
**Batch Processing Plugin**:
|
||||
- Process multiple images simultaneously
|
||||
- Queue management and progress aggregation
|
||||
- Resource optimization across multiple requests
|
||||
|
||||
**Local Processing Plugin**:
|
||||
- Integration with local AI models (Stable Diffusion WebUI)
|
||||
- Reduced latency for development/testing
|
||||
- Offline processing capabilities
|
||||
|
||||
**Cloud Provider Plugins**:
|
||||
- **AWS Bedrock**: Amazon's AI service integration
|
||||
- **Google Vertex AI**: Google's ML platform
|
||||
- **Azure Cognitive Services**: Microsoft AI services
|
||||
- **Replicate**: Cloud-based model hosting
|
||||
|
||||
**Specialized Processing**:
|
||||
- **Upscaling Plugin**: Dedicated image enhancement
|
||||
- **Style Transfer Plugin**: Specialized style application
|
||||
- **Inpainting Plugin**: Content-aware image editing
|
||||
|
||||
## Configuration Management
|
||||
|
||||
### Provider-Specific Settings
|
||||
|
||||
**ComfyUI Settings**:
|
||||
```php
|
||||
// Via ApiProvider parameters (JSON)
|
||||
{
|
||||
"timeout": 180,
|
||||
"retry_attempts": 3,
|
||||
"websocket_enabled": true,
|
||||
"workflow_path": "/custom/workflows"
|
||||
}
|
||||
```
|
||||
|
||||
**RunwareAI Settings**:
|
||||
```php
|
||||
{
|
||||
"request_timeout": 60,
|
||||
"rate_limit_delay": 1000,
|
||||
"model_cache_ttl": 3600,
|
||||
"supported_formats": ["png", "jpg", "webp"]
|
||||
}
|
||||
```
|
||||
|
||||
### Environment-Based Configuration
|
||||
|
||||
**Development**:
|
||||
- Local ComfyUI instance
|
||||
- Mock API responses for testing
|
||||
- Verbose logging enabled
|
||||
|
||||
**Production**:
|
||||
- Multiple load-balanced providers
|
||||
- Failover between providers
|
||||
- Performance monitoring and alerting
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
### Resource Management
|
||||
- **Connection Pooling**: Reuse HTTP connections where possible
|
||||
- **Timeout Configuration**: Appropriate timeouts for different operations
|
||||
- **Memory Management**: Clean up large image data after processing
|
||||
|
||||
### Scalability
|
||||
- **Concurrent Processing**: Handle multiple simultaneous requests
|
||||
- **Queue Management**: Prevent resource exhaustion
|
||||
- **Load Balancing**: Distribute requests across multiple provider instances
|
||||
|
||||
### Monitoring
|
||||
- **Performance Metrics**: Processing time, success rates, error frequencies
|
||||
- **Resource Usage**: Memory, CPU, network utilization
|
||||
- **Business Metrics**: User satisfaction, feature adoption
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Credential Management
|
||||
- **Encrypted Storage**: API tokens encrypted in database
|
||||
- **Environment Variables**: Sensitive configuration in env files
|
||||
- **Access Control**: Restrict plugin configuration to admin users
|
||||
|
||||
### Input Validation
|
||||
- **Image Validation**: Verify uploaded image integrity
|
||||
- **Parameter Sanitization**: Clean and validate all AI parameters
|
||||
- **Output Verification**: Ensure generated images are safe for display
|
||||
|
||||
### Network Security
|
||||
- **HTTPS Enforcement**: All external API calls over TLS
|
||||
- **Certificate Validation**: Verify AI service certificates
|
||||
- **Request Signing**: Authenticate requests where required
|
||||
|
||||
## Deployment Considerations
|
||||
|
||||
### Plugin Distribution
|
||||
- **Composer Packages**: Each plugin as separate package
|
||||
- **Auto-Discovery**: Automatic plugin registration
|
||||
- **Version Management**: Plugin compatibility checking
|
||||
|
||||
### Environment Setup
|
||||
- **Development**: Easy plugin development and testing
|
||||
- **Staging**: Pre-production validation of new plugins
|
||||
- **Production**: Zero-downtime plugin updates
|
||||
|
||||
### Backup and Recovery
|
||||
- **Configuration Backup**: Plugin settings and credentials
|
||||
- **State Preservation**: In-progress processing state
|
||||
- **Failover**: Automatic switching to backup providers
|
||||
Reference in New Issue
Block a user