蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行本地回环单线程下载、3 线程 HTTP 206 Range 并发合并与 DownloadManager 策略实测

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-download1.py
explore-tutorial-download1.py228 行
"""Offline Android single/multi-thread Range download & DownloadManager verifier (Ch 92: tutorial-download1)."""
from __future__ import annotations

import hashlib
import http.client
import json
import math
import re
import sys
import tempfile
import threading
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

VERSION = "CPython 3.12.14 offline Android storage/HTTP/WebView verifier (Android SDK/emulator absent)"

PAYLOAD = bytes((i * 37 + 11) % 256 for i in range(10_000))  # 10,000 bytes (not divisible by 3!)
PAYLOAD_SHA = hashlib.sha256(PAYLOAD).hexdigest()


class RangeFileHandler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def log_message(self, format: str, *args) -> None:
        return

    def do_HEAD(self) -> None:
        if self.path == "/release.bin":
            self.send_response(200)
            self.send_header("Accept-Ranges", "bytes")
            self.send_header("Content-Length", str(len(PAYLOAD)))
            self.end_headers()
        else:
            self.send_response(404)
            self.end_headers()

    def do_GET(self) -> None:
        if self.path != "/release.bin":
            self.send_response(404)
            self.send_header("Content-Length", "0")
            self.end_headers()
            return
        rng = self.headers.get("Range")
        if rng:
            m = re.match(r"bytes=(\d+)-(\d*)", rng)
            if m:
                start = int(m.group(1))
                end = int(m.group(2)) if m.group(2) else len(PAYLOAD) - 1
                end = min(end, len(PAYLOAD) - 1)
                part = PAYLOAD[start : end + 1]
                self.send_response(206)
                self.send_header("Accept-Ranges", "bytes")
                self.send_header("Content-Range", f"bytes {start}-{end}/{len(PAYLOAD)}")
                self.send_header("Content-Length", str(len(part)))
                self.end_headers()
                self.wfile.write(part)
                return
        self.send_response(200)
        self.send_header("Accept-Ranges", "bytes")
        self.send_header("Content-Length", str(len(PAYLOAD)))
        self.end_headers()
        self.wfile.write(PAYLOAD)


def main() -> None:
    cases = []
    server = ThreadingHTTPServer(("127.0.0.1", 0), RangeFileHandler)
    port = server.server_address[1]
    url = f"http://127.0.0.1:{port}/release.bin"
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    try:
        with tempfile.TemporaryDirectory() as tmp:
            tdir = Path(tmp)

            # Case 1: Single-thread stream download to private storage
            single_dest = tdir / "Cache_single.bin"
            with urllib.request.urlopen(url, timeout=5) as resp, single_dest.open("wb") as out:
                while True:
                    chunk = resp.read(1024)
                    if not chunk:
                        break
                    out.write(chunk)
            actual1 = {
                "size": single_dest.stat().st_size,
                "sha_matches": hashlib.sha256(single_dest.read_bytes()).hexdigest() == PAYLOAD_SHA,
            }
            expected1 = {"size": 10_000, "sha_matches": True}
            cases.append({
                "name": "single_thread_stream_download",
                "summary": "Verify single-thread URLConnection.openStream-style download and SHA-256 integrity.",
                "expected": expected1,
                "actual": actual1,
                "passed": actual1 == expected1,
            })

            # Case 2: 3-thread concurrent HTTP 206 Range download + RandomAccessFile seek write
            conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
            conn.request("HEAD", "/release.bin")
            head_resp = conn.getresponse()
            head_resp.read()
            total_len = int(head_resp.getheader("Content-Length"))
            conn.close()

            multi_dest = tdir / "multi_range.bin"
            with multi_dest.open("wb") as fh:
                fh.truncate(total_len)

            thread_count = 3
            block_len = math.ceil(total_len / thread_count)
            statuses: list[int] = [0] * thread_count
            written_counts: list[int] = [0] * thread_count

            def worker(idx: int) -> None:
                start = idx * block_len
                end = min(total_len - 1, (idx + 1) * block_len - 1)
                c = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
                c.request("GET", "/release.bin", headers={"Range": f"bytes={start}-{end}"})
                r = c.getresponse()
                statuses[idx] = r.status
                data = r.read()
                c.close()
                with multi_dest.open("r+b") as fh:
                    fh.seek(start)
                    fh.write(data)
                written_counts[idx] = len(data)

            workers = [threading.Thread(target=worker, args=(i,)) for i in range(thread_count)]
            for w in workers:
                w.start()
            for w in workers:
                w.join()

            actual2 = {
                "statuses": statuses,
                "chunk_sizes": written_counts,
                "total_size": multi_dest.stat().st_size,
                "sha_matches": hashlib.sha256(multi_dest.read_bytes()).hexdigest() == PAYLOAD_SHA,
            }
            expected2 = {
                "statuses": [206, 206, 206],
                "chunk_sizes": [3334, 3334, 3332],
                "total_size": 10_000,
                "sha_matches": True,
            }
            cases.append({
                "name": "multi_thread_http206_range_download",
                "summary": "Verify 3-thread HTTP 206 Partial Content concurrent Range downloads assembled via seek().",
                "expected": expected2,
                "actual": actual2,
                "passed": actual2 == expected2,
            })

            # Case 3: Verify chunk-size math bug in legacy source (filelength % 3 == 0 ? filelength/3 : filelength + 1)
            legacy_bug_val = (total_len // 3) if total_len % 3 == 0 else (total_len + 1)
            correct_val = (total_len // 3) if total_len % 3 == 0 else (total_len // 3 + 1)
            actual3 = {
                "legacy_typo_exceeds_file": legacy_bug_val > total_len,
                "correct_block_len": correct_val,
                "covers_all_bytes": correct_val * 3 >= total_len and (correct_val - 1) * 3 < total_len,
            }
            expected3 = {
                "legacy_typo_exceeds_file": True,
                "correct_block_len": 3334,
                "covers_all_bytes": True,
            }
            cases.append({
                "name": "thread_block_size_formula_check",
                "summary": "Verify corrected block division (filelength/N + 1) vs legacy typo (filelength + 1).",
                "expected": expected3,
                "actual": actual3,
                "passed": actual3 == expected3,
            })

            # Case 4: DownloadManager completion receiver & Android 7.0+ FileProvider APK install URI check
            def resolve_apk_install_intent(api_level: int, status: str, apk_name: str) -> dict:
                if status != "STATUS_SUCCESSFUL":
                    return {"launch": False}
                scheme = "content://" if api_level >= 24 else "file://"
                return {
                    "launch": True,
                    "uri_scheme": scheme,
                    "mime": "application/vnd.android.package-archive",
                    "needs_grant_read_flag": api_level >= 24,
                    "needs_install_packages_perm": api_level >= 26,
                    "filename_match": apk_name.endswith(".apk"),
                }

            actual4 = {
                "api21": resolve_apk_install_intent(21, "STATUS_SUCCESSFUL", "app_v2.apk"),
                "api26": resolve_apk_install_intent(26, "STATUS_SUCCESSFUL", "app_v2.apk"),
            }
            expected4 = {
                "api21": {
                    "launch": True,
                    "uri_scheme": "file://",
                    "mime": "application/vnd.android.package-archive",
                    "needs_grant_read_flag": False,
                    "needs_install_packages_perm": False,
                    "filename_match": True,
                },
                "api26": {
                    "launch": True,
                    "uri_scheme": "content://",
                    "mime": "application/vnd.android.package-archive",
                    "needs_grant_read_flag": True,
                    "needs_install_packages_perm": True,
                    "filename_match": True,
                },
            }
            cases.append({
                "name": "downloadmanager_apk_install_policy",
                "summary": "Verify DownloadManager completion APK MIME type and Android 7/8 FileProvider & install permission transition.",
                "expected": expected4,
                "actual": actual4,
                "passed": actual4 == expected4,
            })
    finally:
        server.shutdown()
        server.server_close()

    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    sys.exit(main())
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/android-tutorial-download1-lab/explore-tutorial-download1.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-download1.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1869.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习