Update LeBonCoinBridge to use the site's API (#795)

* Update LeBonCoinBridge to use the site's API
This commit is contained in:
Teromene 2018-08-28 14:20:02 +01:00 committed by GitHub
parent 558fa50a2a
commit b0e33e4e01
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -150,43 +150,35 @@ class LeBonCoinBridge extends BridgeAbstract {
) )
); );
public static $LBC_API_KEY = 'ba0c2dad52b3ec';
public function collectData(){ public function collectData(){
$params = array( $url = 'https://api.leboncoin.fr/finder/search/';
'text' => $this->getInput('k'), $data = $this->buildRequestJson();
'region' => $this->getInput('r'),
'cities' => $this->getInput('cities'),
'category' => $this->getInput('c'),
'owner_type' => $this->getInput('o'),
);
$url = self::URI . 'recherche/?' . http_build_query($params);
$header = array( $header = array(
'Accept: text/html', 'Content-Type: application/json',
'Accept-Language: ' . getEnv('HTTP_ACCEPT_LANGUAGE'), 'Content-Length: ' . strlen($data),
'Accept-Encoding: identity' 'api_key: ' . self::$LBC_API_KEY
); );
$html = getContents($url, $header) $opts = array(
CURL_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $data
);
$content = getContents($url, $header, $opts)
or returnServerError('Could not request LeBonCoin. Tried: ' . $url); or returnServerError('Could not request LeBonCoin. Tried: ' . $url);
if(!preg_match('/^<script>window.FLUX_STATE[^\r\n]*/m', $html, $matches)) { $json = json_decode($content);
returnServerError('Could not parse JSON in page content.');
}
$clean_match = str_replace( if($json->total === 0) {
array('</script>', '<script>window.FLUX_STATE = '),
array('', ''),
$matches[0]
);
$json = json_decode($clean_match);
if($json->adSearch->data->total === 0) {
return; return;
} }
foreach($json->adSearch->data->ads as $element) { foreach($json->ads as $element) {
$item['title'] = $element->subject; $item['title'] = $element->subject;
$item['content'] = $element->body; $item['content'] = $element->body;
@ -228,4 +220,43 @@ class LeBonCoinBridge extends BridgeAbstract {
$this->items[] = $item; $this->items[] = $item;
} }
} }
private function buildRequestJson() {
$requestJson = new StdClass();
$requestJson->owner_type = $this->getInput('o');
$requestJson->filters->location = array();
if($this->getInput('r') != '') {
$requestJson->filters->location['regions'] = [$this->getInput('r')];
}
if($this->getInput('cities') != '') {
$requestJson->filters->location['city_zipcodes'] = array();
foreach (explode(',', $this->getInput('cities')) as $zipcode) {
$requestJson->filters->location['city_zipcodes'][] = array(
'zipcode' => trim($zipcode)
);
}
}
$requestJson->filters->category = array(
'id' => $this->getInput('c')
);
$requestJson->filters->keywords = array(
'text' => $this->getInput('k')
);
$requestJson->limit = 30;
return json_encode($requestJson);
}
} }