Skip to content

Instantly share code, notes, and snippets.

@hxgdzyuyi
Created October 9, 2017 06:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hxgdzyuyi/87891f0f4ed5eb284a9689fe178ad251 to your computer and use it in GitHub Desktop.
Save hxgdzyuyi/87891f0f4ed5eb284a9689fe178ad251 to your computer and use it in GitHub Desktop.
app/Sns/VideoExtractor/BiliBiliExtractor.php
<?php
namespace App\Sns\VideoExtractor;
use Exception;
use GuzzleHttp\Cookie\CookieJar;
/**
* Example:
* url: https://www.bilibili.com/video/av3643130/?from=search&seid=12348617167729948450
* result:
* "source" => "bilibili"
* "source_id" => "3643130"
* "play_url" => "http://upos-hz-mirrorks3.acgvideo.com/upgcxcode/30/78/5827830/5827830-1-16.mp4?um_deadline=1507517101&platform=html5&rate=109089&oi=3661773676&um_sign=c0736f75d6a35e8f1111119d75133b76&gen=playurl&os=ks3&hfb=M2Y2ZWYwZjM2YmRiYmY5MDljYTBiOWE2ZmEwYjJmYTM="
* "cover" => "https://i1.hdslb.com/bfs/archive/bc23ac6f17c82700d5c1941e0991bc8a6fcbd46c.png"
* "url_type" => "mp4"
*/
class BiliBiliExtractor extends BaseExtractor implements ExtractorInterface
{
const URL_REGEX =
'/https?:\/\/(?:www\.)?bilibili\.(?:tv|com)\/(?:video\/av)(\d+)/';
const MEDIA_TYPE = 'mp4';
const MEDIA_SOURCE = 'bilibili';
/**
* 根据视频 Url 获取视频信息
*
* @param $url
*
* @return array
*/
public function extractVideo()
{
$fingerprint = $this->fingerprint();
$sourceId = $fingerprint['source_id'];
$html = $this->requestUrl(
"https://m.bilibili.com/video/av{$sourceId}.html"
);
$title = $this->retrieveTitle($html);
$cover = $this->retrieveOpenGraphImage($html);
// `金坷垃原版_搞笑_生活_bilibili_哔哩哔哩` => `金坷垃原版`
$title = head(explode('_', $title));
return $fingerprint + [
'play_url' => $this->fetchPlayUrl($sourceId),
'cover' => $cover,
'title' => $title,
'url_type' => static::MEDIA_TYPE,
];
}
public function fetchPlayUrl($sourceId)
{
$cookies = new CookieJar;
// Fetch the cookie `buvid3`.
$this->requestUrl(
'https://data.bilibili.com/v/web/web_page_view',
[
'cookies' => $cookies
]
);
$result = $this->requestUrl(
"https://api.bilibili.com/playurl?aid={$sourceId}&page=1&platform=html5&quality=1&vtype=mp4",
[
'cookies' => $cookies
]
);
$info = json_decode($result, $ASSOC = true);
return array_get($info, 'durl.0.url');
}
/**
* 通过 url 获取 source 和 source_id, fingerprint = ['source', 'source_id']
*
* @param $url
* @return array
*/
public function fingerprint()
{
preg_match(static::URL_REGEX, $this->url, $matches);
return [
'source' => static::MEDIA_SOURCE,
'source_id' => $matches[1],
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment