2019-01-14 22:55:01 +09:00
|
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\MetadataResolver;
|
|
|
|
|
|
2019-02-17 02:58:36 +09:00
|
|
|
|
use GuzzleHttp\Client;
|
2019-01-14 22:55:01 +09:00
|
|
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
|
|
|
|
|
|
class FantiaResolver implements Resolver
|
|
|
|
|
{
|
2019-02-17 02:58:36 +09:00
|
|
|
|
/**
|
|
|
|
|
* @var Client
|
|
|
|
|
*/
|
|
|
|
|
private $client;
|
|
|
|
|
/**
|
|
|
|
|
* @var OGPResolver
|
|
|
|
|
*/
|
|
|
|
|
private $ogpResolver;
|
|
|
|
|
|
|
|
|
|
public function __construct(Client $client, OGPResolver $ogpResolver)
|
|
|
|
|
{
|
|
|
|
|
$this->client = $client;
|
|
|
|
|
$this->ogpResolver = $ogpResolver;
|
|
|
|
|
}
|
2019-01-14 22:55:01 +09:00
|
|
|
|
public function resolve(string $url): Metadata
|
|
|
|
|
{
|
|
|
|
|
preg_match("~\d+~", $url, $match);
|
|
|
|
|
$postId = $match[0];
|
|
|
|
|
|
2019-02-17 02:58:36 +09:00
|
|
|
|
$res = $this->client->get($url);
|
2019-01-14 22:55:01 +09:00
|
|
|
|
if ($res->getStatusCode() === 200) {
|
2019-02-17 02:58:36 +09:00
|
|
|
|
$metadata = $this->ogpResolver->parse($res->getBody());
|
2019-01-14 22:55:01 +09:00
|
|
|
|
|
|
|
|
|
$dom = new \DOMDocument();
|
|
|
|
|
@$dom->loadHTML(mb_convert_encoding($res->getBody(), 'HTML-ENTITIES', 'UTF-8'));
|
|
|
|
|
$xpath = new \DOMXPath($dom);
|
|
|
|
|
|
|
|
|
|
$node = $xpath->query("//meta[@property='twitter:image']")->item(0);
|
|
|
|
|
$ogpUrl = $node->getAttribute('content');
|
|
|
|
|
|
2019-01-14 23:08:37 +09:00
|
|
|
|
// 投稿に画像がない場合(ogp.jpgでない場合)のみ大きい画像に変換する
|
2019-01-19 03:02:37 +09:00
|
|
|
|
if ($ogpUrl != 'http://fantia.jp/images/ogp.jpg') {
|
2019-01-14 23:50:15 +09:00
|
|
|
|
preg_match("~https://fantia\.s3\.amazonaws\.com/uploads/post/file/{$postId}/ogp_(.*?)\.(jpg|png)~", $ogpUrl, $match);
|
2019-01-14 23:08:37 +09:00
|
|
|
|
$uuid = $match[1];
|
2019-01-14 23:50:15 +09:00
|
|
|
|
$extension = $match[2];
|
2019-01-14 23:08:37 +09:00
|
|
|
|
|
|
|
|
|
// 大きい画像に変換
|
2019-01-14 23:50:15 +09:00
|
|
|
|
$metadata->image = "https://c.fantia.jp/uploads/post/file/{$postId}/main_{$uuid}.{$extension}";
|
2019-01-14 23:08:37 +09:00
|
|
|
|
}
|
2019-01-14 22:55:01 +09:00
|
|
|
|
|
|
|
|
|
return $metadata;
|
|
|
|
|
} else {
|
|
|
|
|
throw new \RuntimeException("{$res->getStatusCode()}: $url");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|