1
0
Fork 0
mirror of synced 2024-06-13 16:24:47 +12:00
appwrite/src/Appwrite/Platform/Workers/Messaging.php

652 lines
24 KiB
PHP
Raw Normal View History

2022-06-09 01:57:34 +12:00
<?php
2023-05-30 04:32:33 +12:00
namespace Appwrite\Platform\Workers;
use Appwrite\Auth\Auth;
2024-02-12 14:18:19 +13:00
use Appwrite\Event\Usage;
use Appwrite\Extend\Exception;
use Appwrite\Messaging\Status as MessageStatus;
2023-11-16 09:00:47 +13:00
use Utopia\App;
2022-06-09 01:57:34 +12:00
use Utopia\CLI\Console;
use Utopia\Config\Config;
use Utopia\Database\Validator\Authorization;
2023-11-16 09:00:47 +13:00
use Utopia\DSN\DSN;
use Utopia\Database\Database;
use Utopia\Database\DateTime;
use Utopia\Database\Document;
2024-02-12 14:18:19 +13:00
use Utopia\Database\Helpers\ID;
use Utopia\Database\Query;
2024-02-12 14:18:19 +13:00
use Utopia\Logger\Log;
use Utopia\Messaging\Adapter\Email as EmailAdapter;
use Utopia\Messaging\Adapter\Email\Mailgun;
2024-02-01 01:30:09 +13:00
use Utopia\Messaging\Adapter\Email\SMTP;
2024-02-12 14:18:19 +13:00
use Utopia\Messaging\Adapter\Email\Sendgrid;
use Utopia\Messaging\Adapter\Push as PushAdapter;
use Utopia\Messaging\Adapter\Push\APNS;
use Utopia\Messaging\Adapter\Push\FCM;
use Utopia\Messaging\Adapter\SMS as SMSAdapter;
use Utopia\Messaging\Adapter\SMS\Mock;
use Utopia\Messaging\Adapter\SMS\Msg91;
use Utopia\Messaging\Adapter\SMS\Telesign;
use Utopia\Messaging\Adapter\SMS\Textmagic;
use Utopia\Messaging\Adapter\SMS\Twilio;
use Utopia\Messaging\Adapter\SMS\Vonage;
use Utopia\Messaging\Messages\Email;
use Utopia\Messaging\Messages\Email\Attachment;
use Utopia\Messaging\Messages\Push;
use Utopia\Messaging\Messages\SMS;
2024-02-12 14:18:19 +13:00
use Utopia\Platform\Action;
use Utopia\Queue\Message;
use Utopia\Storage\Device;
use Utopia\Storage\Storage;
2023-10-04 23:45:59 +13:00
use function Swoole\Coroutine\batch;
2023-05-30 04:32:33 +12:00
class Messaging extends Action
2022-06-09 01:57:34 +12:00
{
2023-05-30 04:32:33 +12:00
public static function getName(): string
2022-06-09 01:57:34 +12:00
{
2024-01-11 15:55:08 +13:00
return 'messaging';
}
2023-06-02 15:54:34 +12:00
/**
2024-02-21 01:06:35 +13:00
* @throws \Exception
2023-06-02 15:54:34 +12:00
*/
2023-05-30 04:32:33 +12:00
public function __construct()
{
2023-05-30 04:32:33 +12:00
$this
->desc('Messaging worker')
->inject('message')
->inject('log')
->inject('dbForProject')
2024-02-21 03:10:51 +13:00
->inject('deviceForFiles')
->inject('deviceForLocalFiles')
2024-02-12 14:18:19 +13:00
->inject('queueForUsage')
2024-02-21 03:10:51 +13:00
->callback(fn(Message $message, Log $log, Database $dbForProject, Device $deviceForFiles, Device $deviceForLocalFiles, Usage $queueForUsage) => $this->action($message, $log, $dbForProject, $deviceForFiles, $deviceForLocalFiles, $queueForUsage));
2022-06-09 01:57:34 +12:00
}
2023-06-02 15:54:34 +12:00
/**
2023-10-02 06:39:26 +13:00
* @param Message $message
* @param Log $log
* @param Database $dbForProject
* @param Device $deviceForFiles
* @param Device $deviceForLocalFiles
2024-02-12 14:18:19 +13:00
* @param Usage $queueForUsage
2023-10-02 06:39:26 +13:00
* @return void
2024-02-21 01:06:35 +13:00
* @throws \Exception
2023-06-02 15:54:34 +12:00
*/
public function action(
Message $message,
Log $log,
Database $dbForProject,
2024-02-21 03:10:51 +13:00
Device $deviceForFiles,
Device $deviceForLocalFiles,
Usage $queueForUsage
): void {
2023-05-30 04:32:33 +12:00
$payload = $message->getPayload() ?? [];
if (empty($payload)) {
2024-02-12 14:18:19 +13:00
throw new Exception('Missing payload');
2023-05-30 04:32:33 +12:00
}
2024-02-21 01:06:35 +13:00
$type = $payload['type'] ?? '';
$project = new Document($payload['project'] ?? []);
2024-02-12 14:18:19 +13:00
2024-02-21 01:06:35 +13:00
switch ($type) {
case MESSAGE_SEND_TYPE_INTERNAL:
$message = new Document($payload['message'] ?? []);
$recipients = $payload['recipients'] ?? [];
$this->sendInternalSMSMessage($message, $project, $recipients, $queueForUsage, $log);
break;
case MESSAGE_SEND_TYPE_EXTERNAL:
$message = $dbForProject->getDocument('messages', $payload['messageId']);
2024-02-21 03:10:51 +13:00
$this->sendExternalMessage($dbForProject, $message, $deviceForFiles, $deviceForLocalFiles,);
2024-02-21 01:06:35 +13:00
break;
default:
throw new Exception('Unknown message type: ' . $type);
2023-11-16 09:00:47 +13:00
}
}
2024-02-21 02:50:44 +13:00
private function sendExternalMessage(
Database $dbForProject,
Document $message,
2024-02-21 03:10:51 +13:00
Device $deviceForFiles,
Device $deviceForLocalFiles,
): void {
2024-01-11 15:55:08 +13:00
$topicIds = $message->getAttribute('topics', []);
$targetIds = $message->getAttribute('targets', []);
$userIds = $message->getAttribute('users', []);
/**
2024-01-11 15:55:08 +13:00
* @var array<Document> $recipients
2023-12-15 03:19:24 +13:00
*/
$recipients = [];
2024-01-11 15:55:08 +13:00
if (\count($topicIds) > 0) {
$topics = $dbForProject->find('topics', [
Query::equal('$id', $topicIds),
2024-01-17 14:54:25 +13:00
Query::limit(\count($topicIds)),
2024-01-11 15:55:08 +13:00
]);
2023-10-31 07:07:57 +13:00
foreach ($topics as $topic) {
2024-01-11 15:55:08 +13:00
$targets = \array_filter($topic->getAttribute('targets'), fn(Document $target) =>
$target->getAttribute('providerType') === $message->getAttribute('providerType'));
$recipients = \array_merge($recipients, $targets);
2023-10-31 07:07:57 +13:00
}
}
2024-01-11 15:55:08 +13:00
if (\count($userIds) > 0) {
$users = $dbForProject->find('users', [
Query::equal('$id', $userIds),
2024-01-17 14:54:25 +13:00
Query::limit(\count($userIds)),
2024-01-11 15:55:08 +13:00
]);
2023-10-31 07:07:57 +13:00
foreach ($users as $user) {
2024-01-11 15:55:08 +13:00
$targets = \array_filter($user->getAttribute('targets'), fn(Document $target) =>
$target->getAttribute('providerType') === $message->getAttribute('providerType'));
$recipients = \array_merge($recipients, $targets);
2023-10-31 07:07:57 +13:00
}
}
2024-01-11 15:55:08 +13:00
if (\count($targetIds) > 0) {
$targets = $dbForProject->find('targets', [
Query::equal('$id', $targetIds),
2024-01-17 14:54:25 +13:00
Query::limit(\count($targetIds)),
2024-01-11 15:55:08 +13:00
]);
$targets = \array_filter($targets, fn(Document $target) =>
$target->getAttribute('providerType') === $message->getAttribute('providerType'));
2023-10-31 07:07:57 +13:00
$recipients = \array_merge($recipients, $targets);
}
2024-01-11 15:55:08 +13:00
2024-01-15 18:28:40 +13:00
if (empty($recipients)) {
$dbForProject->updateDocument('messages', $message->getId(), $message->setAttributes([
2024-01-19 16:15:54 +13:00
'status' => MessageStatus::FAILED,
'deliveryErrors' => ['No valid recipients found.']
]));
Console::warning('No valid recipients found.');
return;
2024-01-15 18:28:40 +13:00
}
2024-01-11 15:55:08 +13:00
$fallback = $dbForProject->findOne('providers', [
2023-11-16 09:00:47 +13:00
Query::equal('enabled', [true]),
2023-11-15 01:44:07 +13:00
Query::equal('type', [$recipients[0]->getAttribute('providerType')]),
]);
if ($fallback === false || $fallback->isEmpty()) {
$dbForProject->updateDocument('messages', $message->getId(), $message->setAttributes([
2024-01-19 16:15:54 +13:00
'status' => MessageStatus::FAILED,
'deliveryErrors' => ['No fallback provider found.']
]));
Console::warning('No fallback provider found.');
return;
2024-01-15 18:28:40 +13:00
}
/**
2024-01-11 15:55:08 +13:00
* @var array<string, array<string>> $identifiers
2023-12-15 03:19:24 +13:00
*/
2024-01-11 15:55:08 +13:00
$identifiers = [];
/**
2023-12-15 03:19:24 +13:00
* @var Document[] $providers
*/
$providers = [
2024-01-11 15:55:08 +13:00
$fallback->getId() => $fallback
];
2024-01-11 15:55:08 +13:00
2023-10-27 03:14:06 +13:00
foreach ($recipients as $recipient) {
$providerId = $recipient->getAttribute('providerId');
2023-11-15 01:44:07 +13:00
2024-01-11 15:55:08 +13:00
if (
!$providerId
&& $fallback instanceof Document
&& !$fallback->isEmpty()
&& $fallback->getAttribute('enabled')
) {
$providerId = $fallback->getId();
2023-11-15 01:44:07 +13:00
}
if ($providerId) {
2024-01-11 15:55:08 +13:00
if (!\array_key_exists($providerId, $identifiers)) {
$identifiers[$providerId] = [];
}
2024-01-11 15:55:08 +13:00
$identifiers[$providerId][] = $recipient->getAttribute('identifier');
2023-10-27 03:14:06 +13:00
}
}
/**
2024-01-11 15:55:08 +13:00
* @var array<array> $results
2023-12-15 03:19:24 +13:00
*/
2024-02-21 03:10:51 +13:00
$results = batch(\array_map(function ($providerId) use ($identifiers, $providers, $fallback, $message, $dbForProject, $deviceForFiles, $deviceForLocalFiles) {
return function () use ($providerId, $identifiers, $providers, $fallback, $message, $dbForProject, $deviceForFiles, $deviceForLocalFiles) {
if (\array_key_exists($providerId, $providers)) {
$provider = $providers[$providerId];
2023-11-15 01:44:07 +13:00
} else {
2024-01-11 15:55:08 +13:00
$provider = $dbForProject->getDocument('providers', $providerId);
2024-01-11 15:55:08 +13:00
if ($provider->isEmpty() || !$provider->getAttribute('enabled')) {
$provider = $fallback;
} else {
$providers[$providerId] = $provider;
}
2023-11-15 01:44:07 +13:00
}
2024-01-11 15:55:08 +13:00
$identifiers = $identifiers[$providerId];
2023-10-27 03:14:06 +13:00
$adapter = match ($provider->getAttribute('type')) {
2024-02-21 01:06:35 +13:00
MESSAGE_TYPE_SMS => $this->getSmsAdapter($provider),
MESSAGE_TYPE_PUSH => $this->getPushAdapter($provider),
MESSAGE_TYPE_EMAIL => $this->getEmailAdapter($provider),
2023-10-04 23:45:59 +13:00
default => throw new Exception(Exception::PROVIDER_INCORRECT_TYPE)
};
2023-11-15 01:44:07 +13:00
2023-10-27 03:14:06 +13:00
$maxBatchSize = $adapter->getMaxMessagesPerRequest();
$batches = \array_chunk($identifiers, $maxBatchSize);
$batchIndex = 0;
2024-02-21 03:10:51 +13:00
return batch(\array_map(function ($batch) use ($message, $provider, $adapter, &$batchIndex, $dbForProject, $deviceForFiles, $deviceForLocalFiles) {
return function () use ($batch, $message, $provider, $adapter, &$batchIndex, $dbForProject, $deviceForFiles, $deviceForLocalFiles) {
2023-10-31 07:07:57 +13:00
$deliveredTotal = 0;
2023-10-27 03:14:06 +13:00
$deliveryErrors = [];
$messageData = clone $message;
$messageData->setAttribute('to', $batch);
2023-11-15 01:44:07 +13:00
2023-10-27 03:14:06 +13:00
$data = match ($provider->getAttribute('type')) {
2024-02-21 01:06:35 +13:00
MESSAGE_TYPE_SMS => $this->buildSmsMessage($messageData, $provider),
2023-11-29 17:05:37 +13:00
MESSAGE_TYPE_PUSH => $this->buildPushMessage($messageData),
2024-02-21 03:10:51 +13:00
MESSAGE_TYPE_EMAIL => $this->buildEmailMessage($dbForProject, $messageData, $provider, $deviceForFiles, $deviceForLocalFiles),
2023-10-27 03:14:06 +13:00
default => throw new Exception(Exception::PROVIDER_INCORRECT_TYPE)
};
2023-11-15 01:44:07 +13:00
2023-10-27 03:14:06 +13:00
try {
2024-02-06 04:11:40 +13:00
$response = $adapter->send($data);
$deliveredTotal += $response['deliveredTo'];
foreach ($response['results'] as $result) {
if ($result['status'] === 'failure') {
$deliveryErrors[] = "Failed sending to target {$result['recipient']} with error: {$result['error']}";
}
// Deleting push targets when token has expired.
if (($result['error'] ?? '') === 'Expired device token') {
2024-01-11 15:55:08 +13:00
$target = $dbForProject->findOne('targets', [
2024-02-06 04:11:40 +13:00
Query::equal('identifier', [$result['recipient']])
2024-01-11 15:55:08 +13:00
]);
if ($target instanceof Document && !$target->isEmpty()) {
$dbForProject->updateDocument(
'targets',
$target->getId(),
$target->setAttribute('expired', true)
);
}
}
}
} catch (\Throwable $e) {
$deliveryErrors[] = 'Failed sending to targets ' . $batchIndex + 1 . ' of ' . \count($batch) . ' with error: ' . $e->getMessage();
2023-10-27 03:14:06 +13:00
} finally {
$batchIndex++;
2024-01-11 15:55:08 +13:00
2023-10-27 03:14:06 +13:00
return [
2023-10-31 07:07:57 +13:00
'deliveredTotal' => $deliveredTotal,
2023-10-27 03:14:06 +13:00
'deliveryErrors' => $deliveryErrors,
];
}
};
}, $batches));
2023-10-04 23:45:59 +13:00
};
2024-01-11 15:55:08 +13:00
}, \array_keys($identifiers)));
2023-10-27 03:14:06 +13:00
$results = array_merge(...$results);
2023-10-04 23:45:59 +13:00
2023-10-31 07:07:57 +13:00
$deliveredTotal = 0;
2023-10-04 23:45:59 +13:00
$deliveryErrors = [];
2023-11-15 01:44:07 +13:00
2023-10-04 23:45:59 +13:00
foreach ($results as $result) {
2023-10-31 07:07:57 +13:00
$deliveredTotal += $result['deliveredTotal'];
2023-10-04 23:45:59 +13:00
$deliveryErrors = \array_merge($deliveryErrors, $result['deliveryErrors']);
}
2023-11-15 01:44:07 +13:00
if (empty($deliveryErrors) && $deliveredTotal === 0) {
$deliveryErrors[] = 'Unknown error';
}
2023-10-07 02:53:46 +13:00
$message->setAttribute('deliveryErrors', $deliveryErrors);
2023-10-07 02:53:46 +13:00
if (\count($message->getAttribute('deliveryErrors')) > 0) {
2024-01-19 16:15:54 +13:00
$message->setAttribute('status', MessageStatus::FAILED);
} else {
2024-01-19 16:15:54 +13:00
$message->setAttribute('status', MessageStatus::SENT);
}
2023-11-15 01:44:07 +13:00
2023-10-31 07:07:57 +13:00
$message->removeAttribute('to');
foreach ($providers as $provider) {
$message->setAttribute('search', "{$message->getAttribute('search')} {$provider->getAttribute('name')} {$provider->getAttribute('provider')} {$provider->getAttribute('type')}");
}
2023-10-31 07:07:57 +13:00
$message->setAttribute('deliveredTotal', $deliveredTotal);
2023-10-07 02:53:46 +13:00
$message->setAttribute('deliveredAt', DateTime::now());
2023-10-21 00:32:13 +13:00
$dbForProject->updateDocument('messages', $message->getId(), $message);
// Delete any attachments that were downloaded to the local cache
if ($provider->getAttribute('type') === MESSAGE_TYPE_EMAIL) {
2024-02-21 03:10:51 +13:00
if ($deviceForFiles->getType() === Storage::DEVICE_LOCAL) {
return;
}
$data = $message->getAttribute('data');
$attachments = $data['attachments'] ?? [];
foreach ($attachments as $attachment) {
$bucketId = $attachment['bucketId'];
$fileId = $attachment['fileId'];
$bucket = $dbForProject->getDocument('buckets', $bucketId);
if ($bucket->isEmpty()) {
throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND);
}
$file = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId);
if ($file->isEmpty()) {
throw new Exception(Exception::STORAGE_FILE_NOT_FOUND);
}
$path = $file->getAttribute('path', '');
2024-02-21 03:10:51 +13:00
if ($deviceForLocalFiles->exists($path)) {
$deviceForLocalFiles->delete($path);
}
}
}
2022-06-09 01:57:34 +12:00
}
2024-02-21 01:06:35 +13:00
private function sendInternalSMSMessage(Document $message, Document $project, array $recipients, Usage $queueForUsage, Log $log): void
2023-11-16 09:00:47 +13:00
{
2023-11-16 09:03:05 +13:00
if (empty(App::getEnv('_APP_SMS_PROVIDER')) || empty(App::getEnv('_APP_SMS_FROM'))) {
throw new \Exception('Skipped SMS processing. Missing "_APP_SMS_PROVIDER" or "_APP_SMS_FROM" environment variables.');
2023-11-16 09:00:47 +13:00
}
2024-02-12 14:18:19 +13:00
if ($project->isEmpty()) {
throw new Exception('Project not set in payload');
}
Console::log('Project: ' . $project->getId());
$denyList = App::getEnv('_APP_SMS_PROJECTS_DENY_LIST', '');
$denyList = explode(',', $denyList);
if (\in_array($project->getId(), $denyList)) {
Console::error('Project is in the deny list. Skipping...');
return;
}
2023-11-16 09:00:47 +13:00
$smsDSN = new DSN(App::getEnv('_APP_SMS_PROVIDER'));
$host = $smsDSN->getHost();
$password = $smsDSN->getPassword();
$user = $smsDSN->getUser();
$log->addTag('type', $host);
2023-11-16 09:00:47 +13:00
$from = App::getEnv('_APP_SMS_FROM');
$provider = new Document([
'$id' => ID::unique(),
'provider' => $host,
2023-11-29 17:05:37 +13:00
'type' => MESSAGE_TYPE_SMS,
2023-11-16 09:00:47 +13:00
'name' => 'Internal SMS',
'enabled' => true,
'credentials' => match ($host) {
'twilio' => [
'accountSid' => $user,
'authToken' => $password
],
'textmagic' => [
'username' => $user,
'apiKey' => $password
],
'telesign' => [
2024-02-12 15:10:18 +13:00
'customerId' => $user,
'apiKey' => $password
2023-11-16 09:00:47 +13:00
],
'msg91' => [
'senderId' => $user,
'authKey' => $password
],
'vonage' => [
'apiKey' => $user,
'apiSecret' => $password
],
default => null
},
'options' => [
'from' => $from
]
]);
2023-11-16 09:06:22 +13:00
2024-02-21 01:06:35 +13:00
$adapter = $this->getSmsAdapter($provider);
2023-11-16 09:00:47 +13:00
$maxBatchSize = $adapter->getMaxMessagesPerRequest();
$batches = \array_chunk($recipients, $maxBatchSize);
$batchIndex = 0;
2024-02-12 14:18:19 +13:00
batch(\array_map(function ($batch) use ($message, $provider, $adapter, $batchIndex, $project, $queueForUsage) {
return function () use ($batch, $message, $provider, $adapter, $batchIndex, $project, $queueForUsage) {
2023-11-16 09:00:47 +13:00
$message->setAttribute('to', $batch);
2024-02-21 01:06:35 +13:00
$data = $this->buildSmsMessage($message, $provider);
2023-11-16 09:00:47 +13:00
try {
$adapter->send($data);
2024-02-12 14:18:19 +13:00
$queueForUsage
->setProject($project)
->addMetric(METRIC_MESSAGES, 1)
->trigger();
} catch (\Throwable $e) {
2024-02-12 14:18:19 +13:00
throw new Exception('Failed sending to targets ' . $batchIndex + 1 . '-' . \count($batch) . ' with error: ' . $e->getMessage(), 500);
2023-11-16 09:00:47 +13:00
}
};
}, $batches));
}
2024-02-21 01:06:35 +13:00
private function getSmsAdapter(Document $provider): ?SMSAdapter
2023-10-04 23:45:59 +13:00
{
2023-10-07 02:53:46 +13:00
$credentials = $provider->getAttribute('credentials');
2024-02-12 14:18:19 +13:00
2023-10-07 02:53:46 +13:00
return match ($provider->getAttribute('provider')) {
2023-10-04 23:45:59 +13:00
'mock' => new Mock('username', 'password'),
'twilio' => new Twilio($credentials['accountSid'], $credentials['authToken']),
'textmagic' => new Textmagic($credentials['username'], $credentials['apiKey']),
2024-02-12 15:10:18 +13:00
'telesign' => new Telesign($credentials['customerId'], $credentials['apiKey']),
'msg91' => new Msg91($credentials['senderId'], $credentials['authKey'], $credentials['templateId']),
2023-10-04 23:45:59 +13:00
'vonage' => new Vonage($credentials['apiKey'], $credentials['apiSecret']),
default => null
};
}
2024-02-21 01:06:35 +13:00
private function getPushAdapter(Document $provider): ?PushAdapter
2023-10-04 23:45:59 +13:00
{
2023-10-07 02:53:46 +13:00
$credentials = $provider->getAttribute('credentials');
2024-02-12 14:18:19 +13:00
2023-10-07 02:53:46 +13:00
return match ($provider->getAttribute('provider')) {
'mock' => new Mock('username', 'password'),
2023-10-04 23:45:59 +13:00
'apns' => new APNS(
$credentials['authKey'],
$credentials['authKeyId'],
$credentials['teamId'],
$credentials['bundleId'],
),
2024-02-06 04:13:56 +13:00
'fcm' => new FCM(\json_encode($credentials['serviceAccountJSON'])),
2023-10-04 23:45:59 +13:00
default => null
};
}
2024-02-21 01:06:35 +13:00
private function getEmailAdapter(Document $provider): ?EmailAdapter
2023-10-04 23:45:59 +13:00
{
2024-02-01 17:51:28 +13:00
$credentials = $provider->getAttribute('credentials', []);
$options = $provider->getAttribute('options', []);
2024-02-12 14:18:19 +13:00
2023-10-07 02:53:46 +13:00
return match ($provider->getAttribute('provider')) {
'mock' => new Mock('username', 'password'),
2024-02-01 01:30:09 +13:00
'smtp' => new SMTP(
$credentials['host'],
$credentials['port'],
$credentials['username'],
$credentials['password'],
2024-02-01 17:51:28 +13:00
$options['encryption'],
$options['autoTLS'],
$options['mailer'],
2024-02-01 01:30:09 +13:00
),
'mailgun' => new Mailgun(
$credentials['apiKey'],
$credentials['domain'],
$credentials['isEuRegion']
),
'sendgrid' => new Sendgrid($credentials['apiKey']),
2023-10-04 23:45:59 +13:00
default => null
};
}
private function buildEmailMessage(
Database $dbForProject,
Document $message,
Document $provider,
2024-02-21 03:10:51 +13:00
Device $deviceForFiles,
Device $deviceForLocalFiles,
): Email {
2024-02-01 01:30:09 +13:00
$fromName = $provider['options']['fromName'] ?? null;
$fromEmail = $provider['options']['fromEmail'] ?? null;
$replyToEmail = $provider['options']['replyToEmail'] ?? null;
$replyToName = $provider['options']['replyToName'] ?? null;
2023-12-15 03:19:24 +13:00
$data = $message['data'] ?? [];
$ccTargets = $data['cc'] ?? [];
$bccTargets = $data['bcc'] ?? [];
$cc = [];
$bcc = [];
$attachments = $data['attachments'] ?? [];
2023-12-15 03:19:24 +13:00
if (!empty($ccTargets)) {
$ccTargets = $dbForProject->find('targets', [
Query::equal('$id', $ccTargets),
Query::limit(\count($ccTargets)),
]);
2023-12-15 03:19:24 +13:00
foreach ($ccTargets as $ccTarget) {
$cc[] = ['email' => $ccTarget['identifier']];
}
}
if (!empty($bccTargets)) {
$bccTargets = $dbForProject->find('targets', [
Query::equal('$id', $bccTargets),
Query::limit(\count($bccTargets)),
]);
2023-12-15 03:19:24 +13:00
foreach ($bccTargets as $bccTarget) {
$bcc[] = ['email' => $bccTarget['identifier']];
}
}
if (!empty($attachments)) {
foreach ($attachments as &$attachment) {
$bucketId = $attachment['bucketId'];
$fileId = $attachment['fileId'];
$bucket = $dbForProject->getDocument('buckets', $bucketId);
if ($bucket->isEmpty()) {
throw new Exception(Exception::STORAGE_BUCKET_NOT_FOUND);
}
$file = $dbForProject->getDocument('bucket_' . $bucket->getInternalId(), $fileId);
if ($file->isEmpty()) {
throw new Exception(Exception::STORAGE_FILE_NOT_FOUND);
}
$mimes = Config::getParam('storage-mimes');
$path = $file->getAttribute('path', '');
2024-02-21 03:10:51 +13:00
if (!$deviceForFiles->exists($path)) {
throw new Exception(Exception::STORAGE_FILE_NOT_FOUND, 'File not found in ' . $path);
}
$contentType = 'text/plain';
if (\in_array($file->getAttribute('mimeType'), $mimes)) {
$contentType = $file->getAttribute('mimeType');
}
2024-02-21 03:10:51 +13:00
if ($deviceForFiles->getType() !== Storage::DEVICE_LOCAL) {
$deviceForFiles->transfer($path, $path, $deviceForLocalFiles);
}
$attachment = new Attachment(
$file->getAttribute('name'),
$path,
$contentType
);
}
}
$to = $message['to'];
2023-12-15 03:19:24 +13:00
$subject = $data['subject'];
$content = $data['content'];
2024-02-06 04:13:35 +13:00
$html = $data['html'] ?? false;
2023-10-04 23:45:59 +13:00
return new Email(
$to,
$subject,
$content,
$fromName,
$fromEmail,
$replyToName,
$replyToEmail,
$cc,
$bcc,
$attachments,
$html
);
}
2024-02-21 01:06:35 +13:00
private function buildSmsMessage(Document $message, Document $provider): SMS
{
$to = $message['to'];
$content = $message['data']['content'];
$from = $provider['options']['from'];
return new SMS(
$to,
$content,
$from
);
}
2023-10-04 23:45:59 +13:00
private function buildPushMessage(Document $message): Push
{
$to = $message['to'];
$title = $message['data']['title'];
$body = $message['data']['body'];
2024-02-06 04:13:35 +13:00
$data = $message['data']['data'] ?? null;
$action = $message['data']['action'] ?? null;
$image = $message['data']['image'] ?? null;
2024-02-06 04:13:35 +13:00
$sound = $message['data']['sound'] ?? null;
$icon = $message['data']['icon'] ?? null;
$color = $message['data']['color'] ?? null;
$tag = $message['data']['tag'] ?? null;
$badge = $message['data']['badge'] ?? null;
2023-10-04 23:45:59 +13:00
return new Push(
$to,
$title,
$body,
$data,
$action,
$sound,
$image,
$icon,
$color,
$tag,
$badge
);
}
2022-06-09 01:57:34 +12:00
}