Skip to content

Commit

Permalink
fix notification target logic to allow custom targets later
Browse files Browse the repository at this point in the history
Signed-off-by: Julien Veyssier <[email protected]>
  • Loading branch information
julien-nc committed Jan 31, 2024
1 parent 95b456b commit b448135
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 36 deletions.
12 changes: 3 additions & 9 deletions lib/Listener/SpeechToText/SpeechToTextResultListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
*/
class SpeechToTextResultListener implements IEventListener {
public function __construct(
private SpeechToTextService $sttService,
private LoggerInterface $logger,
private TaskMapper $taskMapper,
private AssistantService $assistantService,
Expand All @@ -54,7 +53,6 @@ public function handle(Event $event): void {

if ($event instanceof TranscriptionSuccessfulEvent) {
$transcript = $event->getTranscript();
$userId = $event->getUserId();
$file = $event->getFile();

$tasks = $this->taskMapper->getTasksByOcpTaskIdAndCategory($file->getId(), Application::TASK_CATEGORY_SPEECH_TO_TEXT);
Expand All @@ -80,11 +78,8 @@ public function handle(Event $event): void {
$assistantTask->setStatus(Application::STT_TASK_SUCCESSFUL);
$assistantTask = $this->taskMapper->update($assistantTask);

// Generate the link to the result page:
$link = $this->urlGenerator->linkToRouteAbsolute(Application::APP_ID . '.SpeechToText.getResultPage', ['id' => $task->getId()]);
$this->logger->error('Generated link to result page: ' . $link);
try {
$this->assistantService->sendNotification($assistantTask, $link, null, $transcript);
$this->assistantService->sendNotification($assistantTask, null, null, $transcript);
} catch (\InvalidArgumentException $e) {
$this->logger->error('Failed to dispatch notification for successful transcription: ' . $e->getMessage());
}
Expand All @@ -93,7 +88,6 @@ public function handle(Event $event): void {
if ($event instanceof TranscriptionFailedEvent) {
$this->logger->error('Transcript generation failed: ' . $event->getErrorMessage());

$userId = $event->getUserId();
$tasks = $this->taskMapper->getTasksByOcpTaskIdAndCategory($file->getId(), Application::TASK_CATEGORY_SPEECH_TO_TEXT);

// Find a matching etag:
Expand All @@ -115,13 +109,13 @@ public function handle(Event $event): void {
// Update the meta task with the new status
$assistantTask->setStatus(Application::STT_TASK_FAILED);
$assistantTask = $this->taskMapper->update($assistantTask);

try {
$this->assistantService->sendNotification($assistantTask);
} catch (\InvalidArgumentException $e) {
$this->logger->error('Failed to dispatch notification for failed transcription: ' . $e->getMessage());
}

}
}
}
22 changes: 4 additions & 18 deletions lib/Listener/Text2Image/Text2ImageResultListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,13 @@

use OCA\TpAssistant\AppInfo\Application;
use OCA\TpAssistant\Db\TaskMapper;
use OCA\TpAssistant\Db\Text2Image\ImageGeneration;
use OCA\TpAssistant\Db\Text2Image\ImageGenerationMapper;
use OCA\TpAssistant\Service\AssistantService;
use OCA\TpAssistant\Service\Text2Image\Text2ImageHelperService;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\EventDispatcher\Event;
use OCP\EventDispatcher\IEventListener;
use OCP\IImage;
use OCP\IURLGenerator;
use OCP\TextToImage\Events\AbstractTextToImageEvent;
use OCP\TextToImage\Events\TaskFailedEvent;
use OCP\TextToImage\Events\TaskSuccessfulEvent;
Expand All @@ -30,7 +27,6 @@ public function __construct(
private ImageGenerationMapper $imageGenerationMapper,
private LoggerInterface $logger,
private AssistantService $assistantService,
private IURLGenerator $urlGenerator,
private TaskMapper $taskMapper,
) {
}
Expand All @@ -43,7 +39,7 @@ public function handle(Event $event): void {
if (!$event instanceof AbstractTextToImageEvent || $event->getTask()->getAppId() !== Application::APP_ID) {
return;
}
$this->logger->debug("TextToImageEvent received");
$this->logger->debug('TextToImageEvent received');

$imageGenId = $event->getTask()->getIdentifier();

Expand All @@ -53,31 +49,22 @@ public function handle(Event $event): void {
}

$assistantTask = $this->taskMapper->getTaskByOcpTaskIdAndCategory($event->getTask()->getId(), Application::TASK_CATEGORY_TEXT_TO_IMAGE);
$link = null; // A link to the image generation page (if the task succeeded)

if ($event instanceof TaskSuccessfulEvent) {
$this->logger->debug("TextToImageEvent succeeded");
/** @var IImage $image */
$this->logger->debug('TextToImageEvent succeeded');

$images = $event->getTask()->getOutputImages();

$this->text2ImageService->storeImages($images, $imageGenId);

$assistantTask->setStatus(Task::STATUS_SUCCESSFUL);
$assistantTask = $this->taskMapper->update($assistantTask);
// Generate the link for the notification
$link = $this->urlGenerator->linkToRouteAbsolute(
Application::APP_ID . '.Text2Image.showGenerationPage',
[
'imageGenId' => $imageGenId,
]
);
}

if ($event instanceof TaskFailedEvent) {
$this->logger->warning('Image generation task failed: ' . $imageGenId);
$this->imageGenerationMapper->setFailed($imageGenId, true);

// Update the assistant meta task status:
$assistantTask->setStatus(Task::STATUS_FAILED);
$assistantTask = $this->taskMapper->update($assistantTask);
Expand All @@ -87,10 +74,9 @@ public function handle(Event $event): void {

// Only send the notification if the user enabled them for this task:
try {
/** @var ImageGeneration $imageGeneration */
$imageGeneration = $this->imageGenerationMapper->getImageGenerationOfImageGenId($imageGenId);
if ($imageGeneration->getNotifyReady()) {
$this->assistantService->sendNotification($assistantTask, $link);
$this->assistantService->sendNotification($assistantTask);
}
} catch (\OCP\Db\Exception | DoesNotExistException | MultipleObjectsReturnedException $e) {
$this->logger->warning('Could not notify user of a generation (id:' . $imageGenId . ') being ready: ' . $e->getMessage());
Expand Down
6 changes: 3 additions & 3 deletions lib/Notification/Notifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,13 @@ public function prepare(INotification $notification, string $languageCode): INot
if ($taskInput) {
$content .= $l->t('Input: %1$s', [$taskInput]);
}

if (isset($params['result'])) {
$content === '' ?: $content .= '\n';
$content .= $l->t('Result: %1$s', [$params['result']]);
}
$link = $params['target'] ?? $this->url->linkToRouteAbsolute(Application::APP_ID . '.assistant.getTextProcessingTaskResultPage', ['taskId' => $params['id']]);

$link = $params['target'];
$iconUrl = $this->url->getAbsoluteURL($this->url->imagePath(Application::APP_ID, 'app-dark.svg'));

$notification
Expand Down
32 changes: 26 additions & 6 deletions lib/Service/AssistantService.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use OCA\TpAssistant\AppInfo\Application;
use OCA\TpAssistant\Db\Task;
use OCA\TpAssistant\Db\TaskMapper;
use OCA\TpAssistant\Db\Text2Image\ImageGenerationMapper;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\Common\Exception\NotFoundException;
Expand All @@ -33,31 +34,32 @@ class AssistantService {
public function __construct(
private INotificationManager $notificationManager,
private ITextProcessingManager $textProcessingManager,
private IURLGenerator $url,
private TaskMapper $taskMapper,
private ImageGenerationMapper $imageGenerationMapper,
private LoggerInterface $logger,
private IRootFolder $storage,
private IURLGenerator $url,
) {
}

/**
* Send a success or failure task result notification
*
* @param Task $task
* @param string|null $target optional notification link target
* @param string|null $customTarget optional notification link target
* @param string|null $actionLabel optional label for the notification action button
* @return void
* @throws \InvalidArgumentException
*/
public function sendNotification(Task $task, ?string $target = null, ?string $actionLabel = null, ?string $resultPreview = null): void {
public function sendNotification(Task $task, ?string $customTarget = null, ?string $actionLabel = null, ?string $resultPreview = null): void {
$manager = $this->notificationManager;
$notification = $manager->createNotification();

$params = [
'appId' => $task->getAppId(),
'id' => $task->getId(),
'inputs' => $task->getInputsAsArray(),
'target' => $target,
'target' => $customTarget ?? $this->getDefaultTarget($task),
'actionLabel' => $actionLabel,
'result' => $resultPreview,
];
Expand Down Expand Up @@ -91,7 +93,7 @@ public function sendNotification(Task $task, ?string $target = null, ?string $ac
? 'success'
: 'failure';

$objectType = $target === null
$objectType = $customTarget === null
? 'task'
: 'task-with-custom-target';

Expand All @@ -104,6 +106,24 @@ public function sendNotification(Task $task, ?string $target = null, ?string $ac
$manager->notify($notification);
}

private function getDefaultTarget(Task $task): string {
$category = $task->getCategory();
if ($category === Application::TASK_CATEGORY_TEXT_GEN) {
return $this->url->linkToRouteAbsolute(Application::APP_ID . '.assistant.getTextProcessingTaskResultPage', ['taskId' => $task->getId()]);
} elseif ($category === Application::TASK_CATEGORY_SPEECH_TO_TEXT) {
return $this->url->linkToRouteAbsolute(Application::APP_ID . '.SpeechToText.getResultPage', ['id' => $task->getId()]);
} elseif ($category === Application::TASK_CATEGORY_TEXT_TO_IMAGE) {
$imageGeneration = $this->imageGenerationMapper->getImageGenerationOfImageGenId($task->getIndentifer());
return $this->url->linkToRouteAbsolute(
Application::APP_ID . '.Text2Image.showGenerationPage',
[
'imageGenId' => $imageGeneration->getImageGenId(),
]
);
}
return '';
}

/**
* @param string $writingStyle
* @param string $sourceMaterial
Expand Down Expand Up @@ -305,7 +325,7 @@ public function parseTextFromFile(string $filePath, string $userId): string {
} catch (NotFoundException $e) {
throw new \Exception('File not found.');
}

try {
if ($file instanceof File) {
$contents = $file->getContent();
Expand Down

0 comments on commit b448135

Please sign in to comment.