This repository was archived by the owner on Mar 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathPlugin.php
More file actions
315 lines (286 loc) · 9.57 KB
/
Plugin.php
File metadata and controls
315 lines (286 loc) · 9.57 KB
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
<?php
/**
* This file is part of PhergieUrl.
*
** (c) 2014 Cees-Jan Kiewiet
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Phergie\Irc\Plugin\React\Url;
use GuzzleHttp\Message\Response;
use React\EventLoop\LoopInterface;
use Phergie\Irc\Bot\React\AbstractPlugin;
use Phergie\Irc\Bot\React\EventQueue;
use Phergie\Irc\Client\React\LoopAwareInterface;
use Phergie\Irc\Event\UserEvent;
use Phergie\Irc\Plugin\React\EventFilter\FilterInterface;
use React\Promise\Deferred;
use Phergie\Plugin\Http\Request;
/**
* Plugin for Display URL information about links.
*
* @category Phergie
* @package Phergie\Irc\Plugin\React\Url
*/
class Plugin extends AbstractPlugin implements LoopAwareInterface
{
const URL_HANDLER_INTERFACE = 'Phergie\Irc\Plugin\React\Url\UrlHandlerInterface';
const EVENT_FILTER_INTERFACE = 'Phergie\Irc\Plugin\React\EventFilter\FilterInterface';
/**
* @var UrlHandlerInterface
*/
protected $handler = null;
/**
* @var UrlHandlerInterface
*/
protected $shortenTimeout = 15;
/**
* @var bool
*/
protected $hostUrlEmitsOnly = false;
/**
* @var FilterInterface
*/
protected $filter = null;
/**
* @var LoopInterface
*/
protected $loop;
/**
* Accepts plugin configuration.
*
* Supported keys:
*
* handler - handler to create a message for the given URL
* shortenTimeout - timeout in seconds how long it can take to short an URL
*
* @param array $config
*/
public function __construct(array $config = [])
{
if (
isset($config['handler']) &&
in_array(static::URL_HANDLER_INTERFACE, class_implements($config['handler']))
) {
$this->handler = $config['handler'];
} else {
$this->handler = new DefaultUrlHandler();
}
if (isset($config['shortenTimeout'])) {
$this->shortenTimeout = $config['shortenTimeout'];
}
if (isset($config['hostUrlEmitsOnly'])) {
$this->hostUrlEmitsOnly = boolval($config['hostUrlEmitsOnly']);
}
if (
isset($config['filter']) &&
in_array(static::EVENT_FILTER_INTERFACE, class_implements($config['filter']))
) {
$this->filter = $config['filter'];
}
}
/**
* @param LoopInterface $loop
*/
public function setLoop(LoopInterface $loop)
{
$this->loop = $loop;
}
/**
*
*
* @return array
*/
public function getSubscribedEvents()
{
return [
'irc.received.privmsg' => 'handleIrcReceived',
];
}
/**
* @return UrlHandlerInterface
*/
public function getHandler()
{
return $this->handler;
}
/**
* @param string $message
*/
public function logDebug($message)
{
$this->logger->debug('[Url]' . $message);
}
public function handleIrcReceived(UserEvent $event, EventQueue $queue)
{
if (
$this->filter !== null &&
$this->filter->filter($event) !== false
) {
return;
}
$params = $event->getParams();
$extractor = new \Twitter_Extractor($params['text']);
$urls = $extractor->extractURLs();
foreach ($urls as $url) {
$this->handleUrl($url, $event, $queue);
}
}
/**
* @param string $url
* @param UserEvent $event
* @param EventQueue $queue
*
* @return bool
*/
public function handleUrl($url, UserEvent $event, EventQueue $queue)
{
$parsedUrl = parse_url($url);
if (
(!isset($parsedUrl['host']) && !isset($parsedUrl['path'])) ||
(!isset($parsedUrl['host']) && isset($parsedUrl['path']) && $parsedUrl['path'] == '')
) {
return false;
}
$requestId = uniqid();
$this->logDebug('[' . $requestId . ']Found url: ' . $url);
if (count($parsedUrl) == 1 && isset($parsedUrl['path'])) {
$url = 'http://' . $parsedUrl['path'] . '/';
$this->logDebug('[' . $requestId . ']Corrected url: ' . $url);
}
if ($this->emitUrlEvents($requestId, $url, $event, $queue) && !$this->hostUrlEmitsOnly) {
$this->logDebug('[' . $requestId . ']Emitting: http.request');
$this->emitter->emit('http.request', [$this->createRequest($requestId, $url, $event, $queue)]);
}
$this->logDebug('[' . $requestId . ']Emitting: url.host.all');
$this->emitter->emit('url.host.all', [$url, $event, $queue]);
return true;
}
/**
* @param string $requestId
* @param string $url
* @param UserEvent $event
* @param EventQueue $queue
*
* @return Request
*/
public function createRequest($requestId, $url, UserEvent $event, EventQueue $queue)
{
$start = microtime(true);
return new Request([
'url' => $url,
'responseCallback' => function ($headers, $code) use ($requestId, $start) {
$end = microtime(true);
$this->logDebug('[' . $requestId . ']Reponse (after ' . ($end - $start) . 's): ' . $code);
},
'resolveCallback' =>
function (Response $response) use ($requestId, $url, $event, $queue, $start) {
$data = $response->getBody()->getContents();
$headers = $response->getHeaders();
array_walk($headers, function (&$value, $key) use ($response) {
$value = $response->getHeader($key);
});
$code = $response->getStatusCode();
$end = microtime(true);
$message = '[';
$message .= $requestId;
$message .= ']Download complete (after ';
$message .= ($end - $start);
$message .= 's): ';
$message .= strlen($data);
$message .= ' in length length';
$this->logDebug($message);
$this->emitShorteningEvents($requestId, $url)->then(
function ($shortUrl) use ($url, $data, $headers, $code, $end, $start, $event, $queue) {
$this->sendMessage(
new Url($url, $data, $headers, $code, $end - $start, $shortUrl),
$event,
$queue
);
},
function () use ($url, $data, $headers, $code, $end, $start, $event, $queue) {
$this->sendMessage(new Url($url, $data, $headers, $code, $end - $start), $event, $queue);
}
);
},
]);
}
/**
* @param string $requestId
* @param string $url
* @param UserEvent $event
* @param EventQueue $queue
*
* @return bool
*/
protected function emitUrlEvents($requestId, $url, UserEvent $event, EventQueue $queue)
{
$host = Url::extractHost($url);
$eventName = 'url.host.' . $host;
if (count($this->emitter->listeners($eventName)) > 0) {
$this->logDebug('[' . $requestId . ']Emitting: ' . $eventName);
$this->emitter->emit($eventName, [$url, $event, $queue]);
return false;
} else {
return true;
}
}
/**
* @param string $requestId
* @param string $url
*
* @return \React\Promise\DeferredPromise
*/
protected function emitShorteningEvents($requestId, $url)
{
$host = Url::extractHost($url);
list($privateDeferred, $userFacingPromise) = $this->preparePromises();
$eventName = 'url.shorten.';
if (count($this->emitter->listeners($eventName . $host)) > 0) {
$eventName .= $host;
$this->logDebug('[' . $requestId . ']Emitting: ' . $eventName);
$this->emitter->emit($eventName, [$url, $privateDeferred]);
} elseif (count($this->emitter->listeners($eventName . 'all')) > 0) {
$eventName .= 'all';
$this->logDebug('[' . $requestId . ']Emitting: ' . $eventName);
$this->emitter->emit($eventName, [$url, $privateDeferred]);
} else {
$this->loop->addTimer(0.1, function () use ($privateDeferred) {
$privateDeferred->reject();
});
}
return $userFacingPromise;
}
/**
* @return array
*/
protected function preparePromises()
{
$userFacingDeferred = new Deferred();
$privateDeferred = new Deferred();
$userFacingPromise = $userFacingDeferred->promise();
$privateDeferred->promise()->then(function ($shortUrl) use ($userFacingDeferred) {
$userFacingDeferred->resolve($shortUrl);
}, function () use ($userFacingDeferred) {
$userFacingDeferred->reject();
});
$this->loop->addTimer($this->shortenTimeout, function () use ($privateDeferred) {
$privateDeferred->reject();
});
return [
$privateDeferred,
$userFacingPromise,
];
}
/**
* @param Url $url
* @param UserEvent $event
* @param EventQueue $queue
*/
protected function sendMessage(Url $url, UserEvent $event, EventQueue $queue)
{
$message = $this->getHandler()->handle($url);
$queue->ircPrivmsg($event->getSource(), $message);
}
}