Spaces:
Sleeping
Sleeping
n8n-fixes
#2
by Yeetek - opened
Files changed (13)
- app.py+1-58
- application/dto/extraction_response.py+3-3
- application/use_cases/process_job.py+33-43
- domain/services/notification_service.py+1-2
- infrastructure/clients/n8n/models.py+2-2
- infrastructure/clients/n8n/n8n_client.py+9-15
- infrastructure/clients/n8n/settings.py+1
- infrastructure/config/settings.py+1-1
- infrastructure/services/container.py+6-12
- infrastructure/services/n8n_notification_service.py+8-6
- interfaces/api/dependencies.py+17-21
- interfaces/api/routes/extraction_routes.py-3
- interfaces/api/routes/job_routes.py+1-3
75 unmodified lines76777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514675 unmodified lines3. **Check status**: Monitor progress with `/jobs/{job_id}`4. **Download result**: Get extracted audio with `/jobs/{job_id}/download`5. **Optional trimming**: Use `start` and `end` parameters to download specific segments### AuthenticationMost endpoints require JWT Bearer token authentication. Include your token in the Authorization header:```Authorization: Bearer <your-jwt-token>```Public endpoints (no authentication required):- `GET /api/v1/info` - API information- `GET /api/v1/health` - Health check""",version=settings.app_version,docs_url="/docs",redoc_url="/redoc",openapi_url="/openapi.json",lifespan=lifespan,# Add OpenAPI security scheme for Bearer token authenticationopenapi_tags=[{"name": "extraction","description": "Audio extraction operations (requires authentication)"},{"name": "jobs","description": "Job management operations (requires authentication)"},{"name": "info","description": "Public API information (no authentication required)"}])# Configure OpenAPI security schemedef custom_openapi():if app.openapi_schema:return app.openapi_schemafrom fastapi.openapi.utils import get_openapiopenapi_schema = get_openapi(title=app.title,version=app.version,description=app.description,routes=app.routes,)# Add Bearer token security schemeopenapi_schema["components"]["securitySchemes"] = {"BearerAuth": {"type": "http","scheme": "bearer","bearerFormat": "JWT","description": "JWT Bearer token authentication"}}app.openapi_schema = openapi_schemareturn app.openapi_schemaapp.openapi = custom_openapi# Let FastAPI handle OpenAPI generation automatically# The HTTPBearer scheme in dependencies.py will be automatically detected# Configure middlewareconfigure_cors(app)register_exception_handlers(app)75 unmodified lines767778798081828384858687888975 unmodified lines3. **Check status**: Monitor progress with `/jobs/{job_id}`4. **Download result**: Get extracted audio with `/jobs/{job_id}/download`5. **Optional trimming**: Use `start` and `end` parameters to download specific segments""",version=settings.app_version,docs_url="/docs",redoc_url="/redoc",openapi_url="/openapi.json",lifespan=lifespan)# Configure middlewareconfigure_cors(app)register_exception_handlers(app)
15 unmodified lines161718192021222324259 unmodified lines353637383940414243444546474815 unmodified linesclass JobStatusDTO:"""DTO for job status."""job_id: strstatus: strcreated_at: datetimeupdated_at: datetimeexternal_job_id: Optional[str] = Nonefilename: Optional[str] = Nonefile_size_mb: Optional[float] = Noneoutput_format: Optional[str] = None9 unmodified linesmedia_type: strfilename: strprocessing_time: floatstorage_key: Optional[str] = None@dataclassclass JobCreationDTO:"""DTO for job creation."""job_id: strstatus: strmessage: strcheck_url: strexternal_job_id: Optional[str] = Nonefile_size_mb: Optional[float] = None15 unmodified lines161718192021222324259 unmodified lines353637383940414243444546474815 unmodified linesclass JobStatusDTO:"""DTO for job status."""job_id: strexternal_job_id: Optional[str] = Nonestatus: strcreated_at: datetimeupdated_at: datetimefilename: Optional[str] = Nonefile_size_mb: Optional[float] = Noneoutput_format: Optional[str] = None9 unmodified linesmedia_type: strfilename: strprocessing_time: floatstorage_key: str = None@dataclassclass JobCreationDTO:"""DTO for job creation."""job_id: strexternal_job_id: Optional[str] = Nonestatus: strmessage: strcheck_url: strfile_size_mb: Optional[float] = None
87 unmodified lines8889909192939495969798991001011021031041051061071081091101111129 unmodified lines12212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215387 unmodified linesprocessing_time=processing_time)# Send notification if service is available and we have a bearer tokenif self.notification_service:# Get job record to retrieve bearer token and external job IDjob_record = await self.job_repository.get(job_id)bearer_token = job_record.bearer_token if job_record else Noneexternal_job_id = job_record.external_job_id if job_record else Noneif bearer_token:await self.notification_service.send_job_completion_notification(job_id=job_id,status="completed",processing_time=processing_time,bearer_token=bearer_token,external_job_id=external_job_id)else:logger.debug(f"Skipping N8N notification for job {job_id} - no bearer token available")# Clear bearer token for security (regardless of notification status)await self.job_repository.clear_bearer_token(job_id)logger.info(f"Job {job_id} completed in {processing_time:.2f} seconds")9 unmodified linesprocessing_time=processing_time)# Send failure notification if service is available and we have a bearer tokenif self.notification_service:try:job_record = await self.job_repository.get(job_id)bearer_token = job_record.bearer_token if job_record else Noneexternal_job_id = job_record.external_job_id if job_record else Noneif bearer_token:await self.notification_service.send_job_completion_notification(job_id=job_id,status="failed",processing_time=processing_time,bearer_token=bearer_token,external_job_id=external_job_id)else:logger.debug(f"Skipping N8N failure notification for job {job_id} - no bearer token available")except Exception as notify_error:# Don't let notification failures mask the original job failurelogger.warning(f"Failed to send failure notification for job {job_id}: {notify_error}")# Clear bearer token for security (regardless of notification status)try:await self.job_repository.clear_bearer_token(job_id)except Exception:logger.warning(f"Failed to clear bearer token for failed job {job_id}")raise87 unmodified lines8889909192939495969798991001011021031041059 unmodified lines11511611711811912012112212312412512612712812913013113213313413513613713813914014114214387 unmodified linesprocessing_time=processing_time)# Get job record to retrieve bearer tokenjob_record = await self.job_repository.get(job_id)bearer_token = job_record.bearer_token if job_record else Noneawait self.notification_service.send_job_completion_notification(job_id=job_id,status="completed",processing_time=processing_time,bearer_token=bearer_token)# Clear bearer token for security after notification is sentawait self.job_repository.clear_bearer_token(job_id)logger.info(f"Job {job_id} completed in {processing_time:.2f} seconds")9 unmodified linesprocessing_time=processing_time)# Get job record to retrieve bearer token for failure notificationtry:job_record = await self.job_repository.get(job_id)bearer_token = job_record.bearer_token if job_record else Noneawait self.notification_service.send_job_completion_notification(job_id=job_id,status="failed",processing_time=processing_time,bearer_token=bearer_token)# Clear bearer token for security after notification is sentawait self.job_repository.clear_bearer_token(job_id)except Exception as notify_error:# Don't let notification failures mask the original job failurelogger.warning(f"Failed to send failure notification for job {job_id}: {notify_error}")# Still clear the token even if notification failedtry:await self.job_repository.clear_bearer_token(job_id)except Exception:logger.warning(f"Failed to clear bearer token for failed job {job_id}")raise
16 unmodified lines17181920212216 unmodified linesjob_id: str,status: str,processing_time: float,bearer_token: str,external_job_id: Optional[str] = None) -> NotificationResponse:...16 unmodified lines171819202116 unmodified linesjob_id: str,status: str,processing_time: float,bearer_token: Optional[str] = None) -> NotificationResponse:...
17 unmodified lines18192021222317 unmodified linesclass N8NClientProtocol(Protocol):"""Protocol defining the API client interface."""async def post_completion_event(self, data: WebhooksRequest, bearer_token: str, external_job_id: Optional[str] = None) -> WebhooksResponse:"""Post to webhooks endpoint with client bearer token for authentication."""...17 unmodified lines18192021222317 unmodified linesclass N8NClientProtocol(Protocol):"""Protocol defining the API client interface."""async def post_completion_event(self, data: WebhooksRequest, bearer_token: Optional[str] = None) -> WebhooksResponse:"""Post to webhooks endpoint with optional client bearer token."""...
20 unmodified lines212223242526272858 unmodified lines8788899091929394959697989910010110210310410510610710810911011111220 unmodified lines)def _get_default_headers(self) -> Dict[str, str]:"""Get default headers (no authentication - client token will be provided per request)."""return {"Content-Type": "application/json","Accept": "application/json"}58 unmodified linesself.logger.error(f"Failed to parse JSON response from {url}: {str(e)}")raise APIResponseError(f"Invalid JSON response: {str(e)}", response.status_code)async def post_completion_event(self, data: WebhooksRequest, bearer_token: str, external_job_id: Optional[str] = None) -> WebhooksResponse:"""Post to webhooks endpoint with client bearer token for authentication."""from dataclasses import asdictpayload = asdict(data)# Extract job_id for header and remove from payloadjob_id = payload.pop("job_id")# Client bearer token is required for authentication to N8Ncustom_headers = {"rowID": job_id,"Authorization": f"Bearer {bearer_token}"}# Add external job ID as custom header if providedif external_job_id:custom_headers["externalJobID"] = external_job_idself.logger.debug(f"Sending N8N notification for job {job_id} with external job ID {external_job_id}")else:self.logger.debug(f"Sending N8N notification for job {job_id} using client bearer token")response_data = await self._make_request("POST", "/lovable-analysis", payload, custom_headers)20 unmodified lines21222324252627282958 unmodified lines88899091929394959697989910010110210310410510620 unmodified lines)def _get_default_headers(self) -> Dict[str, str]:"""Get default headers including authentication."""return {"Authorization": f"Bearer {self.settings.token}","Content-Type": "application/json","Accept": "application/json"}58 unmodified linesself.logger.error(f"Failed to parse JSON response from {url}: {str(e)}")raise APIResponseError(f"Invalid JSON response: {str(e)}", response.status_code)async def post_completion_event(self, data: WebhooksRequest, bearer_token: Optional[str] = None) -> WebhooksResponse:"""Post to webhooks endpoint with optional client bearer token."""from dataclasses import asdictpayload = asdict(data)# Extract job_id for header and remove from payloadjob_id = payload.pop("job_id")custom_headers = {"rowID": job_id}# Add client bearer token if providedif bearer_token:custom_headers["Authorization"] = f"Bearer {bearer_token}"self.logger.debug(f"Adding client bearer token to N8N request for job {job_id}")response_data = await self._make_request("POST", "/lovable-analysis", payload, custom_headers)
5 unmodified lines67895 unmodified linesclass ClientSettings:"""Settings for the HTTP client."""base_url: strtimeout: Optional[int] = 305 unmodified lines6789105 unmodified linesclass ClientSettings:"""Settings for the HTTP client."""base_url: strtoken: strtimeout: Optional[int] = 30
87 unmodified lines888990919293949587 unmodified lines# N8N Configurationn8n_base_url: str = Field(default="http://localhost:5678", env="N8N_BASE_URL")n8n_timeout: int = Field(default=30, env="N8N_TIMEOUT")n8n_enabled: bool = Field(default=True, env="N8N_ENABLED")# Authentication Configurationenforce_authentication: bool = Field(default=True, env="ENFORCE_AUTHENTICATION")87 unmodified lines888990919293949587 unmodified lines# N8N Configurationn8n_base_url: str = Field(default="http://localhost:5678", env="N8N_BASE_URL")n8n_token: str = Field(env="N8N_TOKEN")n8n_timeout: int = Field(default=30, env="N8N_TIMEOUT")# Authentication Configurationenforce_authentication: bool = Field(default=True, env="ENFORCE_AUTHENTICATION")
60 unmodified lines6162636465666768697071727374757620 unmodified lines97989910010110210310410510660 unmodified lineselse:raise ValueError(f"Unsupported storage type: {settings.storage_type}")def _create_notification_service(self) -> Optional[N8NNotificationService]:"""Create N8N notification service if enabled."""# Check if N8N is enabledif not settings.n8n_enabled:logging.getLogger(__name__).info("N8N notifications disabled via configuration")return None# Create N8N client settings (no token needed - client tokens are passed per request)n8n_settings = ClientSettings(base_url=settings.n8n_base_url,timeout=getattr(settings, 'n8n_timeout', 30))20 unmodified linesasync def shutdown(self):"""Cleanup services on shutdown."""await self.cleanup_service.stop()# Close N8N client if it exists and has async cleanupif (self.notification_service andhasattr(self.notification_service, 'n8n_client') andhasattr(self.notification_service.n8n_client, 'close')):await self.notification_service.n8n_client.close()# Convenience function for getting services60 unmodified lines61626364656667686970717220 unmodified lines9394959697989910060 unmodified lineselse:raise ValueError(f"Unsupported storage type: {settings.storage_type}")def _create_notification_service(self) -> N8NNotificationService:"""Create N8N notification service."""# Create N8N client settingsn8n_settings = ClientSettings(base_url=settings.n8n_base_url,token=settings.n8n_token,timeout=getattr(settings, 'n8n_timeout', 30))20 unmodified linesasync def shutdown(self):"""Cleanup services on shutdown."""await self.cleanup_service.stop()# Close N8N client if it has async cleanupif hasattr(self.notification_service.n8n_client, 'close'):await self.notification_service.n8n_client.close()# Convenience function for getting services
24 unmodified lines252627282930313233343536373839404124 unmodified linesjob_id: str,status: str,processing_time: float,bearer_token: str,external_job_id: Optional[str] = None) -> NotificationResponse:"""Send job completion notification via N8N with client bearer token for authentication."""try:message = f"Job {job_id} {status} in {processing_time:.2f}s"request = NotificationRequest(message=message, job_id=job_id)# Pass client bearer token and external job ID to N8N clientresponse = await self.n8n_client.post_completion_event(request, bearer_token, external_job_id)logger.debug(f"Sent N8N notification for job {job_id} using client bearer token")return NotificationResponse(acknowledged=response.acknowledged)24 unmodified lines2526272829303132333435363738394041424324 unmodified linesjob_id: str,status: str,processing_time: float,bearer_token: Optional[str] = None) -> NotificationResponse:"""Send job completion notification via N8N with optional client bearer token."""try:message = f"Job {job_id} {status} in {processing_time:.2f}s"request = NotificationRequest(message=message, job_id=job_id)# Pass bearer token to N8N client if providedresponse = await self.n8n_client.post_completion_event(request, bearer_token)if bearer_token:logger.debug(f"Sent N8N notification for job {job_id} with client bearer token")else:logger.debug(f"Sent N8N notification for job {job_id} without client bearer token")return NotificationResponse(acknowledged=response.acknowledged)
12345671 unmodified line910111213141516171819202141 unmodified lines63646566676869707172737475761 unmodified line787980818283848586878889909192939495969725 unmodified lines123124125126"""FastAPI dependency injection configuration."""from typing import Annotated, Optionalfrom fastapi import Depends, UploadFile, Form, HTTPException, Request, Headerfrom fastapi.security import HTTPBearerfrom pydantic import BaseModel, Field, validatorimport re1 unmodified linefrom infrastructure.services.container import ServiceContainerfrom infrastructure.services.jwt_validation_service import JWTValidationService# Create HTTPBearer scheme that will be recognized by OpenAPIbearer_scheme = HTTPBearer(scheme_name="BearerAuth",bearerFormat="JWT",description="JWT Bearer token authentication")class ExtractionRequest(BaseModel):"""Request model for audio extraction."""output_format: str = Field(default="mp3", description="Output audio format")41 unmodified linesreturn videoasync def get_validated_token(credentials = Depends(bearer_scheme)) -> str:"""Extract and validate bearer token from HTTPBearer scheme.Args:credentials: HTTPAuthorizationCredentials from HTTPBearer schemeReturns:str: The validated bearer token1 unmodified lineRaises:HTTPException: 401 if token is missing or invalid"""from infrastructure.config.settings import settingsif not settings.enforce_authentication:return "authentication-disabled"if not credentials:raise HTTPException(status_code=401,detail="Missing Authorization header",headers={"WWW-Authenticate": "Bearer"})# Extract token from credentialstoken = credentials.credentialsif not token:raise HTTPException(status_code=401,25 unmodified linesExtractionParams = Annotated[ExtractionRequest, Depends(extraction_params)]Services = Annotated[ServiceContainer, Depends(get_services)]UseCases = Annotated[UseCaseContainer, Depends(get_use_cases)]BearerToken = Annotated[str, Depends(get_validated_token)]12345671 unmodified line9101112131441 unmodified lines56575859606162636465666768691 unmodified line717273747576777879808182838485868788899091929325 unmodified lines119120121122# interfaces/api/dependencies.py"""FastAPI dependency injection configuration."""from typing import Annotated, Optionalfrom fastapi import Depends, UploadFile, Form, HTTPException, Request, Headerfrom pydantic import BaseModel, Field, validatorimport re1 unmodified linefrom infrastructure.services.container import ServiceContainerfrom infrastructure.services.jwt_validation_service import JWTValidationServiceclass ExtractionRequest(BaseModel):"""Request model for audio extraction."""output_format: str = Field(default="mp3", description="Output audio format")41 unmodified linesreturn videoasync def validate_bearer_token(authorization: Optional[str] = Header(None, description="Bearer token for authentication")) -> str:"""Extract and validate bearer token from Authorization header.Args:authorization: Authorization header valueReturns:str: The validated bearer token1 unmodified lineRaises:HTTPException: 401 if token is missing or invalid"""if not authorization:raise HTTPException(status_code=401,detail="Missing Authorization header",headers={"WWW-Authenticate": "Bearer"})# Check if it starts with "Bearer "if not authorization.startswith("Bearer "):raise HTTPException(status_code=401,detail="Invalid Authorization header format. Expected: Bearer <token>",headers={"WWW-Authenticate": "Bearer"})# Extract tokentoken = authorization[7:] # Remove "Bearer " prefixif not token:raise HTTPException(status_code=401,25 unmodified linesExtractionParams = Annotated[ExtractionRequest, Depends(extraction_params)]Services = Annotated[ServiceContainer, Depends(get_services)]UseCases = Annotated[UseCaseContainer, Depends(get_use_cases)]BearerToken = Annotated[str, Depends(validate_bearer_token)]
21 unmodified lines22232425262728293031323321 unmodified linesdescription="""Extract audio from uploaded video file.**Authentication Required**: This endpoint requires a valid JWT Bearer token.All files are processed asynchronously and return a job ID for tracking progress.Use the job status endpoint to check processing status and download the result when complete.""",responses={202: {"description": "Job created for async processing",21 unmodified lines22232425262728293021 unmodified linesdescription="""Extract audio from uploaded video file.All files are processed asynchronously and return a job ID for tracking progress.Use the job status endpoint to check processing status and download the result when complete.""",responses={202: {"description": "Job created for async processing",
18 unmodified lines1920212223242552 unmodified lines787980818283848518 unmodified lines@router.get("/jobs/{job_id}",response_model=JobStatusResponse,summary="Get Job Status",description="Check the status of an audio extraction job. **Authentication Required**: This endpoint requires a valid JWT Bearer token.",responses={200: {"description": "Job status retrieved successfully"},401: {"description": "Authentication required", "content": {"application/json": {"example": {"error": "Authentication required", "code": "AUTHENTICATION_ERROR"}}}},52 unmodified linesdescription="""Download the audio file from a completed extraction job.**Authentication Required**: This endpoint requires a valid JWT Bearer token.Optionally specify start and end times to download only a portion of the audio:- start: Start time in HH:MM:SS format (e.g., 00:01:30 for 1 minute 30 seconds)- end: End time in HH:MM:SS format (e.g., 00:03:45 for 3 minutes 45 seconds)18 unmodified lines1920212223242552 unmodified lines78798081828318 unmodified lines@router.get("/jobs/{job_id}",response_model=JobStatusResponse,summary="Get Job Status",description="Check the status of an audio extraction job",responses={200: {"description": "Job status retrieved successfully"},401: {"description": "Authentication required", "content": {"application/json": {"example": {"error": "Authentication required", "code": "AUTHENTICATION_ERROR"}}}},52 unmodified linesdescription="""Download the audio file from a completed extraction job.Optionally specify start and end times to download only a portion of the audio:- start: Start time in HH:MM:SS format (e.g., 00:01:30 for 1 minute 30 seconds)- end: End time in HH:MM:SS format (e.g., 00:03:45 for 3 minutes 45 seconds)
app.py+1-58
application/dto/extraction_response.py+3-3
application/use_cases/process_job.py+33-43
domain/services/notification_service.py+1-2
infrastructure/clients/n8n/models.py+2-2
infrastructure/clients/n8n/n8n_client.py+9-15
infrastructure/clients/n8n/settings.py+1
infrastructure/config/settings.py+1-1
infrastructure/services/container.py+6-12
infrastructure/services/n8n_notification_service.py+8-6
interfaces/api/dependencies.py+17-21
interfaces/api/routes/extraction_routes.py-3
interfaces/api/routes/job_routes.py+1-3