[
  {
    "path": ".dockerignore",
    "content": "# Git 相關\n.git\n.gitignore\n\n# Python 快取\n__pycache__/\n*.pyc\n*.pyo\n*.pyd\n.Python\n*.egg-info/\n\n# 虛擬環境（不要打包進 image）\njable/\nvenv/\nenv/\n\n# 下載的影片（可能很大）\ndownloads/\n*.mp4\n*.ts\n*.m3u8\n\n# 開發工具\n.vscode/\n.idea/\n\n# Windows 批次檔（容器內用不到）\n*.bat\n\n# Kubernetes manifests（不需打包進 image）\nk8s/\n"
  },
  {
    "path": ".gitignore",
    "content": "# Python\n*.pyc\n*.pyo\n__pycache__/\n\n# 虛擬環境\n/jable\nvenv/\nenv/\n\n# 影片與暫存檔\n*.mp4\n*.ts\n*.m3u8\n*.jpg\n\n# macOS\n*.DS_store\n.DS_Store\n\n# ChromeDriver（自動下載，不需 commit）\nchromedriver*\n\n# 下載資料夾（影片可能很大）\ndownloads/"
  },
  {
    "path": "Dockerfile",
    "content": "# ---- Base Image ----\n# 使用輕量的 Python 3.11 映像檔\nFROM python:3.11-slim\n\n# ---- 系統套件安裝 ----\n# 安裝 Chromium (headless browser) + ChromeDriver + FFmpeg\nRUN apt-get update && apt-get install -y --no-install-recommends \\\n    ffmpeg \\\n    chromium \\\n    chromium-driver \\\n    && rm -rf /var/lib/apt/lists/*\n\n# ---- 環境變數 ----\n# 告知 Selenium 使用系統的 Chromium\nENV CHROME_BIN=/usr/bin/chromium\nENV CHROMEDRIVER_PATH=/usr/bin/chromedriver\n\n# ---- 工作目錄 ----\nWORKDIR /app\n\n# ---- 安裝 Python 依賴 ----\n# 先複製 requirements.txt，利用 Docker 快取機制加速重建\nCOPY requirements.txt .\nRUN pip install --no-cache-dir -r requirements.txt\n\n# ---- 複製專案程式碼 ----\nCOPY . .\n\n# ---- 掛載點 ----\n# 下載的影片會存放到 /downloads，可透過 -v 掛載到本機\nVOLUME [\"/downloads\"]\n\n# 預設工作目錄切到下載資料夾\nWORKDIR /downloads\n\n# ---- 啟動指令 ----\n# 執行主程式，透過環境變數 URL 傳入影片網址\n# 用法: docker run -e URL=\"https://jable.tv/...\" jable-downloader\nCMD [\"python\", \"/app/main.py\"]\n"
  },
  {
    "path": "INIT.bat",
    "content": "chcp 65001\n\n@echo off\nSET VENV_PATH=.\\jable\n\nREM 檢查虛擬環境是否存在\nIF EXIST \"%VENV_PATH%\\Scripts\\activate.bat\" (\n    ECHO 虛擬環境已經存在。\n) ELSE (\n    ECHO 虛擬環境不存在，正在創建...\n    python -m venv jable\n    ECHO 虛擬環境創建完成。\n)\n\nREM 激活虛擬環境\nCALL \"%VENV_PATH%\\Scripts\\activate\"\n\npip3 install -r requirements.txt\n\nREM 檢查chromedriver.exe是否存在\nIF EXIST \"chromedriver.exe\" (\n    ECHO chromedriver已存在。\n) ELSE (\n    ECHO chromedriver不存在，正在下載...\n    python getchromedriver.py\n)\n\nREM 檢查FFmpeg是否安裝\nwhere ffmpeg >nul 2>&1\nIF %ERRORLEVEL% EQU 0 (\n    ECHO FFmpeg已安裝，你可以執行RUN.bat了\n) ELSE (\n    ECHO FFmpeg未安裝，請先安裝FFmpeg\n)\n\n\npause\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# JableTVDownload\n\n## 下載JableTV好幫手\n\n每次看正要爽的時候就給我卡住轉圈圈  \n\n直接下載到電腦看沒煩惱\n\n---\n\n## 🐳 Docker 一鍵啟動（推薦）\n\n不需要手動安裝 ChromeDriver、FFmpeg、Python 環境，全部封裝在容器內。\n\n### 前置需求\n- 安裝 [Docker Desktop](https://www.docker.com/products/docker-desktop/)\n\n### 使用方法\n\n```bash\n# 1. 建立 image\ndocker build -t jable-downloader .\n\n# 2. 執行（互動模式，下載影片存至本機 downloads 資料夾）\ndocker run -it -v D:\\downloads:/downloads jable-downloader\n```\n\n---\n\n## 💻 傳統安裝（Windows）\n\n1. 請自行安裝 ffmpeg，裝完之後執行 INIT.bat 將會自動建置其餘環境。\n2. 若收到可以執行 RUN.bat 之訊息，執行 RUN.bat 即可使用此神器。\n\n### 1. 搭建並啟用虛擬環境\n\n```\npython -m venv jable\njable/Scripts/activate\n```\n![image](https://github.com/hcjohn463/JableDownload/blob/main/img/createVenv.PNG)\n\n### 2. 下載所需套件\n\n```\npip install -r requirements.txt\n```\n\n安裝 [FFmpeg] 用於轉檔\n\n### 3. 執行程式\n\n```\npython main.py\n```\n\n### 4. 輸入影片網址\n`https://jable.tv/videos/ipx-486/`  \n![image](https://github.com/hcjohn463/JableDownload/blob/main/img/download2.PNG)\n\n### 5. 等待下載與合成\n\n下載和合成影片皆有即時進度條顯示：\n\n```\n⬇ 下載進度:  73%|██████████████░░░░░  | 1334/1827 [01:12<00:27, 18.2片段/s]\n🎬 合成影片:  45%|█████████░░░░░░░░░░░ |  821/1827 [01:23<01:40]\n```\n\n### 6. 完成\n\n![image](https://github.com/hcjohn463/JableDownload/blob/main/img/demo2.png)\n\n### 如果覺得好用 再麻煩給個星星好評 謝謝!!\n\n---\n\n[FFmpeg]:<https://www.ffmpeg.org/>\n\n---\n\n## Argument Parser\n\n```bash\npython main.py -h\npython main.py --random True       # 下載隨機熱門影片\npython main.py --url <網址>         # 直接指定 URL\npython main.py --all_urls <演員頁>  # 下載演員所有影片\n```\n\n---\n\n## ☸️ Kubernetes 支援\n\n`k8s/` 資料夾內含完整 Kubernetes 配置，可將下載任務部署為 K8s Job：\n\n```bash\nkubectl apply -f k8s/pvc.yaml        # 建立持久化儲存\nkubectl apply -f k8s/configmap.yaml  # 套用設定\nkubectl apply -f k8s/job.yaml        # 執行下載任務\nkubectl get jobs                      # 查看任務狀態\n```\n\n---\n\n## 📜 更新日誌 (Update Log)\n\n| 版本 | 日期 | 內容 |\n| :--- | :--- | :--- |\n| **v2.0** | 2026/03/15 | 🐳 支援 Docker 容器化部署、☸️ K8s (Job/PVC/ConfigMap) 支援 |\n| | | 📊 下載與合成加入 `tqdm` 即時進度條、🚀 優化合成與轉檔速度 |\n| **v1.11**| 2023/04/19 | 🦕 新增 ffmpeg 自動轉檔 |\n| **v1.10**| 2023/04/19 | 🏹 兼容 Ubuntu Server |\n| **v1.9** | 2023/04/15 | 🦅 下載演員所有相關影片 |\n| **v1.8** | 2022/01/25 | 🚗 下載結束後自動抓取封面 |\n| **v1.7** | 2021/06/04 | 🐶 更改 m3u8 獲取方法 (正則表達式) |\n| **v1.6** | 2021/05/28 | 🌏 支援 Unix 系統 (Mac, Linux 等) |\n| **v1.5** | 2021/05/27 | 🍎 更新爬蟲網頁方法 |\n| **v1.4** | 2021/05/20 | 🌳 修改編碼問題 |\n| **v1.3** | 2021/05/06 | 🌈 增加下載進度提示、修改 Crypto 問題 |\n| **v1.2** | 2021/05/05 | ⭐ 更新穩定版本 |\n"
  },
  {
    "path": "RUN.bat",
    "content": "@echo off\ncall \"jable\\Scripts\\activate\"\npython main.py\npause\n"
  },
  {
    "path": "args.py",
    "content": "import argparse\nfrom bs4 import BeautifulSoup\nimport random\nfrom urllib.request import Request, urlopen\nfrom config import headers\nimport re\n\n\ndef get_parser():\n    parser = argparse.ArgumentParser(description=\"Jable TV Downloader\")\n    parser.add_argument(\"--random\", type=bool, default=False,\n                        help=\"Enter True for download random \")\n    parser.add_argument(\"--url\", type=str, default=\"\",\n                        help=\"Jable TV URL to download\")\n    parser.add_argument(\"--all-urls\", type=str, default=\"\",\n                        help=\"Jable URL contains multiple avs\")\n    \n    return parser\n\n\ndef av_recommand():\n    headers = {'User-Agent': 'Mozilla/5.0'}\n    url = 'https://jable.tv/'\n    request = Request(url, headers=headers)\n    web_content = urlopen(request).read()\n    # 得到繞過轉址後的 html\n    soup = BeautifulSoup(web_content, 'html.parser')\n    h6_tags = soup.find_all('h6', class_='title')\n    av_list = re.findall(r'https[^\"]+', str(h6_tags))\n    return random.choice(av_list)\n\n\n# print(av_recommand())\n"
  },
  {
    "path": "config.py",
    "content": "headers = {\n    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36',\n}\n"
  },
  {
    "path": "cover.py",
    "content": "import requests\nimport os\nfrom bs4 import BeautifulSoup\n\n\ndef getCover(html_file, folder_path):\n  # get cover\n  soup = BeautifulSoup(html_file, \"html.parser\")\n  cover_name = f\"{os.path.basename(folder_path)}.jpg\"\n  cover_path = os.path.join(folder_path, cover_name)\n  for meta in soup.find_all(\"meta\"):\n      meta_content = meta.get(\"content\")\n      if not meta_content:\n          continue\n      if \"preview.jpg\" not in meta_content:\n          continue\n      try:\n          r = requests.get(meta_content)\n          with open(cover_path, \"wb\") as cover_fh:\n              r.raw.decode_content = True\n              for chunk in r.iter_content(chunk_size=1024):\n                  if chunk:\n                      cover_fh.write(chunk)\n      except Exception as e:\n          print(f\"unable to download cover: {e}\")\n\n  print(f\"cover downloaded as {cover_name}\")\n"
  },
  {
    "path": "crawler.py",
    "content": "import os\nimport requests\nfrom config import headers\nfrom functools import partial\nimport concurrent.futures\nimport time\nimport copy\nimport threading\nfrom tqdm import tqdm\nfrom Crypto.Cipher import AES\n\n\ndef scrape(ci_params, folderPath, pbar, lock, session, urls):\n    \"\"\"\n    ci_params: dict 包含 key 和 iv\n    session: requests.Session 用於連線複用，加快下載\n    \"\"\"\n    fileName = urls.split('/')[-1][0:-3]\n    saveName = os.path.join(folderPath, fileName + \".mp4\")\n\n    # 如果檔案已存在，進度條不重複更新（因為 startCrawl 已過濾）\n    try:\n        response = session.get(urls, headers=headers, timeout=30)\n        if response.status_code == 200:\n            content_ts = response.content\n            if ci_params:\n                ci = AES.new(ci_params['key'], AES.MODE_CBC, ci_params['iv'])\n                content_ts = ci.decrypt(content_ts)\n            with open(saveName, 'ab') as f:\n                f.write(content_ts)\n            \n            # ✅ 只有成功下載才更新進度條\n            with lock:\n                pbar.update(1)\n            return True\n    except Exception:\n        pass\n    \n    return False\n\n\ndef measureSpeed(tsList, sample_count=3):\n    \"\"\"並行測速，減少啟動延遲\"\"\"\n    sample = tsList[:sample_count]\n    times = []\n    sizes = []\n\n    def _fetch(url):\n        t0 = time.time()\n        try:\n            with requests.Session() as s:\n                response = s.get(url, headers=headers, timeout=15)\n            size_kb = len(response.content) / 1024\n            return time.time() - t0, size_kb\n        except Exception:\n            return 2.0, 0\n\n    print(f'正在測試您的網速（抽樣 {sample_count} 個片段，並行）...', end='', flush=True)\n    with concurrent.futures.ThreadPoolExecutor(max_workers=sample_count) as ex:\n        results = list(ex.map(_fetch, sample))\n    times = [r[0] for r in results]\n    sizes = [r[1] for r in results]\n    avg_sec = sum(times) / len(times) if times else 2.0\n    avg_speed_kb = sum(sizes) / sum(times) if sum(times) > 0 else 0\n    print(f' 平均網速: {avg_speed_kb:.0f} KB/s ({avg_sec:.2f} 秒/片段)')\n    return avg_sec, avg_speed_kb\n\n\ndef prepareCrawl(ci_params, folderPath, tsList):\n    downloadList = copy.deepcopy(tsList)\n    total = len(downloadList)\n\n    avg_sec_per_ts, avg_speed_kb = measureSpeed(tsList)\n    # 提高並發：上限 32、下限 8，公式放寬以善用頻寬\n    workers = min(32, max(8, int(avg_speed_kb / 200)))\n    print(f'開始下載 {total} 個片段（使用 {workers} 個執行緒）')\n\n    estimated_sec = (total * avg_sec_per_ts) / workers\n    est_m = int(estimated_sec // 60)\n    est_s = int(estimated_sec % 60)\n    print(f'預計等待時間: {est_m} 分 {est_s} 秒（依據您的實際網速估算）')\n\n    start_time = time.time()\n    startCrawl(ci_params, folderPath, downloadList, total, workers)\n    end_time = time.time()\n\n    actual_sec = end_time - start_time\n    act_m = int(actual_sec // 60)\n    act_s = int(actual_sec % 60)\n    print(f'\\n花費 {act_m} 分 {act_s} 秒 爬取完成！')\n\n\ndef startCrawl(ci_params, folderPath, downloadList, total, workers):\n    lock = threading.Lock()\n    round_num = 0\n    # 連線池：同一 host 複用 TCP，減少握手指數\n    with requests.Session() as session:\n        _run_crawl(ci_params, folderPath, downloadList, total, workers, lock, session)\n\n\ndef _run_crawl(ci_params, folderPath, downloadList, total, workers, lock, session):\n    round_num = 0\n    # ✅ 初始化進度條，總數固定為 total\n    with tqdm(total=total, unit='片段', desc='⬇ 下載進度',\n              bar_format='{desc}: {percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]',\n              dynamic_ncols=True, colour='cyan') as pbar:\n\n        # 先檢查已經下載過的，更新進度條初始值\n        existing_count = 0\n        initial_list = list(downloadList)\n        for url in initial_list:\n            file_ts = url.split('/')[-1][0:-3] + '.mp4'\n            if os.path.exists(os.path.join(folderPath, file_ts)):\n                existing_count += 1\n                downloadList.remove(url)\n        \n        pbar.update(existing_count)\n\n        while downloadList:\n            round_num += 1\n            batch = list(downloadList)\n\n            with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:\n                # scrape 使用 session 連線複用，加快下載\n                executor.map(partial(scrape, ci_params, folderPath, pbar, lock, session), batch)\n\n            # 更新剩餘清單：移除已成功下載的\n            new_download_list = []\n            for url in downloadList:\n                file_ts = url.split('/')[-1][0:-3] + '.mp4'\n                if not os.path.exists(os.path.join(folderPath, file_ts)):\n                    new_download_list.append(url)\n            \n            downloadList = new_download_list\n\n            if downloadList:\n                tqdm.write(f'⚠ Round {round_num} 結束，還有 {len(downloadList)} 個片段失敗，準備重試...')\n                time.sleep(1) # 短暫休息避免被封鎖\n"
  },
  {
    "path": "delete.py",
    "content": "import os\n\ndef deleteMp4(folderPath):\n    files = os.listdir(folderPath)\n    originFile = folderPath.split(os.path.sep)[-1] + '.mp4'\n    for file in files:\n        if file != originFile:\n            os.remove(os.path.join(folderPath, file))\n\n\ndef deleteM3u8(folderPath):\n    files = os.listdir(folderPath)\n    for file in files:\n        if file.endswith('.m3u8'):\n            os.remove(os.path.join(folderPath, file))\n"
  },
  {
    "path": "docker-compose.yml",
    "content": "version: '3.8'\n\nservices:\n  # ---- 主下載服務 ----\n  downloader:\n    build: .\n    image: jable-downloader:latest\n    container_name: jable_downloader\n    environment:\n      - URL=${URL:-}          # 透過環境變數傳入影片網址\n    volumes:\n      - ./downloads:/downloads  # 本機 downloads 資料夾 ←→ 容器內 /downloads\n    stdin_open: true            # 保持 stdin 開啟（互動模式）\n    tty: true\n\n  # ---- (可選) Redis 任務佇列 ----\n  # 未來擴充成多任務排隊下載時使用\n  redis:\n    image: redis:7-alpine\n    container_name: jable_redis\n    ports:\n      - \"6379:6379\"\n    volumes:\n      - redis_data:/data\n    restart: unless-stopped\n\nvolumes:\n  redis_data:\n"
  },
  {
    "path": "download.py",
    "content": "\nimport requests\nimport os\nimport re\nimport urllib.request\nimport m3u8\nfrom config import headers\nfrom crawler import prepareCrawl\nfrom merge import mergeMp4\nfrom encode import ffmpegEncode\nfrom delete import deleteM3u8, deleteMp4\nfrom cover import getCover\nfrom args import *\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\ndef download(url):\n\n  print('正在下載影片: ' + url)\n  # 建立番號資料夾\n  urlSplit = url.split('/')\n  dirName = urlSplit[-2]\n  if os.path.exists(f'{dirName}/{dirName}.mp4'):\n    print('番號資料夾已存在, 跳過...')\n    return\n  if not os.path.exists(dirName):\n      os.makedirs(dirName)\n  folderPath = os.path.join(os.getcwd(), dirName)\n  \n  #配置Selenium參數\n  options = Options()\n  options.add_argument('--no-sandbox')\n  options.add_argument('--disable-dev-shm-usage')\n  options.add_argument('--disable-extensions')\n  options.add_argument('--headless')\n  options.add_argument(\"user-agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36\")\n  dr = webdriver.Chrome(options=options)\n  dr.get(url)\n  result = re.search(\"https://.+m3u8\", dr.page_source)\n  print(f'result: {result}')\n  m3u8url = result[0]\n  print(f'm3u8url: {m3u8url}')\n\n  # 得到 m3u8 網址\n  m3u8urlList = m3u8url.split('/')\n  m3u8urlList.pop(-1)\n  downloadurl = '/'.join(m3u8urlList)\n\n  # 儲存 m3u8 file 至資料夾\n  m3u8file = os.path.join(folderPath, dirName + '.m3u8')\n  urllib.request.urlretrieve(m3u8url, m3u8file)\n\n  # 得到 m3u8 file裡的 URI和 IV\n  m3u8obj = m3u8.load(m3u8file)\n  m3u8uri = ''\n  m3u8iv = ''\n\n  for key in m3u8obj.keys:\n      if key:\n          m3u8uri = key.uri\n          m3u8iv = key.iv\n\n  # 儲存 ts網址 in tsList\n  tsList = []\n  for seg in m3u8obj.segments:\n      tsUrl = downloadurl + '/' + seg.uri\n      tsList.append(tsUrl)\n\n  # 有加密\n  if m3u8uri:\n      m3u8keyurl = downloadurl + '/' + m3u8uri\n      response = requests.get(m3u8keyurl, headers=headers, timeout=10)\n      contentKey = response.content\n      vt = m3u8iv.replace(\"0x\", \"\")[:16].encode()  # IV 取前 16 位\n      # ✅ 改存 dict，讓每個執行緒自行建立 AES cipher（避免 Race Condition）\n      ci_params = {'key': contentKey, 'iv': vt}\n  else:\n      ci_params = None\n\n  # 刪除m3u8 file\n  deleteM3u8(folderPath)\n\n  # 開始爬蟲並下載mp4片段至資料夾\n  prepareCrawl(ci_params, folderPath, tsList)\n\n  # 合成 mp4（Python 二進位串接）\n  mergeMp4(folderPath, tsList)\n\n  # 轉檔：-c copy + faststart，讓播放器可邊下載邊播\n  ffmpegEncode(folderPath, dirName, 1)\n\n  # 刪除子mp4\n  deleteMp4(folderPath)\n\n  # 取得封面\n  getCover(html_file=dr.page_source, folder_path=folderPath)\n"
  },
  {
    "path": "encode.py",
    "content": "import os\nimport subprocess\nfrom tqdm import tqdm\n\n\ndef get_segment_count(folder_path):\n    \"\"\"取得 concat_list.txt 中的片段總數以顯示進度\"\"\"\n    try:\n        with open(os.path.join(folder_path, 'concat_list.txt'), 'r', encoding='utf-8') as f:\n            return sum(1 for line in f if line.startswith('file'))\n    except Exception:\n        return None\n\n\ndef ffmpegEncode(folder_path, file_name, action=1):\n    \"\"\"\n    結合合成與快速無損轉檔\n    - 使用 concat demuxer 避免兩次讀寫\n    - 不重新壓縮畫面，畫質完全不變\n    - 修正音訊封包格式（ADTS → ASC）\n    - 加上 faststart\n    \"\"\"\n    if action == 0:\n        return\n\n    os.chdir(folder_path)\n    concat_list = 'concat_list.txt'\n    dst = f'{file_name}.mp4'\n\n    if not os.path.exists(concat_list):\n        print(f'❌ 找不到合成清單 {concat_list}')\n        return\n\n    # 取得片段總數（用於進度條）\n    total_segments = get_segment_count(folder_path)\n\n    # 這裡我們觀察 FFmpeg 的進度輸出\n    # 因為是 concat copy，通常很快，我們追蹤 frame 或者是 time\n    # 但因為總幀數難算，我們顯示處理進度\n    cmd = ['ffmpeg', '-y',\n           '-f', 'concat',\n           '-safe', '0',\n           '-i', concat_list,\n           '-c', 'copy',\n           '-bsf:a', 'aac_adtstoasc',\n           '-movflags', '+faststart',\n           '-progress', 'pipe:1',\n           '-nostats',\n           '-loglevel', 'info',   # 改為 info 以便抓取 \"Opening\" 訊息\n           dst]\n\n    process = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n                                stderr=subprocess.STDOUT, text=True,\n                                bufsize=1, encoding='utf-8')\n\n    desc = '🚀 快速合成與轉檔'\n    with tqdm(total=total_segments, unit='片段', desc=desc,\n              bar_format='{desc}: {percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}]',\n              dynamic_ncols=True, colour='yellow') as pbar:\n\n        processed_segments = 0\n        last_frame_count = 0\n        for line in process.stdout:\n            # 這裡列出幾種可能的格式以增加相容性\n            # 1. [concat @ 0x...] Opening 'xxxxx.mp4' for reading\n            # 2. Opening 'xxxxx.mp4' for reading\n            if 'Opening' in line and 'for reading' in line:\n                processed_segments += 1\n                if processed_segments <= total_segments:\n                    pbar.update(1)\n            \n            # 作為備案：如果一直沒有 Opening 訊息（某些環境會過濾），\n            # 我們可以透過 frame 的變動來讓進度條「動起來」表示沒死掉，\n            # 雖然這裡 total 是片段數，所以我們只在描述增加訊息。\n            if 'frame=' in line:\n                try:\n                    parts = line.split('=')\n                    if len(parts) > 1:\n                        frame_val = parts[1].split()[0]\n                        if frame_val.isdigit():\n                            pbar.set_postfix_str(f\"已處理 {frame_val} 幀\")\n                except:\n                    pass\n\n            if line.startswith('progress=end'):\n                if processed_segments < total_segments:\n                    pbar.update(total_segments - processed_segments)\n\n    process.wait()\n\n    if process.returncode == 0:\n        if os.path.exists(concat_list):\n            os.remove(concat_list)\n        print('✅ 合成與轉檔成功!')\n    else:\n        print('❌ 合成與轉檔失敗!')\n"
  },
  {
    "path": "getchromedriver.py",
    "content": "import requests\nfrom bs4 import BeautifulSoup\nimport zipfile\nimport shutil\nimport os\n\ndef get_chromedriver_version():\n    url = 'https://googlechromelabs.github.io/chrome-for-testing/'\n    response = requests.get(url)\n\n    if response.status_code == 200:\n        soup = BeautifulSoup(response.text, 'html.parser')\n        formatted_html = soup.prettify()\n        \n        # print(formatted_html)\n\n        tr_tags = soup.find_all('tr', class_='status-ok')\n        for tr in tr_tags:\n            if tr.find('a', string=\"Stable\"):\n                version_code = tr.find('code').text.strip()\n                print(version_code)\n                break\n        return version_code\n    else:\n        print(\"Fail, Code:\", response.status_code)\n\ndef download_chromedriver(download_link):\n    url = download_link\n    response = requests.get(url)\n\n    if response.status_code == 200:\n        with open('chromedriver.zip', 'wb') as file:\n            file.write(response.content)\n        print(\"success!\")\n    else:\n        print(\"Fail, Code:\", response.status_code)\n\ndef unzip_chromedriver():\n    with zipfile.ZipFile('chromedriver.zip', 'r') as zip_ref:\n        zip_ref.extractall('./')\n\nchromedriver_version = get_chromedriver_version()\ndownload_link = f\"https://storage.googleapis.com/chrome-for-testing-public/{chromedriver_version}/win64/chromedriver-win64.zip\"\ndownload_chromedriver(download_link)\nunzip_chromedriver()\n\n# move chromedriver to the root directory\nfile_source = \"chromedriver-win64/chromedriver.exe\"\nfile_destination = \"./\"\nshutil.move(file_source, file_destination)\n\n# clean up\nshutil.rmtree('chromedriver-win64')\nos.remove(\"chromedriver.zip\")"
  },
  {
    "path": "k8s/configmap.yaml",
    "content": "# ============================================================\n# ConfigMap\n# 用途：集中管理設定值（不寫死在程式或 Job 裡）\n# ============================================================\napiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: jable-config\n  namespace: default\ndata:\n  # 預設下載網址（可在 Job 中被 env 覆蓋）\n  DEFAULT_URL: \"https://jable.tv/videos/ipx-486/\"\n  # Chrome 相關設定\n  CHROME_BIN: \"/usr/bin/chromium\"\n  CHROMEDRIVER_PATH: \"/usr/bin/chromedriver\"\n"
  },
  {
    "path": "k8s/job.yaml",
    "content": "# ============================================================\n# Kubernetes Job\n# 用途：每次下載任務就建立一個 Job，跑完自動結束\n# 這是最適合「批次下載」場景的 K8s 資源類型\n# ============================================================\napiVersion: batch/v1\nkind: Job\nmetadata:\n  name: jable-download-job\n  namespace: default\n  labels:\n    app: jable-downloader\nspec:\n  # ttlSecondsAfterFinished: Job 完成後 300 秒自動清除\n  ttlSecondsAfterFinished: 300\n  template:\n    metadata:\n      labels:\n        app: jable-downloader\n    spec:\n      restartPolicy: OnFailure   # 失敗時重試，成功後不重啟\n      containers:\n        - name: downloader\n          image: jable-downloader:latest\n          imagePullPolicy: IfNotPresent  # 本地測試用，不強制從 Registry 拉取\n          env:\n            # 傳入目標影片網址\n            - name: URL\n              value: \"https://jable.tv/videos/ipx-486/\"  # ← 修改這裡\n            # 從 ConfigMap 取得設定\n            - name: CHROME_BIN\n              valueFrom:\n                configMapKeyRef:\n                  name: jable-config\n                  key: CHROME_BIN\n            - name: CHROMEDRIVER_PATH\n              valueFrom:\n                configMapKeyRef:\n                  name: jable-config\n                  key: CHROMEDRIVER_PATH\n          volumeMounts:\n            - name: downloads-storage\n              mountPath: /downloads  # 容器內的下載路徑\n          resources:\n            requests:\n              memory: \"512Mi\"\n              cpu: \"250m\"\n            limits:\n              memory: \"2Gi\"\n              cpu: \"1000m\"\n      volumes:\n        - name: downloads-storage\n          persistentVolumeClaim:\n            claimName: jable-downloads-pvc  # 掛載 PVC\n"
  },
  {
    "path": "k8s/pvc.yaml",
    "content": "# ============================================================\n# PersistentVolumeClaim (PVC)\n# 用途：給下載的影片提供持久化儲存空間\n# ============================================================\napiVersion: v1\nkind: PersistentVolumeClaim\nmetadata:\n  name: jable-downloads-pvc\n  namespace: default\nspec:\n  accessModes:\n    - ReadWriteOnce       # 單一 Node 讀寫\n  resources:\n    requests:\n      storage: 50Gi       # 申請 50GB 儲存空間\n  storageClassName: standard\n"
  },
  {
    "path": "main.py",
    "content": "# author: hcjohn463\n#!/usr/bin/env python\n# coding: utf-8\nfrom args import *\nfrom download import download\nfrom movies import movieLinks\n# In[2]:\n\nparser = get_parser()\nargs = parser.parse_args()\n\nif(len(args.url) != 0):\n    url = args.url\n    download(url)\nelif(args.random == True):\n    url = av_recommand()\n    download(url)\nelif(args.all_urls != \"\"):\n    all_urls = args.all_urls\n    urls = movieLinks(all_urls)\n    for url in urls:\n        download(url)\nelse:\n    # 使用者輸入Jable網址\n    url = input('輸入jable網址:')\n    download(url)\n"
  },
  {
    "path": "merge.py",
    "content": "import os\nimport time\nfrom tqdm import tqdm\n\n\ndef mergeMp4(folderPath, tsList):\n    \"\"\"產生 FFmpeg concat 用的清單檔案，不再進行二進位串接以節省時間與 IO\"\"\"\n    start_time = time.time()\n    # video_name = folderPath.split(os.path.sep)[-1]\n    concat_list_path = os.path.join(folderPath, 'concat_list.txt')\n\n    print('正在準備合成清單..')\n    total = len(tsList)\n    with open(concat_list_path, 'w', encoding='utf-8') as f:\n        for i in range(total):\n            file = tsList[i].split('/')[-1][0:-3] + '.mp4'\n            full_path = os.path.join(folderPath, file)\n            if os.path.exists(full_path):\n                # FFmpeg concat file 格式: file 'path/to/file'\n                # 使用相對路徑或絕對路徑皆可，這裡用檔名即可，因為會在 folderPath 執行 ffmpeg\n                f.write(f\"file '{file}'\\n\")\n            else:\n                print(f'警告: 缺少片段 {file}')\n\n    elapsed = time.time() - start_time\n    print('花費 {0:.2f} 秒 準備合成清單'.format(elapsed))\n\n"
  },
  {
    "path": "movies.py",
    "content": "# In[0]:\nimport requests\nfrom config import headers\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\n\n\ndef movieLinks(url):\n  links = []\n  dr = webdriver.Chrome()\n  dr.get(url)\n  bs = BeautifulSoup(dr.page_source,\"html.parser\")\n  a_tags = bs.select('div.img-box>a')\n  print(a_tags)\n  for a_tag in a_tags:\n    links.append(a_tag['href'])\n  print('获取到 {0} 個影片'.format(len(links)))\n  print(links)\n  return links\n\n# %%\n"
  },
  {
    "path": "requirements.txt",
    "content": "requests==2.31.0\r\nbeautifulsoup4==4.12.3\r\nm3u8==0.8.0\r\npycryptodome==3.17\r\nselenium\r\nsoupsieve==2.5\r\nurllib3==2.2.1\r\ncertifi==2024.2.2\r\ncharset-normalizer==3.3.2\r\nidna==3.6\r\ntqdm\r\n"
  }
]