Skip to content

Commit

Permalink
Added IMDB plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
PeeHaa committed Jan 16, 2016
1 parent abc119f commit ad888db
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
2 changes: 2 additions & 0 deletions cli/run.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Room11\Jeeves\Chat\Plugin\Wikipedia as WikipediaPlugin;
use Room11\Jeeves\Chat\Plugin\SwordFight as SwordFightPlugin;
use Room11\Jeeves\Chat\Plugin\Docs as DocsPlugin;
use Room11\Jeeves\Chat\Plugin\Imdb as ImdbPlugin;

use Room11\Jeeves\Chat\Client\Xhr as ChatClient;

Expand All @@ -41,6 +42,7 @@
->register(new WikipediaPlugin($chatClient))
->register(new SwordFightPlugin($chatClient))
->register(new DocsPlugin($chatClient))
->register(new ImdbPlugin($chatClient))
;

$webSocketUrl = $openIdClient->getWebSocketUri($roomId);
Expand Down
69 changes: 69 additions & 0 deletions src/Chat/Plugin/Imdb.php
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
);
}
}

0 comments on commit ad888db

Please sign in to comment.