API/library/Account.php

118 lines
3.5 KiB
PHP
Raw Normal View History

2016-08-20 23:02:05 +02:00
<?php
namespace Shikiryu\LBCReposter;
use Goutte\Client;
class Account
{
const HOME_URL = 'https://www.leboncoin.fr/';
const LOGIN_URL = 'https://www.leboncoin.fr/beta/ajax/popins/connexion.html';
const ACCOUNT_URL = 'https://compteperso.leboncoin.fr/account/index.html';
const ADD_URL = 'https://www2.leboncoin.fr/ai/form/0';
2016-08-20 23:02:05 +02:00
/** @var Client */
protected $client;
/** @var string */
protected $login;
/** @var string */
protected $password;
/** @var bool */
protected $is_connected = false;
/**
* Account constructor.
* @param Client $client
* @param string $login
* @param string $password
*/
public function __construct(Client $client, $login, $password)
{
$this->client = $client;
$this->login = $login;
$this->password = $password;
}
/**
* @return Client
*/
public function getClient()
{
return $this->client;
}
/**
* Check if it's connected
* (if there's a "logout" link)
*
* @return bool
*/
2016-08-20 23:02:05 +02:00
public function isConnected()
{
if (!$this->is_connected) {
$crawler = $this->client->request('GET', self::HOME_URL);
$this->is_connected = $crawler->filter('.loggedOut')->count() == 0;
}
return $this->is_connected;
}
/**
* Check if connected, if not, try to connect you
*
* @see this#isConnected
*
* @return bool
*/
2016-08-20 23:02:05 +02:00
public function connect()
{
if (!$this->isConnected()) {
$crawler = $this->client->request('GET', self::LOGIN_URL);
$form = $crawler->selectButton('Se connecter')->form();
$crawler = $this->client->submit($form, ['st_username' => $this->login, 'st_passwd' => $this->password]);
$this->is_connected = $crawler->filter('.account_userinfo')->count() > 0;
}
return $this->is_connected;
}
/**
* Retrieve all deals from the current account
*
* @return Deals
*/
2016-08-20 23:02:05 +02:00
public function getDeals()
{
if ($this->connect()) {
2016-08-20 23:02:05 +02:00
$crawler = $this->client->request('GET', self::ACCOUNT_URL);
$deals = $crawler->filter('#dashboard .list .element')->each(
function ($node) {
return $node->filter('.detail .title')->each(
function ($n) {
return $n->filter('a')->first()->attr('href');
}
);
}
);
return new Deals($this, $deals);
}
return new Deals($this, []);
}
public function addDeal(Deal $deal)
{
$crawler = $this->client->request('GET', self::ADD_URL);
$form = $crawler->selectButton('Valider')->form();
$image0 = fopen(sprintf('%s/%s/image0.jpg', DEALS_DIR, $deal->getId()), 'rb');
// TODO manage location
$fields = [
'category' => $deal->getCategory(),
'type' => $deal->getType(),
'subject' => $deal->getSubject(),
'body' => $deal->getBody(),
'price' => $deal->getPrice(),
'image0' => $image0,
'no_salesmen' => 1,
'phone_hidden' => 0,
];
$crawler = $this->client->request('POST', $form->getUri(), ['Content-Type => multipart/form-data'], [], [], $fields);
}
2016-08-19 23:02:07 +02:00
}