Skip to content

Commit

Permalink
Картинки сохраняются локально.
Browse files Browse the repository at this point in the history
  • Loading branch information
ProklUng committed May 21, 2021
1 parent 4c8815e commit 0a4045f
Show file tree
Hide file tree
Showing 6 changed files with 131 additions and 1 deletion.
1 change: 1 addition & 0 deletions DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public function getConfigTreeBuilder(): TreeBuilder
->scalarNode('instagram_user_id')->end()
->scalarNode('instagram_user_name')->defaultValue('')->end()
->scalarNode('rapid_api_key')->end()
->scalarNode('path_image')->defaultValue('/upload/instagram')->end()
->scalarNode('fixture_response_path')->defaultValue(
'/local/config/Fixture/response.txt'
)->end()
Expand Down
1 change: 1 addition & 0 deletions DependencyInjection/InstagramParserRapidApiExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public function load(array $configs, ContainerBuilder $container) : void
$container->setParameter('instagram_parser_rapid_api.mock', $config['mock']);
$container->setParameter('instagram_parser_rapid_api.fixture_response_path', $config['fixture_response_path']);
$container->setParameter('instagram_parser_rapid_api.fixture_user_path', $config['fixture_user_path']);
$container->setParameter('instagram_parser_rapid_api.save_path', $config['path_image']);

$loader = new YamlFileLoader(
$container,
Expand Down
8 changes: 8 additions & 0 deletions Resources/config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ services:
# Трансформер данных, получаемых из rapidAPI.
instagram_parser_rapid_api.data_transformer:
public: false
arguments:
- '@instagram_parser_rapid_api.curl_downloader'
- '%instagram_parser_rapid_api.save_path%'
class: Prokl\InstagramParserRapidApiBundle\Services\InstagramDataTransformerRapidApi

Prokl\InstagramParserRapidApiBundle\Services\InstagramDataTransformerRapidApi: '@instagram_parser_rapid_api.data_transformer'
Expand All @@ -54,6 +57,11 @@ services:

Prokl\InstagramParserRapidApiBundle\Services\ComplexParser: '@instagram_parser_rapid_api.parser'

# Загрузчик файлов через Curl
instagram_parser_rapid_api.curl_downloader:
class: Prokl\InstagramParserRapidApiBundle\Services\Transport\CurlDownloader
arguments: ['%kernel.project_dir%']

#####################
# Консольные команды
####################
Expand Down
33 changes: 32 additions & 1 deletion Services/InstagramDataTransformerRapidApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Prokl\InstagramParserRapidApiBundle\Services;

use Prokl\InstagramParserRapidApiBundle\Services\Interfaces\InstagramDataTransformerInterface;
use Prokl\InstagramParserRapidApiBundle\Services\Transport\CurlDownloader;
use RuntimeException;

/**
Expand All @@ -13,11 +14,35 @@
*/
class InstagramDataTransformerRapidApi implements InstagramDataTransformerInterface
{
/**
* @var CurlDownloader $curlDownloader
*/
private $curlDownloader;

/**
* @var array $arMedias Результат.
*/
private $arMedias = [];

/**
* @var string $dirSave
*/
private $dirSave;

/**
* InstagramDataTransformerRapidApi constructor.
*
* @param CurlDownloader $curlDownloader
* @param string $dirSave
*/
public function __construct(
CurlDownloader $curlDownloader,
string $dirSave
) {
$this->curlDownloader = $curlDownloader;
$this->dirSave = $dirSave;
}

/**
* @inheritDoc
*/
Expand Down Expand Up @@ -45,9 +70,15 @@ public function processMedias(array $arDataFeed, int $count = 3): array
continue;
}

$resultPathImage = '';
if ($item['display_url']) {
$destinationName = '/' . md5($item['display_url']) . '.jpg';
$resultPathImage = $this->curlDownloader->download($item['display_url'], $this->dirSave . $destinationName);
}

$this->arMedias [] = [
'link' => $item['shortcode'] ? 'https://www.instagram.com/p/' . $item['shortcode'] : '',
'image' => $item['display_url'] ?? '',
'image' => $resultPathImage,
'description' => $item['edge_media_to_caption']['edges'][0]['node']['text'] ?? '',
];

Expand Down
86 changes: 86 additions & 0 deletions Services/Transport/CurlDownloader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php

namespace Prokl\InstagramParserRapidApiBundle\Services\Transport;

use RuntimeException;

/**
* Class CurlDownloader
* @package Prokl\InstagramParserRapidApiBundle\Services\Transport
*
* @since 21.05.2021
*/
class CurlDownloader
{
/**
* @var string $documentRoot DOCUMENT_ROOT.
*/
private $documentRoot;

/**
* CurlDownloader constructor.
*
* @param string $documentRoot DOCUMENT_ROOT.
*/
public function __construct(string $documentRoot)
{
$this->documentRoot = $documentRoot;
}

/**
* @param string $url
* @param string $dest
*
* @return string
* @throws RuntimeException Когда проблемы с закачкой файла.
*
* @internal Если файл существует, то не перезаписывается.
*/
public function download(string $url, string $dest) : string
{
if (@file_exists($this->documentRoot . $dest)) {
return $dest;
}

$curl = curl_init();

curl_setopt_array(
$curl,
[
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
throw new RuntimeException('Get Request Error: ' . $err);
}

$fp = fopen($this->documentRoot . $dest, 'w');

if ($fp === false) {
throw new RuntimeException('File error: ' . $this->documentRoot . $dest);
}

$success = fwrite($fp, $response);
if ($success === false) {
throw new RuntimeException('File write error: ' . $this->documentRoot . $dest);
}

fclose($fp);

return $dest;
}
}
3 changes: 3 additions & 0 deletions readme.MD
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ instagram_parser_rapid_api:
# Путь к фикстуре запроса данных пользователя.
fixture_user_path: '/local/config/Fixture/user.txt'

# Куда локально сохранять картинки из Инстаграма.
path_image: '/upload/instagram'

###########################
# Информация о пользователе
###########################
Expand Down

0 comments on commit 0a4045f

Please sign in to comment.