app/i18n.py (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 |
from __future__ import annotations
from urllib.parse import urlparse
from starlette.requests import Request
from starlette.responses import RedirectResponse
LOCALES = ("pt", "en")
DEFAULT = "pt"
COOKIE = "lang"
COOKIE_MAX_AGE = 60 * 60 * 24 * 365
_PT = {
"tagline": "Observatório público de trackers BitTorrent",
"nav_trackers": "Trackers",
"nav_trackers_sub": "lista",
"nav_lists": "Criar lista",
"nav_lists_sub": "smart",
"nav_github": "GitHub",
"nav_github_sub": "código",
"footer_utc": "medições em UTC",
"footer_disclaimer": "Não é um tracker BitTorrent · não indexa torrents",
"stats_label": "Resumo",
"stats_monitored": "monitorados",
"stats_up": "ativos",
"stats_degraded": "degradados",
"stats_down": "indisponíveis",
"stats_unknown": "desconhecidos",
"stats_last_import": "última importação",
"stats_last_probe": "última medição",
"filter_search": "Busca",
"filter_search_ph": "hostname ou URL",
"filter_protocol": "Protocolo",
"filter_any": "qualquer",
"filter_status": "Status",
"filter_source": "Origem",
"filter_sort": "Ordenar",
"sort_checked": "última verificação",
"sort_latency": "latência",
"sort_url": "URL",
"sort_status": "status",
"sort_protocol": "protocolo",
"filter_order": "Ordem",
"order_desc": "desc",
"order_asc": "asc",
"filter_submit": "Filtrar",
"col_tracker": "Tracker",
"col_protocol": "Protocolo",
"col_status": "Status",
"col_uptime7": "Uptime 7d",
"col_latency": "Latência med.",
"col_ip": "IPv4 / IPv6",
"col_asn": "ASN / rede",
"col_sources": "Fontes",
"col_aliases": "Aliases",
"col_last_check": "Última verificação",
"copy": "copiar",
"copy_btn": "Copiar",
"copied": "copiado",
"th_latency": "Latência",
"provisional": "provisório",
"empty_inventory": "Nenhum tracker no inventário ainda.",
"pagination": "Paginação",
"prev": "Anterior",
"next": "Próxima",
"page_of": "Página {page} / {pages} ({total})",
"lists_title": "Criar lista",
"lists_heading": "Smart List",
"lists_blurb": (
"Seleção de trackers estáveis e com diversidade de infraestrutura. "
"Classificações das fontes externas não substituem as medições próprias."
),
"min_uptime": "Uptime mínimo (0–1)",
"max_latency": "Latência máxima (ms)",
"filter_ip": "IP",
"filter_limit": "Quantidade (1–50)",
"min_age": "Idade mínima (dias)",
"diversity": "Diversidade de infraestrutura",
"diversity_on": "ligada",
"diversity_off": "desligada",
"generate": "Gerar",
"selected_count": "trackers selecionados.",
"download_txt": "Baixar TXT",
"open_json": "Abrir JSON",
"permalink": "URL permanente",
"back": "voltar",
"score": "pontuação",
"score_insufficient": "insuficiente",
"uptime_24h": "Uptime 24h",
"uptime_7d": "Uptime 7d",
"uptime_30d": "Uptime 30d",
"latency_med_7d": "Latência med. 7d",
"latency_p95": "Latência p95 7d",
"valid_rate": "Respostas válidas 7d",
"measurements": "Medições",
"tracking": "Acompanhamento",
"days": "dias",
"spark_label": "Latências recentes",
"sources": "Origens",
"best_at_source": "best na origem",
"stable_at_source": "stable na origem",
"live_at_source": "live na origem",
"seen": "visto",
"no_source": "Sem associação de origem",
"dns": "DNS",
"terminal_cname": "CNAME terminal",
"infra_fp": "Fingerprint de infraestrutura",
"asn": "ASN",
"unknown": "desconhecido",
"country": "País",
"no_dns": "Sem registros DNS armazenados",
"shared_infra": "Infraestrutura compartilhada",
"shared_infra_blurb": (
"Outros endpoints com o mesmo fingerprint (sinal, não prova de operador):"
),
"recent_history": "Histórico recente",
"when": "Quando (UTC)",
"valid": "Válida",
"error": "Erro",
"yes": "sim",
"no": "não",
"no_probes": "Sem medições ainda",
"not_found": "Tracker não encontrado",
"bootstrap_empty": (
"Inventário vazio: não foi possível importar fontes na inicialização ({exc}). "
"O site está no ar; tente novamente com `python -m app.cli import-sources`."
),
"bootstrap_stale": (
"Listas desatualizadas: não foi possível importar fontes na inicialização ({exc}). "
"O site está no ar; tente novamente com `python -m app.cli import-sources`."
),
}
_EN = {
"tagline": "Public observatory of BitTorrent trackers",
"nav_trackers": "Trackers",
"nav_trackers_sub": "list",
"nav_lists": "Build a list",
"nav_lists_sub": "smart",
"nav_github": "GitHub",
"nav_github_sub": "code",
"footer_utc": "measurements in UTC",
"footer_disclaimer": "Not a BitTorrent tracker · does not index torrents",
"stats_label": "Overview",
"stats_monitored": "watched",
"stats_up": "up",
"stats_degraded": "degraded",
"stats_down": "down",
"stats_unknown": "unknown",
"stats_last_import": "last import",
"stats_last_probe": "last probe",
"filter_search": "Search",
"filter_search_ph": "hostname or URL",
"filter_protocol": "Protocol",
"filter_any": "any",
"filter_status": "Status",
"filter_source": "Source",
"filter_sort": "Sort",
"sort_checked": "last check",
"sort_latency": "latency",
"sort_url": "URL",
"sort_status": "status",
"sort_protocol": "protocol",
"filter_order": "Order",
"order_desc": "desc",
"order_asc": "asc",
"filter_submit": "Filter",
"col_tracker": "Tracker",
"col_protocol": "Protocol",
"col_status": "Status",
"col_uptime7": "Uptime 7d",
"col_latency": "Median latency",
"col_ip": "IPv4 / IPv6",
"col_asn": "ASN / net",
"col_sources": "Sources",
"col_aliases": "Aliases",
"col_last_check": "Last check",
"copy": "copy",
"copy_btn": "Copy",
"copied": "copied",
"th_latency": "Latency",
"provisional": "provisional",
"empty_inventory": "No trackers in the inventory yet.",
"pagination": "Pagination",
"prev": "Previous",
"next": "Next",
"page_of": "Page {page} / {pages} ({total})",
"lists_title": "Build a list",
"lists_heading": "Smart List",
"lists_blurb": (
"Stable trackers with some infrastructure spread. "
"Labels from the upstream lists do not replace our own probes."
),
"min_uptime": "Min uptime (0–1)",
"max_latency": "Max latency (ms)",
"filter_ip": "IP",
"filter_limit": "Count (1–50)",
"min_age": "Min age (days)",
"diversity": "Infrastructure diversity",
"diversity_on": "on",
"diversity_off": "off",
"generate": "Build",
"selected_count": "trackers selected.",
"download_txt": "Download TXT",
"open_json": "Open JSON",
"permalink": "Permalink",
"back": "back",
"score": "score",
"score_insufficient": "not enough data",
"uptime_24h": "Uptime 24h",
"uptime_7d": "Uptime 7d",
"uptime_30d": "Uptime 30d",
"latency_med_7d": "Median latency 7d",
"latency_p95": "p95 latency 7d",
"valid_rate": "Valid replies 7d",
"measurements": "Probes",
"tracking": "Watched for",
"days": "days",
"spark_label": "Recent latencies",
"sources": "Sources",
"best_at_source": "best at source",
"stable_at_source": "stable at source",
"live_at_source": "live at source",
"seen": "seen",
"no_source": "No source association",
"dns": "DNS",
"terminal_cname": "Terminal CNAME",
"infra_fp": "Infrastructure fingerprint",
"asn": "ASN",
"unknown": "unknown",
"country": "Country",
"no_dns": "No stored DNS records",
"shared_infra": "Shared infrastructure",
"shared_infra_blurb": (
"Other endpoints with the same fingerprint (a hint, not proof of the same operator):"
),
"recent_history": "Recent history",
"when": "When (UTC)",
"valid": "Valid",
"error": "Error",
"yes": "yes",
"no": "no",
"no_probes": "No probes yet",
"not_found": "Tracker not found",
"bootstrap_empty": (
"Empty inventory: could not import sources on startup ({exc}). "
"The site is up; retry with `python -m app.cli import-sources`."
),
"bootstrap_stale": (
"Stale lists: could not import sources on startup ({exc}). "
"The site is up; retry with `python -m app.cli import-sources`."
),
}
STRINGS = {"pt": _PT, "en": _EN}
_BOOTSTRAP_KEYS = {
"empty_import": "bootstrap_empty",
"stale_import": "bootstrap_stale",
}
def normalize_lang(code: str | None) -> str:
if not code:
return DEFAULT
tag = code.strip().lower().replace("_", "-")
if tag in LOCALES:
return tag
if tag.startswith("en"):
return "en"
if tag.startswith("pt"):
return "pt"
return DEFAULT
def from_accept_language(header: str | None) -> str:
if not header:
return DEFAULT
for part in header.split(","):
tag = part.split(";", 1)[0].strip()
if not tag:
continue
return normalize_lang(tag)
return DEFAULT
def resolve_lang(request: Request) -> str:
cookie = request.cookies.get(COOKIE)
if cookie in LOCALES:
return cookie
return from_accept_language(request.headers.get("accept-language"))
def html_lang(lang: str) -> str:
return "pt-BR" if lang == "pt" else "en"
def translate(lang: str, key: str, **kwargs: object) -> str:
table = STRINGS.get(lang) or STRINGS[DEFAULT]
text = table.get(key) or STRINGS[DEFAULT].get(key) or key
if kwargs:
return text.format(**kwargs)
return text
def translator(lang: str):
def _t(key: str, **kwargs: object) -> str:
return translate(lang, key, **kwargs)
return _t
def encode_bootstrap_note(kind: str, exc: object) -> str:
return f"{kind}|{exc}"
def render_bootstrap_note(lang: str, raw: str | None) -> str:
if not raw:
return ""
kind, sep, detail = raw.partition("|")
key = _BOOTSTRAP_KEYS.get(kind)
if key and sep:
return translate(lang, key, exc=detail)
return raw
def safe_back(request: Request) -> str:
ref = request.headers.get("referer")
if not ref:
return "/"
parsed = urlparse(ref)
if parsed.netloc and parsed.netloc != request.url.netloc:
return "/"
path = parsed.path or "/"
if path.startswith("/lang"):
return "/"
if parsed.query:
return f"{path}?{parsed.query}"
return path
def lang_redirect(request: Request, code: str) -> RedirectResponse:
lang = normalize_lang(code)
resp = RedirectResponse(safe_back(request), status_code=303)
resp.set_cookie(
COOKIE,
lang,
max_age=COOKIE_MAX_AGE,
path="/",
samesite="lax",
httponly=True,
)
return resp
|