module cleanup
This commit is contained in:
@@ -1,155 +1,136 @@
|
||||
import type { UseCase, Logger } from '@core/shared/application';
|
||||
/**
|
||||
* Use Case: RequestAvatarGenerationUseCase
|
||||
*
|
||||
* Handles the business logic for requesting avatar generation from a face photo.
|
||||
*/
|
||||
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import type { IAvatarGenerationRepository } from '../../domain/repositories/IAvatarGenerationRepository';
|
||||
import type { FaceValidationPort } from '../ports/FaceValidationPort';
|
||||
import type { AvatarGenerationPort } from '../ports/AvatarGenerationPort';
|
||||
import type { IRequestAvatarGenerationPresenter, RequestAvatarGenerationResultDTO } from '../presenters/IRequestAvatarGenerationPresenter';
|
||||
import type { Logger } from '@core/shared/application';
|
||||
import { AvatarGenerationRequest } from '../../domain/entities/AvatarGenerationRequest';
|
||||
import type { RacingSuitColor, AvatarStyle } from '../../domain/types/AvatarGenerationRequest';
|
||||
import type { IRequestAvatarGenerationPresenter } from '../presenters/IRequestAvatarGenerationPresenter';
|
||||
import type { RacingSuitColor } from '../../domain/types/AvatarGenerationRequest';
|
||||
|
||||
export interface RequestAvatarGenerationCommand {
|
||||
export interface RequestAvatarGenerationInput {
|
||||
userId: string;
|
||||
facePhotoData: string; // Base64 encoded image data
|
||||
facePhotoData: string;
|
||||
suitColor: RacingSuitColor;
|
||||
style?: AvatarStyle;
|
||||
style?: 'realistic' | 'cartoon' | 'pixel-art';
|
||||
}
|
||||
|
||||
export class RequestAvatarGenerationUseCase
|
||||
implements UseCase<RequestAvatarGenerationCommand, RequestAvatarGenerationResultDTO, any, IRequestAvatarGenerationPresenter> {
|
||||
export class RequestAvatarGenerationUseCase {
|
||||
constructor(
|
||||
private readonly avatarRepository: IAvatarGenerationRepository,
|
||||
private readonly avatarRepo: IAvatarGenerationRepository,
|
||||
private readonly faceValidation: FaceValidationPort,
|
||||
private readonly avatarGeneration: AvatarGenerationPort,
|
||||
private readonly logger: Logger,
|
||||
) {}
|
||||
|
||||
async execute(command: RequestAvatarGenerationCommand, presenter: IRequestAvatarGenerationPresenter): Promise<void> {
|
||||
presenter.reset();
|
||||
this.logger.debug(
|
||||
`Executing RequestAvatarGenerationUseCase for userId: ${command.userId}`,
|
||||
command,
|
||||
);
|
||||
|
||||
async execute(
|
||||
input: RequestAvatarGenerationInput,
|
||||
presenter: IRequestAvatarGenerationPresenter,
|
||||
): Promise<void> {
|
||||
try {
|
||||
// Create the generation request
|
||||
const requestId = this.generateId();
|
||||
this.logger.info('[RequestAvatarGenerationUseCase] Starting avatar generation request', {
|
||||
userId: input.userId,
|
||||
suitColor: input.suitColor,
|
||||
});
|
||||
|
||||
// Create the avatar generation request entity
|
||||
const requestId = uuidv4();
|
||||
const request = AvatarGenerationRequest.create({
|
||||
id: requestId,
|
||||
userId: command.userId,
|
||||
facePhotoUrl: `data:image/jpeg;base64,${command.facePhotoData}`,
|
||||
suitColor: command.suitColor,
|
||||
...(command.style ? { style: command.style } : {}),
|
||||
userId: input.userId,
|
||||
facePhotoUrl: input.facePhotoData, // Assuming facePhotoData is a URL or base64
|
||||
suitColor: input.suitColor,
|
||||
style: input.style,
|
||||
});
|
||||
|
||||
this.logger.info(`Avatar generation request created with ID: ${requestId}`);
|
||||
// Save initial request
|
||||
await this.avatarRepo.save(request);
|
||||
|
||||
// Mark as validating
|
||||
// Present initial status
|
||||
presenter.present({
|
||||
requestId,
|
||||
status: 'validating',
|
||||
});
|
||||
|
||||
// Validate face photo
|
||||
request.markAsValidating();
|
||||
await this.avatarRepository.save(request);
|
||||
this.logger.debug(`Request ${requestId} marked as validating.`);
|
||||
await this.avatarRepo.save(request);
|
||||
|
||||
// Validate the face photo
|
||||
const validationResult = await this.faceValidation.validateFacePhoto(command.facePhotoData);
|
||||
this.logger.debug(
|
||||
`Face validation result for request ${requestId}:`,
|
||||
validationResult,
|
||||
);
|
||||
|
||||
if (!validationResult.isValid) {
|
||||
const errorMessage = validationResult.errorMessage || 'Face validation failed';
|
||||
const validationResult = await this.faceValidation.validateFacePhoto(input.facePhotoData);
|
||||
|
||||
if (!validationResult.isValid || !validationResult.hasFace || validationResult.faceCount !== 1) {
|
||||
const errorMessage = validationResult.errorMessage || 'Invalid face photo: must contain exactly one face';
|
||||
request.fail(errorMessage);
|
||||
await this.avatarRepository.save(request);
|
||||
this.logger.error(`Face validation failed for request ${requestId}: ${errorMessage}`);
|
||||
await this.avatarRepo.save(request);
|
||||
|
||||
presenter.present({
|
||||
requestId,
|
||||
status: 'failed',
|
||||
errorMessage: validationResult.errorMessage || 'Please upload a clear photo of your face',
|
||||
errorMessage,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!validationResult.hasFace) {
|
||||
const errorMessage = 'No face detected in the image';
|
||||
request.fail(errorMessage);
|
||||
await this.avatarRepository.save(request);
|
||||
this.logger.error(`No face detected for request ${requestId}: ${errorMessage}`);
|
||||
presenter.present({
|
||||
requestId,
|
||||
status: 'failed',
|
||||
errorMessage: 'No face detected. Please upload a photo that clearly shows your face.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (validationResult.faceCount > 1) {
|
||||
const errorMessage = 'Multiple faces detected';
|
||||
request.fail(errorMessage);
|
||||
await this.avatarRepository.save(request);
|
||||
this.logger.error(`Multiple faces detected for request ${requestId}: ${errorMessage}`);
|
||||
presenter.present({
|
||||
requestId,
|
||||
status: 'failed',
|
||||
errorMessage: 'Multiple faces detected. Please upload a photo with only your face.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.logger.info(`Face validation successful for request ${requestId}.`);
|
||||
|
||||
// Mark as generating
|
||||
request.markAsGenerating();
|
||||
await this.avatarRepository.save(request);
|
||||
this.logger.debug(`Request ${requestId} marked as generating.`);
|
||||
|
||||
// Generate avatars
|
||||
const generationResult = await this.avatarGeneration.generateAvatars({
|
||||
facePhotoUrl: request.facePhotoUrl.value,
|
||||
request.markAsGenerating();
|
||||
await this.avatarRepo.save(request);
|
||||
|
||||
const generationOptions = {
|
||||
facePhotoUrl: input.facePhotoData,
|
||||
prompt: request.buildPrompt(),
|
||||
suitColor: request.suitColor,
|
||||
style: request.style,
|
||||
count: 3, // Generate 3 options
|
||||
});
|
||||
this.logger.debug(
|
||||
`Avatar generation service result for request ${requestId}:`,
|
||||
generationResult,
|
||||
);
|
||||
suitColor: input.suitColor,
|
||||
style: input.style || 'realistic',
|
||||
count: 3, // Generate 3 avatar options
|
||||
};
|
||||
|
||||
const generationResult = await this.avatarGeneration.generateAvatars(generationOptions);
|
||||
|
||||
if (!generationResult.success) {
|
||||
const errorMessage = generationResult.errorMessage || 'Avatar generation failed';
|
||||
const errorMessage = generationResult.errorMessage || 'Failed to generate avatars';
|
||||
request.fail(errorMessage);
|
||||
await this.avatarRepository.save(request);
|
||||
this.logger.error(`Avatar generation failed for request ${requestId}: ${errorMessage}`);
|
||||
await this.avatarRepo.save(request);
|
||||
|
||||
presenter.present({
|
||||
requestId,
|
||||
status: 'failed',
|
||||
errorMessage: generationResult.errorMessage || 'Failed to generate avatars. Please try again.',
|
||||
errorMessage,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Complete with generated avatars
|
||||
const avatarUrls = generationResult.avatars.map(a => a.url);
|
||||
// Complete the request
|
||||
const avatarUrls = generationResult.avatars.map(avatar => avatar.url);
|
||||
request.completeWithAvatars(avatarUrls);
|
||||
await this.avatarRepository.save(request);
|
||||
this.logger.info(`Avatar generation completed successfully for request ${requestId}.`);
|
||||
await this.avatarRepo.save(request);
|
||||
|
||||
presenter.present({
|
||||
requestId,
|
||||
status: 'completed',
|
||||
avatarUrls,
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`An unexpected error occurred during avatar generation for userId: ${command.userId}`,
|
||||
error as Error,
|
||||
);
|
||||
// Re-throw or return a generic error, depending on desired error handling strategy
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private generateId(): string {
|
||||
if (typeof crypto !== 'undefined' && crypto.randomUUID) {
|
||||
return crypto.randomUUID();
|
||||
this.logger.info('[RequestAvatarGenerationUseCase] Avatar generation completed', {
|
||||
requestId,
|
||||
userId: input.userId,
|
||||
avatarCount: avatarUrls.length,
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
this.logger.error('[RequestAvatarGenerationUseCase] Error during avatar generation', {
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
userId: input.userId,
|
||||
});
|
||||
|
||||
presenter.present({
|
||||
requestId: uuidv4(), // Fallback ID
|
||||
status: 'failed',
|
||||
errorMessage: 'Internal error occurred during avatar generation',
|
||||
});
|
||||
}
|
||||
return 'avatar-' + Date.now().toString(36) + Math.random().toString(36).substr(2, 9);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user