-
Notifications
You must be signed in to change notification settings - Fork 19
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
71 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
<?php declare(strict_types=1); | ||
|
||
namespace Room11\Jeeves\Chat\Plugin; | ||
|
||
use Room11\Jeeves\Chat\Client\Xhr as ChatClient; | ||
use Room11\Jeeves\Chat\Command\Message; | ||
use Amp\Artax\Response; | ||
|
||
class Imdb implements Plugin | ||
{ | ||
const COMMAND = 'imdb'; | ||
|
||
private $chatClient; | ||
|
||
public function __construct(ChatClient $chatClient) | ||
{ | ||
$this->chatClient = $chatClient; | ||
} | ||
|
||
public function handle(Message $message): \Generator | ||
{ | ||
if (!$this->validMessage($message)) { | ||
return; | ||
} | ||
|
||
yield from $this->getResult($message); | ||
} | ||
|
||
private function validMessage(Message $message): bool | ||
{ | ||
return get_class($message) === 'Room11\Jeeves\Chat\Command\Command' | ||
&& $message->getCommand() === self::COMMAND | ||
&& $message->getParameters(); | ||
} | ||
|
||
private function getResult(Message $message): \Generator | ||
{ | ||
$response = yield from $this->chatClient->request( | ||
'http://www.imdb.com/xml/find?xml=1&nr=1&tt=on&q=' . rawurlencode(implode(' ', $message->getParameters())) | ||
); | ||
|
||
yield from $this->chatClient->postMessage( | ||
$this->getMessage($response) | ||
); | ||
} | ||
|
||
private function getMessage(Response $response): string | ||
{ | ||
$internalErrors = libxml_use_internal_errors(true); | ||
|
||
$dom = new \DOMDocument(); | ||
$dom->loadHTML($response->getBody()); | ||
|
||
libxml_use_internal_errors($internalErrors); | ||
|
||
if ($dom->getElementsByTagName('resultset')->length === 0) { | ||
return 'I cannot find that title.'; | ||
} | ||
|
||
$result = $dom->getElementsByTagName('imdbentity')->item(0); | ||
|
||
return sprintf( | ||
'[ [%s](%s) ] %s', | ||
$result->firstChild->wholeText, | ||
'http://www.imdb.com/title/' . $result->getAttribute('id'), | ||
$result->getElementsByTagName('description')->item(0)->textContent | ||
); | ||
} | ||
} |