Skip to content

Commit

Permalink
refactoring lampa api commands (#14)
Browse files Browse the repository at this point in the history
* refactoring commands

* add check to null

* php cs fix
  • Loading branch information
akeinhell authored Apr 8, 2017
1 parent af9c6a6 commit 4e46ded
Show file tree
Hide file tree
Showing 2 changed files with 118 additions and 103 deletions.
99 changes: 4 additions & 95 deletions app/Http/Controllers/Lampa.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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);
}
}
122 changes: 114 additions & 8 deletions app/Services/Lampa/LampaService.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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);

Expand All @@ -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;
}

Expand All @@ -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
*/
Expand All @@ -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();
}

/**
Expand All @@ -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()),
Expand All @@ -124,4 +186,48 @@ private function parseGames(int $pageCount): Collection

return $games;
}
}


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());
}
}

0 comments on commit 4e46ded

Please sign in to comment.