mirror of
https://github.com/OwO-Network/DeepLX.git
synced 2026-12-01 23:07:51 +00:00
Compare commits
6
Commits
e5d8e78f79
..
v1.2.5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
54158cddd5 | ||
|
|
6ff3cfac2f | ||
|
|
11c94403ec | ||
|
|
ef3979d915 | ||
|
|
9f76381eb4 | ||
|
|
5e7e2129c0 |
@@ -15,7 +15,7 @@ jobs:
|
|||||||
- name: Set up Go
|
- name: Set up Go
|
||||||
uses: actions/setup-go@v4
|
uses: actions/setup-go@v4
|
||||||
with:
|
with:
|
||||||
go-version: '1.24.2'
|
go-version: '1.27.1'
|
||||||
|
|
||||||
- name: Install golint
|
- name: Install golint
|
||||||
run: go install golang.org/x/lint/golint@latest
|
run: go install golang.org/x/lint/golint@latest
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ jobs:
|
|||||||
|
|
||||||
- uses: actions/setup-go@v4
|
- uses: actions/setup-go@v4
|
||||||
with:
|
with:
|
||||||
go-version: "1.24.2"
|
go-version: "1.27.1"
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
env:
|
env:
|
||||||
@@ -58,16 +58,79 @@ jobs:
|
|||||||
needs: Build
|
needs: Build
|
||||||
if: startsWith(github.ref, 'refs/tags/v')
|
if: startsWith(github.ref, 'refs/tags/v')
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
steps:
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
- name: Download artifacts
|
- name: Download artifacts
|
||||||
uses: actions/download-artifact@v4
|
uses: actions/download-artifact@v4
|
||||||
with:
|
with:
|
||||||
path: dist
|
path: dist
|
||||||
merge-multiple: true
|
merge-multiple: true
|
||||||
|
|
||||||
|
# Start from GitHub's auto-generated notes (What's Changed / New
|
||||||
|
# Contributors / Full Changelog) and add a "Thanks" section naming every
|
||||||
|
# PR author who is not a repository collaborator or a bot.
|
||||||
|
- name: Generate release notes
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
TAG: ${{ github.ref_name }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
prev=$(git describe --tags --abbrev=0 "${TAG}^" 2>/dev/null || true)
|
||||||
|
args=(-f tag_name="$TAG")
|
||||||
|
if [ -n "$prev" ]; then
|
||||||
|
args+=(-f previous_tag_name="$prev")
|
||||||
|
fi
|
||||||
|
gh api "repos/${GITHUB_REPOSITORY}/releases/generate-notes" \
|
||||||
|
"${args[@]}" --jq .body > notes.md
|
||||||
|
|
||||||
|
declare -A prs=()
|
||||||
|
while read -r login num; do
|
||||||
|
prs["$login"]="${prs[$login]:-}${prs[$login]:+, }#${num}"
|
||||||
|
done < <(grep -oE 'by @[A-Za-z0-9_-]+ in https://github\.com/[^ ]+/pull/[0-9]+' notes.md \
|
||||||
|
| sed -E 's#by @([^ ]+) in .*/pull/([0-9]+)#\1 \2#' | sort -u -k1,1 -k2,2n)
|
||||||
|
|
||||||
|
thanks=()
|
||||||
|
for login in "${!prs[@]}"; do
|
||||||
|
case "$login" in
|
||||||
|
dependabot*|renovate*|github-actions*|*\[bot\]) continue ;;
|
||||||
|
esac
|
||||||
|
perm=$(gh api "repos/${GITHUB_REPOSITORY}/collaborators/${login}/permission" \
|
||||||
|
--jq .permission 2>/dev/null || echo none)
|
||||||
|
case "$perm" in
|
||||||
|
admin|maintain|write) continue ;;
|
||||||
|
esac
|
||||||
|
thanks+=("* Thanks @${login} for ${prs[$login]}")
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ "${#thanks[@]}" -gt 0 ]; then
|
||||||
|
if grep -q '^\*\*Full Changelog' notes.md; then
|
||||||
|
{
|
||||||
|
sed '/^\*\*Full Changelog/,$d' notes.md
|
||||||
|
printf '## Thanks\n'
|
||||||
|
printf '%s\n' "${thanks[@]}" | sort
|
||||||
|
printf '\n'
|
||||||
|
grep '^\*\*Full Changelog' notes.md
|
||||||
|
} > notes.out
|
||||||
|
else
|
||||||
|
{
|
||||||
|
cat notes.md
|
||||||
|
printf '\n## Thanks\n'
|
||||||
|
printf '%s\n' "${thanks[@]}" | sort
|
||||||
|
} > notes.out
|
||||||
|
fi
|
||||||
|
mv notes.out notes.md
|
||||||
|
fi
|
||||||
|
echo "::group::Release notes"; cat notes.md; echo "::endgroup::"
|
||||||
|
|
||||||
- name: Release
|
- name: Release
|
||||||
uses: softprops/action-gh-release@v1
|
uses: softprops/action-gh-release@v1
|
||||||
with:
|
with:
|
||||||
draft: false
|
draft: false
|
||||||
generate_release_notes: true
|
body_path: notes.md
|
||||||
files: dist/*
|
files: dist/*
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
FROM golang:1.25 AS builder
|
FROM golang:1.27 AS builder
|
||||||
WORKDIR /go/src/github.com/OwO-Network/DLX
|
WORKDIR /go/src/github.com/OwO-Network/DLX
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN go get -d -v ./
|
RUN go get -d -v ./
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
module github.com/OwO-Network/DLX
|
module github.com/OwO-Network/DLX
|
||||||
|
|
||||||
go 1.25.0
|
go 1.27.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/andybalholm/brotli v1.2.2
|
github.com/andybalholm/brotli v1.2.2
|
||||||
|
|||||||
+5
-1
@@ -240,14 +240,17 @@ func Router(cfg *Config) *gin.Engine {
|
|||||||
proxyURL := cfg.Proxy
|
proxyURL := cfg.Proxy
|
||||||
|
|
||||||
var translateText string
|
var translateText string
|
||||||
|
var sourceLang string
|
||||||
var targetLang string
|
var targetLang string
|
||||||
|
|
||||||
translateText = c.PostForm("text")
|
translateText = c.PostForm("text")
|
||||||
|
sourceLang = c.PostForm("source_lang")
|
||||||
targetLang = c.PostForm("target_lang")
|
targetLang = c.PostForm("target_lang")
|
||||||
|
|
||||||
if translateText == "" || targetLang == "" {
|
if translateText == "" || targetLang == "" {
|
||||||
var jsonData struct {
|
var jsonData struct {
|
||||||
Text []string `json:"text"`
|
Text []string `json:"text"`
|
||||||
|
SourceLang string `json:"source_lang"`
|
||||||
TargetLang string `json:"target_lang"`
|
TargetLang string `json:"target_lang"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -260,10 +263,11 @@ func Router(cfg *Config) *gin.Engine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
translateText = strings.Join(jsonData.Text, "\n")
|
translateText = strings.Join(jsonData.Text, "\n")
|
||||||
|
sourceLang = jsonData.SourceLang
|
||||||
targetLang = jsonData.TargetLang
|
targetLang = jsonData.TargetLang
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := translate.TranslateByDLX("", targetLang, translateText, "", proxyURL, "")
|
result, err := translate.TranslateByDLX(sourceLang, targetLang, translateText, "", proxyURL, "")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Translation failed: %s", err)
|
log.Printf("Translation failed: %s", err)
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{
|
c.JSON(http.StatusInternalServerError, gin.H{
|
||||||
|
|||||||
@@ -0,0 +1,193 @@
|
|||||||
|
/*
|
||||||
|
* @Author: Vincent Young
|
||||||
|
* @Date: 2026-10-08 00:00:00
|
||||||
|
* @LastEditors: Vincent Yang
|
||||||
|
* @LastEditTime: 2026-10-08 00:00:00
|
||||||
|
* @FilePath: /DLX/translate/appversion.go
|
||||||
|
* @Telegram: https://t.me/missuo
|
||||||
|
* @GitHub: https://github.com/missuo
|
||||||
|
*
|
||||||
|
* Copyright © 2024 by Vincent, All Rights Reserved.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package translate
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DeepL's iOS app on the US App Store. Apple's public lookup endpoint is
|
||||||
|
// key-less and returns, in results[0].version, the marketing version the iOS
|
||||||
|
// client reports as CFBundleShortVersionString in its User-Agent and
|
||||||
|
// app_information.app_version.
|
||||||
|
//
|
||||||
|
// DeepL rate-limits clients whose iOS TLS fingerprint and advertised app
|
||||||
|
// version are inconsistent (see OwO-Network/DLX#236): once the pinned version
|
||||||
|
// goes stale, *every* request is answered with HTTP 429. Resolving the version
|
||||||
|
// at runtime keeps that profile coherent without a rebuild.
|
||||||
|
const (
|
||||||
|
deeplAppStoreTrackID = 1552407475
|
||||||
|
deeplAppStoreBundleID = "com.linguee.DeepLMobileTranslator"
|
||||||
|
deeplAppStoreSeller = "DeepL SE"
|
||||||
|
)
|
||||||
|
|
||||||
|
// deeplAppStoreLookupURL is a var rather than a const so tests can point it at
|
||||||
|
// a local server.
|
||||||
|
var deeplAppStoreLookupURL = fmt.Sprintf(
|
||||||
|
"https://itunes.apple.com/lookup?id=%d&country=us", deeplAppStoreTrackID,
|
||||||
|
)
|
||||||
|
|
||||||
|
// Lookup policy, mirroring the approach of tisfeng/Easydict#1341. The App Store
|
||||||
|
// is only contacted lazily, on the first translation after the cache expires —
|
||||||
|
// never at startup — so an unreachable App Store cannot delay or prevent the
|
||||||
|
// process from serving.
|
||||||
|
const (
|
||||||
|
appVersionCacheTTL = 24 * time.Hour
|
||||||
|
appVersionRetryBackoff = 15 * time.Minute
|
||||||
|
appVersionLookupTimeout = 3 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
// appVersionHTTPClient is shared so repeat lookups reuse the connection pool.
|
||||||
|
// It is separate from the translation client: no TLS fingerprint, no cookies,
|
||||||
|
// no proxy.
|
||||||
|
var appVersionHTTPClient = &http.Client{Timeout: appVersionLookupTimeout}
|
||||||
|
|
||||||
|
// appVersionProvider resolves and caches the DeepL iOS version this client
|
||||||
|
// advertises. The zero value is ready to use.
|
||||||
|
type appVersionProvider struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
version string // last successfully resolved version, "" if none
|
||||||
|
fetchedAt time.Time // when version was resolved
|
||||||
|
attemptedAt time.Time // when a lookup was last started
|
||||||
|
}
|
||||||
|
|
||||||
|
var iosAppVersionProvider appVersionProvider
|
||||||
|
|
||||||
|
// currentIOSAppVersion returns the DeepL iOS marketing version to advertise in
|
||||||
|
// both the User-Agent and app_information. A successful lookup is cached for
|
||||||
|
// appVersionCacheTTL; a failed one is not retried for appVersionRetryBackoff.
|
||||||
|
// Any failure falls back to the last resolved version, or to the pinned
|
||||||
|
// iosAppVersion if none was ever resolved, so behaviour degrades to the
|
||||||
|
// previous hardcoded value instead of failing.
|
||||||
|
func currentIOSAppVersion() string {
|
||||||
|
p := &iosAppVersionProvider
|
||||||
|
// The lock is held across the lookup so a burst of cold requests performs
|
||||||
|
// at most one App Store query; callers block for no longer than
|
||||||
|
// appVersionLookupTimeout and then share the result.
|
||||||
|
p.mu.Lock()
|
||||||
|
defer p.mu.Unlock()
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
if isValidAppVersion(p.version) && now.Sub(p.fetchedAt) < appVersionCacheTTL {
|
||||||
|
return p.version
|
||||||
|
}
|
||||||
|
if !p.attemptedAt.IsZero() && now.Sub(p.attemptedAt) < appVersionRetryBackoff {
|
||||||
|
return p.cachedOrFallback()
|
||||||
|
}
|
||||||
|
|
||||||
|
p.attemptedAt = now
|
||||||
|
version, err := fetchLatestIOSAppVersion()
|
||||||
|
if err == nil && !isValidAppVersion(version) {
|
||||||
|
err = fmt.Errorf("implausible version %q", version)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
fallback := p.cachedOrFallback()
|
||||||
|
log.Printf("DeepL iOS app version lookup failed, falling back to %s: %v", fallback, err)
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
p.version = version
|
||||||
|
p.fetchedAt = now
|
||||||
|
return version
|
||||||
|
}
|
||||||
|
|
||||||
|
// cachedOrFallback prefers a previously resolved version over the pinned
|
||||||
|
// constant: a version that was current recently is a better guess than one
|
||||||
|
// hardcoded at build time.
|
||||||
|
func (p *appVersionProvider) cachedOrFallback() string {
|
||||||
|
if isValidAppVersion(p.version) {
|
||||||
|
return p.version
|
||||||
|
}
|
||||||
|
return iosAppVersion
|
||||||
|
}
|
||||||
|
|
||||||
|
// appStoreLookup is the subset of Apple's lookup response we consume.
|
||||||
|
type appStoreLookup struct {
|
||||||
|
ResultCount int `json:"resultCount"`
|
||||||
|
Results []appStoreResult `json:"results"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type appStoreResult struct {
|
||||||
|
TrackID int64 `json:"trackId"`
|
||||||
|
BundleID string `json:"bundleId"`
|
||||||
|
ArtistName string `json:"artistName"`
|
||||||
|
Version string `json:"version"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetchLatestIOSAppVersion queries Apple's lookup API for the DeepL iOS app.
|
||||||
|
func fetchLatestIOSAppVersion() (string, error) {
|
||||||
|
resp, err := appVersionHTTPClient.Get(deeplAppStoreLookupURL)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return "", fmt.Errorf("app store lookup: unexpected status %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
// Cap the read so a misbehaving endpoint cannot make us allocate without
|
||||||
|
// bound.
|
||||||
|
body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
var lookup appStoreLookup
|
||||||
|
if err := json.Unmarshal(body, &lookup); err != nil {
|
||||||
|
return "", fmt.Errorf("app store lookup: %w", err)
|
||||||
|
}
|
||||||
|
return lookup.deepLVersion()
|
||||||
|
}
|
||||||
|
|
||||||
|
// deepLVersion validates that the lookup result really is the DeepL iOS app
|
||||||
|
// and returns its marketing version. A wrong or unexpected answer is rejected
|
||||||
|
// rather than advertised, which keeps the fallback path honest.
|
||||||
|
func (l appStoreLookup) deepLVersion() (string, error) {
|
||||||
|
if l.ResultCount != 1 || len(l.Results) != 1 {
|
||||||
|
return "", fmt.Errorf("app store lookup: expected 1 result, got %d", len(l.Results))
|
||||||
|
}
|
||||||
|
r := l.Results[0]
|
||||||
|
if r.TrackID != deeplAppStoreTrackID || r.BundleID != deeplAppStoreBundleID || r.ArtistName != deeplAppStoreSeller {
|
||||||
|
return "", fmt.Errorf("app store lookup: unexpected app %d/%q/%q", r.TrackID, r.BundleID, r.ArtistName)
|
||||||
|
}
|
||||||
|
if !isValidAppVersion(r.Version) {
|
||||||
|
return "", fmt.Errorf("app store lookup: implausible version %q", r.Version)
|
||||||
|
}
|
||||||
|
return r.Version, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// isValidAppVersion accepts the dotted numeric forms DeepL ships ("26.42",
|
||||||
|
// "26.52.1", "1.2.3.4") and rejects everything else.
|
||||||
|
func isValidAppVersion(version string) bool {
|
||||||
|
parts := strings.Split(version, ".")
|
||||||
|
if len(parts) < 2 || len(parts) > 4 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, part := range parts {
|
||||||
|
if part == "" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, r := range part {
|
||||||
|
if r < '0' || r > '9' {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
/*
|
||||||
|
* @Author: Vincent Young
|
||||||
|
* @Date: 2026-10-08 00:00:00
|
||||||
|
* @LastEditors: Vincent Yang
|
||||||
|
* @LastEditTime: 2026-10-08 00:00:00
|
||||||
|
* @FilePath: /DLX/translate/appversion_test.go
|
||||||
|
* @Telegram: https://t.me/missuo
|
||||||
|
* @GitHub: https://github.com/missuo
|
||||||
|
*
|
||||||
|
* Copyright © 2024 by Vincent, All Rights Reserved.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package translate
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestIsValidAppVersion(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
version string
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"26.42", true},
|
||||||
|
{"26.53", true},
|
||||||
|
{"26.52.1", true},
|
||||||
|
{"1.2.3.4", true},
|
||||||
|
{"", false},
|
||||||
|
{"26", false},
|
||||||
|
{"26.42.1.2.3", false},
|
||||||
|
{"26..42", false},
|
||||||
|
{".26.42", false},
|
||||||
|
{"26.42.", false},
|
||||||
|
{"26.42-beta", false},
|
||||||
|
{"v26.42", false},
|
||||||
|
{"26.4 2", false},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
if got := isValidAppVersion(tt.version); got != tt.want {
|
||||||
|
t.Errorf("isValidAppVersion(%q) = %v, want %v", tt.version, got, tt.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAppStoreLookupDeepLVersion(t *testing.T) {
|
||||||
|
result := func(trackID int64, bundleID, artist, version string) appStoreResult {
|
||||||
|
return appStoreResult{TrackID: trackID, BundleID: bundleID, ArtistName: artist, Version: version}
|
||||||
|
}
|
||||||
|
valid := result(deeplAppStoreTrackID, deeplAppStoreBundleID, deeplAppStoreSeller, "26.53")
|
||||||
|
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
lookup appStoreLookup
|
||||||
|
want string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{"valid", appStoreLookup{ResultCount: 1, Results: []appStoreResult{valid}}, "26.53", false},
|
||||||
|
{"no results", appStoreLookup{ResultCount: 0}, "", true},
|
||||||
|
{"two results", appStoreLookup{ResultCount: 2, Results: []appStoreResult{valid, valid}}, "", true},
|
||||||
|
{"wrong track id", appStoreLookup{ResultCount: 1, Results: []appStoreResult{result(1, deeplAppStoreBundleID, deeplAppStoreSeller, "26.53")}}, "", true},
|
||||||
|
{"wrong bundle", appStoreLookup{ResultCount: 1, Results: []appStoreResult{result(deeplAppStoreTrackID, "com.example.app", deeplAppStoreSeller, "26.53")}}, "", true},
|
||||||
|
{"wrong seller", appStoreLookup{ResultCount: 1, Results: []appStoreResult{result(deeplAppStoreTrackID, deeplAppStoreBundleID, "Someone Else", "26.53")}}, "", true},
|
||||||
|
{"implausible version", appStoreLookup{ResultCount: 1, Results: []appStoreResult{result(deeplAppStoreTrackID, deeplAppStoreBundleID, deeplAppStoreSeller, "latest")}}, "", true},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
got, err := tt.lookup.deepLVersion()
|
||||||
|
if (err != nil) != tt.wantErr {
|
||||||
|
t.Fatalf("deepLVersion() error = %v, wantErr %v", err, tt.wantErr)
|
||||||
|
}
|
||||||
|
if got != tt.want {
|
||||||
|
t.Fatalf("deepLVersion() = %q, want %q", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// lookupServer serves an App Store lookup response with the given version and
|
||||||
|
// counts how many times it was queried.
|
||||||
|
func lookupServer(t *testing.T, version string, status int) (*httptest.Server, func() int) {
|
||||||
|
t.Helper()
|
||||||
|
var (
|
||||||
|
mu sync.Mutex
|
||||||
|
requests int
|
||||||
|
)
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
mu.Lock()
|
||||||
|
requests++
|
||||||
|
mu.Unlock()
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.WriteHeader(status)
|
||||||
|
if status != http.StatusOK {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
_ = json.NewEncoder(w).Encode(appStoreLookup{
|
||||||
|
ResultCount: 1,
|
||||||
|
Results: []appStoreResult{{
|
||||||
|
TrackID: deeplAppStoreTrackID,
|
||||||
|
BundleID: deeplAppStoreBundleID,
|
||||||
|
ArtistName: deeplAppStoreSeller,
|
||||||
|
Version: version,
|
||||||
|
}},
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
t.Cleanup(srv.Close)
|
||||||
|
count := func() int {
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
return requests
|
||||||
|
}
|
||||||
|
return srv, count
|
||||||
|
}
|
||||||
|
|
||||||
|
// resetProvider points the resolver at url and clears its cache for the test.
|
||||||
|
func resetProvider(t *testing.T, url string) {
|
||||||
|
t.Helper()
|
||||||
|
originalURL := deeplAppStoreLookupURL
|
||||||
|
iosAppVersionProvider = appVersionProvider{}
|
||||||
|
t.Cleanup(func() {
|
||||||
|
deeplAppStoreLookupURL = originalURL
|
||||||
|
iosAppVersionProvider = appVersionProvider{}
|
||||||
|
})
|
||||||
|
deeplAppStoreLookupURL = url
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCurrentIOSAppVersionUsesLookupAndCaches(t *testing.T) {
|
||||||
|
srv, count := lookupServer(t, "26.99", http.StatusOK)
|
||||||
|
resetProvider(t, srv.URL)
|
||||||
|
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
if got := currentIOSAppVersion(); got != "26.99" {
|
||||||
|
t.Fatalf("currentIOSAppVersion() = %q, want %q", got, "26.99")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := count(); got != 1 {
|
||||||
|
t.Fatalf("lookup served %d requests, want 1 (result must be cached)", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCurrentIOSAppVersionFallsBackAndBacksOff(t *testing.T) {
|
||||||
|
srv, count := lookupServer(t, "", http.StatusInternalServerError)
|
||||||
|
resetProvider(t, srv.URL)
|
||||||
|
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
if got := currentIOSAppVersion(); got != iosAppVersion {
|
||||||
|
t.Fatalf("currentIOSAppVersion() = %q, want fallback %q", got, iosAppVersion)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := count(); got != 1 {
|
||||||
|
t.Fatalf("lookup served %d requests, want 1 (failure must back off)", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCurrentIOSAppVersionFallsBackOnMalformedBody(t *testing.T) {
|
||||||
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fmt.Fprint(w, "not json")
|
||||||
|
}))
|
||||||
|
t.Cleanup(srv.Close)
|
||||||
|
resetProvider(t, srv.URL)
|
||||||
|
|
||||||
|
if got := currentIOSAppVersion(); got != iosAppVersion {
|
||||||
|
t.Fatalf("currentIOSAppVersion() = %q, want fallback %q", got, iosAppVersion)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCurrentIOSAppVersionSingleFlight(t *testing.T) {
|
||||||
|
srv, count := lookupServer(t, "26.99", http.StatusOK)
|
||||||
|
resetProvider(t, srv.URL)
|
||||||
|
|
||||||
|
const goroutines = 16
|
||||||
|
results := make([]string, goroutines)
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
for i := 0; i < goroutines; i++ {
|
||||||
|
wg.Add(1)
|
||||||
|
go func(i int) {
|
||||||
|
defer wg.Done()
|
||||||
|
results[i] = currentIOSAppVersion()
|
||||||
|
}(i)
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
for i, got := range results {
|
||||||
|
if got != "26.99" {
|
||||||
|
t.Fatalf("goroutine %d got %q, want %q", i, got, "26.99")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := count(); got != 1 {
|
||||||
|
t.Fatalf("lookup served %d requests, want 1 (concurrent callers must share one lookup)", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
/*
|
||||||
|
* @Author: Vincent Young
|
||||||
|
* @Date: 2026-10-08 00:00:00
|
||||||
|
* @LastEditors: Vincent Yang
|
||||||
|
* @LastEditTime: 2026-10-08 00:00:00
|
||||||
|
* @FilePath: /DLX/translate/lang_test.go
|
||||||
|
* @Telegram: https://t.me/missuo
|
||||||
|
* @GitHub: https://github.com/missuo
|
||||||
|
*
|
||||||
|
* Copyright © 2024 by Vincent, All Rights Reserved.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package translate
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestResolveSourceLang(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
in string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"", ""},
|
||||||
|
{"auto", ""},
|
||||||
|
{"AUTO", ""},
|
||||||
|
{"EN", "en"},
|
||||||
|
{"en-us", "en-US"},
|
||||||
|
{"PT", "pt"},
|
||||||
|
{"PT-BR", "pt-BR"},
|
||||||
|
// DeepL only accepts the generic "zh" as a source hint; the
|
||||||
|
// script variants are target-only (#239).
|
||||||
|
{"ZH", "zh"},
|
||||||
|
{"zh", "zh"},
|
||||||
|
{"ZH-HANS", "zh"},
|
||||||
|
{"zh-hant", "zh"},
|
||||||
|
{"JA", "ja"},
|
||||||
|
{"ES-419", "es-419"},
|
||||||
|
{"DE-CH", "de-CH"},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
got, err := resolveSourceLang(c.in)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("resolveSourceLang(%q) error: %v", c.in, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if got != c.want {
|
||||||
|
t.Errorf("resolveSourceLang(%q) = %q, want %q", c.in, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := resolveSourceLang("xx"); err == nil {
|
||||||
|
t.Errorf("resolveSourceLang(%q) expected error", "xx")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolveTargetLang(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
in string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"EN", "en-US"},
|
||||||
|
{"en-gb", "en-GB"},
|
||||||
|
{"PT", "pt-BR"},
|
||||||
|
{"ZH", "zh-Hans"},
|
||||||
|
{"ZH-HANS", "zh-Hans"},
|
||||||
|
{"zh-hant", "zh-Hant"},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
got, err := resolveTargetLang(c.in)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("resolveTargetLang(%q) error: %v", c.in, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if got != c.want {
|
||||||
|
t.Errorf("resolveTargetLang(%q) = %q, want %q", c.in, got, c.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, bad := range []string{"", "auto", "xx"} {
|
||||||
|
if _, err := resolveTargetLang(bad); err == nil {
|
||||||
|
t.Errorf("resolveTargetLang(%q) expected error", bad)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,151 +0,0 @@
|
|||||||
package translate
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"compress/flate"
|
|
||||||
"compress/gzip"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/andybalholm/brotli"
|
|
||||||
"github.com/imroc/req/v3"
|
|
||||||
)
|
|
||||||
|
|
||||||
// useHermeticClient pre-seeds the process-wide client cache for the empty
|
|
||||||
// proxy key so callOneshot reuses it instead of building the real
|
|
||||||
// ImpersonateChrome client, whose creation also fires a background warmup
|
|
||||||
// GET to www.deepl.com. The client mirrors production where it matters for
|
|
||||||
// this layer: it pins Accept-Encoding so Go's transport does not auto-
|
|
||||||
// decompress, which is exactly why callOneshot decompresses by hand.
|
|
||||||
func useHermeticClient(t *testing.T) {
|
|
||||||
t.Helper()
|
|
||||||
c := req.C().
|
|
||||||
SetTimeout(5*time.Second).
|
|
||||||
SetCommonHeader("Accept-Encoding", "gzip, deflate, br")
|
|
||||||
oneshotClients.Store("", c)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCallOneshotRequestShaping(t *testing.T) {
|
|
||||||
useHermeticClient(t)
|
|
||||||
|
|
||||||
var gotHeader http.Header
|
|
||||||
var gotBody []byte
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
gotHeader = r.Header.Clone()
|
|
||||||
gotBody, _ = io.ReadAll(r.Body)
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
_, _ = w.Write([]byte(`{"translations":[{"text":"hallo","detected_source_language":"EN"}]}`))
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
body := []byte(`{"text":["hello"],"target_lang":"de"}`)
|
|
||||||
|
|
||||||
t.Run("anonymous sends Authorization None and extension headers", func(t *testing.T) {
|
|
||||||
res, status, err := callOneshot(srv.URL, body, "", "")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("callOneshot error: %v", err)
|
|
||||||
}
|
|
||||||
if status != http.StatusOK {
|
|
||||||
t.Fatalf("status = %d, want 200", status)
|
|
||||||
}
|
|
||||||
if got := res.Get("translations.0.text").String(); got != "hallo" {
|
|
||||||
t.Errorf("parsed body wrong, translations.0.text = %q", got)
|
|
||||||
}
|
|
||||||
if h := gotHeader.Get("Authorization"); h != "None" {
|
|
||||||
t.Errorf("Authorization = %q, want %q", h, "None")
|
|
||||||
}
|
|
||||||
if h := gotHeader.Get("Content-Type"); h != "application/json" {
|
|
||||||
t.Errorf("Content-Type = %q, want application/json", h)
|
|
||||||
}
|
|
||||||
if h := gotHeader.Get("Origin"); h != "chrome-extension://"+chromeExtensionID {
|
|
||||||
t.Errorf("Origin = %q, want chrome-extension://%s", h, chromeExtensionID)
|
|
||||||
}
|
|
||||||
for k, want := range map[string]string{
|
|
||||||
"Sec-Fetch-Site": "cross-site",
|
|
||||||
"Sec-Fetch-Mode": "cors",
|
|
||||||
"Sec-Fetch-Dest": "empty",
|
|
||||||
} {
|
|
||||||
if h := gotHeader.Get(k); h != want {
|
|
||||||
t.Errorf("%s = %q, want %q", k, h, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !bytes.Equal(gotBody, body) {
|
|
||||||
t.Errorf("forwarded body = %q, want %q", gotBody, body)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("bearer token used when session provided", func(t *testing.T) {
|
|
||||||
if _, _, err := callOneshot(srv.URL, body, "tok123", ""); err != nil {
|
|
||||||
t.Fatalf("callOneshot error: %v", err)
|
|
||||||
}
|
|
||||||
if h := gotHeader.Get("Authorization"); h != "Bearer tok123" {
|
|
||||||
t.Errorf("Authorization = %q, want %q", h, "Bearer tok123")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestCallOneshotDecompression covers the three hand-rolled decode paths
|
|
||||||
// (gzip/deflate/br) plus identity. This code exists only because the client
|
|
||||||
// pins Accept-Encoding, and it was previously untested — a decode regression
|
|
||||||
// would surface to users as a blind "Translation failed".
|
|
||||||
func TestCallOneshotDecompression(t *testing.T) {
|
|
||||||
useHermeticClient(t)
|
|
||||||
|
|
||||||
const payload = `{"translations":[{"text":"decoded"}]}`
|
|
||||||
|
|
||||||
cases := []struct {
|
|
||||||
name string
|
|
||||||
encoding string
|
|
||||||
compress func([]byte) []byte
|
|
||||||
}{
|
|
||||||
{"identity", "", func(b []byte) []byte { return b }},
|
|
||||||
{"gzip", "gzip", func(b []byte) []byte {
|
|
||||||
var buf bytes.Buffer
|
|
||||||
w := gzip.NewWriter(&buf)
|
|
||||||
_, _ = w.Write(b)
|
|
||||||
_ = w.Close()
|
|
||||||
return buf.Bytes()
|
|
||||||
}},
|
|
||||||
{"deflate", "deflate", func(b []byte) []byte {
|
|
||||||
var buf bytes.Buffer
|
|
||||||
w, _ := flate.NewWriter(&buf, flate.DefaultCompression)
|
|
||||||
_, _ = w.Write(b)
|
|
||||||
_ = w.Close()
|
|
||||||
return buf.Bytes()
|
|
||||||
}},
|
|
||||||
{"brotli", "br", func(b []byte) []byte {
|
|
||||||
var buf bytes.Buffer
|
|
||||||
w := brotli.NewWriter(&buf)
|
|
||||||
_, _ = w.Write(b)
|
|
||||||
_ = w.Close()
|
|
||||||
return buf.Bytes()
|
|
||||||
}},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range cases {
|
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
|
||||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
if tc.encoding != "" {
|
|
||||||
w.Header().Set("Content-Encoding", tc.encoding)
|
|
||||||
}
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
_, _ = w.Write(tc.compress([]byte(payload)))
|
|
||||||
}))
|
|
||||||
defer srv.Close()
|
|
||||||
|
|
||||||
res, status, err := callOneshot(srv.URL, []byte(`{}`), "", "")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("callOneshot(%s) error: %v", tc.name, err)
|
|
||||||
}
|
|
||||||
if status != http.StatusOK {
|
|
||||||
t.Fatalf("status = %d, want 200", status)
|
|
||||||
}
|
|
||||||
if got := res.Get("translations.0.text").String(); got != "decoded" {
|
|
||||||
t.Errorf("decoded text = %q, want %q (encoding %q)", got, "decoded", tc.encoding)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+36
-12
@@ -42,8 +42,11 @@ import (
|
|||||||
// traffic hard; oneshot lives on a separate pool and accepts the literal
|
// traffic hard; oneshot lives on a separate pool and accepts the literal
|
||||||
// header `Authorization: None` for free requests.
|
// header `Authorization: None` for free requests.
|
||||||
//
|
//
|
||||||
// Request shape reverse-engineered from DeepL iOS 26.42 (build 5443737,
|
// Request shape reverse-engineered from the DeepL iOS client (bundle
|
||||||
// bundle com.linguee.DeepLMobileTranslator, IPA Info.plist + ItaClient.framework):
|
// com.linguee.DeepLMobileTranslator, IPA Info.plist + ItaClient.framework).
|
||||||
|
// The advertised app version is resolved at runtime from the App Store
|
||||||
|
// (appversion.go) so a DeepL release cannot silently invalidate the profile;
|
||||||
|
// iosAppVersion below is only the fallback.
|
||||||
//
|
//
|
||||||
// Transport
|
// Transport
|
||||||
// ItaClient oneshot uses Ktor Darwin engine
|
// ItaClient oneshot uses Ktor Darwin engine
|
||||||
@@ -73,8 +76,13 @@ const (
|
|||||||
oneshotFreeEndpoint = "https://oneshot-free.www.deepl.com/v1/translate"
|
oneshotFreeEndpoint = "https://oneshot-free.www.deepl.com/v1/translate"
|
||||||
oneshotProEndpoint = "https://oneshot-pro.www.deepl.com/v1/translate"
|
oneshotProEndpoint = "https://oneshot-pro.www.deepl.com/v1/translate"
|
||||||
|
|
||||||
// Pinned to DeepL iOS IPA (CFBundleShortVersionString / CFBundleVersion).
|
// Fallback DeepL iOS version, used only when the runtime App Store
|
||||||
iosAppVersion = "26.42"
|
// lookup fails (appversion.go). Keep it tracking DeepL's current App Store
|
||||||
|
// release: a stale version is answered with HTTP 429 on every request
|
||||||
|
// ("your IP has been blocked by DeepL temporarily"), from any IP. The build
|
||||||
|
// number stays pinned because Apple's lookup API does not expose
|
||||||
|
// CFBundleVersion.
|
||||||
|
iosAppVersion = "26.52"
|
||||||
iosAppBuild = "5443737"
|
iosAppBuild = "5443737"
|
||||||
|
|
||||||
// Reported OS version for app_information.os_version + x-app-os-version.
|
// Reported OS version for app_information.os_version + x-app-os-version.
|
||||||
@@ -187,7 +195,8 @@ var targetLangMap = map[string]string{
|
|||||||
|
|
||||||
// sourceLangMap is what the API accepts as `source_lang`. It is a
|
// sourceLangMap is what the API accepts as `source_lang`. It is a
|
||||||
// superset of targetLangMap: EN and PT are first-class source codes
|
// superset of targetLangMap: EN and PT are first-class source codes
|
||||||
// mapping to the generic "en"/"pt".
|
// mapping to the generic "en"/"pt", and the Chinese codes all map to the
|
||||||
|
// generic "zh".
|
||||||
var sourceLangMap = func() map[string]string {
|
var sourceLangMap = func() map[string]string {
|
||||||
m := make(map[string]string, len(targetLangMap)+2)
|
m := make(map[string]string, len(targetLangMap)+2)
|
||||||
for k, v := range targetLangMap {
|
for k, v := range targetLangMap {
|
||||||
@@ -195,6 +204,13 @@ var sourceLangMap = func() map[string]string {
|
|||||||
}
|
}
|
||||||
m["EN"] = "en"
|
m["EN"] = "en"
|
||||||
m["PT"] = "pt"
|
m["PT"] = "pt"
|
||||||
|
// DeepL's source codes are the generic language forms. zh-Hans/zh-Hant
|
||||||
|
// are target-only script variants: sent as a source hint they are
|
||||||
|
// silently ignored, so ambiguous mixed-script Chinese fell back to
|
||||||
|
// auto-detection and came back untranslated (#239).
|
||||||
|
m["ZH"] = "zh"
|
||||||
|
m["ZH-HANS"] = "zh"
|
||||||
|
m["ZH-HANT"] = "zh"
|
||||||
return m
|
return m
|
||||||
}()
|
}()
|
||||||
|
|
||||||
@@ -305,12 +321,13 @@ func newOneshotClient(proxyURL string) (*req.Client, error) {
|
|||||||
// - TLS ClientHello ≈ real iOS (utls HelloIOS_Auto)
|
// - TLS ClientHello ≈ real iOS (utls HelloIOS_Auto)
|
||||||
// - Cookie jar shared like URLSession's HTTPCookieStorage
|
// - Cookie jar shared like URLSession's HTTPCookieStorage
|
||||||
// - Common headers = what URLSession attaches by default
|
// - Common headers = what URLSession attaches by default
|
||||||
// Per-request headers (Authorization, x-app-*) are set in callOneshot.
|
// Per-request headers (Authorization, User-Agent, x-app-*) are set in
|
||||||
|
// callOneshot; the client-level User-Agent is only a default.
|
||||||
client := req.C().
|
client := req.C().
|
||||||
SetTLSFingerprintIOS().
|
SetTLSFingerprintIOS().
|
||||||
SetCookieJar(sharedCookieJar()).
|
SetCookieJar(sharedCookieJar()).
|
||||||
SetTimeout(oneshotTimeout).
|
SetTimeout(oneshotTimeout).
|
||||||
SetUserAgent(iosUserAgent()).
|
SetUserAgent(iosUserAgent(iosAppVersion)).
|
||||||
// URLSession default Accept-Encoding for data tasks.
|
// URLSession default Accept-Encoding for data tasks.
|
||||||
SetCommonHeader("Accept-Encoding", "gzip, deflate, br").
|
SetCommonHeader("Accept-Encoding", "gzip, deflate, br").
|
||||||
SetCommonHeader("Accept", "*/*").
|
SetCommonHeader("Accept", "*/*").
|
||||||
@@ -332,10 +349,10 @@ func newOneshotClient(proxyURL string) (*req.Client, error) {
|
|||||||
// Darwin stack emits (CFBundleName/CFBundleShortVersionString + CFNetwork
|
// Darwin stack emits (CFBundleName/CFBundleShortVersionString + CFNetwork
|
||||||
// + Darwin). Do NOT invent alternate formats (e.g. embedding the bundle
|
// + Darwin). Do NOT invent alternate formats (e.g. embedding the bundle
|
||||||
// ID) — mismatched UA + iOS TLS fingerprint is a cheap ban signal.
|
// ID) — mismatched UA + iOS TLS fingerprint is a cheap ban signal.
|
||||||
func iosUserAgent() string {
|
func iosUserAgent(appVersion string) string {
|
||||||
return fmt.Sprintf(
|
return fmt.Sprintf(
|
||||||
"DeepL/%s CFNetwork/%s Darwin/%s",
|
"DeepL/%s CFNetwork/%s Darwin/%s",
|
||||||
iosAppVersion, iosCFNetworkVersion, iosDarwinVersion,
|
appVersion, iosCFNetworkVersion, iosDarwinVersion,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -343,7 +360,9 @@ func iosUserAgent() string {
|
|||||||
// For anonymous traffic bearerToken is empty and we send the literal
|
// For anonymous traffic bearerToken is empty and we send the literal
|
||||||
// header `Authorization: None` — matching ItaClient.LoginNone. Omitting
|
// header `Authorization: None` — matching ItaClient.LoginNone. Omitting
|
||||||
// that header puts the request on a different server-side auth branch.
|
// that header puts the request on a different server-side auth branch.
|
||||||
func callOneshot(endpoint string, body []byte, bearerToken, proxyURL string) (gjson.Result, int, error) {
|
// appVersion is the value the request body advertises; the same value is
|
||||||
|
// echoed in the User-Agent so TLS, UA and app_information stay consistent.
|
||||||
|
func callOneshot(endpoint string, body []byte, bearerToken, proxyURL, appVersion string) (gjson.Result, int, error) {
|
||||||
client, err := getOneshotClient(proxyURL)
|
client, err := getOneshotClient(proxyURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return gjson.Result{}, 0, err
|
return gjson.Result{}, 0, err
|
||||||
@@ -359,6 +378,7 @@ func callOneshot(endpoint string, body []byte, bearerToken, proxyURL string) (gj
|
|||||||
DisableAutoReadResponse().
|
DisableAutoReadResponse().
|
||||||
SetHeader("Content-Type", "application/json").
|
SetHeader("Content-Type", "application/json").
|
||||||
SetHeader("Authorization", authValue).
|
SetHeader("Authorization", authValue).
|
||||||
|
SetHeader("User-Agent", iosUserAgent(appVersion)).
|
||||||
// ClientInfos.appHeaders (Util/ClientInfos.swift) — only these three
|
// ClientInfos.appHeaders (Util/ClientInfos.swift) — only these three
|
||||||
// x-app-* keys exist in the iOS binary.
|
// x-app-* keys exist in the iOS binary.
|
||||||
SetHeader("x-app-os-version", iosOSVersion).
|
SetHeader("x-app-os-version", iosOSVersion).
|
||||||
@@ -435,6 +455,10 @@ func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, pro
|
|||||||
// official v2 API does — ignored upstream.
|
// official v2 API does — ignored upstream.
|
||||||
_ = tagHandling
|
_ = tagHandling
|
||||||
|
|
||||||
|
// Resolve the advertised version once per request so the User-Agent and
|
||||||
|
// app_information always agree; the lookup itself is cached (appversion.go).
|
||||||
|
appVersion := currentIOSAppVersion()
|
||||||
|
|
||||||
reqStruct := oneshotRequest{
|
reqStruct := oneshotRequest{
|
||||||
Text: []string{text},
|
Text: []string{text},
|
||||||
TargetLang: resolvedTarget,
|
TargetLang: resolvedTarget,
|
||||||
@@ -444,7 +468,7 @@ func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, pro
|
|||||||
AppInformation: appInformation{
|
AppInformation: appInformation{
|
||||||
OS: "iOS",
|
OS: "iOS",
|
||||||
OSVersion: iosOSVersion,
|
OSVersion: iosOSVersion,
|
||||||
AppVersion: iosAppVersion,
|
AppVersion: appVersion,
|
||||||
AppBuild: iosAppBuild,
|
AppBuild: iosAppBuild,
|
||||||
InstanceID: instanceID,
|
InstanceID: instanceID,
|
||||||
},
|
},
|
||||||
@@ -457,7 +481,7 @@ func TranslateByDLX(sourceLang, targetLang, text string, tagHandling string, pro
|
|||||||
}
|
}
|
||||||
|
|
||||||
id := time.Now().UnixMilli()
|
id := time.Now().UnixMilli()
|
||||||
result, status, err := callOneshot(endpoint, bodyBytes, dlSession, proxyURL)
|
result, status, err := callOneshot(endpoint, bodyBytes, dlSession, proxyURL, appVersion)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// Map upstream timeouts to 504 so callers can distinguish "DeepL
|
// Map upstream timeouts to 504 so callers can distinguish "DeepL
|
||||||
// took too long" from other 503 failure modes (DNS, TLS, etc.).
|
// took too long" from other 503 failure modes (DNS, TLS, etc.).
|
||||||
|
|||||||
@@ -1,206 +0,0 @@
|
|||||||
package translate
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestResolveTargetLang(t *testing.T) {
|
|
||||||
cases := []struct {
|
|
||||||
name string
|
|
||||||
in string
|
|
||||||
want string
|
|
||||||
wantErr bool
|
|
||||||
errHas string
|
|
||||||
}{
|
|
||||||
{"lowercase normalizes to canonical", "zh-hans", "zh-Hans", false, ""},
|
|
||||||
{"uppercase ZH maps to Simplified", "ZH", "zh-Hans", false, ""},
|
|
||||||
{"EN convenience alias resolves to en-US", "EN", "en-US", false, ""},
|
|
||||||
{"PT convenience alias resolves to pt-BR", "PT", "pt-BR", false, ""},
|
|
||||||
{"regional EN-GB preserved", "en-gb", "en-GB", false, ""},
|
|
||||||
{"plain de", "de", "de", false, ""},
|
|
||||||
{"empty is required", "", "", true, "required"},
|
|
||||||
{"auto is rejected as a target", "auto", "", true, "cannot be"},
|
|
||||||
{"AUTO rejected case-insensitively", "AUTO", "", true, "cannot be"},
|
|
||||||
{"unsupported code is reported", "xx", "", true, "unsupported target_lang"},
|
|
||||||
}
|
|
||||||
for _, tc := range cases {
|
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
|
||||||
got, err := resolveTargetLang(tc.in)
|
|
||||||
if tc.wantErr {
|
|
||||||
if err == nil {
|
|
||||||
t.Fatalf("resolveTargetLang(%q) = %q, want error", tc.in, got)
|
|
||||||
}
|
|
||||||
if tc.errHas != "" && !strings.Contains(err.Error(), tc.errHas) {
|
|
||||||
t.Errorf("error %q does not contain %q", err.Error(), tc.errHas)
|
|
||||||
}
|
|
||||||
if got != "" {
|
|
||||||
t.Errorf("on error want empty result, got %q", got)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("resolveTargetLang(%q) unexpected error: %v", tc.in, err)
|
|
||||||
}
|
|
||||||
if got != tc.want {
|
|
||||||
t.Errorf("resolveTargetLang(%q) = %q, want %q", tc.in, got, tc.want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestResolveSourceLang(t *testing.T) {
|
|
||||||
cases := []struct {
|
|
||||||
name string
|
|
||||||
in string
|
|
||||||
want string
|
|
||||||
wantErr bool
|
|
||||||
}{
|
|
||||||
{"empty means autodetect", "", "", false},
|
|
||||||
{"auto means autodetect", "auto", "", false},
|
|
||||||
{"AUTO case-insensitive", "AUTO", "", false},
|
|
||||||
// EN/PT are first-class *source* codes and resolve to the generic
|
|
||||||
// form, unlike the target map which forces a regional default
|
|
||||||
// (EN -> en-US there). This asymmetry is easy to regress.
|
|
||||||
{"EN as source resolves to generic en", "EN", "en", false},
|
|
||||||
{"PT as source resolves to generic pt", "PT", "pt", false},
|
|
||||||
{"target-only code ZH is also a valid source", "ZH", "zh-Hans", false},
|
|
||||||
{"plain de", "de", "de", false},
|
|
||||||
{"unsupported code errors", "xx", "", true},
|
|
||||||
}
|
|
||||||
for _, tc := range cases {
|
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
|
||||||
got, err := resolveSourceLang(tc.in)
|
|
||||||
if tc.wantErr {
|
|
||||||
if err == nil {
|
|
||||||
t.Fatalf("resolveSourceLang(%q) = %q, want error", tc.in, got)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("resolveSourceLang(%q) unexpected error: %v", tc.in, err)
|
|
||||||
}
|
|
||||||
if got != tc.want {
|
|
||||||
t.Errorf("resolveSourceLang(%q) = %q, want %q", tc.in, got, tc.want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestTranslateByDeepLXPreflight exercises only the early-return validation
|
|
||||||
// paths that complete BEFORE any network I/O, so the suite stays hermetic.
|
|
||||||
func TestTranslateByDeepLXPreflight(t *testing.T) {
|
|
||||||
cases := []struct {
|
|
||||||
name string
|
|
||||||
source string
|
|
||||||
target string
|
|
||||||
text string
|
|
||||||
wantCode int
|
|
||||||
msgHas string
|
|
||||||
}{
|
|
||||||
{"empty text returns 404 (shipped contract)", "", "EN", "", http.StatusNotFound, "No text to translate"},
|
|
||||||
{"invalid target returns 400", "", "XX", "hello", http.StatusBadRequest, "unsupported target_lang"},
|
|
||||||
{"invalid source returns 400", "XX", "EN", "hello", http.StatusBadRequest, "unsupported source_lang"},
|
|
||||||
{"over-length ASCII returns 413", "", "EN", strings.Repeat("a", maxFreeTextLength+1), http.StatusRequestEntityTooLarge, "exceeds maximum length"},
|
|
||||||
// The cap counts runes, not bytes: 1501 multibyte runes is well over
|
|
||||||
// 1500 even though it is ~4500 bytes.
|
|
||||||
{"over-length multibyte counts runes returns 413", "", "EN", strings.Repeat("你", maxFreeTextLength+1), http.StatusRequestEntityTooLarge, "exceeds maximum length"},
|
|
||||||
}
|
|
||||||
for _, tc := range cases {
|
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
|
||||||
res, err := TranslateByDeepLX(tc.source, tc.target, tc.text, "", "", "")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
if res.Code != tc.wantCode {
|
|
||||||
t.Fatalf("Code = %d, want %d (message: %q)", res.Code, tc.wantCode, res.Message)
|
|
||||||
}
|
|
||||||
if tc.msgHas != "" && !strings.Contains(res.Message, tc.msgHas) {
|
|
||||||
t.Errorf("Message %q does not contain %q", res.Message, tc.msgHas)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var uuidV4Re = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`)
|
|
||||||
|
|
||||||
func TestNewInstanceIDIsUUIDv4(t *testing.T) {
|
|
||||||
for i := 0; i < 100; i++ {
|
|
||||||
id := newInstanceID()
|
|
||||||
if !uuidV4Re.MatchString(id) {
|
|
||||||
t.Fatalf("newInstanceID() = %q, not a valid RFC 4122 v4 UUID", id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// The process-wide instanceID must itself be a valid v4 UUID.
|
|
||||||
if !uuidV4Re.MatchString(instanceID) {
|
|
||||||
t.Errorf("package instanceID = %q, not a valid v4 UUID", instanceID)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestOneshotRequestJSONShape locks the serialized request body: the field
|
|
||||||
// order and omitempty behavior are reverse-engineered to be byte-identical
|
|
||||||
// to the Chrome extension, so a struct-field reorder or tag change is a
|
|
||||||
// silent WAF signal that this test turns into a failure.
|
|
||||||
func TestOneshotRequestJSONShape(t *testing.T) {
|
|
||||||
anon := oneshotRequest{
|
|
||||||
Text: []string{"hello"},
|
|
||||||
TargetLang: "de",
|
|
||||||
UsageType: "Translate",
|
|
||||||
AppInformation: appInformation{
|
|
||||||
OS: "brex_macOS",
|
|
||||||
OSVersion: "brex_chrome_" + impersonatedChromeMajor + ".0.0.0",
|
|
||||||
AppVersion: chromeExtensionVersion,
|
|
||||||
AppBuild: "chrome_web_store",
|
|
||||||
InstanceID: instanceID,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
b, err := json.Marshal(anon)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("marshal: %v", err)
|
|
||||||
}
|
|
||||||
s := string(b)
|
|
||||||
|
|
||||||
if strings.Contains(s, "source_lang") {
|
|
||||||
t.Errorf("source_lang must be omitted when empty, got %s", s)
|
|
||||||
}
|
|
||||||
for _, key := range []string{`"text"`, `"target_lang"`, `"usage_type"`, `"app_information"`, `"os_version"`, `"app_version"`, `"app_build"`, `"instance_id"`} {
|
|
||||||
if !strings.Contains(s, key) {
|
|
||||||
t.Errorf("missing expected key %s in %s", key, s)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// encoding/json emits struct fields in declaration order; the body
|
|
||||||
// contract depends on it.
|
|
||||||
assertOrder(t, s, `"text"`, `"target_lang"`, `"usage_type"`, `"app_information"`)
|
|
||||||
|
|
||||||
// os_version must track the pinned Chrome major so the TLS handshake,
|
|
||||||
// user-agent, and self-reported version all tell one consistent story.
|
|
||||||
if !strings.Contains(s, "brex_chrome_"+impersonatedChromeMajor+".0.0.0") {
|
|
||||||
t.Errorf("os_version should embed impersonatedChromeMajor %q; got %s", impersonatedChromeMajor, s)
|
|
||||||
}
|
|
||||||
|
|
||||||
// With a source language set, the field appears with its value.
|
|
||||||
withSrc := anon
|
|
||||||
withSrc.SourceLang = "en"
|
|
||||||
b2, _ := json.Marshal(withSrc)
|
|
||||||
if !strings.Contains(string(b2), `"source_lang":"en"`) {
|
|
||||||
t.Errorf("source_lang should be present when set, got %s", string(b2))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func assertOrder(t *testing.T, haystack string, needles ...string) {
|
|
||||||
t.Helper()
|
|
||||||
last := -1
|
|
||||||
for _, n := range needles {
|
|
||||||
idx := strings.Index(haystack, n)
|
|
||||||
if idx == -1 {
|
|
||||||
t.Fatalf("missing %s in %s", n, haystack)
|
|
||||||
}
|
|
||||||
if idx < last {
|
|
||||||
t.Fatalf("field %s appears out of order in %s", n, haystack)
|
|
||||||
}
|
|
||||||
last = idx
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user