-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mailbox.php
333 lines (298 loc) · 8.55 KB
/
Mailbox.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
<?php
/**
* OriginPHP Framework
* Copyright 2018 - 2021 Jamiel Sharief.
*
* Licensed under The MIT License
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* @copyright Copyright (c) Jamiel Sharief
* @link https://www.originphp.com
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
declare(strict_types = 1);
namespace Origin\Mailbox;
use Origin\Log\Log;
use Origin\Model\Entity;
use Origin\Core\Resolver;
use Origin\Core\HookTrait;
use Origin\Service\Result;
use Origin\Core\ModelTrait;
use Origin\Core\CallbacksTrait;
use Origin\Model\ModelRegistry;
use Origin\Core\Exception\Exception;
use Origin\Mailbox\Model\ImapMessage;
use Origin\Mailbox\Model\InboundEmail;
use Origin\Mailbox\Service\MailboxDownloadService;
use Origin\Core\Exception\InvalidArgumentException;
use Origin\Configurable\StaticConfigurable as Configurable;
/**
* Add the process method to your class
* @method void process() This will be called by dispatch
*/
abstract class Mailbox
{
use HookTrait;
use Configurable;
use ModelTrait;
use CallbacksTrait;
/**
* Inbound email id (not email message id)
*
* @var int
*/
protected $id;
/**
* Mail object created when mailbox is dispatched.
*
* @internal Similar to how a request is placed in controller
*
* @var \Origin\Mailbox\Mail
*/
protected $mail;
/**
* Inbound Email Model
*
* @var \Origin\Mailbox\InboundEmail
*/
protected $InboundEmail;
/**
* Holds the mailbox routes
*
* example ['/^support@/i' => 'Support']
*
* @var array
*/
private static $routes = [];
/**
* Has the mail been bounced?
*
* @var bool
*/
private $bounced = false;
/**
* Constructor
*
* @param \Origin\Model\Entity $inboundEmai
*/
public function __construct(Entity $inboundEmail)
{
$this->id = (int) $inboundEmail->id;
$this->mail = new Mail($inboundEmail->message);
$this->InboundEmail = ModelRegistry::get('InboundEmail', ['className' => InboundEmail::class]);
$this->executeHook('initialize', [$inboundEmail]);
}
/**
* Registers a callback before an email is processed
*
* example
*
* protected function initialize(): void
* {
* $this->loadModel('User');
* $this->beforeProcess('checkIsUser');
* }
*
* protected function checkIsUser(): void
* {
* if (!$this->User->findBy(['email' => $this->mail->from])) {
* $this->bounceWith(UnkownUserMailer::class);
* }
* }
*
* @param string $method
* @return void
*/
protected function beforeProcess(string $method): void
{
$this->registerCallback('beforeProcess', $method);
}
/**
* Registers a callback after an email is processed
*
* @param string $method
* @return void
*/
protected function afterProcess(string $method): void
{
$this->registerCallback('afterProcess', $method);
}
/**
* Registers a callback for handling errors
*
* @param string $method
* @return void
*/
protected function onError(string $method): void
{
$this->registerCallback('onError', $method);
}
/**
* Registers a callback which run if successful
*
* @param string $method
* @return void
*/
protected function onSuccess(string $method): void
{
$this->registerCallback('onSuccess', $method);
}
/**
* Dispatches the message to the mailbox
*
* @param \Origin\Model\Entity $message
* @return bool
*/
public function dispatch(): bool
{
$this->executeHook('startup');
$result = $this->performProcessing();
$this->executeHook('shutdown');
return $result;
}
/**
* Sets
*
* @return boolean
*/
private function performProcessing(): bool
{
$this->setStatus('processing');
try {
if ($this->dispatchCallback('beforeProcess') && $this->bounced === false) {
$this->process();
$this->dispatchCallback('afterProcess');
$this->setStatus('delivered');
$this->dispatchCallback('onSuccess');
}
return true;
} catch (\Exception $exception) {
$this->setStatus('failed');
Log::error($exception->getMessage());
$this->dispatchCallback('onError', [$exception], false);
}
return false;
}
/**
* Bounces a message with a mailer, the \Origin\Mailbox\Mail object will be passed
* to the mailer. This will also halt futher processing
*
* @param \Origin\Mailer\Mailer $mailer UnkownUserMailer::class or 'UnkownUser' or 'App\Mailer\UnownUserMailer'
* @return bool result of dispatchLater
*/
protected function bounceWith(string $mailerClass): bool
{
$this->setStatus('bounced');
$this->bounced = true;
$className = Resolver::className($mailerClass, 'Mailer');
if ($className) {
return (new $className())->dispatchLater($this->mail);
}
throw new Exception('Missing class ' . $mailerClass);
}
/**
* Adds a route for a mailbox using a regex pattern
*
* Examples :
* - /^support@/i
* - /@replies\./i
* - /reply-(.+)@reply.example.com
*
* @param string $regex /^support@/i , /@replies\./i
* @param string $mailbox name of the mailbox in studly caps without Mailbox prefix
* @return void
*/
public static function route(string $regex, string $mailbox): void
{
static::$routes[$regex] = $mailbox;
}
/**
* Gets the routes for the Mailboxes
*
* @return mixed
*/
public static function routes(string $regex = null)
{
if ($regex === null) {
return static::$routes;
}
return static::$routes[$regex] ?? null;
}
/**
* Finds the mailbox by matching recipient email address to route
*
* @param array $recipients
* @return string|null
*/
public static function mailbox(array $recipients): ?string
{
foreach (static::routes() as $route => $mailbox) {
foreach ($recipients as $address) {
if (preg_match($route, $address)) {
return Resolver::className($mailbox, 'Mailbox', 'Mailbox');
}
}
}
return null;
}
/**
* Gets the configured email account
*
* @param string $account
* @return array
*/
public static function account(string $account): array
{
if (isset(static::$config[$account])) {
$config = static::$config[$account];
$config += [
'host' => 'localhost',
'port' => 143,
'username' => null,
'password' => null,
'encryption' => null,
'validateCert' => true,
'protocol' => 'imap',
'timeout' => 30
];
return $config;
}
throw new InvalidArgumentException(sprintf('The email account `%s` does not exist.', $account));
}
/**
* Undocumented function
*
* @param string $account
* @param array $options The following options keys are supported
* - limit: the maximum number of messages to download
* - messageId: The last message id downloaded (IMAP)
* @return \Origin\Service\Result
*/
public static function download(string $account, array $options = []): Result
{
$options += ['limit' => null,'messageId' => null];
$Imap = ModelRegistry::get('Imap', ['className' => ImapMessage::class]);
$InboundEmail = ModelRegistry::get('InboundEmail', ['className' => InboundEmail::class]);
return (new MailboxDownloadService($InboundEmail, $Imap))->dispatch($account, $options);
}
/**
* Sets the status for the inbound email
*
* @param string $status processing/delivered/failed/bounced
* @return void
*/
private function setStatus(string $status): void
{
$this->InboundEmail->setStatus($this->id, $status);
}
/**
* Gets the mail object
*
* @return \Origin\Mailbox\Mail
*/
public function mail(): Mail
{
return $this->mail;
}
}