61 lines
1.7 KiB
PHP
61 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace Shikiryu\WebGobbler\Collector;
|
|
|
|
use Samwilson\PhpFlickr\PhpFlickr;
|
|
use Shikiryu\WebGobbler\Collector;
|
|
|
|
class FlickrCollector extends Collector
|
|
{
|
|
/**
|
|
* @return string
|
|
*/
|
|
public function getName()
|
|
{
|
|
return 'collector_flickr';
|
|
}
|
|
|
|
/**
|
|
* @return int
|
|
* @throws \Exception
|
|
*/
|
|
public function getRandomImage()
|
|
{
|
|
return $this->getRandomImages(1);
|
|
}
|
|
|
|
/**
|
|
* @param int $number
|
|
*
|
|
* @return int
|
|
* @throws \Exception
|
|
*/
|
|
public function getRandomImages(int $number)
|
|
{
|
|
if (!$this->getConfig()->has('collector.flickr.key')) {
|
|
throw new \Exception('Flickr API key not found.');
|
|
}
|
|
$flickr_client = new PhpFlickr(
|
|
$this->getConfig()->get('collector.flickr.key'),
|
|
$this->getConfig()->get('collector.flickr.secret')
|
|
);
|
|
|
|
$word_to_search = $this->getConfig()->get('collector.keywords.keywords', $this->generateRandomWord());
|
|
|
|
$photos = $flickr_client->photos()->search(['text' => $word_to_search]);
|
|
$photos = $photos['photo'];
|
|
$index_to_download = array_rand($photos, $number);
|
|
if (!is_array($index_to_download)) {
|
|
$index_to_download = [$index_to_download];
|
|
}
|
|
|
|
foreach ($index_to_download as $photo_index) {
|
|
$photo = $photos[$photo_index];
|
|
$img_url = sprintf('https://live.staticflickr.com/%s/%s_%s_b.jpg', $photo['server'], $photo['id'], $photo['secret']);
|
|
file_put_contents($this->getPoolDirectory() . '/' . basename(parse_url($img_url, PHP_URL_PATH)), file_get_contents($img_url));
|
|
}
|
|
|
|
return $number;
|
|
}
|
|
}
|