Full Code of hcjohn463/JableTVDownload for AI

main c8de50f1700a cached
23 files
34.2 KB
10.3k tokens
18 symbols
1 requests
Download .txt
Repository: hcjohn463/JableTVDownload
Branch: main
Commit: c8de50f1700a
Files: 23
Total size: 34.2 KB

Directory structure:
gitextract_m85xy9ir/

├── .dockerignore
├── .gitignore
├── Dockerfile
├── INIT.bat
├── LICENSE
├── README.md
├── RUN.bat
├── args.py
├── config.py
├── cover.py
├── crawler.py
├── delete.py
├── docker-compose.yml
├── download.py
├── encode.py
├── getchromedriver.py
├── k8s/
│   ├── configmap.yaml
│   ├── job.yaml
│   └── pvc.yaml
├── main.py
├── merge.py
├── movies.py
└── requirements.txt

================================================
FILE CONTENTS
================================================

================================================
FILE: .dockerignore
================================================
# Git 相關
.git
.gitignore

# Python 快取
__pycache__/
*.pyc
*.pyo
*.pyd
.Python
*.egg-info/

# 虛擬環境(不要打包進 image)
jable/
venv/
env/

# 下載的影片(可能很大)
downloads/
*.mp4
*.ts
*.m3u8

# 開發工具
.vscode/
.idea/

# Windows 批次檔(容器內用不到)
*.bat

# Kubernetes manifests(不需打包進 image)
k8s/


================================================
FILE: .gitignore
================================================
# Python
*.pyc
*.pyo
__pycache__/

# 虛擬環境
/jable
venv/
env/

# 影片與暫存檔
*.mp4
*.ts
*.m3u8
*.jpg

# macOS
*.DS_store
.DS_Store

# ChromeDriver(自動下載,不需 commit)
chromedriver*

# 下載資料夾(影片可能很大)
downloads/

================================================
FILE: Dockerfile
================================================
# ---- Base Image ----
# 使用輕量的 Python 3.11 映像檔
FROM python:3.11-slim

# ---- 系統套件安裝 ----
# 安裝 Chromium (headless browser) + ChromeDriver + FFmpeg
RUN apt-get update && apt-get install -y --no-install-recommends \
    ffmpeg \
    chromium \
    chromium-driver \
    && rm -rf /var/lib/apt/lists/*

# ---- 環境變數 ----
# 告知 Selenium 使用系統的 Chromium
ENV CHROME_BIN=/usr/bin/chromium
ENV CHROMEDRIVER_PATH=/usr/bin/chromedriver

# ---- 工作目錄 ----
WORKDIR /app

# ---- 安裝 Python 依賴 ----
# 先複製 requirements.txt,利用 Docker 快取機制加速重建
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# ---- 複製專案程式碼 ----
COPY . .

# ---- 掛載點 ----
# 下載的影片會存放到 /downloads,可透過 -v 掛載到本機
VOLUME ["/downloads"]

# 預設工作目錄切到下載資料夾
WORKDIR /downloads

# ---- 啟動指令 ----
# 執行主程式,透過環境變數 URL 傳入影片網址
# 用法: docker run -e URL="https://jable.tv/..." jable-downloader
CMD ["python", "/app/main.py"]


================================================
FILE: INIT.bat
================================================
chcp 65001

@echo off
SET VENV_PATH=.\jable

REM 檢查虛擬環境是否存在
IF EXIST "%VENV_PATH%\Scripts\activate.bat" (
    ECHO 虛擬環境已經存在。
) ELSE (
    ECHO 虛擬環境不存在,正在創建...
    python -m venv jable
    ECHO 虛擬環境創建完成。
)

REM 激活虛擬環境
CALL "%VENV_PATH%\Scripts\activate"

pip3 install -r requirements.txt

REM 檢查chromedriver.exe是否存在
IF EXIST "chromedriver.exe" (
    ECHO chromedriver已存在。
) ELSE (
    ECHO chromedriver不存在,正在下載...
    python getchromedriver.py
)

REM 檢查FFmpeg是否安裝
where ffmpeg >nul 2>&1
IF %ERRORLEVEL% EQU 0 (
    ECHO FFmpeg已安裝,你可以執行RUN.bat了
) ELSE (
    ECHO FFmpeg未安裝,請先安裝FFmpeg
)


pause


================================================
FILE: LICENSE
================================================
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: README.md
================================================
# JableTVDownload

## 下載JableTV好幫手

每次看正要爽的時候就給我卡住轉圈圈  

直接下載到電腦看沒煩惱

---

## 🐳 Docker 一鍵啟動(推薦)

不需要手動安裝 ChromeDriver、FFmpeg、Python 環境,全部封裝在容器內。

### 前置需求
- 安裝 [Docker Desktop](https://www.docker.com/products/docker-desktop/)

### 使用方法

```bash
# 1. 建立 image
docker build -t jable-downloader .

# 2. 執行(互動模式,下載影片存至本機 downloads 資料夾)
docker run -it -v D:\downloads:/downloads jable-downloader
```

---

## 💻 傳統安裝(Windows)

1. 請自行安裝 ffmpeg,裝完之後執行 INIT.bat 將會自動建置其餘環境。
2. 若收到可以執行 RUN.bat 之訊息,執行 RUN.bat 即可使用此神器。

### 1. 搭建並啟用虛擬環境

```
python -m venv jable
jable/Scripts/activate
```
![image](https://github.com/hcjohn463/JableDownload/blob/main/img/createVenv.PNG)

### 2. 下載所需套件

```
pip install -r requirements.txt
```

安裝 [FFmpeg] 用於轉檔

### 3. 執行程式

```
python main.py
```

### 4. 輸入影片網址
`https://jable.tv/videos/ipx-486/`  
![image](https://github.com/hcjohn463/JableDownload/blob/main/img/download2.PNG)

### 5. 等待下載與合成

下載和合成影片皆有即時進度條顯示:

```
⬇ 下載進度:  73%|██████████████░░░░░  | 1334/1827 [01:12<00:27, 18.2片段/s]
🎬 合成影片:  45%|█████████░░░░░░░░░░░ |  821/1827 [01:23<01:40]
```

### 6. 完成

![image](https://github.com/hcjohn463/JableDownload/blob/main/img/demo2.png)

### 如果覺得好用 再麻煩給個星星好評 謝謝!!

---

[FFmpeg]:<https://www.ffmpeg.org/>

---

## Argument Parser

```bash
python main.py -h
python main.py --random True       # 下載隨機熱門影片
python main.py --url <網址>         # 直接指定 URL
python main.py --all_urls <演員頁>  # 下載演員所有影片
```

---

## ☸️ Kubernetes 支援

`k8s/` 資料夾內含完整 Kubernetes 配置,可將下載任務部署為 K8s Job:

```bash
kubectl apply -f k8s/pvc.yaml        # 建立持久化儲存
kubectl apply -f k8s/configmap.yaml  # 套用設定
kubectl apply -f k8s/job.yaml        # 執行下載任務
kubectl get jobs                      # 查看任務狀態
```

---

## 📜 更新日誌 (Update Log)

| 版本 | 日期 | 內容 |
| :--- | :--- | :--- |
| **v2.0** | 2026/03/15 | 🐳 支援 Docker 容器化部署、☸️ K8s (Job/PVC/ConfigMap) 支援 |
| | | 📊 下載與合成加入 `tqdm` 即時進度條、🚀 優化合成與轉檔速度 |
| **v1.11**| 2023/04/19 | 🦕 新增 ffmpeg 自動轉檔 |
| **v1.10**| 2023/04/19 | 🏹 兼容 Ubuntu Server |
| **v1.9** | 2023/04/15 | 🦅 下載演員所有相關影片 |
| **v1.8** | 2022/01/25 | 🚗 下載結束後自動抓取封面 |
| **v1.7** | 2021/06/04 | 🐶 更改 m3u8 獲取方法 (正則表達式) |
| **v1.6** | 2021/05/28 | 🌏 支援 Unix 系統 (Mac, Linux 等) |
| **v1.5** | 2021/05/27 | 🍎 更新爬蟲網頁方法 |
| **v1.4** | 2021/05/20 | 🌳 修改編碼問題 |
| **v1.3** | 2021/05/06 | 🌈 增加下載進度提示、修改 Crypto 問題 |
| **v1.2** | 2021/05/05 | ⭐ 更新穩定版本 |


================================================
FILE: RUN.bat
================================================
@echo off
call "jable\Scripts\activate"
python main.py
pause


================================================
FILE: args.py
================================================
import argparse
from bs4 import BeautifulSoup
import random
from urllib.request import Request, urlopen
from config import headers
import re


def get_parser():
    parser = argparse.ArgumentParser(description="Jable TV Downloader")
    parser.add_argument("--random", type=bool, default=False,
                        help="Enter True for download random ")
    parser.add_argument("--url", type=str, default="",
                        help="Jable TV URL to download")
    parser.add_argument("--all-urls", type=str, default="",
                        help="Jable URL contains multiple avs")
    
    return parser


def av_recommand():
    headers = {'User-Agent': 'Mozilla/5.0'}
    url = 'https://jable.tv/'
    request = Request(url, headers=headers)
    web_content = urlopen(request).read()
    # 得到繞過轉址後的 html
    soup = BeautifulSoup(web_content, 'html.parser')
    h6_tags = soup.find_all('h6', class_='title')
    av_list = re.findall(r'https[^"]+', str(h6_tags))
    return random.choice(av_list)


# print(av_recommand())


================================================
FILE: config.py
================================================
headers = {
    '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',
}


================================================
FILE: cover.py
================================================
import requests
import os
from bs4 import BeautifulSoup


def getCover(html_file, folder_path):
  # get cover
  soup = BeautifulSoup(html_file, "html.parser")
  cover_name = f"{os.path.basename(folder_path)}.jpg"
  cover_path = os.path.join(folder_path, cover_name)
  for meta in soup.find_all("meta"):
      meta_content = meta.get("content")
      if not meta_content:
          continue
      if "preview.jpg" not in meta_content:
          continue
      try:
          r = requests.get(meta_content)
          with open(cover_path, "wb") as cover_fh:
              r.raw.decode_content = True
              for chunk in r.iter_content(chunk_size=1024):
                  if chunk:
                      cover_fh.write(chunk)
      except Exception as e:
          print(f"unable to download cover: {e}")

  print(f"cover downloaded as {cover_name}")


================================================
FILE: crawler.py
================================================
import os
import requests
from config import headers
from functools import partial
import concurrent.futures
import time
import copy
import threading
from tqdm import tqdm
from Crypto.Cipher import AES


def scrape(ci_params, folderPath, pbar, lock, session, urls):
    """
    ci_params: dict 包含 key 和 iv
    session: requests.Session 用於連線複用,加快下載
    """
    fileName = urls.split('/')[-1][0:-3]
    saveName = os.path.join(folderPath, fileName + ".mp4")

    # 如果檔案已存在,進度條不重複更新(因為 startCrawl 已過濾)
    try:
        response = session.get(urls, headers=headers, timeout=30)
        if response.status_code == 200:
            content_ts = response.content
            if ci_params:
                ci = AES.new(ci_params['key'], AES.MODE_CBC, ci_params['iv'])
                content_ts = ci.decrypt(content_ts)
            with open(saveName, 'ab') as f:
                f.write(content_ts)
            
            # ✅ 只有成功下載才更新進度條
            with lock:
                pbar.update(1)
            return True
    except Exception:
        pass
    
    return False


def measureSpeed(tsList, sample_count=3):
    """並行測速,減少啟動延遲"""
    sample = tsList[:sample_count]
    times = []
    sizes = []

    def _fetch(url):
        t0 = time.time()
        try:
            with requests.Session() as s:
                response = s.get(url, headers=headers, timeout=15)
            size_kb = len(response.content) / 1024
            return time.time() - t0, size_kb
        except Exception:
            return 2.0, 0

    print(f'正在測試您的網速(抽樣 {sample_count} 個片段,並行)...', end='', flush=True)
    with concurrent.futures.ThreadPoolExecutor(max_workers=sample_count) as ex:
        results = list(ex.map(_fetch, sample))
    times = [r[0] for r in results]
    sizes = [r[1] for r in results]
    avg_sec = sum(times) / len(times) if times else 2.0
    avg_speed_kb = sum(sizes) / sum(times) if sum(times) > 0 else 0
    print(f' 平均網速: {avg_speed_kb:.0f} KB/s ({avg_sec:.2f} 秒/片段)')
    return avg_sec, avg_speed_kb


def prepareCrawl(ci_params, folderPath, tsList):
    downloadList = copy.deepcopy(tsList)
    total = len(downloadList)

    avg_sec_per_ts, avg_speed_kb = measureSpeed(tsList)
    # 提高並發:上限 32、下限 8,公式放寬以善用頻寬
    workers = min(32, max(8, int(avg_speed_kb / 200)))
    print(f'開始下載 {total} 個片段(使用 {workers} 個執行緒)')

    estimated_sec = (total * avg_sec_per_ts) / workers
    est_m = int(estimated_sec // 60)
    est_s = int(estimated_sec % 60)
    print(f'預計等待時間: {est_m} 分 {est_s} 秒(依據您的實際網速估算)')

    start_time = time.time()
    startCrawl(ci_params, folderPath, downloadList, total, workers)
    end_time = time.time()

    actual_sec = end_time - start_time
    act_m = int(actual_sec // 60)
    act_s = int(actual_sec % 60)
    print(f'\n花費 {act_m} 分 {act_s} 秒 爬取完成!')


def startCrawl(ci_params, folderPath, downloadList, total, workers):
    lock = threading.Lock()
    round_num = 0
    # 連線池:同一 host 複用 TCP,減少握手指數
    with requests.Session() as session:
        _run_crawl(ci_params, folderPath, downloadList, total, workers, lock, session)


def _run_crawl(ci_params, folderPath, downloadList, total, workers, lock, session):
    round_num = 0
    # ✅ 初始化進度條,總數固定為 total
    with tqdm(total=total, unit='片段', desc='⬇ 下載進度',
              bar_format='{desc}: {percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]',
              dynamic_ncols=True, colour='cyan') as pbar:

        # 先檢查已經下載過的,更新進度條初始值
        existing_count = 0
        initial_list = list(downloadList)
        for url in initial_list:
            file_ts = url.split('/')[-1][0:-3] + '.mp4'
            if os.path.exists(os.path.join(folderPath, file_ts)):
                existing_count += 1
                downloadList.remove(url)
        
        pbar.update(existing_count)

        while downloadList:
            round_num += 1
            batch = list(downloadList)

            with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
                # scrape 使用 session 連線複用,加快下載
                executor.map(partial(scrape, ci_params, folderPath, pbar, lock, session), batch)

            # 更新剩餘清單:移除已成功下載的
            new_download_list = []
            for url in downloadList:
                file_ts = url.split('/')[-1][0:-3] + '.mp4'
                if not os.path.exists(os.path.join(folderPath, file_ts)):
                    new_download_list.append(url)
            
            downloadList = new_download_list

            if downloadList:
                tqdm.write(f'⚠ Round {round_num} 結束,還有 {len(downloadList)} 個片段失敗,準備重試...')
                time.sleep(1) # 短暫休息避免被封鎖


================================================
FILE: delete.py
================================================
import os

def deleteMp4(folderPath):
    files = os.listdir(folderPath)
    originFile = folderPath.split(os.path.sep)[-1] + '.mp4'
    for file in files:
        if file != originFile:
            os.remove(os.path.join(folderPath, file))


def deleteM3u8(folderPath):
    files = os.listdir(folderPath)
    for file in files:
        if file.endswith('.m3u8'):
            os.remove(os.path.join(folderPath, file))


================================================
FILE: docker-compose.yml
================================================
version: '3.8'

services:
  # ---- 主下載服務 ----
  downloader:
    build: .
    image: jable-downloader:latest
    container_name: jable_downloader
    environment:
      - URL=${URL:-}          # 透過環境變數傳入影片網址
    volumes:
      - ./downloads:/downloads  # 本機 downloads 資料夾 ←→ 容器內 /downloads
    stdin_open: true            # 保持 stdin 開啟(互動模式)
    tty: true

  # ---- (可選) Redis 任務佇列 ----
  # 未來擴充成多任務排隊下載時使用
  redis:
    image: redis:7-alpine
    container_name: jable_redis
    ports:
      - "6379:6379"
    volumes:
      - redis_data:/data
    restart: unless-stopped

volumes:
  redis_data:


================================================
FILE: download.py
================================================

import requests
import os
import re
import urllib.request
import m3u8
from config import headers
from crawler import prepareCrawl
from merge import mergeMp4
from encode import ffmpegEncode
from delete import deleteM3u8, deleteMp4
from cover import getCover
from args import *
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

def download(url):

  print('正在下載影片: ' + url)
  # 建立番號資料夾
  urlSplit = url.split('/')
  dirName = urlSplit[-2]
  if os.path.exists(f'{dirName}/{dirName}.mp4'):
    print('番號資料夾已存在, 跳過...')
    return
  if not os.path.exists(dirName):
      os.makedirs(dirName)
  folderPath = os.path.join(os.getcwd(), dirName)
  
  #配置Selenium參數
  options = Options()
  options.add_argument('--no-sandbox')
  options.add_argument('--disable-dev-shm-usage')
  options.add_argument('--disable-extensions')
  options.add_argument('--headless')
  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")
  dr = webdriver.Chrome(options=options)
  dr.get(url)
  result = re.search("https://.+m3u8", dr.page_source)
  print(f'result: {result}')
  m3u8url = result[0]
  print(f'm3u8url: {m3u8url}')

  # 得到 m3u8 網址
  m3u8urlList = m3u8url.split('/')
  m3u8urlList.pop(-1)
  downloadurl = '/'.join(m3u8urlList)

  # 儲存 m3u8 file 至資料夾
  m3u8file = os.path.join(folderPath, dirName + '.m3u8')
  urllib.request.urlretrieve(m3u8url, m3u8file)

  # 得到 m3u8 file裡的 URI和 IV
  m3u8obj = m3u8.load(m3u8file)
  m3u8uri = ''
  m3u8iv = ''

  for key in m3u8obj.keys:
      if key:
          m3u8uri = key.uri
          m3u8iv = key.iv

  # 儲存 ts網址 in tsList
  tsList = []
  for seg in m3u8obj.segments:
      tsUrl = downloadurl + '/' + seg.uri
      tsList.append(tsUrl)

  # 有加密
  if m3u8uri:
      m3u8keyurl = downloadurl + '/' + m3u8uri
      response = requests.get(m3u8keyurl, headers=headers, timeout=10)
      contentKey = response.content
      vt = m3u8iv.replace("0x", "")[:16].encode()  # IV 取前 16 位
      # ✅ 改存 dict,讓每個執行緒自行建立 AES cipher(避免 Race Condition)
      ci_params = {'key': contentKey, 'iv': vt}
  else:
      ci_params = None

  # 刪除m3u8 file
  deleteM3u8(folderPath)

  # 開始爬蟲並下載mp4片段至資料夾
  prepareCrawl(ci_params, folderPath, tsList)

  # 合成 mp4(Python 二進位串接)
  mergeMp4(folderPath, tsList)

  # 轉檔:-c copy + faststart,讓播放器可邊下載邊播
  ffmpegEncode(folderPath, dirName, 1)

  # 刪除子mp4
  deleteMp4(folderPath)

  # 取得封面
  getCover(html_file=dr.page_source, folder_path=folderPath)


================================================
FILE: encode.py
================================================
import os
import subprocess
from tqdm import tqdm


def get_segment_count(folder_path):
    """取得 concat_list.txt 中的片段總數以顯示進度"""
    try:
        with open(os.path.join(folder_path, 'concat_list.txt'), 'r', encoding='utf-8') as f:
            return sum(1 for line in f if line.startswith('file'))
    except Exception:
        return None


def ffmpegEncode(folder_path, file_name, action=1):
    """
    結合合成與快速無損轉檔
    - 使用 concat demuxer 避免兩次讀寫
    - 不重新壓縮畫面,畫質完全不變
    - 修正音訊封包格式(ADTS → ASC)
    - 加上 faststart
    """
    if action == 0:
        return

    os.chdir(folder_path)
    concat_list = 'concat_list.txt'
    dst = f'{file_name}.mp4'

    if not os.path.exists(concat_list):
        print(f'❌ 找不到合成清單 {concat_list}')
        return

    # 取得片段總數(用於進度條)
    total_segments = get_segment_count(folder_path)

    # 這裡我們觀察 FFmpeg 的進度輸出
    # 因為是 concat copy,通常很快,我們追蹤 frame 或者是 time
    # 但因為總幀數難算,我們顯示處理進度
    cmd = ['ffmpeg', '-y',
           '-f', 'concat',
           '-safe', '0',
           '-i', concat_list,
           '-c', 'copy',
           '-bsf:a', 'aac_adtstoasc',
           '-movflags', '+faststart',
           '-progress', 'pipe:1',
           '-nostats',
           '-loglevel', 'info',   # 改為 info 以便抓取 "Opening" 訊息
           dst]

    process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT, text=True,
                                bufsize=1, encoding='utf-8')

    desc = '🚀 快速合成與轉檔'
    with tqdm(total=total_segments, unit='片段', desc=desc,
              bar_format='{desc}: {percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}]',
              dynamic_ncols=True, colour='yellow') as pbar:

        processed_segments = 0
        last_frame_count = 0
        for line in process.stdout:
            # 這裡列出幾種可能的格式以增加相容性
            # 1. [concat @ 0x...] Opening 'xxxxx.mp4' for reading
            # 2. Opening 'xxxxx.mp4' for reading
            if 'Opening' in line and 'for reading' in line:
                processed_segments += 1
                if processed_segments <= total_segments:
                    pbar.update(1)
            
            # 作為備案:如果一直沒有 Opening 訊息(某些環境會過濾),
            # 我們可以透過 frame 的變動來讓進度條「動起來」表示沒死掉,
            # 雖然這裡 total 是片段數,所以我們只在描述增加訊息。
            if 'frame=' in line:
                try:
                    parts = line.split('=')
                    if len(parts) > 1:
                        frame_val = parts[1].split()[0]
                        if frame_val.isdigit():
                            pbar.set_postfix_str(f"已處理 {frame_val} 幀")
                except:
                    pass

            if line.startswith('progress=end'):
                if processed_segments < total_segments:
                    pbar.update(total_segments - processed_segments)

    process.wait()

    if process.returncode == 0:
        if os.path.exists(concat_list):
            os.remove(concat_list)
        print('✅ 合成與轉檔成功!')
    else:
        print('❌ 合成與轉檔失敗!')


================================================
FILE: getchromedriver.py
================================================
import requests
from bs4 import BeautifulSoup
import zipfile
import shutil
import os

def get_chromedriver_version():
    url = 'https://googlechromelabs.github.io/chrome-for-testing/'
    response = requests.get(url)

    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'html.parser')
        formatted_html = soup.prettify()
        
        # print(formatted_html)

        tr_tags = soup.find_all('tr', class_='status-ok')
        for tr in tr_tags:
            if tr.find('a', string="Stable"):
                version_code = tr.find('code').text.strip()
                print(version_code)
                break
        return version_code
    else:
        print("Fail, Code:", response.status_code)

def download_chromedriver(download_link):
    url = download_link
    response = requests.get(url)

    if response.status_code == 200:
        with open('chromedriver.zip', 'wb') as file:
            file.write(response.content)
        print("success!")
    else:
        print("Fail, Code:", response.status_code)

def unzip_chromedriver():
    with zipfile.ZipFile('chromedriver.zip', 'r') as zip_ref:
        zip_ref.extractall('./')

chromedriver_version = get_chromedriver_version()
download_link = f"https://storage.googleapis.com/chrome-for-testing-public/{chromedriver_version}/win64/chromedriver-win64.zip"
download_chromedriver(download_link)
unzip_chromedriver()

# move chromedriver to the root directory
file_source = "chromedriver-win64/chromedriver.exe"
file_destination = "./"
shutil.move(file_source, file_destination)

# clean up
shutil.rmtree('chromedriver-win64')
os.remove("chromedriver.zip")

================================================
FILE: k8s/configmap.yaml
================================================
# ============================================================
# ConfigMap
# 用途:集中管理設定值(不寫死在程式或 Job 裡)
# ============================================================
apiVersion: v1
kind: ConfigMap
metadata:
  name: jable-config
  namespace: default
data:
  # 預設下載網址(可在 Job 中被 env 覆蓋)
  DEFAULT_URL: "https://jable.tv/videos/ipx-486/"
  # Chrome 相關設定
  CHROME_BIN: "/usr/bin/chromium"
  CHROMEDRIVER_PATH: "/usr/bin/chromedriver"


================================================
FILE: k8s/job.yaml
================================================
# ============================================================
# Kubernetes Job
# 用途:每次下載任務就建立一個 Job,跑完自動結束
# 這是最適合「批次下載」場景的 K8s 資源類型
# ============================================================
apiVersion: batch/v1
kind: Job
metadata:
  name: jable-download-job
  namespace: default
  labels:
    app: jable-downloader
spec:
  # ttlSecondsAfterFinished: Job 完成後 300 秒自動清除
  ttlSecondsAfterFinished: 300
  template:
    metadata:
      labels:
        app: jable-downloader
    spec:
      restartPolicy: OnFailure   # 失敗時重試,成功後不重啟
      containers:
        - name: downloader
          image: jable-downloader:latest
          imagePullPolicy: IfNotPresent  # 本地測試用,不強制從 Registry 拉取
          env:
            # 傳入目標影片網址
            - name: URL
              value: "https://jable.tv/videos/ipx-486/"  # ← 修改這裡
            # 從 ConfigMap 取得設定
            - name: CHROME_BIN
              valueFrom:
                configMapKeyRef:
                  name: jable-config
                  key: CHROME_BIN
            - name: CHROMEDRIVER_PATH
              valueFrom:
                configMapKeyRef:
                  name: jable-config
                  key: CHROMEDRIVER_PATH
          volumeMounts:
            - name: downloads-storage
              mountPath: /downloads  # 容器內的下載路徑
          resources:
            requests:
              memory: "512Mi"
              cpu: "250m"
            limits:
              memory: "2Gi"
              cpu: "1000m"
      volumes:
        - name: downloads-storage
          persistentVolumeClaim:
            claimName: jable-downloads-pvc  # 掛載 PVC


================================================
FILE: k8s/pvc.yaml
================================================
# ============================================================
# PersistentVolumeClaim (PVC)
# 用途:給下載的影片提供持久化儲存空間
# ============================================================
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: jable-downloads-pvc
  namespace: default
spec:
  accessModes:
    - ReadWriteOnce       # 單一 Node 讀寫
  resources:
    requests:
      storage: 50Gi       # 申請 50GB 儲存空間
  storageClassName: standard


================================================
FILE: main.py
================================================
# author: hcjohn463
#!/usr/bin/env python
# coding: utf-8
from args import *
from download import download
from movies import movieLinks
# In[2]:

parser = get_parser()
args = parser.parse_args()

if(len(args.url) != 0):
    url = args.url
    download(url)
elif(args.random == True):
    url = av_recommand()
    download(url)
elif(args.all_urls != ""):
    all_urls = args.all_urls
    urls = movieLinks(all_urls)
    for url in urls:
        download(url)
else:
    # 使用者輸入Jable網址
    url = input('輸入jable網址:')
    download(url)


================================================
FILE: merge.py
================================================
import os
import time
from tqdm import tqdm


def mergeMp4(folderPath, tsList):
    """產生 FFmpeg concat 用的清單檔案,不再進行二進位串接以節省時間與 IO"""
    start_time = time.time()
    # video_name = folderPath.split(os.path.sep)[-1]
    concat_list_path = os.path.join(folderPath, 'concat_list.txt')

    print('正在準備合成清單..')
    total = len(tsList)
    with open(concat_list_path, 'w', encoding='utf-8') as f:
        for i in range(total):
            file = tsList[i].split('/')[-1][0:-3] + '.mp4'
            full_path = os.path.join(folderPath, file)
            if os.path.exists(full_path):
                # FFmpeg concat file 格式: file 'path/to/file'
                # 使用相對路徑或絕對路徑皆可,這裡用檔名即可,因為會在 folderPath 執行 ffmpeg
                f.write(f"file '{file}'\n")
            else:
                print(f'警告: 缺少片段 {file}')

    elapsed = time.time() - start_time
    print('花費 {0:.2f} 秒 準備合成清單'.format(elapsed))



================================================
FILE: movies.py
================================================
# In[0]:
import requests
from config import headers
from bs4 import BeautifulSoup
from selenium import webdriver


def movieLinks(url):
  links = []
  dr = webdriver.Chrome()
  dr.get(url)
  bs = BeautifulSoup(dr.page_source,"html.parser")
  a_tags = bs.select('div.img-box>a')
  print(a_tags)
  for a_tag in a_tags:
    links.append(a_tag['href'])
  print('获取到 {0} 個影片'.format(len(links)))
  print(links)
  return links

# %%


================================================
FILE: requirements.txt
================================================
requests==2.31.0
beautifulsoup4==4.12.3
m3u8==0.8.0
pycryptodome==3.17
selenium
soupsieve==2.5
urllib3==2.2.1
certifi==2024.2.2
charset-normalizer==3.3.2
idna==3.6
tqdm
Download .txt
gitextract_m85xy9ir/

├── .dockerignore
├── .gitignore
├── Dockerfile
├── INIT.bat
├── LICENSE
├── README.md
├── RUN.bat
├── args.py
├── config.py
├── cover.py
├── crawler.py
├── delete.py
├── docker-compose.yml
├── download.py
├── encode.py
├── getchromedriver.py
├── k8s/
│   ├── configmap.yaml
│   ├── job.yaml
│   └── pvc.yaml
├── main.py
├── merge.py
├── movies.py
└── requirements.txt
Download .txt
SYMBOL INDEX (18 symbols across 9 files)

FILE: args.py
  function get_parser (line 9) | def get_parser():
  function av_recommand (line 21) | def av_recommand():

FILE: cover.py
  function getCover (line 6) | def getCover(html_file, folder_path):

FILE: crawler.py
  function scrape (line 13) | def scrape(ci_params, folderPath, pbar, lock, session, urls):
  function measureSpeed (line 42) | def measureSpeed(tsList, sample_count=3):
  function prepareCrawl (line 69) | def prepareCrawl(ci_params, folderPath, tsList):
  function startCrawl (line 93) | def startCrawl(ci_params, folderPath, downloadList, total, workers):
  function _run_crawl (line 101) | def _run_crawl(ci_params, folderPath, downloadList, total, workers, lock...

FILE: delete.py
  function deleteMp4 (line 3) | def deleteMp4(folderPath):
  function deleteM3u8 (line 11) | def deleteM3u8(folderPath):

FILE: download.py
  function download (line 17) | def download(url):

FILE: encode.py
  function get_segment_count (line 6) | def get_segment_count(folder_path):
  function ffmpegEncode (line 15) | def ffmpegEncode(folder_path, file_name, action=1):

FILE: getchromedriver.py
  function get_chromedriver_version (line 7) | def get_chromedriver_version():
  function download_chromedriver (line 27) | def download_chromedriver(download_link):
  function unzip_chromedriver (line 38) | def unzip_chromedriver():

FILE: merge.py
  function mergeMp4 (line 6) | def mergeMp4(folderPath, tsList):

FILE: movies.py
  function movieLinks (line 8) | def movieLinks(url):
Condensed preview — 23 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (41K chars).
[
  {
    "path": ".dockerignore",
    "chars": 267,
    "preview": "# 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/\nven"
  },
  {
    "path": ".gitignore",
    "chars": 197,
    "preview": "# 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_St"
  },
  {
    "path": "Dockerfile",
    "chars": 876,
    "preview": "# ---- Base Image ----\n# 使用輕量的 Python 3.11 映像檔\nFROM python:3.11-slim\n\n# ---- 系統套件安裝 ----\n# 安裝 Chromium (headless browser"
  },
  {
    "path": "INIT.bat",
    "chars": 592,
    "preview": "chcp 65001\n\n@echo off\nSET VENV_PATH=.\\jable\n\nREM 檢查虛擬環境是否存在\nIF EXIST \"%VENV_PATH%\\Scripts\\activate.bat\" (\n    ECHO 虛擬環境已"
  },
  {
    "path": "LICENSE",
    "chars": 11357,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "README.md",
    "chars": 2335,
    "preview": "# JableTVDownload\n\n## 下載JableTV好幫手\n\n每次看正要爽的時候就給我卡住轉圈圈  \n\n直接下載到電腦看沒煩惱\n\n---\n\n## 🐳 Docker 一鍵啟動(推薦)\n\n不需要手動安裝 ChromeDriver、FF"
  },
  {
    "path": "RUN.bat",
    "chars": 61,
    "preview": "@echo off\ncall \"jable\\Scripts\\activate\"\npython main.py\npause\n"
  },
  {
    "path": "args.py",
    "chars": 1037,
    "preview": "import argparse\nfrom bs4 import BeautifulSoup\nimport random\nfrom urllib.request import Request, urlopen\nfrom config impo"
  },
  {
    "path": "config.py",
    "chars": 150,
    "preview": "headers = {\n    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/7"
  },
  {
    "path": "cover.py",
    "chars": 855,
    "preview": "import requests\nimport os\nfrom bs4 import BeautifulSoup\n\n\ndef getCover(html_file, folder_path):\n  # get cover\n  soup = B"
  },
  {
    "path": "crawler.py",
    "chars": 4636,
    "preview": "import os\nimport requests\nfrom config import headers\nfrom functools import partial\nimport concurrent.futures\nimport time"
  },
  {
    "path": "delete.py",
    "chars": 418,
    "preview": "import os\n\ndef deleteMp4(folderPath):\n    files = os.listdir(folderPath)\n    originFile = folderPath.split(os.path.sep)["
  },
  {
    "path": "docker-compose.yml",
    "chars": 594,
    "preview": "version: '3.8'\n\nservices:\n  # ---- 主下載服務 ----\n  downloader:\n    build: .\n    image: jable-downloader:latest\n    containe"
  },
  {
    "path": "download.py",
    "chars": 2524,
    "preview": "\nimport requests\nimport os\nimport re\nimport urllib.request\nimport m3u8\nfrom config import headers\nfrom crawler import pr"
  },
  {
    "path": "encode.py",
    "chars": 3020,
    "preview": "import os\nimport subprocess\nfrom tqdm import tqdm\n\n\ndef get_segment_count(folder_path):\n    \"\"\"取得 concat_list.txt 中的片段總數"
  },
  {
    "path": "getchromedriver.py",
    "chars": 1651,
    "preview": "import requests\nfrom bs4 import BeautifulSoup\nimport zipfile\nimport shutil\nimport os\n\ndef get_chromedriver_version():\n  "
  },
  {
    "path": "k8s/configmap.yaml",
    "chars": 429,
    "preview": "# ============================================================\n# ConfigMap\n# 用途:集中管理設定值(不寫死在程式或 Job 裡)\n# ==============="
  },
  {
    "path": "k8s/job.yaml",
    "chars": 1598,
    "preview": "# ============================================================\n# Kubernetes Job\n# 用途:每次下載任務就建立一個 Job,跑完自動結束\n# 這是最適合「批次下載"
  },
  {
    "path": "k8s/pvc.yaml",
    "chars": 436,
    "preview": "# ============================================================\n# PersistentVolumeClaim (PVC)\n# 用途:給下載的影片提供持久化儲存空間\n# ===="
  },
  {
    "path": "main.py",
    "chars": 532,
    "preview": "# author: hcjohn463\n#!/usr/bin/env python\n# coding: utf-8\nfrom args import *\nfrom download import download\nfrom movies i"
  },
  {
    "path": "merge.py",
    "chars": 900,
    "preview": "import os\nimport time\nfrom tqdm import tqdm\n\n\ndef mergeMp4(folderPath, tsList):\n    \"\"\"產生 FFmpeg concat 用的清單檔案,不再進行二進位串接"
  },
  {
    "path": "movies.py",
    "chars": 427,
    "preview": "# In[0]:\nimport requests\nfrom config import headers\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\n\n\ndef m"
  },
  {
    "path": "requirements.txt",
    "chars": 180,
    "preview": "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\ncer"
  }
]

About this extraction

This page contains the full source code of the hcjohn463/JableTVDownload GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 23 files (34.2 KB), approximately 10.3k tokens, and a symbol index with 18 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!