Skip to content

Commit

Permalink
feat: support b23tv short url
Browse files Browse the repository at this point in the history
  • Loading branch information
JimmyLv committed Mar 12, 2023
1 parent fba9a02 commit 32fcb3e
Show file tree
Hide file tree
Showing 11 changed files with 66 additions and 28 deletions.
4 changes: 2 additions & 2 deletions lib/bilibili/fetchBilibiliSubtitle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import { fetchBilibiliSubtitleUrls } from "./fetchBilibiliSubtitleUrls";

export async function fetchBilibiliSubtitle(
videoId: string,
partNumber?: null | string,
pageNumber?: null | string,
shouldShowTimestamp?: boolean
) {
const res = await fetchBilibiliSubtitleUrls(videoId, partNumber);
const res = await fetchBilibiliSubtitleUrls(videoId, pageNumber);
const { title, desc, dynamic, subtitle } = res || {};
const hasDescription = desc || dynamic;
const descriptionText = hasDescription ? `${desc} ${dynamic}` : undefined;
Expand Down
6 changes: 3 additions & 3 deletions lib/bilibili/fetchBilibiliSubtitleUrls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ interface BilibiliVideoInfo {
}
export const fetchBilibiliSubtitleUrls = async (
videoId: string,
partNumber?: null | string
pageNumber?: null | string
): Promise<BilibiliVideoInfo> => {
const sessdata = sample(process.env.BILIBILI_SESSION_TOKEN?.split(","));
const headers = {
Expand Down Expand Up @@ -43,9 +43,9 @@ export const fetchBilibiliSubtitleUrls = async (
const json = await response.json();

// support multiple parts of video
if (partNumber) {
if (pageNumber) {
const { aid, pages } = json?.data || {};
const { cid } = find(pages, { page: Number(partNumber) }) || {};
const { cid } = find(pages, { page: Number(pageNumber) }) || {};

// https://api.bilibili.com/x/player/v2?aid=865462240&cid=1035524244
const pageUrl = `https://api.bilibili.com/x/player/v2?aid=${aid}&cid=${cid}`;
Expand Down
4 changes: 2 additions & 2 deletions lib/fetchSubtitle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ export async function fetchSubtitle(
subtitlesArray?: null | Array<CommonSubtitleItem>;
descriptionText?: string;
}> {
const { service, videoId, partNumber } = videoConfig;
const { service, videoId, pageNumber } = videoConfig;
if (service === VideoService.Youtube) {
return await fetchYoutubeSubtitle(videoId, shouldShowTimestamp);
}
return await fetchBilibiliSubtitle(videoId, partNumber, shouldShowTimestamp);
return await fetchBilibiliSubtitle(videoId, pageNumber, shouldShowTimestamp);
}
2 changes: 1 addition & 1 deletion lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export type UserConfig = {
export type VideoConfig = {
videoId: string;
service?: VideoService;
partNumber?: null | string;
pageNumber?: null | string;
};

export enum VideoService {
Expand Down
41 changes: 28 additions & 13 deletions pages/[...slug].tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import getVideoId from "get-video-id";
import type { NextPage } from "next";
import { useSearchParams } from "next/navigation";
import { useRouter } from "next/router";
Expand All @@ -11,12 +12,11 @@ import { UsageAction } from "~/components/UsageAction";
import { UsageDescription } from "~/components/UsageDescription";
import { UserKeyInput } from "~/components/UserKeyInput";
import { useToast } from "~/hooks/use-toast";
import { useLocalStorage } from "~/hooks/useLocalStorage";
import { useSummarize } from "~/hooks/useSummarize";
import { VideoService } from "~/lib/types";
import { extractUrl } from "~/utils/extractUrl";
import { extractPage, extractUrl } from "~/utils/extractUrl";
import { getVideoIdFromUrl } from "~/utils/getVideoIdFromUrl";
import getVideoId from "get-video-id";
import { useLocalStorage } from "~/hooks/useLocalStorage";

export const Home: NextPage<{
showSingIn: (show: boolean) => void;
Expand Down Expand Up @@ -56,7 +56,7 @@ export const Home: NextPage<{
validatedUrl && generateSummary(validatedUrl);
}, [router.isReady, urlState, searchParams]);

const validateUrl = (url?: string) => {
const validateUrlFromAddressBar = (url?: string) => {
// note: auto refactor by ChatGPT
const videoUrl = url || currentVideoUrl;
if (
Expand All @@ -72,7 +72,7 @@ export const Home: NextPage<{
) {
toast({
title: "暂不支持此视频链接",
description: "请输入哔哩哔哩视频长链接,暂不支持b23.tv",
description: "请输入哔哩哔哩或YouTub视频链接,已支持b23.tv短链接",
});
return;
}
Expand All @@ -88,7 +88,7 @@ export const Home: NextPage<{
};
const generateSummary = async (url?: string) => {
resetSummary();
validateUrl(url);
validateUrlFromAddressBar(url);

const videoUrl = url || currentVideoUrl;
const { id, service } = getVideoId(videoUrl);
Expand All @@ -101,15 +101,15 @@ export const Home: NextPage<{
return;
}

const bvId = extractUrl(videoUrl);
if (!bvId) {
const videoId = extractUrl(videoUrl);
if (!videoId) {
return;
}

const partNumber = searchParams.get("p");
setCurrentVideoId(bvId);
const pageNumber = extractPage(currentVideoUrl, searchParams);
setCurrentVideoId(videoId);
await summarize(
{ service: VideoService.Bilibili, videoId: bvId, partNumber },
{ service: VideoService.Bilibili, videoId, pageNumber },
{ userKey, shouldShowTimestamp }
);
setTimeout(() => {
Expand All @@ -118,7 +118,7 @@ export const Home: NextPage<{
};
const onFormSubmit = async (e: any) => {
e.preventDefault();
await generateSummary();
await generateSummary(currentVideoUrl);
analytics.track("GenerateButton Clicked");
};
const handleApiKeyChange = (e: any) => {
Expand All @@ -138,6 +138,21 @@ export const Home: NextPage<{
// throw new Error("Sentry Frontend Error");
}

const handleInputChange = async (e: any) => {
const value = e.target.value;
const regex = /((?:https?:\/\/|www\.)\S+)/g;
const matches = value.match(regex);
if (matches) {
const url = matches[0];
toast({ title: "正在自动转换此视频链接..." });
const response = await fetch(`/api/b23tv?url=${url}`);
const json = await response.json();
setCurrentVideoUrl(json.url);
} else {
setCurrentVideoUrl(value);
}
};

return (
<div className="mt-10 w-full sm:mt-40">
<UsageDescription />
Expand All @@ -148,7 +163,7 @@ export const Home: NextPage<{
<input
type="text"
value={currentVideoUrl}
onChange={(e) => setCurrentVideoUrl(e.target.value)}
onChange={handleInputChange}
className="mx-auto mt-10 w-full appearance-none rounded-lg rounded-md border bg-transparent py-2 pl-2 text-sm leading-6 text-slate-900 shadow-sm ring-1 ring-slate-200 placeholder:text-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder={"输入 bilibili.com 视频链接,按下「回车」"}
/>
Expand Down
17 changes: 17 additions & 0 deletions pages/api/b23tv.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { NextApiRequest, NextApiResponse } from "next";

type Data = {
url: string;
};

export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
console.log("========b23.tv URL========", req.query);
// https://b23.tv/MP6B0qw
// @ts-ignore
let response = await fetch(req.query.url);
console.log("======response.url=======", response.url);
res.status(200).json({ url: response.url });
}
File renamed without changes.
13 changes: 13 additions & 0 deletions utils/extractUrl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export function extractUrl(videoUrl: string) {
const matchResult = videoUrl.match(/\/video\/([^\/\?]+)/);
if (!matchResult) {
return;
}
return matchResult[1];
}

export function extractPage(currentVideoUrl: string, searchParams: URLSearchParams) {
const queryString = currentVideoUrl.split("?")[1];
const urlParams = new URLSearchParams(queryString);
return searchParams.get("p") || urlParams.get("p");
}
7 changes: 0 additions & 7 deletions utils/extractUrl.tsx

This file was deleted.

File renamed without changes.
File renamed without changes.

1 comment on commit 32fcb3e

@vercel
Copy link

@vercel vercel bot commented on 32fcb3e Mar 12, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.