На ночь глядя, чтобы икалось лучше ночью, выкладываю свой класс. Критикуем безжалостно. Что умеет, спрашиваете вы?-да файлы с инстаграма качать да и все. Стойте, ну куда же вы сразу пошли :lol: ах, вы за ведрами :lol:
$url = "https://www.instagram.com/p/BimQ4UUBOro/?utm_source=ig_share_sheet&igshid=t5gf4kno7ffm";
try {
$m = new Instagram($url);
$o = $m->getJson();
$count = $m->countNode();
$x = 0;
$m->setPath($x);
$m->setRange("1,2");
$commonInfo = $m->commonInfo();
$m->createDir("q/",$commonInfo["username"]);
while($x<$count){
$fileInfo = $m->getInfoFile($x);
echo $m->download($fileInfo["url"],"q/".$commonInfo["username"]."/",$commonInfo["username"]."_".time().".".$m->getExt($fileInfo["url"])) . "<br>";
print_r($fileInfo);
$x++;
}
} catch (NetworkFailException $e) {
echo 'Выброшено исключение: ', $e->errorMessage(true), "\n";
}catch (InstagramParseErrorException $e) {
echo 'Выброшено исключение1: ', $e->errorMessage(true), "\n";
} catch (DownloadException $e) {
echo 'Выброшено исключение: ', $e->errorMessage(true), "\n";
} catch (Exception $e) {
echo 'Выброшено исключение: ', $e->getMessage(), "\n";
}
class InstagramParseErrorException extends Exception {
@param @return
public function errorMessage($responseType = false) {
$message = $this->message;
$response = array(
"status" => "0",
"error" => $message
);
return $responseType ? json_encode( $response ) : "status:0 ".$message;
}
}
class NetworkFailException extends Exception {
@param @return
public function errorMessage($responseType = false) {
$message = $this->message;
$response = array(
"status" => "0",
"error" => $message
);
return $responseType ? json_encode( $response ) : "status:0 ".$message;
}
}
class DownloadException extends Exception {
@param @return
public function errorMessage($responseType = false) {
$message = $this->message;
$response = array(
"status" => "0",
"msg" => $message
);
return $responseType ? json_encode( $response ) : "status:0 ".$message;
}
}
class Instagram {
@var
protected $_json;
@var
protected $_mainJson;
@var
protected $_clear_url;
@var
protected $_json_url;
@var
protected $_range = array();
@var
protected $_count;
@var
protected $_path;
@param @throws @throws @return
public function __construct($url) {
$this->getTrueUrls($url);
$detect_url = $this->detectUrl($this->getClearUrl());
if(!$detect_url){
throw new InstagramParseErrorException("Ссылка не является корректной");
}
$json = @file_get_contents($this->getJsonUrl());
if (!$json) {
throw new NetworkFailException('Страница недоступна');
}
$this->_json = json_decode($json);
$this->_mainJson = $this->_json->graphql->shortcode_media;
}
@return
public function getJson() {
return $this->_mainJson;
}
public function getTrueUrls($url) {
$chunk = explode("?", $url);
$this->_clear_url = $chunk[0];
$this->_json_url = $chunk[0]. "?__a=1";
}
public function getClearUrl(){
return $this->_clear_url;
}
@return
public function getJsonUrl(){
return $this->_json_url;
}
@param @return
public function detectUrl($url){
if(preg_match("/^(?:(?:http(s|)\:\/\/|)(?:www\.)|)instagram.com\/p\/[a-zA-Z0-9\._-]{9,}(?:(?:\/\?taken\-by=[a-zA-Z0-9\._-]{1,}|\/)|)$/is", $url)) {
return true;
}
else {
return false;
}
}
public function getTypename() {
return $this->_mainJson->__typename;
}
public function setRange($range = false){
$this->_range = !empty($range) ? array_merge(explode(',', $range )) : array_merge(explode(',', "0,1,2,3,4,5,6,7,8,9,10" ));
}
@return
public function getRange(){
return $this->_range;
}
todo
public function check($properties){
$resultArray = array();
$arrayProperties = explode(",", $properties);
foreach($arrayProperties as $propertie){
if(isset($this->_mainJson->{$propertie})){
$resultArray[$propertie] = true;
}
else{
$resultArray[$propertie] = false;
}
}
return $resultArray;
}
@return
public function countNode() {
$this->_count = isset($this->_mainJson->edge_sidecar_to_children->edges) ? count($this->_mainJson->edge_sidecar_to_children->edges) : 1;
return $this->_count;
}
@param @return
public function setPath($iterator) {
$this->_path = $this->_count > 1 ? $this->_mainJson->edge_sidecar_to_children->edges[isset($iterator) ? $iterator : 0]->node : $this->_mainJson;
}
@return
public function getPath() {
return $this->_path;
}
@return
public function commonInfo() {
return array("location" => isset($this->_mainJson->location->name) ? $this->_mainJson->location->name : "", "username" => $this->_mainJson->owner->username);
}
@param @param @throws @return
public function createDir($path,$dirName){
if(!file_exists($path.$dirName)){
if (!mkdir($path.$dirName)) {
throw new Exception('Не удалось создать директорию');
}
file_put_contents($path.$dirName."/.htaccess","Options -Indexes");
}
}
@param @return
public function getInfoFile($number) {
$this->setPath($number);
$url = (!empty($this->_path->video_url)) ? $this->_path->video_url : $this->_path->display_url;
$pr_url = explode("?", $url);
return array("shortcode" => (!empty($this->_path->shortcode)) ? $this->_path->shortcode : '',
"url" => $pr_url[0],
"dimensions_h" =>$this->_path->dimensions->height,
"dimensions_w" =>$this->_path->dimensions->width
);
}
@param @param @param @throws @retrn
public function download($fileName, $dir, $newName) {
$fp = fopen($fileName, "r");
if ( !$fp ) {
throw new DownloadException("Невозможно открыть файл ".$fileName);
}
$str = stream_get_contents($fp);
if ( !$str ) {
throw new DownloadException('Файл пуст.');
}
$path = $dir.$newName;
file_put_contents($path,$str);
fclose($fp);
return round(filesize($path)/1024,2);
}
@param @return
public function getExt($fileName) {
return substr(strrchr($fileName, '.'), 1);
}
@return
public function reset() {
$this->_clear_url = '';
$this->_count = 0;
$this->_json = '';
$this->_json_url = '';
$this->_mainJson = '';
$this->_path = '';
$this->_range = array();
}
}