JKVideo Cliente React Native para Bilibili
Skill de ara.so — Colección Diaria de Skills 2026.
JKVideo es un cliente de Bilibili de terceros con todas las funcionalidades, construido con React Native 0.83 + Expo SDK 55. Soporta transmisión adaptativa DASH, danmaku en tiempo real (comentarios flotantes), firma de API WBI, inicio de sesión mediante código QR, transmisión en vivo con WebSocket danmaku y un gestor de descargas con uso compartido por QR en LAN.
Instalación y Configuración
Requisitos previos
- Node.js 18+
- npm o yarn
- Para Android: Android Studio + SDK
- Para iOS: macOS + Xcode 15+
Inicio rápido (Expo Go — sin compilación)
git clone https://github.com/tiajinsha/JKVideo.git
cd JKVideo
npm install
npx expo start
Escanea el código QR con la aplicación Expo Go. Nota: DASH 1080P+ requiere Dev Build.
Dev Build (Funciones completas — Recomendado)
npm install
npx expo run:android # Android
npx expo run:ios # iOS (macOS + Xcode requerido)
Web con Proxy de Imágenes
npm install
npx expo start --web
# En una terminal separada:
node scripts/proxy.js # Inicia el proxy en el puerto 3001 para evitar las restricciones del referer de Bilibili
Instalar APK directamente (Android)
Descárgalo desde Releases — habilita "Instalar desde fuentes desconocidas" en la configuración de Android.
Estructura del Proyecto
app/
index.tsx # Inicio (pestañas de videos populares/en vivo de PagerView)
video/[bvid].tsx # Detalle del video (reproducción + comentarios + danmaku)
live/[roomId].tsx # Detalle de en vivo (HLS + danmaku en tiempo real)
search.tsx # Página de búsqueda
downloads.tsx # Gestor de descargas
settings.tsx # Configuración (calidad, cerrar sesión)
components/ # UI: reproductor, superposición de danmaku, tarjetas
hooks/ # Hooks de datos: lista de videos, streams, danmaku
services/ # API de Bilibili (axios + interceptor de cookies)
store/ # Stores de Zustand: autenticación, descarga, video, configuración
utils/ # Utilidades: formato, proxy de imágenes, constructor de MPD
Pila de Tecnología Clave
| Capa | Tecnología |
|---|---|
| Framework | React Native 0.83 + Expo SDK 55 |
| Enrutamiento | expo-router v4 (sistema de archivos, navegación Stack) |
| Estado | Zustand |
| HTTP | Axios |
| Almacenamiento | @react-native-async-storage/async-storage |
| Video | react-native-video (DASH MPD / HLS / MP4) |
| Fallback | react-native-webview (inyección de video HTML5) |
| Paginación | react-native-pager-view |
| Iconos | @expo/vector-icons (Ionicons) |
Implementación de la Firma WBI
Bilibili requiere firma WBI para la mayoría de las llamadas a la API. JKVideo implementa MD5 en TypeScript puro con caché de navegación de 12h.
// utils/wbi.ts — MD5 en TS puro, sin dependencias criptográficas externas
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 };
// Ordenar parámetros alfabéticamente, filtrar caracteres especiales
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); // md5 en TS puro
return { ...signParams, w_rid: wRid };
}
// Obtener y almacenar en caché las claves de navegación (TTL de 12h)
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;
}
Servicio de API de Bilibili
// 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',
},
});
// Inyectar cookie SESSDATA desde el store
api.interceptors.request.use(async (config) => {
const sessdata = await AsyncStorage.getItem('SESSDATA');
if (sessdata) {
config.headers['Cookie'] = `SESSDATA=${sessdata}`;
}
return config;
});
// Lista de videos populares (firmado con 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;
}
// Información del stream de video (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 del stream en vivo
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
}
Constructor de MPD DASH
ExoPlayer necesita un archivo MPD local. JKVideo lo genera a partir de la respuesta DASH de Bilibili:
// 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>`;
// Escribir en un archivo temporal, devolver URI file:// para ExoPlayer
const path = `${FileSystem.cacheDirectory}dash_${Date.now()}.mpd`;
FileSystem.writeAsStringAsync(path, mpd);
return path;
}
Componente del Reproductor de Video
// 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) {
// Fallback de WebView para Expo Go / Web
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 })}
/>
);
}
Sistema de Danmaku
Danmaku de Video (sincronización con línea de tiempo 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',
});
// Analizar danmaku XML
const xml = new TextDecoder('utf-8').decode(res.data);
const items = parseXmlDanmaku(xml); // analizar <d p="time,...">text</d>
setDanmakuList(items);
}
return danmakuList;
}
// components/DanmakuOverlay.tsx — visualización flotante de 5 carriles
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>
);
}
Danmaku en Vivo (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 = () => {
// Enviar paquete de unión a la sala
const body = JSON.stringify({ roomid: roomId, uid: 0, protover: 2 });
ws.send(buildPacket(body, 7)); // op=7: enter room
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, // Marca de capitán
}, ...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;
}
Stores de Estado con 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 });
},
}));
Inicio de Sesión con Código 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) {
// Extraer SESSDATA de la cabecera Set-Cookie
const setCookie = res.headers['set-cookie'] ?? [];
const sessdataCookie = setCookie
.find((c: string) => c.includes('SESSDATA='));
const sessdata = sessdataCookie?.match(/SESSDATA=([^;]+)/)?.[1];
if (sessdata) {
clearInterval(pollRef.current);
await login(sessdata);
router.replace('/');
}
}
}, 3000);
}
return { qrUrl, generateQr };
}
Gestor de Descargas (con Compartición por QR en LAN)
// hooks/useDownload.ts
export function useDownload() {
const { addDownload, updateProgress, completeDownload } = useDownloadStore();
async function startDownload(bvid: string, cid: number, quality: number) {
const stream = await getVideoStream(bvid, cid, quality);
const downloadId = `${bvid}_${cid}_${quality}`;
addDownload({ id: downloadId, bvid, cid, quality, progress: 0, status: 'downloading' });
// Usar FileSystem.downloadAsync para cada segmento
if (stream.dash) {
const { video, audio } = stream.dash;
const videoUrl = video[0].baseUrl;
const audioUrl = audio[0].baseUrl;
const videoPath = `${FileSystem.documentDirectory}${downloadId}_video.mp4`;
const audioPath = `${FileSystem.documentDirectory}${downloadId}_audio.mp4`;
await FileSystem.downloadAsync(videoUrl, videoPath);
updateProgress(downloadId, 50);
await FileSystem.downloadAsync(audioUrl, audioPath);
updateProgress(downloadId, 90);
// Fusionar con ffmpeg (en Dev Build)
const outputPath = `${FileSystem.documentDirectory}${downloadId}.mp4`;
await mergeAudioVideo(videoPath, audioPath, outputPath);
completeDownload(downloadId, outputPath);
}
}
return { startDownload };
}
Soporte de Transmisión en Vivo
- Stream de video: JKVideo obtiene URL HLS m3u8 de
https://api.live.bilibili.com/room/v1/Room/playUrlconplatform=h5. - Danmaku en tiempo real: Se conecta a
wss://broadcastlv.chat.bilibili.com/suby maneja los comandosDANMU_MSGySEND_GIFT. - Componente:
app/live/[roomId].tsxrenderiza<Video>con la fuente HLS y unDanmakuOverlaysuperpuesto.
Mejores Prácticas y Consejos
- Usar Dev Build para la reproducción DASH: Expo Go no admite react-native-video con MPD; siempre usa
npx expo run:android/iospara las funciones completas. - Implementar tu propia lógica de firma WBI: Las claves de Bilibili rotan; el almacenamiento en caché con TTL de 12h evita llamadas innecesarias a la API.
- Escape de XML para la generación de MPD: Siempre usa
escapeXmlpara los valores de las URL base para evitar contenido XML malicioso. - Probar con el modo oscuro: interruptor de tema usando Context API de React Native o proveedor Zustand.
Solución de Problemas
| Problema | Causa Probable | Solución |
|---|---|---|
| DASH falla en Expo Go | Falta la compilación nativa | Ejecutar npx expo run:android o ios |
| El proxy de imágenes falla | Puerto 3001 ocupado | Cambiar el puerto en scripts/proxy.js |
| El QR no se escanea | URL del QR inválida | Verificar redes WiFi (misma LAN para el proxy) |
| Sin danmaku en vivo | WebSocket bloqueado por el cortafuegos | Verificar la conectividad con wss://broadcastlv.chat.bilibili.com |
Este skill es parte de la colección de skills de ara.so. Construye aplicaciones de video con tecnología nativa más rápido. 🚀