Commit 0c18719

benny-dou <60535774+benny-dou@users.noreply.github.com>
2025-01-23 17:30:27
feat(bilibili): make bvid in description clickable
1 parent 1fbe0f9
Changed files (1)
src
preview
src/preview/ytdlp.py
@@ -177,7 +177,8 @@ async def preview_ytdlp(
     if not true(kwargs.get("no_description")) and (desc := info.get("description")) and (desc != "-"):
         warnings.simplefilter("ignore", MarkupResemblesLocatorWarning)
         soup = BeautifulSoup(desc, "html.parser")
-        texts += f"\n{soup_to_text(soup)}"
+        desc_text = soup_to_text(soup)
+        texts += f"\n{make_bvid_clickable(desc_text)}"
     # comments
     comments = []
     if platform == "bilibili":
@@ -482,6 +483,34 @@ async def get_youtube_comments(vid: str | None, provider: str = PROVIDER.YOUTUBE
     return comments
 
 
+def make_bvid_clickable(texts: str) -> str:
+    """Make bvid in texts clickable.
+
+    "BV1234567890" -> [BV1234567890](https://www.bilibili.com/video/BV1234567890)
+
+    bvid format: https://github.com/SocialSisterYi/bilibili-API-collect/blob/18c1efb/docs/misc/bvid_desc.md
+    Args:
+        texts (str): The texts to process.
+
+    Returns:
+        str: bvid with markdown url.
+    """
+    if not texts:
+        return ""
+
+    def markdown_url(match):
+        if match.group(1):  # full url
+            bvid = match.group(3)
+            return f"[{bvid}](https://www.bilibili.com/video/{bvid})"
+        # bvid only
+        bvid = match.group(0)
+        return f"[{bvid}](https://www.bilibili.com/video/{bvid})"
+
+    # match bilibili links or bvid only
+    pattern = r"(https?://)?(:?m\.|www\.)?bilibili\.com/video/(BV1[a-zA-Z0-9]{9})\b|\bBV1[a-zA-Z0-9]{9}\b"
+    return re.sub(pattern, markdown_url, texts)
+
+
 def cleanup_ytdlp(title: str):
     """Clean up ytdlp files.