|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +""" |
| 5 | +Utility helpers for resolving the latest X-FE-Version value from chat.z.ai. |
| 6 | +
|
| 7 | +The upstream service embeds the current front-end release identifier inside |
| 8 | +its landing page static asset URLs (e.g. `prod-fe-1.0.107`). The helpers in |
| 9 | +this module fetch the landing page, extract the version string, and cache it |
| 10 | +with a configurable TTL so the expensive network fetch only happens when |
| 11 | +necessary. |
| 12 | +""" |
| 13 | + |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import re |
| 17 | +import time |
| 18 | +from typing import Optional |
| 19 | + |
| 20 | +import httpx |
| 21 | + |
| 22 | +from app.utils.logger import get_logger |
| 23 | +from app.utils.user_agent import get_random_user_agent |
| 24 | + |
| 25 | +# Base URL to probe for the version string. |
| 26 | +FE_VERSION_SOURCE_URL = "https://chat.z.ai" |
| 27 | + |
| 28 | +# Cache TTL in seconds (default: 30 minutes). |
| 29 | +CACHE_TTL_SECONDS = 1800 |
| 30 | + |
| 31 | +_logger = get_logger() |
| 32 | +_version_pattern = re.compile(r"prod-fe-\d+\.\d+\.\d+") |
| 33 | + |
| 34 | +_cached_version: str = "" |
| 35 | +_cached_at: float = 0.0 |
| 36 | + |
| 37 | + |
| 38 | +def _extract_version(page_content: str) -> Optional[str]: |
| 39 | + """Extract the version string from the page content.""" |
| 40 | + if not page_content: |
| 41 | + return None |
| 42 | + |
| 43 | + matches = _version_pattern.findall(page_content) |
| 44 | + if not matches: |
| 45 | + return None |
| 46 | + |
| 47 | + # Choose the highest lexical value to guard against mixed versions. |
| 48 | + return max(matches) |
| 49 | + |
| 50 | + |
| 51 | + |
| 52 | + |
| 53 | +def _should_use_cache(force_refresh: bool) -> bool: |
| 54 | + """Determine whether the cached value can be reused.""" |
| 55 | + if force_refresh: |
| 56 | + return False |
| 57 | + if not _cached_version: |
| 58 | + return False |
| 59 | + if _cached_at <= 0: |
| 60 | + return False |
| 61 | + return (time.time() - _cached_at) < CACHE_TTL_SECONDS |
| 62 | + |
| 63 | + |
| 64 | +def get_latest_fe_version(force_refresh: bool = False) -> str: |
| 65 | + """ |
| 66 | + Resolve the latest X-FE-Version value from chat.z.ai. |
| 67 | +
|
| 68 | + The lookup order is: |
| 69 | + 1. Cached value within TTL. |
| 70 | + 2. Remote fetch from chat.z.ai. |
| 71 | + |
| 72 | + Raises: |
| 73 | + Exception: If unable to fetch the version from the remote source. |
| 74 | + """ |
| 75 | + global _cached_version, _cached_at |
| 76 | + |
| 77 | + if _should_use_cache(force_refresh): |
| 78 | + return _cached_version |
| 79 | + |
| 80 | + try: |
| 81 | + headers = {"User-Agent": get_random_user_agent("chrome")} |
| 82 | + except Exception: |
| 83 | + headers = { |
| 84 | + "User-Agent": ( |
| 85 | + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " |
| 86 | + "AppleWebKit/537.36 (KHTML, like Gecko) " |
| 87 | + "Chrome/120.0.0.0 Safari/537.36" |
| 88 | + ) |
| 89 | + } |
| 90 | + |
| 91 | + try: |
| 92 | + with httpx.Client(timeout=10.0, follow_redirects=True) as client: |
| 93 | + response = client.get(FE_VERSION_SOURCE_URL, headers=headers) |
| 94 | + response.raise_for_status() |
| 95 | + version = _extract_version(response.text) |
| 96 | + if version: |
| 97 | + if version != _cached_version: |
| 98 | + _logger.info(f"[Z.AI] Detected X-FE-Version update: {version}") |
| 99 | + _cached_version = version |
| 100 | + _cached_at = time.time() |
| 101 | + return version |
| 102 | + |
| 103 | + _logger.error("[Z.AI] Unable to locate X-FE-Version in landing page") |
| 104 | + raise Exception("Unable to locate X-FE-Version in landing page") |
| 105 | + except Exception as exc: |
| 106 | + _logger.error(f"[Z.AI] Failed to fetch X-FE-Version from {FE_VERSION_SOURCE_URL}: {exc}") |
| 107 | + raise Exception(f"Failed to fetch X-FE-Version: {exc}") |
| 108 | + |
| 109 | + |
| 110 | +def refresh_fe_version() -> str: |
| 111 | + """Force refresh the cached version by bypassing the TTL.""" |
| 112 | + return get_latest_fe_version(force_refresh=True) |
0 commit comments