JKVideo Bilibili React Nativeクライアント は何をしますか?
ara.so によるスキル — Daily 2026 Skillsコレクション。
JKVideoは、React Native 0.83 + Expo SDK 55で構築されたフル機能のサードパーティBilibiliクライアントです。DASHアダプティブストリーミング、リアルタイム弾幕(コメント弾幕)、WBI API署名、QRコードログイン、WebSocket弾幕によるライブ配信、LAN QR共有に対応したダウンロードマネージャーをサポートしています。
インストールとセットアップ
前提条件
- Node.js 18+
- npm または yarn
- Androidの場合: Android Studio + SDK
- iOSの場合: macOS + Xcode 15+
クイックスタート(Expo Go — コンパイル不要)
git clone https://github.com/tiajinsha/JKVideo.git
cd JKVideo
npm install
npx expo start
Expo GoアプリでQRコードをスキャンしてください。注意: DASH 1080P+ はDev Buildが必要です。
Dev Build(全機能 — 推奨)
npm install
npx expo run:android # Android
npx expo run:ios # iOS (macOS + Xcode 必須)
イメージプロキシを使用したWeb版
npm install
npx expo start --web
# 別のターミナルで:
node scripts/proxy.js # Bilibiliのリファラ制限を回避するため、ポート3001でプロキシを起動
APKを直接インストール(Android)
Releases からダウンロード — Androidの設定で「不明なアプリのインストール」を有効にしてください。
プロジェクト構成
app/
index.tsx # ホーム (PagerView ホット/ライブタブ)
video/[bvid].tsx # 動画詳細 (再生 + コメント + 弾幕)
live/[roomId].tsx # ライブ詳細 (HLS + リアルタイム弾幕)
search.tsx # 検索ページ
downloads.tsx # ダウンロードマネージャー
settings.tsx # 設定 (画質、ログアウト)
components/ # UI: プレーヤー、弾幕オーバーレイ、カード
hooks/ # データフック: 動画リスト、ストリーム、弾幕
services/ # Bilibili API (axios + クッキーインターセプター)
store/ # Zustand ストア: 認証、ダウンロード、動画、設定
utils/ # ヘルパー: フォーマット、画像プロキシ、MPDビルダー
主要技術スタック
| レイヤー | 技術 |
|---|---|
| フレームワーク | React Native 0.83 + Expo SDK 55 |
| ルーティング | expo-router v4 (ファイルシステム、Stackナビゲーション) |
| 状態管理 | Zustand |
| HTTP | Axios |
| ストレージ | @react-native-async-storage/async-storage |
| 動画 | react-native-video (DASH MPD / HLS / MP4) |
| フォールバック | react-native-webview (HTML5動画インジェクション) |
| ページング | react-native-pager-view |
| アイコン | @expo/vector-icons (Ionicons) |
WBI署名の実装
BilibiliはほとんどのAPI呼び出しにWBI署名を必要とします。JKVideoは、12時間のナビゲーションキーキャッシュを備えた純粋なTypeScript MD5を実装しています。
// utils/wbi.ts — 純粋なTS MD5、外部暗号化依存関係なし
const MIXIN_KEY_ENC_TAB = [
46, 47, 18, 2, 53, 8, 23, 32, 15, 50, 10, 31, 58, 3, 45, 35,
27, 43, 5, 49, 33, 9, 42, 19, 29, 28, 14, 39, 12, 38, 41, 13
];
function getMixinKey(rawKey: string): string {
return MIXIN_KEY_ENC_TAB
.map(i => rawKey[i])
.join('')
.slice(0, 32);
}
export async function signWbi(
params: Record<string, string | number>,
imgKey: string,
subKey: string
): Promise<Record<string, string | number>> {
const mixinKey = getMixinKey(imgKey + subKey);
const wts = Math.floor(Date.now() / 1000);
const signParams = { ...params, wts };
// パラメータをアルファベット順にソートし、特殊文字をフィルタリング
const query = Object.keys(signParams)
.sort()
.map(k => {
const val = String(signParams[k]).replace(/[!'()*]/g, '');
return `${encodeURIComponent(k)}=${encodeURIComponent(val)}`;
})
.join('&');
const wRid = md5(query + mixinKey); // 純粋なTS md5
return { ...signParams, w_rid: wRid };
}
// ナビゲーションキーを取得してキャッシュ(12時間TTL)
export async function getWbiKeys(): Promise<{ imgKey: string; subKey: string }> {
const cached = await AsyncStorage.getItem('wbi_keys');
if (cached) {
const { keys, ts } = JSON.parse(cached);
if (Date.now() - ts < 12 * 3600 * 1000) return keys;
}
const res = await api.get('/x/web-interface/nav');
const { img_url, sub_url } = res.data.data.wbi_img;
const imgKey = img_url.split('/').pop()!.replace('.png', '');
const subKey = sub_url.split('/').pop()!.replace('.png', '');
const keys = { imgKey, subKey };
await AsyncStorage.setItem('wbi_keys', JSON.stringify({ keys, ts: Date.now() }));
return keys;
}
Bilibili API サービス
// services/api.ts
import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
export const api = axios.create({
baseURL: 'https://api.bilibili.com',
timeout: 15000,
headers: {
'User-Agent': 'Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36',
'Referer': 'https://www.bilibili.com',
},
});
// ストアからSESSDATAクッキーを注入
api.interceptors.request.use(async (config) => {
const sessdata = await AsyncStorage.getItem('SESSDATA');
if (sessdata) {
config.headers['Cookie'] = `SESSDATA=${sessdata}`;
}
return config;
});
// 人気動画リスト(WBI署名付き)
export async function getPopularVideos(pn = 1, ps = 20) {
const { imgKey, subKey } = await getWbiKeys();
const signed = await signWbi({ pn, ps }, imgKey, subKey);
const res = await api.get('/x/web-interface/popular', { params: signed });
return res.data.data.list;
}
// 動画ストリーム情報(DASH)
export async function getVideoStream(bvid: string, cid: number, qn = 80) {
const { imgKey, subKey } = await getWbiKeys();
const signed = await signWbi(
{ bvid, cid, qn, fnval: 4048, fnver: 0, fourk: 1 },
imgKey, subKey
);
const res = await api.get('/x/player/wbi/playurl', { params: signed });
return res.data.data;
}
// ライブストリームURL
export async function getLiveStreamUrl(roomId: number) {
const res = await api.get('/room/v1/Room/playUrl', {
params: { cid: roomId, quality: 4, platform: 'h5' },
baseURL: 'https://api.live.bilibili.com',
});
return res.data.data.durl[0].url; // HLS m3u8
}
DASH MPD ビルダー
ExoPlayerはローカルMPDファイルを必要とします。JKVideoはBilibiliのDASHレスポンスからそれを生成します:
// utils/buildDashMpd.ts
export function buildDashMpdUri(dashData: BiliDashData): string {
const { duration, video, audio } = dashData;
const videoAdaptations = video.map((v) => `
<AdaptationSet mimeType="video/mp4" segmentAlignment="true">
<Representation id="${v.id}" bandwidth="${v.bandwidth}"
codecs="${v.codecs}" width="${v.width}" height="${v.height}">
<BaseURL>${escapeXml(v.baseUrl)}</BaseURL>
<SegmentBase indexRange="${v.segmentBase.indexRange}">
<Initialization range="${v.segmentBase.initialization}"/>
</SegmentBase>
</Representation>
</AdaptationSet>`).join('');
const audioAdaptations = audio.map((a) => `
<AdaptationSet mimeType="audio/mp4" segmentAlignment="true">
<Representation id="${a.id}" bandwidth="${a.bandwidth}" codecs="${a.codecs}">
<BaseURL>${escapeXml(a.baseUrl)}</BaseURL>
<SegmentBase indexRange="${a.segmentBase.indexRange}">
<Initialization range="${a.segmentBase.initialization}"/>
</SegmentBase>
</Representation>
</AdaptationSet>`).join('');
const mpd = `<?xml version="1.0" encoding="UTF-8"?>
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static"
mediaPresentationDuration="PT${duration}S" minBufferTime="PT1.5S">
<Period duration="PT${duration}S">
${videoAdaptations}
${audioAdaptations}
</Period>
</MPD>`;
// 一時ファイルに書き込み、ExoPlayer用のfile:// URIを返す
const path = `${FileSystem.cacheDirectory}dash_${Date.now()}.mpd`;
FileSystem.writeAsStringAsync(path, mpd);
return path;
}
ビデオプレーヤーコンポーネント
// components/VideoPlayer.tsx
import Video from 'react-native-video';
import { WebView } from 'react-native-webview';
import { useVideoStore } from '../store/videoStore';
interface VideoPlayerProps {
bvid: string;
cid: number;
autoPlay?: boolean;
}
export function VideoPlayer({ bvid, cid, autoPlay = false }: VideoPlayerProps) {
const [mpdUri, setMpdUri] = useState<string | null>(null);
const [useFallback, setUseFallback] = useState(false);
const { setCurrentVideo } = useVideoStore();
useEffect(() => {
loadStream();
}, [bvid, cid]);
async function loadStream() {
try {
const stream = await getVideoStream(bvid, cid);
if (stream.dash) {
const uri = await buildDashMpdUri(stream.dash);
setMpdUri(uri);
} else {
setUseFallback(true);
}
} catch {
setUseFallback(true);
}
}
if (useFallback) {
// Expo Go / Web用のWebViewフォールバック
return (
<WebView
source={{ uri: `https://www.bilibili.com/video/${bvid}` }}
allowsInlineMediaPlayback
mediaPlaybackRequiresUserAction={false}
/>
);
}
return (
<Video
source={{ uri: mpdUri! }}
style={{ width: '100%', aspectRatio: 16 / 9 }}
controls
paused={!autoPlay}
resizeMode="contain"
onLoad={() => setCurrentVideo({ bvid, cid })}
/>
);
}
弾幕システム
動画弾幕(XMLタイムライン同期)
// hooks/useDanmaku.ts
export function useDanmaku(cid: number) {
const [danmakuList, setDanmakuList] = useState<Danmaku[]>([]);
useEffect(() => {
fetchDanmaku(cid);
}, [cid]);
async function fetchDanmaku(cid: number) {
const res = await api.get(`/x/v1/dm/list.so?oid=${cid}`, {
responseType: 'arraybuffer',
});
// XML弾幕を解析
const xml = new TextDecoder('utf-8').decode(res.data);
const items = parseXmlDanmaku(xml); // <d p="time,...">text</d> を解析
setDanmakuList(items);
}
return danmakuList;
}
// components/DanmakuOverlay.tsx — 5レーン浮遊表示
const LANE_COUNT = 5;
export function DanmakuOverlay({ danmakuList, currentTime }: Props) {
const activeDanmaku = danmakuList.filter(
d => d.time >= currentTime - 0.1 && d.time < currentTime + 0.1
);
return (
<View style={StyleSheet.absoluteFillObject} pointerEvents="none">
{activeDanmaku.map((d, i) => (
<DanmakuItem
key={d.id}
text={d.text}
color={d.color}
lane={i % LANE_COUNT}
/>
))}
</View>
);
}
ライブ弾幕(WebSocket)
// hooks/useLiveDanmaku.ts
const LIVE_WS = 'wss://broadcastlv.chat.bilibili.com/sub';
export function useLiveDanmaku(roomId: number) {
const [messages, setMessages] = useState<LiveMessage[]>([]);
const wsRef = useRef<WebSocket | null>(null);
useEffect(() => {
const ws = new WebSocket(LIVE_WS);
wsRef.current = ws;
ws.onopen = () => {
// 入室パケットを送信
const body = JSON.stringify({ roomid: roomId, uid: 0, protover: 2 });
ws.send(buildPacket(body, 7)); // op=7: 入室
startHeartbeat(ws);
};
ws.onmessage = async (event) => {
const packets = await decompressPacket(event.data);
packets.forEach(packet => {
if (packet.op === 5) {
const msg = JSON.parse(packet.body);
handleCommand(msg);
}
});
};
return () => ws.close();
}, [roomId]);
function handleCommand(msg: any) {
switch (msg.cmd) {
case 'DANMU_MSG':
setMessages(prev => [{
type: 'danmaku',
text: msg.info[1],
user: msg.info[2][1],
isGuard: msg.info[7] > 0, // 艦長マーク
}, ...prev].slice(0, 200));
break;
case 'SEND_GIFT':
setMessages(prev => [{
type: 'gift',
user: msg.data.uname,
gift: msg.data.giftName,
count: msg.data.num,
}, ...prev].slice(0, 200));
break;
}
}
return messages;
}
Zustand 状態ストア
// store/videoStore.ts
import { create } from 'zustand';
interface VideoState {
currentVideo: { bvid: string; cid: number } | null;
isMiniplayer: boolean;
quality: number; // 80=1080P, 112=1080P+, 120=4K
setCurrentVideo: (video: { bvid: string; cid: number }) => void;
setMiniplayer: (val: boolean) => void;
setQuality: (q: number) => void;
}
export const useVideoStore = create<VideoState>((set) => ({
currentVideo: null,
isMiniplayer: false,
quality: 80,
setCurrentVideo: (video) => set({ currentVideo: video }),
setMiniplayer: (val) => set({ isMiniplayer: val }),
setQuality: (q) => set({ quality: q }),
}));
// store/authStore.ts
interface AuthState {
sessdata: string | null;
isLoggedIn: boolean;
login: (sessdata: string) => Promise<void>;
logout: () => Promise<void>;
}
export const useAuthStore = create<AuthState>((set) => ({
sessdata: null,
isLoggedIn: false,
login: async (sessdata) => {
await AsyncStorage.setItem('SESSDATA', sessdata);
set({ sessdata, isLoggedIn: true });
},
logout: async () => {
await AsyncStorage.removeItem('SESSDATA');
set({ sessdata: null, isLoggedIn: false });
},
}));
QRコードログイン
// hooks/useQrLogin.ts
export function useQrLogin() {
const { login } = useAuthStore();
const [qrUrl, setQrUrl] = useState('');
const [qrKey, setQrKey] = useState('');
const pollRef = useRef<ReturnType<typeof setInterval>>();
async function generateQr() {
const res = await api.get('/x/passport-login/web/qrcode/generate');
const { url, qrcode_key } = res.data.data;
setQrUrl(url);
setQrKey(qrcode_key);
startPolling(qrcode_key);
}
function startPolling(key: string) {
pollRef.current = setInterval(async () => {
const res = await api.get('/x/passport-login/web/qrcode/poll', {
params: { qrcode_key: key },
});
const { code } = res.data.data;
if (code === 0) {
// Set-CookieヘッダーからSESSDATAを抽出
const setCookie = res.headers['set-cookie'] ?? [];
const sessdataCookie = setCookie
.find((c: string) => c.includes('SESSDATA='));
const sessdata = sessdataCookie?.match(/SESSDATA=([^;]+)/)?.[1];
if (sessdata) {
await login(sessdata);
clearInterval(pollRef.current!);
}
}
}, 1000);
}
// コンポーネントアンマウント時にポーリングをクリーンアップ
useEffect(() => {
return () => clearInterval(pollRef.current);
}, []);
return { qrUrl, qrKey, generateQr };
}
ダウンロードマネージャーとLAN QR共有
// hooks/useDownloadManager.ts
import { useDownloadStore } from '../store/downloadStore';
import * as FileSystem from 'expo-file-system';
import { shareAsync } from 'expo-sharing';
export function useDownloadManager() {
const { downloads, addDownload, updateProgress, removeDownload } = useDownloadStore();
async function startDownload(bvid: string, title: string, url: string) {
const callback = FileSystem.createDownloadResumable(
url,
`${FileSystem.documentDirectory}downloads/${bvid}.mp4`,
{},
(progress) => {
const pct = progress.totalBytesExpectedToWrite > 0
? progress.totalBytesWritten / progress.totalBytesExpectedToWrite
: 0;
updateProgress(bvid, pct);
}
);
addDownload({ bvid, title, progress: 0, status: 'downloading' });
try {
const result = await callback.downloadAsync();
if (result) {
updateProgress(bvid, 1);
// 完了済みとしてマーク
useDownloadStore.getState().setStatus(bvid, 'completed');
}
} catch (error) {
useDownloadStore.getState().setStatus(bvid, 'failed');
}
}
// LAN QR共有(簡易HTTPサーバーを起動)
async function shareViaLan() {
// ダウンロード済みファイルのリストを取得
const files = useDownloadStore.getState().downloads
.filter(d => d.status === 'completed')
.map(d => ({
bvid: d.bvid,
title: d.title,
path: `${FileSystem.documentDirectory}downloads/${d.bvid}.mp4`,
}));
// 簡易HTTPサーバーを起動
const server = await FileSystem.createHttpServer(files);
// QRコードを表示(サーバーのURLを含む)
return server.url;
}
return { startDownload, shareViaLan };
}
デバッグと開発のヒント
ネットワークログ
npx expo start --dev-client # Dev Client
# 開発者メニューからネットワークインスペクタを有効化
共通の問題
| 問題 | 解決策 |
|---|---|
| DASHがExpo Goで再生されない | Dev Buildを使用するか、WebViewフォールバックを有効にする |
| QRコードログインがタイムアウトする | ネットワーク接続を確認し、DNSがBilibiliを解決できることを確認 |
| 画像が読み込まれない | Web版ではnode scripts/proxy.jsを実行するか、画像プロキシ設定を確認 |
| WBI署名エラー | wbi_keysキャッシュをクリアし、Bilibiliがキーを更新していないか確認 |
パフォーマンス最適化
- 弾幕レンダリングには
react-native-reanimatedを使用 - 仮想化リスト(
FlashList)で長いコメントスレッドを表示 - 動画プレーヤーでプログレッシブローディングを有効化
貢献とライセンス
JKVideoはMITライセンスのオープンソースプロジェクトです。問題の報告や機能リクエストは GitHub Issues までお寄せください。
商用利用の前に、Bilibiliの利用規約 を確認してください。
このスキルは ara.so のDaily 2026 Skillsコレクションの一部です。