2018-04-15 02:05:41 +09:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\MetadataResolver;
|
|
|
|
|
2019-02-17 02:58:36 +09:00
|
|
|
use GuzzleHttp\Client;
|
2019-08-21 03:40:47 +09:00
|
|
|
use Symfony\Component\DomCrawler\Crawler;
|
2019-02-17 02:58:36 +09:00
|
|
|
|
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-08-21 03:40:47 +09:00
|
|
|
$res = $this->client->get($url);
|
2019-09-10 07:03:46 +09:00
|
|
|
$html = (string) $res->getBody();
|
|
|
|
$metadata = $this->ogpResolver->parse($html);
|
|
|
|
$crawler = new Crawler($html);
|
|
|
|
|
2019-09-22 01:44:01 +09:00
|
|
|
$json = $crawler->filter('script[type="application/ld+json"]')->first()->text();
|
2019-09-10 07:03:46 +09:00
|
|
|
|
|
|
|
// 改行がそのまま入っていることがあるのでデコード前にエスケープが必要
|
|
|
|
$data = json_decode(preg_replace('/\r?\n/', '\n', $json), true);
|
|
|
|
|
2019-09-22 01:44:01 +09:00
|
|
|
// DomCrawler内でjson内の日本語がHTMLエンティティに変換されるので、全要素に対してhtml_entity_decode
|
|
|
|
array_walk_recursive($data, function (&$v) {
|
|
|
|
$v = html_entity_decode($v);
|
|
|
|
});
|
|
|
|
|
2019-09-10 07:03:46 +09:00
|
|
|
$metadata->title = $data['name'];
|
|
|
|
$metadata->description = '投稿者: ' . $data['author']['name'] . PHP_EOL . $data['description'];
|
|
|
|
if (
|
|
|
|
isset($data['thumbnailUrl']) &&
|
|
|
|
!ends_with($data['thumbnailUrl'], '.gif') &&
|
|
|
|
!ends_with($data['thumbnailUrl'], '.mp4')
|
|
|
|
) {
|
|
|
|
// サムネイルからメイン画像に
|
|
|
|
$metadata->image = str_replace('__rs_l160x160/', '', $data['thumbnailUrl']);
|
2018-04-15 02:05:41 +09:00
|
|
|
}
|
2019-09-10 07:03:46 +09:00
|
|
|
$metadata->tags = $crawler->filter('#view-tag span.tag_name')->extract('_text');
|
|
|
|
|
|
|
|
return $metadata;
|
2018-04-15 02:05:41 +09:00
|
|
|
}
|
2019-01-15 00:05:01 +09:00
|
|
|
}
|