2018-04-15 02:05:41 +09:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\MetadataResolver;
|
|
|
|
|
2019-02-17 02:58:36 +09:00
|
|
|
use GuzzleHttp\Client;
|
|
|
|
|
2018-04-15 02:05:41 +09:00
|
|
|
class NijieResolver implements Resolver
|
|
|
|
{
|
2019-02-17 03:18:59 +09:00
|
|
|
/**
|
|
|
|
* @var Client
|
|
|
|
*/
|
2019-02-17 02:58:36 +09:00
|
|
|
protected $client;
|
2019-02-17 03:18:59 +09:00
|
|
|
/**
|
|
|
|
* @var OGPResolver
|
|
|
|
*/
|
|
|
|
private $ogpResolver;
|
2019-02-17 02:58:36 +09:00
|
|
|
|
2019-02-17 03:18:59 +09:00
|
|
|
public function __construct(Client $client, OGPResolver $ogpResolver)
|
2019-02-17 02:58:36 +09:00
|
|
|
{
|
|
|
|
$this->client = $client;
|
2019-02-17 03:18:59 +09:00
|
|
|
$this->ogpResolver = $ogpResolver;
|
2019-02-17 02:58:36 +09:00
|
|
|
}
|
|
|
|
|
2018-04-15 02:05:41 +09:00
|
|
|
public function resolve(string $url): Metadata
|
|
|
|
{
|
2018-04-15 21:46:49 +09:00
|
|
|
if (mb_strpos($url, '//sp.nijie.info') !== false) {
|
|
|
|
$url = preg_replace('~//sp\.nijie\.info~', '//nijie.info', $url);
|
|
|
|
}
|
2018-12-17 23:27:19 +09:00
|
|
|
if (mb_strpos($url, 'view_popup.php') !== false) {
|
|
|
|
$url = preg_replace('~view_popup\.php~', 'view.php', $url);
|
|
|
|
}
|
2018-04-15 21:46:49 +09:00
|
|
|
|
2019-02-17 02:58:36 +09:00
|
|
|
$client = $this->client;
|
2018-04-15 02:05:41 +09:00
|
|
|
$res = $client->get($url);
|
|
|
|
if ($res->getStatusCode() === 200) {
|
2019-02-17 03:18:59 +09:00
|
|
|
$metadata = $this->ogpResolver->parse($res->getBody());
|
2018-04-15 02:05:41 +09:00
|
|
|
|
|
|
|
$dom = new \DOMDocument();
|
|
|
|
@$dom->loadHTML(mb_convert_encoding($res->getBody(), 'HTML-ENTITIES', 'UTF-8'));
|
|
|
|
$xpath = new \DOMXPath($dom);
|
|
|
|
$dataNode = $xpath->query('//script[substring(@type, string-length(@type) - 3, 4) = "json"]');
|
|
|
|
foreach ($dataNode as $node) {
|
|
|
|
// 改行がそのまま入っていることがあるのでデコード前にエスケープが必要
|
|
|
|
$imageData = json_decode(preg_replace('/\r?\n/', '\n', $node->nodeValue), true);
|
2018-04-15 22:27:38 +09:00
|
|
|
if (isset($imageData['thumbnailUrl']) && !ends_with($imageData['thumbnailUrl'], '.gif') && !ends_with($imageData['thumbnailUrl'], '.mp4')) {
|
2018-04-15 02:05:41 +09:00
|
|
|
$metadata->image = preg_replace('~nijie\\.info/.*/nijie_picture/~', 'nijie.info/nijie_picture/', $imageData['thumbnailUrl']);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $metadata;
|
|
|
|
} else {
|
|
|
|
throw new \RuntimeException("{$res->getStatusCode()}: $url");
|
|
|
|
}
|
|
|
|
}
|
2019-01-15 00:05:01 +09:00
|
|
|
}
|