1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-09-21 17:01:33 +02:00
invoiceninja/app/Jobs/Mail/NinjaMailerJob.php

452 lines
15 KiB
PHP
Raw Normal View History

2021-02-14 11:43:44 +01:00
<?php
/**
* Invoice Ninja (https://invoiceninja.com).
*
* @link https://github.com/invoiceninja/invoiceninja source repository
*
2022-04-27 05:20:41 +02:00
* @copyright Copyright (c) 2022. Invoice Ninja LLC (https://invoiceninja.com)
2021-02-14 11:43:44 +01:00
*
2021-06-16 08:58:16 +02:00
* @license https://www.elastic.co/licensing/elastic-license
2021-02-14 11:43:44 +01:00
*/
namespace App\Jobs\Mail;
use App\DataMapper\Analytics\EmailFailure;
2021-04-24 15:19:46 +02:00
use App\DataMapper\Analytics\EmailSuccess;
2021-02-16 13:56:12 +01:00
use App\Events\Invoice\InvoiceWasEmailedAndFailed;
2021-02-18 00:30:31 +01:00
use App\Events\Payment\PaymentWasEmailedAndFailed;
2021-02-14 11:43:44 +01:00
use App\Jobs\Mail\NinjaMailerObject;
use App\Jobs\Util\SystemLogger;
use App\Libraries\Google\Google;
use App\Libraries\MultiDB;
2021-02-16 13:56:12 +01:00
use App\Mail\TemplateEmail;
2021-02-14 11:43:44 +01:00
use App\Models\ClientContact;
2021-05-13 15:37:25 +02:00
use App\Models\Company;
2021-02-18 00:30:31 +01:00
use App\Models\Invoice;
use App\Models\Payment;
2021-02-14 11:43:44 +01:00
use App\Models\SystemLog;
use App\Models\User;
use App\Providers\MailServiceProvider;
use App\Utils\Ninja;
use App\Utils\Traits\MakesHash;
2021-02-18 00:30:31 +01:00
use Dacastro4\LaravelGmail\Facade\LaravelGmail;
2021-09-06 05:07:11 +02:00
use GuzzleHttp\Exception\ClientException;
2021-02-14 11:43:44 +01:00
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Mail;
use Turbo124\Beacon\Facades\LightLogs;
2021-08-07 11:32:31 +02:00
use Illuminate\Support\Facades\Cache;
2021-02-14 11:43:44 +01:00
/*Multi Mailer implemented*/
class NinjaMailerJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, MakesHash;
public $tries = 3; //number of retries
2021-02-14 11:43:44 +01:00
2022-09-17 05:30:02 +02:00
public $backoff = 30; //seconds to wait until retry
2021-02-14 11:43:44 +01:00
public $deleteWhenMissingModels = true;
public $nmo;
public $override;
public $company;
2021-06-17 09:48:23 +02:00
private $mailer;
public function __construct(NinjaMailerObject $nmo, bool $override = false)
2021-02-14 11:43:44 +01:00
{
$this->nmo = $nmo;
2021-05-22 08:03:34 +02:00
$this->override = $override;
2021-02-14 11:43:44 +01:00
}
public function handle()
{
2021-06-29 22:23:23 +02:00
2021-02-16 13:56:12 +01:00
/*Set the correct database*/
2021-02-14 11:43:44 +01:00
MultiDB::setDb($this->nmo->company->db);
/* Serializing models from other jobs wipes the primary key */
$this->company = Company::where('company_key', $this->nmo->company->company_key)->first();
2021-05-13 15:37:25 +02:00
2021-08-07 12:56:42 +02:00
if($this->preFlightChecksFail())
return;
2021-02-16 13:56:12 +01:00
/* Set the email driver */
2021-02-14 11:43:44 +01:00
$this->setMailDriver();
2021-02-24 00:39:37 +01:00
if (strlen($this->nmo->settings->reply_to_email) > 1) {
2021-05-03 06:50:55 +02:00
if(property_exists($this->nmo->settings, 'reply_to_name'))
$reply_to_name = strlen($this->nmo->settings->reply_to_name) > 3 ? $this->nmo->settings->reply_to_name : $this->nmo->settings->reply_to_email;
else
$reply_to_name = $this->nmo->settings->reply_to_email;
2021-02-24 00:39:37 +01:00
$this->nmo->mailable->replyTo($this->nmo->settings->reply_to_email, $reply_to_name);
}
2021-05-13 00:13:33 +02:00
else {
$this->nmo->mailable->replyTo($this->company->owner()->email, $this->company->owner()->present()->name());
2021-05-13 00:13:33 +02:00
}
2022-08-07 09:34:23 +02:00
$this->nmo->mailable->tag($this->company->company_key);
2022-08-17 09:18:30 +02:00
if($this->nmo->invitation)
{
$this->nmo
->mailable
->withSymfonyMessage(function ($message) {
$message->getHeaders()->addTextHeader('x-invitation', $this->nmo->invitation->key);
});
}
2021-02-14 11:43:44 +01:00
//send email
try {
nlog("trying to send to {$this->nmo->to_user->email} ". now()->toDateTimeString());
2021-06-23 00:17:22 +02:00
nlog("Using mailer => ". $this->mailer);
2021-06-17 09:48:23 +02:00
Mail::mailer($this->mailer)
->to($this->nmo->to_user->email)
2021-02-14 11:43:44 +01:00
->send($this->nmo->mailable);
2021-04-25 00:18:35 +02:00
2021-08-07 11:32:31 +02:00
/* Count the amount of emails sent across all the users accounts */
Cache::increment($this->company->account->key);
2021-07-23 11:38:30 +02:00
LightLogs::create(new EmailSuccess($this->nmo->company->company_key))
->send();
2022-10-26 04:27:04 +02:00
} catch (\Exception | \RuntimeException | \Google\Service\Exception $e) {
2021-07-23 11:38:30 +02:00
2021-02-14 12:36:36 +01:00
nlog("error failed with {$e->getMessage()}");
2021-02-16 13:56:12 +01:00
2021-09-06 05:07:11 +02:00
$message = $e->getMessage();
2022-10-26 04:27:04 +02:00
if($e instanceof \Google\Service\Exception){
if(($e->getCode() == 429) && ($this->nmo->to_user instanceof ClientContact))
$this->logMailError("Google rate limiter hit, we will retry in 30 seconds.", $this->nmo->to_user->client);
}
2021-09-08 03:04:50 +02:00
/**
* Post mark buries the proper message in a a guzzle response
* this merges a text string with a json object
* need to harvest the ->Message property using the following
*/
2021-09-06 05:07:11 +02:00
if($e instanceof ClientException) { //postmark specific failure
$response = $e->getResponse();
2021-09-08 03:04:50 +02:00
$message_body = json_decode($response->getBody()->getContents());
if($message_body && property_exists($message_body, 'Message')){
2021-09-08 03:04:50 +02:00
$message = $message_body->Message;
nlog($message);
}
2021-09-07 08:18:07 +02:00
2021-09-06 05:07:11 +02:00
}
2021-09-08 03:04:50 +02:00
/* If the is an entity attached to the message send a failure mailer */
2021-02-18 00:30:31 +01:00
if($this->nmo->entity)
2021-09-06 05:07:11 +02:00
$this->entityEmailFailed($message);
2021-05-20 23:58:46 +02:00
2021-09-08 03:04:50 +02:00
/* Don't send postmark failures to Sentry */
if(Ninja::isHosted() && (!$e instanceof ClientException))
2021-05-20 23:58:46 +02:00
app('sentry')->captureException($e);
2021-02-16 13:56:12 +01:00
}
}
/* Switch statement to handle failure notifications */
private function entityEmailFailed($message)
{
2021-02-18 00:30:31 +01:00
$class = get_class($this->nmo->entity);
switch ($class) {
case Invoice::class:
2021-04-14 06:41:04 +02:00
event(new InvoiceWasEmailedAndFailed($this->nmo->invitation, $this->nmo->company, $message, $this->nmo->reminder_template, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
2021-02-16 13:56:12 +01:00
break;
2021-02-18 00:30:31 +01:00
case Payment::class:
2021-04-14 07:28:05 +02:00
event(new PaymentWasEmailedAndFailed($this->nmo->entity, $this->nmo->company, $message, Ninja::eventVars(auth()->user() ? auth()->user()->id : null)));
2021-02-18 00:30:31 +01:00
break;
2021-02-16 13:56:12 +01:00
default:
# code...
break;
2021-02-14 11:43:44 +01:00
}
2021-02-18 00:30:31 +01:00
if ($this->nmo->to_user instanceof ClientContact)
2021-02-18 01:12:49 +01:00
$this->logMailError($message, $this->nmo->to_user->client);
2021-02-14 11:43:44 +01:00
}
private function setMailDriver()
{
/* Singletons need to be rebooted each time just in case our Locale is changing*/
App::forgetInstance('translator');
2021-05-31 12:40:34 +02:00
$t = app('translator');
$t->replace(Ninja::transformTranslations($this->nmo->settings));
2021-02-14 11:43:44 +01:00
switch ($this->nmo->settings->email_sending_method) {
case 'default':
2021-06-17 09:48:23 +02:00
$this->mailer = config('mail.default');
2021-02-14 11:43:44 +01:00
break;
case 'gmail':
2021-06-17 09:48:23 +02:00
$this->mailer = 'gmail';
2021-02-14 11:43:44 +01:00
$this->setGmailMailer();
break;
2022-06-17 10:28:31 +02:00
case 'office365':
$this->mailer = 'office365';
$this->setOfficeMailer();
break;
2021-02-14 11:43:44 +01:00
default:
break;
}
2021-02-17 01:25:30 +01:00
2021-02-14 11:43:44 +01:00
}
2022-06-17 10:28:31 +02:00
private function setOfficeMailer()
{
$sending_user = $this->nmo->settings->gmail_sending_user_id;
$user = User::find($this->decodePrimaryKey($sending_user));
2022-06-17 10:37:45 +02:00
2022-06-27 08:37:18 +02:00
/* Always ensure the user is set on the correct account */
if($user->account_id != $this->company->account_id){
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
2022-06-17 10:28:31 +02:00
nlog("Sending via {$user->name()}");
2022-06-17 10:37:45 +02:00
$token = $this->refreshOfficeToken($user);
if($token)
{
$user->oauth_user_token = $token;
$user->save();
}
else {
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
2022-06-17 10:28:31 +02:00
$this->nmo
->mailable
->from($user->email, $user->name())
2022-07-31 11:11:32 +02:00
->withSymfonyMessage(function ($message) use($token) {
2022-07-31 13:51:35 +02:00
$message->getHeaders()->addTextHeader('gmailtoken', $token);
2022-06-17 10:28:31 +02:00
});
2022-06-17 10:37:45 +02:00
sleep(rand(1,3));
2022-06-17 10:28:31 +02:00
}
2021-02-14 11:43:44 +01:00
private function setGmailMailer()
{
2021-02-17 01:25:30 +01:00
2021-02-16 11:59:49 +01:00
$sending_user = $this->nmo->settings->gmail_sending_user_id;
2021-02-14 11:43:44 +01:00
$user = User::find($this->decodePrimaryKey($sending_user));
2022-06-27 08:37:18 +02:00
/* Always ensure the user is set on the correct account */
if($user->account_id != $this->company->account_id){
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
2021-02-22 10:54:46 +01:00
nlog("Sending via {$user->name()}");
2021-02-16 12:19:07 +01:00
2021-02-14 11:43:44 +01:00
$google = (new Google())->init();
try{
if ($google->getClient()->isAccessTokenExpired()) {
$google->refreshToken($user);
$user = $user->fresh();
}
$google->getClient()->setAccessToken(json_encode($user->oauth_user_token));
sleep(rand(2,4));
}
catch(\Exception $e) {
$this->logMailError('Gmail Token Invalid', $this->company->clients()->first());
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
2021-02-14 11:43:44 +01:00
2022-03-23 22:34:52 +01:00
/**
* If the user doesn't have a valid token, notify them
*/
if(!$user->oauth_user_token) {
$this->company->account->gmailCredentialNotification();
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
2022-03-23 22:34:52 +01:00
}
2021-02-14 11:43:44 +01:00
/*
* Now that our token is refreshed and valid we can boot the
* mail driver at runtime and also set the token which will persist
* just for this request.
*/
$token = $user->oauth_user_token->access_token;
2021-02-17 01:25:30 +01:00
if(!$token) {
$this->company->account->gmailCredentialNotification();
$this->nmo->settings->email_sending_method = 'default';
return $this->setMailDriver();
}
$this->nmo
->mailable
2021-02-22 10:54:46 +01:00
->from($user->email, $user->name())
2022-07-31 11:11:32 +02:00
->withSymfonyMessage(function ($message) use($token) {
2022-07-31 13:51:35 +02:00
$message->getHeaders()->addTextHeader('gmailtoken', $token);
});
2021-02-14 11:43:44 +01:00
}
2021-06-29 22:23:23 +02:00
private function preFlightChecksFail()
{
2021-06-29 22:23:23 +02:00
/* If we are migrating data we don't want to fire any emails */
2022-07-01 13:08:20 +02:00
if($this->company->is_disabled && !$this->override)
2021-06-29 22:23:23 +02:00
return true;
2022-08-19 04:09:50 +02:00
/* To handle spam users we drop all emails from flagged accounts */
if(Ninja::isHosted() && $this->company->account && $this->company->account->is_flagged)
return true;
2021-06-29 22:23:23 +02:00
/* On the hosted platform we set default contacts a @example.com email address - we shouldn't send emails to these types of addresses */
if(Ninja::isHosted() && $this->nmo->to_user && strpos($this->nmo->to_user->email, '@example.com') !== false)
2021-06-29 22:23:23 +02:00
return true;
2021-08-09 12:33:59 +02:00
/* GMail users are uncapped */
if(Ninja::isHosted() && ($this->nmo->settings->email_sending_method == 'gmail' || $this->nmo->settings->email_sending_method == 'office365'))
2021-08-09 12:33:59 +02:00
return false;
2022-08-19 02:36:13 +02:00
/* On the hosted platform, if the user is over the email quotas, we do not send the email. */
if(Ninja::isHosted() && $this->company->account && $this->company->account->emailQuotaExceeded())
return true;
2022-07-23 01:19:06 +02:00
/* If the account is verified, we allow emails to flow */
2022-07-24 09:44:40 +02:00
if(Ninja::isHosted() && $this->company->account && $this->company->account->is_verified_account) {
/* Continue to analyse verified accounts in case they later start sending poor quality emails*/
if(class_exists(\Modules\Admin\Jobs\Account\EmailQuality::class))
(new \Modules\Admin\Jobs\Account\EmailQuality($this->nmo, $this->company))->run();
2022-07-23 01:19:06 +02:00
return false;
2022-07-24 09:44:40 +02:00
}
2022-07-23 01:19:06 +02:00
/* Ensure the user has a valid email address */
if(!str_contains($this->nmo->to_user->email, "@"))
return true;
2022-08-31 06:30:23 +02:00
/* On the hosted platform if the user has not verified their account we fail here - but still check what they are trying to send! */
if(Ninja::isHosted() && $this->company->account && !$this->company->account->account_sms_verified){
if(class_exists(\Modules\Admin\Jobs\Account\EmailQuality::class))
return (new \Modules\Admin\Jobs\Account\EmailQuality($this->nmo, $this->company))->run();
return true;
2022-08-31 06:30:23 +02:00
}
2022-08-31 04:05:15 +02:00
/* On the hosted platform we actively scan all outbound emails to ensure outbound email quality remains high */
if(class_exists(\Modules\Admin\Jobs\Account\EmailQuality::class))
return (new \Modules\Admin\Jobs\Account\EmailQuality($this->nmo, $this->company))->run();
2021-06-29 22:23:23 +02:00
return false;
}
2021-02-14 11:43:44 +01:00
private function logMailError($errors, $recipient_object)
{
2021-09-06 05:07:11 +02:00
2021-02-14 11:43:44 +01:00
SystemLogger::dispatch(
$errors,
SystemLog::CATEGORY_MAIL,
SystemLog::EVENT_MAIL_SEND,
SystemLog::TYPE_FAILURE,
$recipient_object,
$this->nmo->company
2021-02-14 11:43:44 +01:00
);
2021-04-24 15:19:46 +02:00
$job_failure = new EmailFailure($this->nmo->company->company_key);
2021-04-25 06:36:22 +02:00
$job_failure->string_metric5 = 'failed_email';
2021-09-06 05:07:11 +02:00
$job_failure->string_metric6 = substr($errors, 0, 150);
2021-02-14 11:43:44 +01:00
LightLogs::create($job_failure)
->send();
2021-02-14 11:43:44 +01:00
}
2021-08-07 11:32:31 +02:00
2021-09-06 05:07:11 +02:00
public function failed($exception = null)
{
}
2022-06-17 10:37:45 +02:00
private function refreshOfficeToken($user)
{
2022-06-22 11:18:00 +02:00
$expiry = $user->oauth_user_token_expiry ?: now()->subDay();
2022-06-17 10:37:45 +02:00
2022-06-22 11:18:00 +02:00
if($expiry->lt(now()))
2022-06-22 11:15:31 +02:00
{
$guzzle = new \GuzzleHttp\Client();
$url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
$token = json_decode($guzzle->post($url, [
'form_params' => [
'client_id' => config('ninja.o365.client_id') ,
'client_secret' => config('ninja.o365.client_secret') ,
'scope' => 'email Mail.Send offline_access profile User.Read openid',
2022-06-22 11:15:31 +02:00
'grant_type' => 'refresh_token',
'refresh_token' => $user->oauth_user_refresh_token
],
])->getBody()->getContents());
2022-06-22 11:26:14 +02:00
nlog($token);
2022-06-22 11:15:31 +02:00
if($token){
2022-06-22 11:21:58 +02:00
$user->oauth_user_refresh_token = property_exists($token, 'refresh_token') ? $token->refresh_token : $user->oauth_user_refresh_token;
2022-06-22 11:15:31 +02:00
$user->oauth_user_token = $token->access_token;
$user->oauth_user_token_expiry = now()->addSeconds($token->expires_in);
$user->save();
return $token->access_token;
}
return false;
}
2022-07-03 07:52:13 +02:00
return $user->oauth_user_token;
2022-06-22 11:15:31 +02:00
2022-06-17 10:37:45 +02:00
}
2022-06-23 10:47:44 +02:00
/**
* Is this the cleanest way to requeue a job?
*
* $this->delete();
*
* $job = NinjaMailerJob::dispatch($this->nmo, $this->override)->delay(3600);
*/
2021-08-07 11:32:31 +02:00
}