From 4e46ded6374f5f183a5b9a7445ef822fb1e850d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9=20=D0=94=D0=BE?= =?UTF-8?q?=D1=80=D0=BE=D1=85=D0=BE=D0=B2?= Date: Sun, 9 Apr 2017 01:38:59 +0700 Subject: [PATCH] refactoring lampa api commands (#14) * refactoring commands * add check to null * php cs fix --- app/Http/Controllers/Lampa.php | 99 +--------------------- app/Services/Lampa/LampaService.php | 122 ++++++++++++++++++++++++++-- 2 files changed, 118 insertions(+), 103 deletions(-) diff --git a/app/Http/Controllers/Lampa.php b/app/Http/Controllers/Lampa.php index c1c8b47..f766a02 100644 --- a/app/Http/Controllers/Lampa.php +++ b/app/Http/Controllers/Lampa.php @@ -2,16 +2,9 @@ namespace App\Http\Controllers; -use App\Games\Sender; use GuzzleHttp\Client; -use GuzzleHttp\Cookie\FileCookieJar; -use GuzzleHttp\HandlerStack; -use GuzzleHttp\MessageFormatter; -use GuzzleHttp\Middleware; -use Illuminate\Database\Eloquent\Collection; use Illuminate\Http\Request; use Symfony\Component\DomCrawler\Crawler; -use Symfony\Component\HttpKernel\Exception\HttpException; class Lampa extends Controller { @@ -41,99 +34,15 @@ public function games($domain) public function commands(Request $request, $domain) { - $this->domain = $domain; - $this->getClient($domain); $gameId = $request->get('gameId'); if (!$gameId) { return response()->json(['error' => 'gameId not set'], 422); } - $cacheKey = sprintf('LampaCrawler:commands:%s:%s', $domain, $gameId); - if (!($teams = \Cache::get($cacheKey))) { - $crawler = $this->get('games/' . $gameId . '/enter', true); - if ($crawler->filter('#login-form')->count()) { - $crawler = $this->post('/login', [ - 'LoginForm[username]' => env('LAMPA_LOGIN'), - 'LoginForm[password]' => env('LAMPA_PASS'), - 'LoginForm[rememberMe]' => 1, - ]); - if ($crawler->filter('#login-form')->count()) { - throw new HttpException('Cannot authorize in lampa'); - } - } + $commands = \Lampa::setDomain($domain) + ->setGame($gameId) + ->getGameCommands(); - $teams = new Collection($crawler->filter('select#GamesTeams_id option') - ->each(function(Crawler $option) { - return [ - 'id' => $option->attr('value'), - 'name' => $option->text(), - ]; - })); - - \Cache::put($cacheKey, $teams, 10); - } - - return response()->json($teams->filter(function($team) { - return array_get($team, 'id'); - })); - } - - /** - * @param $domain - * - * @return Client - */ - private function getClient($domain) - { - $url = sprintf('http://%s.lampagame.ru', $domain); - $cookieFile = storage_path('cookies/lampa_site.jar'); - $jar = new FileCookieJar($cookieFile, true); - $stack = HandlerStack::create(); - $stack->push( - Middleware::log( - \Log::getMonolog(), - new MessageFormatter('[{code}] {method} {uri}') - ) - ); - $params = [ - 'base_uri' => $url, - 'cookies' => $jar, - 'headers' => [ - 'User-Agent' => Sender::getUserAgent(), - ], - 'handler' => $stack, - ]; - $this->client = new Client($params); - } - - /** - * @param string $url - * @param bool $noCache - * - * @return Crawler - */ - private function get($url, $noCache = false) - { - $cacheKey = sprintf('LampaCrawler:%s:%s', $this->domain, $url); - - if (!($result = \Cache::get($cacheKey)) || $noCache) { - $result = $this->client->get($url)->getBody()->__toString(); - \Cache::put($cacheKey, $result, 60); - } - - return new Crawler($result); - } - - /** - * @param string $url - * @param $array - * - * @return Crawler - */ - private function post($url, $array) - { - $result = $this->client->post($url, ['form_params' => $array])->getBody()->__toString(); - - return new Crawler($result); + return response()->json($commands); } } diff --git a/app/Services/Lampa/LampaService.php b/app/Services/Lampa/LampaService.php index 3a35d5b..9bbdd1f 100644 --- a/app/Services/Lampa/LampaService.php +++ b/app/Services/Lampa/LampaService.php @@ -2,8 +2,13 @@ namespace App\Services\Lampa; - +use App\Games\Sender; use GuzzleHttp\Client; +use GuzzleHttp\Cookie\FileCookieJar; +use GuzzleHttp\HandlerStack; +use GuzzleHttp\MessageFormatter; +use GuzzleHttp\Middleware; +use GuzzleHttp\RequestOptions; use Illuminate\Support\Collection; use Symfony\Component\DomCrawler\Crawler; @@ -26,18 +31,25 @@ class LampaService */ private $client; - function __construct() + /** @var int */ + private $gameId; + + public function __construct() { $this->crawler = new Crawler(); } /** - * @param $url + * @param string $url * @param bool $force * @return Crawler + * @throws \Exception */ private function fetch(string $url, bool $force = false): Crawler { + if (!$this->client) { + throw new \Exception('Client is not initialized'); + } \Log::debug(__METHOD__, ['domain' => $this->domain, 'url' => $url, 'force' => $force]); $cacheKey = sprintf(self::CACHE_KEY, $this->domain, $url); @@ -58,7 +70,8 @@ private function fetch(string $url, bool $force = false): Crawler public function setDomain(string $domain): LampaService { $this->domain = $domain; - $this->client = new Client(['base_uri' => sprintf('http://%s.lampagame.ru', $domain)]); + $this->initClient(); + return $this; } @@ -78,6 +91,55 @@ public function getAnnounceGames(): Collection return $this->parseGames($pageCount); } + /** + * @param int $gameId + * @return LampaService + */ + public function setGame(int $gameId): LampaService + { + $this->gameId = $gameId; + + return $this; + } + + /** + * @return Collection + * @throws \Exception + */ + public function getGameCommands(): Collection + { + \Log::debug(__METHOD__); + $url = sprintf('games/%d/enter', $this->gameId); + $html = $this->fetch($url, true); + if (!$this->isAuth($html)) { + $html = $this->doAuth(env('LAMPA_LOGIN'), env('LAMPA_PASS')); + if (!$this->isAuth($html)) { + throw new \Exception('Cannot auth in lampa'); + } + } + + $teams = collect(); + $teamIterator = $html->filter('#GamesTeams_id option')->getIterator(); + foreach ($teamIterator as $htmlNode) { + $node = new Crawler($htmlNode); + $id = $node->attr('value'); + if ($id !== null) { + $teams->push([ + 'id' => $id, + 'name' => $node->text(), + ]); + } + } + + return $teams; + } + + private function isAuth(Crawler $crawler): bool + { + \Log::debug(__METHOD__); + return $crawler->filter('#login-form')->count() == 0; + } + /** * @return int */ @@ -93,7 +155,7 @@ private function detectPageCount(): int $lastPage = explode('/', $paginator->filter('.last a')->attr('href')); - return (int) collect($lastPage)->last(); + return (int)collect($lastPage)->last(); } /** @@ -111,9 +173,9 @@ private function parseGames(int $pageCount): Collection $pages->push($html); } - $pages->each(function(Crawler $page) use ($games) { + $pages->each(function (Crawler $page) use ($games) { $gameBlock = $page->filter('#games-list .list-item'); - $gameBlock->each(function(Crawler $game) use ($games) { + $gameBlock->each(function (Crawler $game) use ($games) { $link = $game->filter('.list-text-name'); $games->push([ 'title' => trim($link->text()), @@ -124,4 +186,48 @@ private function parseGames(int $pageCount): Collection return $games; } -} \ No newline at end of file + + + private function initClient(): void + { + $cookieFile = storage_path('cookies/lampa_site.jar'); + $jar = new FileCookieJar($cookieFile, true); + $stack = HandlerStack::create(); + $stack->push( + Middleware::log( + \Log::getMonolog(), + new MessageFormatter('[{code}] {method} {uri}') + ) + ); + $params = [ + 'base_uri' => sprintf('http://%s.lampagame.ru/', $this->domain), + 'cookies' => $jar, + 'headers' => [ + 'User-Agent' => Sender::getUserAgent(), + ], + 'handler' => $stack, + RequestOptions::ALLOW_REDIRECTS => [ + 'max' => 10, // allow at most 10 redirects. + 'strict' => true, // use "strict" RFC compliant redirects. + 'referer' => true, // add a Referer header + 'track_redirects' => true, + ], + ]; + \Log::debug(__METHOD__, $params); + $this->client = new Client($params); + } + + private function doAuth(string $login, string $pass): Crawler + { + \Log::debug(__METHOD__); + $result = $this->client + ->post('/login', [ + 'form_params' => [ + 'LoginForm[username]' => $login, + 'LoginForm[password]' => $pass, + ], + ]); + + return new Crawler($result->getBody()->__toString()); + } +}