Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 07c019c387 | |||
| 0f4518da45 | |||
| da4b521aba |
@ -1,28 +0,0 @@
|
||||
.git
|
||||
.github
|
||||
.gitignore
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.pyo
|
||||
*.egg-info/
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
.venv/
|
||||
venv/
|
||||
dist/
|
||||
build/
|
||||
packaging/
|
||||
windows.py
|
||||
icon.ico
|
||||
*.spec
|
||||
*.spec.bak
|
||||
*.manifest
|
||||
*.log
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
Desktop.ini
|
||||
20
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
20
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@ -1,20 +0,0 @@
|
||||
name: 🐛 Проблема
|
||||
title: '[Проблема] '
|
||||
description: Сообщить о проблеме
|
||||
labels: ['type: проблема', 'status: нуждается в сортировке']
|
||||
|
||||
body:
|
||||
- type: textarea
|
||||
id: description
|
||||
attributes:
|
||||
label: Опишите вашу проблему
|
||||
description: Чётко опишите проблему с которой вы столкнулись
|
||||
placeholder: Описание проблемы
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
id: additions
|
||||
attributes:
|
||||
label: Дополнительные детали
|
||||
description: Если у вас проблемы с работой прокси, то приложите файл логов в момент возникновения проблемы.
|
||||
439
.github/workflows/build.yml
vendored
439
.github/workflows/build.yml
vendored
@ -1,349 +1,160 @@
|
||||
name: Build & Release
|
||||
name: Build tg-ws-proxy
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
make_release:
|
||||
description: 'Create Github Release?'
|
||||
type: boolean
|
||||
required: true
|
||||
default: false
|
||||
version:
|
||||
description: "Release version tag (e.g. v1.0.0)"
|
||||
required: false
|
||||
default: "v1.0.0"
|
||||
release:
|
||||
types:
|
||||
- created
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build-windows:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Python
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: "pip"
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install .
|
||||
|
||||
- name: Install pyinstaller
|
||||
run: pip install "pyinstaller==6.13.0"
|
||||
|
||||
- name: Build EXE with PyInstaller
|
||||
run: pyinstaller packaging/windows.spec --noconfirm
|
||||
|
||||
- name: Rename artifact
|
||||
run: mv dist/TgWsProxy.exe dist/TgWsProxy_windows.exe
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: TgWsProxy
|
||||
path: dist/TgWsProxy_windows.exe
|
||||
|
||||
build-win7:
|
||||
runs-on: windows-latest
|
||||
build:
|
||||
runs-on: ubuntu-22.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: x64
|
||||
suffix: 64bit
|
||||
- arch: x86
|
||||
suffix: 32bit
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- arch: aarch64
|
||||
pkg_arch: aarch64-3.10
|
||||
goarch: arm64
|
||||
goarm: ""
|
||||
gomips: ""
|
||||
- arch: mipsel
|
||||
pkg_arch: mipsel-3.4
|
||||
goarch: mipsle
|
||||
goarm: ""
|
||||
gomips: softfloat
|
||||
- arch: mips
|
||||
pkg_arch: mips-3.4
|
||||
goarch: mips
|
||||
goarm: ""
|
||||
gomips: softfloat
|
||||
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: "3.8"
|
||||
architecture: ${{ matrix.arch }}
|
||||
cache: "pip"
|
||||
|
||||
- name: Install dependencies & pyinstaller
|
||||
run: pip install . "pyinstaller==5.13.2"
|
||||
|
||||
- name: Build EXE with PyInstaller
|
||||
run: pyinstaller packaging/windows.spec --noconfirm
|
||||
|
||||
- name: Rename artifact
|
||||
run: mv dist/TgWsProxy.exe dist/TgWsProxy_windows_7_${{ matrix.suffix }}.exe
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: TgWsProxy-win7-${{ matrix.suffix }}
|
||||
path: dist/TgWsProxy_windows_7_${{ matrix.suffix }}.exe
|
||||
|
||||
build-macos:
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Install universal2 Python
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: src/go.mod
|
||||
cache: true
|
||||
cache-dependency-path: src/go.sum
|
||||
|
||||
- name: Install build tools
|
||||
run: |
|
||||
set -euo pipefail
|
||||
curl -LO https://www.python.org/ftp/python/3.12.10/python-3.12.10-macos11.pkg
|
||||
sudo installer -pkg python-3.12.10-macos11.pkg -target /
|
||||
echo "/Library/Frameworks/Python.framework/Versions/3.12/bin" >> "$GITHUB_PATH"
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y dos2unix
|
||||
|
||||
- name: Install dependencies
|
||||
- name: Resolve project directory
|
||||
id: project-dir
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python3.12 -m pip install --upgrade pip setuptools wheel
|
||||
python3.12 -m pip install delocate==0.13.0
|
||||
|
||||
mkdir -p wheelhouse/arm64 wheelhouse/x86_64 wheelhouse/universal2
|
||||
|
||||
python3.12 -m pip download \
|
||||
--only-binary=:all: \
|
||||
--platform macosx_11_0_arm64 \
|
||||
--python-version 3.12 \
|
||||
--implementation cp \
|
||||
-d wheelhouse/arm64 \
|
||||
'cffi>=2.0.0' \
|
||||
Pillow==12.1.0 \
|
||||
psutil==7.0.0
|
||||
|
||||
python3.12 -m pip download \
|
||||
--only-binary=:all: \
|
||||
--platform macosx_10_13_x86_64 \
|
||||
--python-version 3.12 \
|
||||
--implementation cp \
|
||||
-d wheelhouse/x86_64 \
|
||||
'cffi>=2.0.0' \
|
||||
Pillow==12.1.0
|
||||
|
||||
python3.12 -m pip download \
|
||||
--only-binary=:all: \
|
||||
--platform macosx_10_9_x86_64 \
|
||||
--python-version 3.12 \
|
||||
--implementation cp \
|
||||
-d wheelhouse/x86_64 \
|
||||
psutil==7.0.0
|
||||
|
||||
delocate-merge \
|
||||
wheelhouse/arm64/cffi-*.whl \
|
||||
wheelhouse/x86_64/cffi-*.whl \
|
||||
-w wheelhouse/universal2
|
||||
|
||||
delocate-merge \
|
||||
wheelhouse/arm64/pillow-12.1.0-*.whl \
|
||||
wheelhouse/x86_64/pillow-12.1.0-*.whl \
|
||||
-w wheelhouse/universal2
|
||||
|
||||
delocate-merge \
|
||||
wheelhouse/arm64/psutil-7.0.0-*.whl \
|
||||
wheelhouse/x86_64/psutil-7.0.0-*.whl \
|
||||
-w wheelhouse/universal2
|
||||
|
||||
python3.12 -m pip install --no-deps wheelhouse/universal2/*.whl
|
||||
python3.12 -m pip install .
|
||||
python3.12 -m pip install pyinstaller==6.13.0
|
||||
|
||||
- name: Create macOS icon from ICO
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python3.12 - <<'PY'
|
||||
from PIL import Image
|
||||
|
||||
image = Image.open('icon.ico')
|
||||
image = image.resize((1024, 1024), Image.LANCZOS)
|
||||
image.save('icon_1024.png', 'PNG')
|
||||
PY
|
||||
|
||||
mkdir -p icon.iconset
|
||||
sips -z 16 16 icon_1024.png --out icon.iconset/icon_16x16.png
|
||||
sips -z 32 32 icon_1024.png --out icon.iconset/icon_16x16@2x.png
|
||||
sips -z 32 32 icon_1024.png --out icon.iconset/icon_32x32.png
|
||||
sips -z 64 64 icon_1024.png --out icon.iconset/icon_32x32@2x.png
|
||||
sips -z 128 128 icon_1024.png --out icon.iconset/icon_128x128.png
|
||||
sips -z 256 256 icon_1024.png --out icon.iconset/icon_128x128@2x.png
|
||||
sips -z 256 256 icon_1024.png --out icon.iconset/icon_256x256.png
|
||||
sips -z 512 512 icon_1024.png --out icon.iconset/icon_256x256@2x.png
|
||||
sips -z 512 512 icon_1024.png --out icon.iconset/icon_512x512.png
|
||||
sips -z 1024 1024 icon_1024.png --out icon.iconset/icon_512x512@2x.png
|
||||
iconutil -c icns icon.iconset -o icon.icns
|
||||
rm -rf icon.iconset icon_1024.png
|
||||
|
||||
- name: Build app with PyInstaller
|
||||
run: python3.12 -m PyInstaller packaging/macos.spec --noconfirm
|
||||
|
||||
- name: Validate universal2 app bundle
|
||||
run: |
|
||||
set -euo pipefail
|
||||
found=0
|
||||
while IFS= read -r -d '' file; do
|
||||
if file "$file" | grep -q "Mach-O"; then
|
||||
found=1
|
||||
archs="$(lipo -archs "$file" 2>/dev/null || true)"
|
||||
case "$archs" in
|
||||
*arm64*x86_64*|*x86_64*arm64*) ;;
|
||||
*)
|
||||
echo "Missing universal2 slices in $file: ${archs:-unknown}" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
done < <(find "dist/TG WS Proxy.app" -type f -print0)
|
||||
|
||||
if [ "$found" -eq 0 ]; then
|
||||
echo "No Mach-O files found in app bundle" >&2
|
||||
if [ -f tg-ws-proxy/Makefile ]; then
|
||||
echo "dir=tg-ws-proxy" >> "$GITHUB_OUTPUT"
|
||||
elif [ -f Makefile ] && [ -d common ] && [ -d .github/workflows ]; then
|
||||
echo "dir=." >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "Could not find tg-ws-proxy project directory"
|
||||
echo "Repository root content:"
|
||||
ls -la
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Create DMG
|
||||
- name: Build package
|
||||
run: |
|
||||
set -euo pipefail
|
||||
APP_NAME="TG WS Proxy"
|
||||
DMG_TEMP="dist/dmg_temp"
|
||||
|
||||
rm -rf "$DMG_TEMP"
|
||||
mkdir -p "$DMG_TEMP"
|
||||
cp -R "dist/${APP_NAME}.app" "$DMG_TEMP/"
|
||||
ln -s /Applications "$DMG_TEMP/Applications"
|
||||
|
||||
hdiutil create \
|
||||
-volname "$APP_NAME" \
|
||||
-srcfolder "$DMG_TEMP" \
|
||||
-ov \
|
||||
-format UDZO \
|
||||
"dist/TgWsProxy_macos_universal.dmg"
|
||||
|
||||
rm -rf "$DMG_TEMP"
|
||||
GOARCH_INPUT="${{ matrix.goarch }}"
|
||||
GOARM_INPUT="${{ matrix.goarm }}"
|
||||
GOMIPS_INPUT="${{ matrix.gomips }}"
|
||||
PKG_ARCH_INPUT="${{ matrix.pkg_arch }}"
|
||||
PROJECT_DIR="${{ steps.project-dir.outputs.dir }}"
|
||||
GO_PROXY_PATH="src"
|
||||
VERSION_INPUT="$(cat "$PROJECT_DIR/VERSION")"
|
||||
if [ -z "$VERSION_INPUT" ]; then
|
||||
echo "VERSION file is empty: $PROJECT_DIR/VERSION"
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -d "$PROJECT_DIR/$GO_PROXY_PATH" ]; then
|
||||
echo "src directory not found in project root"
|
||||
echo "Expected: $PROJECT_DIR/$GO_PROXY_PATH"
|
||||
ls -la "$PROJECT_DIR"
|
||||
exit 1
|
||||
fi
|
||||
make -C "$PROJECT_DIR" tg-ws-proxy-ipk PKG_ARCH="$PKG_ARCH_INPUT" GO_PROXY_DIR="$GO_PROXY_PATH" GOARCH="$GOARCH_INPUT" GOARM="$GOARM_INPUT" GOMIPS="$GOMIPS_INPUT"
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: TgWsProxy-macOS
|
||||
path: dist/TgWsProxy_macos_universal.dmg
|
||||
name: tg-ws-proxy-${{ matrix.arch }}
|
||||
path: ${{ steps.project-dir.outputs.dir }}/out/tg-ws-proxy_*_${{ matrix.pkg_arch }}.ipk
|
||||
if-no-files-found: error
|
||||
|
||||
build-linux:
|
||||
publish-latest-release:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [ build ]
|
||||
env:
|
||||
GH_REPO: ${{ github.repository }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
python3-venv \
|
||||
python3-dev \
|
||||
python3-gi \
|
||||
gir1.2-ayatanaappindicator3-0.1 \
|
||||
python3-tk
|
||||
|
||||
- name: Create venv with system site-packages
|
||||
run: python3 -m venv --system-site-packages .venv
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
.venv/bin/pip install --upgrade pip
|
||||
.venv/bin/pip install .
|
||||
.venv/bin/pip install "pyinstaller==6.13.0"
|
||||
|
||||
- name: Build binary with PyInstaller
|
||||
run: .venv/bin/pyinstaller packaging/linux.spec --noconfirm
|
||||
|
||||
- name: Rename binary artifact
|
||||
run: mv dist/TgWsProxy dist/TgWsProxy_linux_amd64
|
||||
|
||||
- name: Create .deb package
|
||||
run: |
|
||||
set -euo pipefail
|
||||
VERSION="${{ github.event.inputs.version }}"
|
||||
VERSION="${VERSION#v}"
|
||||
PKG_ROOT="pkg"
|
||||
|
||||
rm -rf "$PKG_ROOT"
|
||||
mkdir -p \
|
||||
"$PKG_ROOT/DEBIAN" \
|
||||
"$PKG_ROOT/usr/bin" \
|
||||
"$PKG_ROOT/usr/share/applications" \
|
||||
"$PKG_ROOT/usr/share/icons/hicolor/256x256/apps"
|
||||
|
||||
install -m 755 dist/TgWsProxy_linux_amd64 "$PKG_ROOT/usr/bin/tg-ws-proxy"
|
||||
|
||||
.venv/bin/python - <<PY
|
||||
from PIL import Image
|
||||
|
||||
Image.open("icon.ico").save(
|
||||
"${PKG_ROOT}/usr/share/icons/hicolor/256x256/apps/tg-ws-proxy.png",
|
||||
"PNG",
|
||||
)
|
||||
PY
|
||||
|
||||
cat > "$PKG_ROOT/usr/share/applications/tg-ws-proxy.desktop" <<EOF
|
||||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=TG WS Proxy
|
||||
GenericName=Telegram Proxy
|
||||
Comment=Telegram Desktop WebSocket Bridge Proxy
|
||||
Exec=tg-ws-proxy
|
||||
Icon=tg-ws-proxy
|
||||
Terminal=false
|
||||
Categories=Network;
|
||||
StartupNotify=true
|
||||
Keywords=telegram;proxy;websocket;
|
||||
EOF
|
||||
|
||||
cat > "$PKG_ROOT/DEBIAN/control" <<EOF
|
||||
Package: tg-ws-proxy
|
||||
Version: ${VERSION}
|
||||
Section: net
|
||||
Priority: optional
|
||||
Architecture: amd64
|
||||
Maintainer: Flowseal
|
||||
Depends: libgtk-3-0, libayatana-appindicator3-1, python3-tk
|
||||
Description: Telegram Desktop WebSocket Bridge Proxy
|
||||
MTProto/WebSocket bridge proxy for Telegram Desktop with tray UI.
|
||||
EOF
|
||||
|
||||
dpkg-deb --build --root-owner-group \
|
||||
"$PKG_ROOT" \
|
||||
"dist/TgWsProxy_linux_amd64.deb"
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v7
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: TgWsProxy-linux
|
||||
path: |
|
||||
dist/TgWsProxy_linux_amd64
|
||||
dist/TgWsProxy_linux_amd64.deb
|
||||
|
||||
release:
|
||||
needs: [build-windows, build-win7, build-macos, build-linux]
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.event.inputs.make_release == 'true' }}
|
||||
steps:
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: TgWsProxy*
|
||||
path: dist
|
||||
path: out
|
||||
merge-multiple: true
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
- name: Resolve latest target release
|
||||
id: target-release
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
tag_name: ${{ github.event.inputs.version }}
|
||||
name: "TG WS Proxy ${{ github.event.inputs.version }}"
|
||||
body: |
|
||||
## TG WS Proxy ${{ github.event.inputs.version }}
|
||||
files: |
|
||||
dist/TgWsProxy_windows.exe
|
||||
dist/TgWsProxy_windows_7_64bit.exe
|
||||
dist/TgWsProxy_windows_7_32bit.exe
|
||||
dist/TgWsProxy_macos_universal.dmg
|
||||
dist/TgWsProxy_linux_amd64
|
||||
dist/TgWsProxy_linux_amd64.deb
|
||||
draft: false
|
||||
prerelease: false
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const releases = await github.paginate(github.rest.repos.listReleases, {
|
||||
owner,
|
||||
repo,
|
||||
per_page: 100,
|
||||
});
|
||||
|
||||
const picked = releases.find((rel) => !rel.draft && !rel.prerelease);
|
||||
if (!picked) {
|
||||
core.setFailed('No release found to update');
|
||||
return;
|
||||
}
|
||||
|
||||
core.setOutput('id', String(picked.id));
|
||||
core.setOutput('tag', picked.tag_name);
|
||||
|
||||
- name: Remove previous ipk assets
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
RELEASE_ID: ${{ steps.target-release.outputs.id }}
|
||||
run: |
|
||||
gh api "repos/${{ github.repository }}/releases/${RELEASE_ID}/assets" \
|
||||
--jq '.[] | select(.name | test("^tg-ws-proxy.*\\.ipk$")) | .id' \
|
||||
| while read -r asset_id; do
|
||||
[ -n "$asset_id" ] || continue
|
||||
gh api -X DELETE "repos/${{ github.repository }}/releases/assets/${asset_id}"
|
||||
done
|
||||
|
||||
- name: Upload new ipk assets to latest release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
TAG: ${{ steps.target-release.outputs.tag }}
|
||||
run: |
|
||||
mapfile -t files < <(find out -type f -name 'tg-ws-proxy_*.ipk' | sort)
|
||||
if [ ${#files[@]} -eq 0 ]; then
|
||||
echo "No ipk files found"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf '%s\n' "${files[@]}"
|
||||
gh release upload "$TAG" "${files[@]}" --clobber
|
||||
|
||||
- name: Dispatch to feedly
|
||||
if: success()
|
||||
run: |
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: token ${{ secrets.AGGREGATOR_PAT }}" \
|
||||
-H "X-GitHub-Api-Version: 2022-11-28" \
|
||||
https://api.github.com/repos/spatiumstas/feedly/dispatches \
|
||||
-d '{"event_type":"package-built","client_payload":{"package":"'"${{ github.repository }}"'","channel":"release","tag":"'"${{ steps.target-release.outputs.tag }}"'"}}'
|
||||
30
.gitignore
vendored
30
.gitignore
vendored
@ -1,30 +0,0 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.pyo
|
||||
*.egg-info/
|
||||
dist/
|
||||
build/
|
||||
*.spec.bak
|
||||
|
||||
# PyInstaller
|
||||
*.manifest
|
||||
*.log
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# OS
|
||||
Thumbs.db
|
||||
Desktop.ini
|
||||
.DS_Store
|
||||
|
||||
# Project-specific (not for the repo)
|
||||
scan_ips.py
|
||||
scan.txt
|
||||
AyuGramDesktop-dev/
|
||||
tweb-master/
|
||||
/icon.icns
|
||||
45
Dockerfile
45
Dockerfile
@ -1,45 +0,0 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
|
||||
FROM python:3.12-slim AS builder
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
||||
PIP_NO_CACHE_DIR=1 \
|
||||
VIRTUAL_ENV=/opt/venv
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends build-essential cargo libffi-dev libssl-dev \
|
||||
&& python -m venv "$VIRTUAL_ENV" \
|
||||
&& "$VIRTUAL_ENV/bin/pip" install --upgrade pip setuptools wheel \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
RUN "$VIRTUAL_ENV/bin/pip" install cryptography==46.0.5
|
||||
|
||||
FROM python:3.12-slim AS runtime
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PATH=/opt/venv/bin:$PATH \
|
||||
TG_WS_PROXY_HOST=0.0.0.0 \
|
||||
TG_WS_PROXY_PORT=1443 \
|
||||
TG_WS_PROXY_DC_IPS="2:149.154.167.220 4:149.154.167.220"
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends tini ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& groupadd --system app \
|
||||
&& useradd --system --gid app --create-home --home-dir /home/app app
|
||||
|
||||
WORKDIR /app
|
||||
COPY --from=builder /opt/venv /opt/venv
|
||||
COPY proxy ./proxy
|
||||
COPY README.md LICENSE ./
|
||||
|
||||
USER app
|
||||
|
||||
EXPOSE 1443/tcp
|
||||
|
||||
ENTRYPOINT ["/usr/bin/tini", "--", "/bin/sh", "-lc", "set -eu; args=\"--host ${TG_WS_PROXY_HOST} --port ${TG_WS_PROXY_PORT}\"; for dc in ${TG_WS_PROXY_DC_IPS}; do args=\"$args --dc-ip $dc\"; done; exec python -u proxy/tg_ws_proxy.py $args \"$@\"", "--"]
|
||||
CMD []
|
||||
21
LICENSE
21
LICENSE
@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Flowseal
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
90
Makefile
Normal file
90
Makefile
Normal file
@ -0,0 +1,90 @@
|
||||
SHELL := /bin/bash
|
||||
PACKAGE := tg-ws-proxy
|
||||
ROOT_DIR := /opt
|
||||
DEPENDENCIES := ca-certificates xxd
|
||||
GOOS ?= linux
|
||||
GOARCH ?= arm64
|
||||
GOARM ?=
|
||||
GOMIPS ?=
|
||||
CGO_ENABLED ?= 0
|
||||
GO_PROXY_DIR ?= src
|
||||
GO_BIN_NAME ?= tg-ws-proxy
|
||||
GO_BIN ?= out/$(GO_BIN_NAME)-$(GOARCH)
|
||||
|
||||
DEFAULT_PKG_ARCH := $(GOARCH)
|
||||
ifeq ($(GOARCH),amd64)
|
||||
DEFAULT_PKG_ARCH := x64
|
||||
endif
|
||||
ifeq ($(GOARCH),arm64)
|
||||
DEFAULT_PKG_ARCH := aarch64
|
||||
endif
|
||||
ifeq ($(GOARCH),arm)
|
||||
ifeq ($(GOARM),7)
|
||||
DEFAULT_PKG_ARCH := armv7
|
||||
else
|
||||
DEFAULT_PKG_ARCH := arm
|
||||
endif
|
||||
endif
|
||||
ifeq ($(GOARCH),mipsle)
|
||||
DEFAULT_PKG_ARCH := mipsel
|
||||
endif
|
||||
|
||||
PKG_ARCH ?= $(DEFAULT_PKG_ARCH)
|
||||
VERSION := $(shell cat VERSION)
|
||||
|
||||
.PHONY: clean _build-go _pkg-clean _pkg-control _pkg-scripts _pkg-data _pkg-ipk tg-ws-proxy-ipk
|
||||
|
||||
clean:
|
||||
rm -rf out
|
||||
|
||||
_build-go:
|
||||
mkdir -p out
|
||||
cd "$(GO_PROXY_DIR)" && \
|
||||
GOOS=$(GOOS) GOARCH=$(GOARCH) GOARM=$(GOARM) GOMIPS=$(GOMIPS) CGO_ENABLED=$(CGO_ENABLED) \
|
||||
go build -o "$(abspath $(GO_BIN))" .
|
||||
echo "$(VERSION)" > out/VERSION
|
||||
|
||||
_pkg-clean:
|
||||
rm -rf out/pkg
|
||||
mkdir -p out/pkg/control
|
||||
mkdir -p out/pkg/data
|
||||
|
||||
_pkg-control:
|
||||
version="$$(cat out/VERSION)"; \
|
||||
echo "Package: $(PACKAGE)" > out/pkg/control/control; \
|
||||
echo "Version: $$version-1" >> out/pkg/control/control; \
|
||||
echo "Depends: $(DEPENDENCIES)" >> out/pkg/control/control; \
|
||||
echo "Section: net" >> out/pkg/control/control; \
|
||||
echo "Architecture: $(PKG_ARCH)" >> out/pkg/control/control; \
|
||||
echo "License: MIT" >> out/pkg/control/control; \
|
||||
echo "Description: Telegram MTProto WS bridge proxy (Go binary)" >> out/pkg/control/control
|
||||
|
||||
_pkg-scripts:
|
||||
cp common/ipk/prerm out/pkg/control/prerm
|
||||
cp common/ipk/postinst out/pkg/control/postinst
|
||||
cp common/ipk/postrm out/pkg/control/postrm
|
||||
cp common/ipk/conffiles out/pkg/control/conffiles
|
||||
find out/pkg/control -type f -print0 | xargs -0 dos2unix
|
||||
chmod +x out/pkg/control/prerm out/pkg/control/postinst out/pkg/control/postrm
|
||||
|
||||
_pkg-data:
|
||||
mkdir -p out/pkg/data$(ROOT_DIR)/etc/init.d
|
||||
mkdir -p out/pkg/data$(ROOT_DIR)/etc
|
||||
mkdir -p out/pkg/data$(ROOT_DIR)/bin
|
||||
cp "$(GO_BIN)" out/pkg/data$(ROOT_DIR)/bin/tg-ws-proxy
|
||||
cat common/tg-ws-proxy-common.sh > out/pkg/data$(ROOT_DIR)/etc/init.d/S61tg-ws-proxy
|
||||
awk '/^start\(\)/{p=1} p{print}' common/S61tg-ws-proxy >> out/pkg/data$(ROOT_DIR)/etc/init.d/S61tg-ws-proxy
|
||||
cp common/tg-ws-proxy.conf out/pkg/data$(ROOT_DIR)/etc/tg-ws-proxy.conf
|
||||
find out/pkg/data -type f -print0 | xargs -0 dos2unix
|
||||
chmod +x out/pkg/data$(ROOT_DIR)/bin/tg-ws-proxy
|
||||
chmod +x out/pkg/data$(ROOT_DIR)/etc/init.d/S61tg-ws-proxy
|
||||
|
||||
_pkg-ipk: _pkg-clean _pkg-control _pkg-scripts _pkg-data
|
||||
cd out/pkg/control; tar czf ../control.tar.gz .; cd ../../..
|
||||
cd out/pkg/data; tar czf ../data.tar.gz .; cd ../../..
|
||||
echo 2.0 > out/pkg/debian-binary
|
||||
version="$$(cat out/VERSION)"; \
|
||||
cd out/pkg; tar czf ../$(PACKAGE)_$$version-1_$(PKG_ARCH).ipk control.tar.gz data.tar.gz debian-binary; cd ../..
|
||||
|
||||
tg-ws-proxy-ipk: _build-go _pkg-ipk
|
||||
@echo "Built: out/$(PACKAGE)_$$(cat out/VERSION)-1_$(PKG_ARCH).ipk"
|
||||
242
README.md
242
README.md
@ -1,222 +1,76 @@
|
||||
> [!CAUTION]
|
||||
>
|
||||
> ### Реакция антивирусов
|
||||
>
|
||||
> Windows Defender часто ошибочно помечает приложение как **Wacatac**.
|
||||
> Если вы не можете скачать из-за блокировки, то:
|
||||
>
|
||||
> 1) Попробуйте скачать версию win7 (она ничем не отличается в плане функционала)
|
||||
> 2) Отключите антивирус на время скачивания, добавьте файл в исключения и включите обратно
|
||||
>
|
||||
> **Всегда проверяйте, что скачиваете из интернета, тем более из непроверенных источников. Всегда лучше смотреть на детекты широко известных антивирусов на VirusTotal**
|
||||
# TG WS Proxy Go (KeeneticOS)
|
||||
|
||||
# TG WS Proxy
|
||||
|
||||
**Локальный MTProto-прокси** для Telegram Desktop, который **ускоряет работу Telegram**, перенаправляя трафик через WebSocket-соединения. Данные передаются в том же зашифрованном виде, а для работы не нужны сторонние сервера.
|
||||
|
||||
<img width="529" height="487" alt="image" src="https://github.com/user-attachments/assets/6a4cf683-0df8-43af-86c1-0e8f08682b62" />
|
||||
|
||||
## Как это работает
|
||||
### Install
|
||||
|
||||
Repository:
|
||||
```shell
|
||||
curl -fsSL https://raw.githubusercontent.com/spatiumstas/feedly/main/add-repo.sh | sh
|
||||
```
|
||||
Telegram Desktop → MTProto Proxy (127.0.0.1:1443) → WebSocket → Telegram DC
|
||||
Package:
|
||||
```shell
|
||||
opkg install tg-ws-proxy
|
||||
```
|
||||
|
||||
1. Приложение поднимает MTProto прокси на `127.0.0.1:1443`
|
||||
2. Перехватывает подключения к IP-адресам Telegram
|
||||
3. Извлекает DC ID из MTProto obfuscation init-пакета
|
||||
4. Устанавливает WebSocket (TLS) соединение к соответствующему DC через домены Telegram
|
||||
5. Если WS недоступен (302 redirect) — автоматически переключается на прямое TCP-соединение
|
||||
### Config
|
||||
|
||||
## 🚀 Быстрый старт
|
||||
|
||||
### Windows
|
||||
|
||||
Перейдите на [страницу релизов](https://github.com/Flowseal/tg-ws-proxy/releases) и скачайте **`TgWsProxy_windows.exe`**. Он собирается автоматически через [Github Actions](https://github.com/Flowseal/tg-ws-proxy/actions) из открытого исходного кода.
|
||||
|
||||
При первом запуске откроется окно с инструкцией по подключению Telegram Desktop. Приложение сворачивается в системный трей.
|
||||
|
||||
**Меню трея:**
|
||||
|
||||
- **Открыть в Telegram** — автоматически настроить прокси через `tg://proxy` ссылку
|
||||
- **Перезапустить прокси** — перезапуск без выхода из приложения
|
||||
- **Настройки...** — GUI-редактор конфигурации (в т.ч. версия приложения, опциональная проверка обновлений с GitHub)
|
||||
- **Открыть логи** — открыть файл логов
|
||||
- **Выход** — остановить прокси и закрыть приложение
|
||||
|
||||
При первом запуске после старта может появиться запрос об открытии страницы релиза, если на GitHub вышла новая версия (отключается в настройках).
|
||||
|
||||
### macOS
|
||||
|
||||
Перейдите на [страницу релизов](https://github.com/Flowseal/tg-ws-proxy/releases) и скачайте **`TgWsProxy_macos_universal.dmg`** — универсальная сборка для Apple Silicon и Intel.
|
||||
|
||||
1. Открыть образ
|
||||
2. Перенести **TG WS Proxy.app** в папку **Applications**
|
||||
3. При первом запуске macOS может попросить подтвердить открытие: **Системные настройки → Конфиденциальность и безопасность → Всё равно открыть**
|
||||
|
||||
### Linux
|
||||
|
||||
Для Debian/Ubuntu скачайте со [страницы релизов](https://github.com/Flowseal/tg-ws-proxy/releases) пакет **`TgWsProxy_linux_amd64.deb`**.
|
||||
|
||||
Для Arch и Arch-Based дистрибутивов подготовлены пакеты в AUR: [tg-ws-proxy-bin](https://aur.archlinux.org/packages/tg-ws-proxy-bin), [tg-ws-proxy-git](https://aur.archlinux.org/packages/tg-ws-proxy-git), [tg-ws-proxy-cli](https://aur.archlinux.org/packages/tg-ws-proxy-cli)
|
||||
Main config file:
|
||||
|
||||
```shell
|
||||
# Установка без AUR-helper
|
||||
git clone https://aur.archlinux.org/tg-ws-proxy-bin.git
|
||||
cd tg-ws-proxy-bin
|
||||
makepkg -si
|
||||
|
||||
# При помощи AUR-helper
|
||||
paru -S tg-ws-proxy-bin
|
||||
|
||||
# Если вы установили -cli пакет, то запуск осуществляется через systemctl, где 8888 это номер порта прокси:
|
||||
sudo systemctl start tg-ws-proxy-cli@8888
|
||||
/opt/etc/tg-ws-proxy.conf
|
||||
```
|
||||
|
||||
Для остальных дистрибутивов можно использовать **`TgWsProxy_linux_amd64`** (бинарный файл для x86_64).
|
||||
Minimal config example:
|
||||
|
||||
```bash
|
||||
chmod +x TgWsProxy_linux_amd64
|
||||
./TgWsProxy_linux_amd64
|
||||
```conf
|
||||
HOST=0.0.0.0
|
||||
PORT=1443
|
||||
SECRET=
|
||||
LOG_LEVEL=0
|
||||
DC_IP_DEFAULT=149.154.167.220
|
||||
DC_IP_DEFAULT_POOL=""
|
||||
EXTRA_ARGS=""
|
||||
```
|
||||
|
||||
При первом запуске откроется окно с инструкцией. Приложение работает в системном трее (требуется AppIndicator).
|
||||
> Notes:
|
||||
|
||||
## Установка из исходников
|
||||
1. `SECRET` must be 32 hex chars. If empty, it is auto-generated during install.
|
||||
2. `DC_IP_DEFAULT` and `DC_IP_DEFAULT_POOL` are global defaults for implicit DC map (`2,4`).
|
||||
3. `EXTRA_ARGS` is for per-DC overrides and extra runtime flags.
|
||||
|
||||
### Консольный proxy
|
||||
Override examples:
|
||||
|
||||
Для запуска только proxy без tray-интерфейса достаточно базовой установки:
|
||||
```conf
|
||||
# Per-DC pool override (DC2)
|
||||
EXTRA_ARGS="--dc-ip-pool 2:149.154.175.50,149.154.167.220"
|
||||
|
||||
```bash
|
||||
pip install -e .
|
||||
tg-ws-proxy
|
||||
# Per-DC single IP override (DC203) + verbose logs
|
||||
EXTRA_ARGS="--dc-ip 203:91.105.192.100 -v"
|
||||
```
|
||||
|
||||
### Windows 7/10+
|
||||
### Run
|
||||
|
||||
```bash
|
||||
pip install -e .
|
||||
tg-ws-proxy-tray-win
|
||||
```shell
|
||||
/opt/etc/init.d/S61tg-ws-proxy start
|
||||
/opt/etc/init.d/S61tg-ws-proxy status
|
||||
/opt/etc/init.d/S61tg-ws-proxy restart
|
||||
/opt/etc/init.d/S61tg-ws-proxy stop
|
||||
```
|
||||
|
||||
### macOS
|
||||
### Logs
|
||||
|
||||
```bash
|
||||
pip install -e .
|
||||
tg-ws-proxy-tray-macos
|
||||
If `LOG_LEVEL=1`, service logs are written to:
|
||||
|
||||
```shell
|
||||
/opt/var/log/tg-ws-proxy.log
|
||||
```
|
||||
|
||||
### Linux
|
||||
### Remove
|
||||
|
||||
```bash
|
||||
pip install -e .
|
||||
tg-ws-proxy-tray-linux
|
||||
```shell
|
||||
opkg remove tg-ws-proxy
|
||||
```
|
||||
|
||||
### Консольный режим из исходников
|
||||
|
||||
```bash
|
||||
tg-ws-proxy [--port PORT] [--host HOST] [--dc-ip DC:IP ...] [-v]
|
||||
```
|
||||
|
||||
**Аргументы:**
|
||||
|
||||
| Аргумент | По умолчанию | Описание |
|
||||
|---|---|---|
|
||||
| `--port` | `1443` | Порт прокси |
|
||||
| `--host` | `127.0.0.1` | Хост прокси |
|
||||
| `--secret` | `random` | 32 hex chars secret для авторизации клиентов |
|
||||
| `--dc-ip` | `2:149.154.167.220`, `4:149.154.167.220` | Целевой IP для DC (можно указать несколько раз) |
|
||||
| `--buf-kb` | `256` | Размер буфера в КБ
|
||||
| `--pool-size` | `4` | Количество заготовленных соединений на каждый DC
|
||||
| `--log-file` | выкл. | Путь до файла, в который сохранять логи
|
||||
| `--log-max-mb` | `5` | Максимальный размер файла логов в МБ (после идёт перезапись)
|
||||
| `--log-backups` | `0` | Количество сохранений логов после перезаписи
|
||||
| `-v`, `--verbose` | выкл. | Подробное логирование (DEBUG) |
|
||||
|
||||
**Примеры:**
|
||||
|
||||
```bash
|
||||
# Стандартный запуск
|
||||
tg-ws-proxy
|
||||
|
||||
# Другой порт и дополнительные DC
|
||||
tg-ws-proxy --port 9050 --dc-ip 1:149.154.175.205 --dc-ip 2:149.154.167.220
|
||||
|
||||
# С подробным логированием
|
||||
tg-ws-proxy -v
|
||||
```
|
||||
|
||||
## CLI-скрипты (pyproject.toml)
|
||||
|
||||
CLI команды объявляются в `pyproject.toml` в секции `[project.scripts]` и должны указывать на `module:function`.
|
||||
|
||||
Пример:
|
||||
|
||||
```toml
|
||||
[project.scripts]
|
||||
tg-ws-proxy = "proxy.tg_ws_proxy:main"
|
||||
tg-ws-proxy-tray-win = "windows:main"
|
||||
tg-ws-proxy-tray-macos = "macos:main"
|
||||
tg-ws-proxy-tray-linux = "linux:main"
|
||||
```
|
||||
|
||||
## Настройка Telegram Desktop
|
||||
|
||||
### Автоматически
|
||||
|
||||
ПКМ по иконке в трее → **«Открыть в Telegram»**
|
||||
|
||||
### Вручную
|
||||
|
||||
1. Telegram → **Настройки** → **Продвинутые настройки** → **Тип подключения** → **Прокси**
|
||||
2. Добавить прокси:
|
||||
- **Тип:** MTProto
|
||||
- **Сервер:** `127.0.0.1` (или переопределенный вами)
|
||||
- **Порт:** `1443` (или переопределенный вами)
|
||||
- **Secret:** из настроек или логов
|
||||
|
||||
## Конфигурация
|
||||
|
||||
Tray-приложение хранит данные в:
|
||||
|
||||
- **Windows:** `%APPDATA%/TgWsProxy`
|
||||
- **macOS:** `~/Library/Application Support/TgWsProxy`
|
||||
- **Linux:** `~/.config/TgWsProxy` (или `$XDG_CONFIG_HOME/TgWsProxy`)
|
||||
|
||||
```json
|
||||
{
|
||||
"host": "127.0.0.1",
|
||||
"port": 1443,
|
||||
"secret": "...",
|
||||
"dc_ip": [
|
||||
"2:149.154.167.220",
|
||||
"4:149.154.167.220"
|
||||
],
|
||||
"verbose": false,
|
||||
"buf_kb": 256,
|
||||
"pool_size": 4,
|
||||
"log_max_mb": 5.0,
|
||||
"check_updates": true
|
||||
}
|
||||
```
|
||||
|
||||
Ключ **`check_updates`** — при `true` при запросе к GitHub сравнивается версия с последним релизом (только уведомление и ссылка на страницу загрузки). На Windows в конфиге может быть **`autostart`** (автозапуск при входе в систему).
|
||||
|
||||
## Автоматическая сборка
|
||||
|
||||
Проект содержит спецификации PyInstaller ([`packaging/windows.spec`](packaging/windows.spec), [`packaging/macos.spec`](packaging/macos.spec), [`packaging/linux.spec`](packaging/linux.spec)) и GitHub Actions workflow ([`.github/workflows/build.yml`](.github/workflows/build.yml)) для автоматической сборки.
|
||||
|
||||
Минимально поддерживаемые версии ОС для текущих бинарных сборок:
|
||||
|
||||
- Windows 10+ для `TgWsProxy_windows.exe`
|
||||
- Windows 7 (x64) для `TgWsProxy_windows_7_64bit.exe`
|
||||
- Windows 7 (x32) для `TgWsProxy_windows_7_32bit.exe`
|
||||
- Intel macOS 10.15+
|
||||
- Apple Silicon macOS 11.0+
|
||||
- Linux x86_64 (требуется AppIndicator для системного трея)
|
||||
|
||||
## Лицензия
|
||||
|
||||
[MIT License](LICENSE)
|
||||
### Remove repository
|
||||
```shell
|
||||
rm /opt/etc/opkg/feedly.conf
|
||||
```
|
||||
107
common/S61tg-ws-proxy
Normal file
107
common/S61tg-ws-proxy
Normal file
@ -0,0 +1,107 @@
|
||||
#!/bin/sh
|
||||
|
||||
COMMON_FILE=/opt/etc/init.d/tg-ws-proxy-common.sh
|
||||
|
||||
if [ ! -f "$COMMON_FILE" ]; then
|
||||
echo "Missing common script: $COMMON_FILE" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
. "$COMMON_FILE"
|
||||
|
||||
start() {
|
||||
[ -x "$BIN" ] || return 1
|
||||
mkdir -p /opt/var/run /opt/var/log
|
||||
if [ ! -f "$CONFFILE" ]; then
|
||||
echo "Config file not found: $CONFFILE" >&2
|
||||
return 1
|
||||
fi
|
||||
if [ -z "$SECRET" ]; then
|
||||
echo "SECRET is empty in $CONFFILE" >&2
|
||||
return 1
|
||||
fi
|
||||
if [ -z "$DC_IP_DEFAULT" ]; then
|
||||
echo "DC_IP_DEFAULT is empty in $CONFFILE" >&2
|
||||
return 1
|
||||
fi
|
||||
cleanup_stale_pid
|
||||
if is_running; then
|
||||
echo "tg-ws-proxy already running"
|
||||
return 0
|
||||
fi
|
||||
if [ "$LOG_LEVEL" = "1" ]; then
|
||||
"$BIN" --host "$HOST" --port "$PORT" --secret "$SECRET" --dc-ip-default "$DC_IP_DEFAULT" --dc-ip-default-pool "$DC_IP_DEFAULT_POOL" $EXTRA_ARGS >>"$LOGFILE" 2>&1 &
|
||||
else
|
||||
"$BIN" --host "$HOST" --port "$PORT" --secret "$SECRET" --dc-ip-default "$DC_IP_DEFAULT" --dc-ip-default-pool "$DC_IP_DEFAULT_POOL" $EXTRA_ARGS >/dev/null 2>&1 &
|
||||
fi
|
||||
echo $! > "$PIDFILE"
|
||||
|
||||
i=0
|
||||
while [ "$i" -lt 5 ]; do
|
||||
if is_running; then
|
||||
echo "tg-ws-proxy started"
|
||||
print_connect_link || true
|
||||
return 0
|
||||
fi
|
||||
i=$((i + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
echo "tg-ws-proxy failed to start" >&2
|
||||
cleanup_stale_pid
|
||||
if [ -f "$LOGFILE" ]; then
|
||||
tail -n 20 "$LOGFILE" >&2 || true
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
stop() {
|
||||
cleanup_stale_pid
|
||||
if ! is_running; then
|
||||
echo "tg-ws-proxy is not running"
|
||||
return 0
|
||||
fi
|
||||
|
||||
pid="$(get_pid)"
|
||||
kill "$pid" 2>/dev/null || true
|
||||
|
||||
i=0
|
||||
while [ "$i" -lt 5 ]; do
|
||||
if ! kill -0 "$pid" 2>/dev/null; then
|
||||
rm -f "$PIDFILE"
|
||||
echo "tg-ws-proxy stopped"
|
||||
return 0
|
||||
fi
|
||||
i=$((i + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
kill -9 "$pid" 2>/dev/null || true
|
||||
rm -f "$PIDFILE"
|
||||
echo "tg-ws-proxy force stopped"
|
||||
return 0
|
||||
}
|
||||
|
||||
status() {
|
||||
cleanup_stale_pid
|
||||
if is_running; then
|
||||
echo "tg-ws-proxy is running (pid $(get_pid))"
|
||||
print_connect_link || true
|
||||
return 0
|
||||
fi
|
||||
echo "tg-ws-proxy is not running"
|
||||
return 1
|
||||
}
|
||||
|
||||
restart() {
|
||||
stop
|
||||
start
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
start) start ;;
|
||||
stop) stop ;;
|
||||
restart) restart ;;
|
||||
status) status ;;
|
||||
*) echo "Usage: $0 {start|stop|restart|status}"; exit 1 ;;
|
||||
esac
|
||||
1
common/ipk/conffiles
Normal file
1
common/ipk/conffiles
Normal file
@ -0,0 +1 @@
|
||||
/opt/etc/tg-ws-proxy.conf
|
||||
27
common/ipk/postinst
Normal file
27
common/ipk/postinst
Normal file
@ -0,0 +1,27 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
chmod +x /opt/bin/tg-ws-proxy || true
|
||||
chmod +x /opt/etc/init.d/S61tg-ws-proxy || true
|
||||
|
||||
CONFFILE=/opt/etc/tg-ws-proxy.conf
|
||||
INIT_SCRIPT=/opt/etc/init.d/S61tg-ws-proxy
|
||||
|
||||
if [ -f "$CONFFILE" ]; then
|
||||
. "$CONFFILE" || true
|
||||
if [ -z "${SECRET:-}" ]; then
|
||||
secret="$(head -c 16 /dev/urandom | xxd -ps 2>/dev/null | tr -d ' \r\n')"
|
||||
if [ "${#secret}" -eq 32 ]; then
|
||||
if grep -Eq '^[[:space:]]*SECRET=' "$CONFFILE"; then
|
||||
sed -i "s|^[[:space:]]*SECRET=.*$|SECRET=$secret|" "$CONFFILE"
|
||||
else
|
||||
printf '\nSECRET=%s\n' "$secret" >> "$CONFFILE"
|
||||
fi
|
||||
echo "Generated SECRET in $CONFFILE"
|
||||
else
|
||||
echo "WARNING: failed to generate SECRET automatically" >&2
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
"$INIT_SCRIPT" restart || true
|
||||
9
common/ipk/postrm
Normal file
9
common/ipk/postrm
Normal file
@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
[ "${PKG_UPGRADE}" = "1" ] && exit 0
|
||||
|
||||
rm -f /opt/bin/tg-ws-proxy
|
||||
rm -f /opt/etc/init.d/S61tg-ws-proxy
|
||||
|
||||
echo "tg-ws-proxy removed"
|
||||
13
common/ipk/prerm
Normal file
13
common/ipk/prerm
Normal file
@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
|
||||
INIT_SCRIPT="/opt/etc/init.d/S61tg-ws-proxy"
|
||||
|
||||
stop_func() {
|
||||
if [ -f "$INIT_SCRIPT" ]; then
|
||||
"$INIT_SCRIPT" stop
|
||||
fi
|
||||
}
|
||||
|
||||
stop_func
|
||||
|
||||
exit 0
|
||||
104
common/tg-ws-proxy-common.sh
Normal file
104
common/tg-ws-proxy-common.sh
Normal file
@ -0,0 +1,104 @@
|
||||
#!/bin/sh
|
||||
|
||||
PATH=/opt/sbin:/opt/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
||||
|
||||
PIDFILE=/opt/var/run/tg-ws-proxy.pid
|
||||
LOGFILE=/opt/var/log/tg-ws-proxy.log
|
||||
BIN=/opt/bin/tg-ws-proxy
|
||||
CONFFILE=/opt/etc/tg-ws-proxy.conf
|
||||
|
||||
if [ -f "$CONFFILE" ]; then
|
||||
. "$CONFFILE"
|
||||
fi
|
||||
|
||||
get_pid() {
|
||||
[ -f "$PIDFILE" ] || return 1
|
||||
pid="$(cat "$PIDFILE" 2>/dev/null)"
|
||||
case "$pid" in
|
||||
''|*[!0-9]*) return 1 ;;
|
||||
esac
|
||||
echo "$pid"
|
||||
}
|
||||
|
||||
is_running() {
|
||||
pid_saved="$(get_pid)" || return 1
|
||||
if ! kill -0 "$pid_saved" 2>/dev/null; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
cmdline_file="/proc/$pid_saved/cmdline"
|
||||
[ -r "$cmdline_file" ] || return 1
|
||||
cmdline="$(tr '\000' ' ' < "$cmdline_file")"
|
||||
|
||||
case "$cmdline" in
|
||||
*"$BIN"*) return 0 ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
cleanup_stale_pid() {
|
||||
if [ -f "$PIDFILE" ] && ! is_running; then
|
||||
rm -f "$PIDFILE"
|
||||
fi
|
||||
}
|
||||
|
||||
load_runtime_args_from_pid() {
|
||||
pid="$(get_pid)" || return 1
|
||||
cmdline_file="/proc/$pid/cmdline"
|
||||
[ -r "$cmdline_file" ] || return 1
|
||||
|
||||
rt_host=""
|
||||
rt_port=""
|
||||
rt_secret=""
|
||||
|
||||
set -- $(tr '\000' ' ' < "$cmdline_file")
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
--host)
|
||||
rt_host="$2"
|
||||
shift 2
|
||||
;;
|
||||
--port)
|
||||
rt_port="$2"
|
||||
shift 2
|
||||
;;
|
||||
--secret)
|
||||
rt_secret="$2"
|
||||
shift 2
|
||||
;;
|
||||
*)
|
||||
shift
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
RT_HOST="$rt_host"
|
||||
RT_PORT="$rt_port"
|
||||
RT_SECRET="$rt_secret"
|
||||
return 0
|
||||
}
|
||||
|
||||
print_connect_link() {
|
||||
link_host="$HOST"
|
||||
link_port="$PORT"
|
||||
link_secret="$SECRET"
|
||||
|
||||
if is_running && load_runtime_args_from_pid; then
|
||||
[ -n "$RT_HOST" ] && link_host="$RT_HOST"
|
||||
[ -n "$RT_PORT" ] && link_port="$RT_PORT"
|
||||
[ -n "$RT_SECRET" ] && link_secret="$RT_SECRET"
|
||||
fi
|
||||
|
||||
if [ -z "$link_secret" ]; then
|
||||
echo "SECRET is empty in $CONFFILE" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
if [ "$link_host" = "0.0.0.0" ]; then
|
||||
br0_ip="$(ip -f inet addr show dev br0 2>/dev/null | sed -n 's/.*inet \([0-9.]\+\)\/.*/\1/p' | head -n 1)"
|
||||
[ -n "$br0_ip" ] && link_host="$br0_ip"
|
||||
fi
|
||||
|
||||
echo "Connect link:"
|
||||
echo " tg://proxy?server=$link_host&port=$link_port&secret=dd$link_secret"
|
||||
}
|
||||
16
common/tg-ws-proxy.conf
Normal file
16
common/tg-ws-proxy.conf
Normal file
@ -0,0 +1,16 @@
|
||||
HOST=0.0.0.0
|
||||
PORT=1443
|
||||
# 32 hex chars
|
||||
SECRET=
|
||||
# Proxy verbosity: 0 = no service log file, 1 = write /opt/var/log/tg-ws-proxy.log
|
||||
LOG_LEVEL=0
|
||||
# Default WS target IP used for implicit DC map (2,4) when no --dc-ip is provided
|
||||
DC_IP_DEFAULT=149.154.167.220
|
||||
# Optional default target IP pool for implicit DC map, comma-separated
|
||||
# Example: DC_IP_DEFAULT_POOL="149.154.167.220,149.154.175.50"
|
||||
# Applies to implicit DCs (2,4) unless overridden via --dc-ip/--dc-ip-pool in EXTRA_ARGS.
|
||||
DC_IP_DEFAULT_POOL=""
|
||||
# Optional per-DC overrides and extra runtime flags.
|
||||
# Keep defaults in DC_IP_DEFAULT / DC_IP_DEFAULT_POOL, and use EXTRA_ARGS only for exceptions.
|
||||
# Example: EXTRA_ARGS="--dc-ip-pool 2:149.154.175.50,149.154.167.220 --dc-ip 203:91.105.192.100 -v"
|
||||
EXTRA_ARGS=""
|
||||
286
linux.py
286
linux.py
@ -1,286 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
import customtkinter as ctk
|
||||
import pyperclip
|
||||
import pystray
|
||||
from PIL import Image, ImageTk
|
||||
|
||||
import proxy.tg_ws_proxy as tg_ws_proxy
|
||||
|
||||
from utils.tray_common import (
|
||||
APP_NAME, DEFAULT_CONFIG, FIRST_RUN_MARKER, LOG_FILE,
|
||||
acquire_lock, bootstrap, check_ipv6_warning, ctk_run_dialog,
|
||||
ensure_ctk_thread, ensure_dirs, load_config, load_icon, log,
|
||||
maybe_notify_update, quit_ctk, release_lock, restart_proxy,
|
||||
save_config, start_proxy, stop_proxy, tg_proxy_url,
|
||||
)
|
||||
from ui.ctk_tray_ui import (
|
||||
install_tray_config_buttons, install_tray_config_form,
|
||||
populate_first_run_window, tray_settings_scroll_and_footer,
|
||||
validate_config_form,
|
||||
)
|
||||
from ui.ctk_theme import (
|
||||
CONFIG_DIALOG_FRAME_PAD, CONFIG_DIALOG_SIZE, FIRST_RUN_SIZE,
|
||||
create_ctk_toplevel, ctk_theme_for_platform, main_content_frame,
|
||||
)
|
||||
|
||||
_tray_icon: Optional[object] = None
|
||||
_config: dict = {}
|
||||
_exiting = False
|
||||
|
||||
# dialogs (tkinter messagebox)
|
||||
|
||||
|
||||
def _msgbox(kind: str, text: str, title: str, **kw):
|
||||
import tkinter as _tk
|
||||
from tkinter import messagebox as _mb
|
||||
|
||||
root = _tk.Tk()
|
||||
root.withdraw()
|
||||
try:
|
||||
root.attributes("-topmost", True)
|
||||
except Exception:
|
||||
pass
|
||||
result = getattr(_mb, kind)(title, text, parent=root, **kw)
|
||||
root.destroy()
|
||||
return result
|
||||
|
||||
|
||||
def _show_error(text: str, title: str = "TG WS Proxy — Ошибка") -> None:
|
||||
_msgbox("showerror", text, title)
|
||||
|
||||
|
||||
def _show_info(text: str, title: str = "TG WS Proxy") -> None:
|
||||
_msgbox("showinfo", text, title)
|
||||
|
||||
|
||||
def _ask_yes_no(text: str, title: str = "TG WS Proxy") -> bool:
|
||||
return bool(_msgbox("askyesno", text, title))
|
||||
|
||||
|
||||
def _apply_window_icon(root) -> None:
|
||||
icon_img = load_icon()
|
||||
if icon_img:
|
||||
root._ctk_icon_photo = ImageTk.PhotoImage(icon_img.resize((64, 64)))
|
||||
root.iconphoto(False, root._ctk_icon_photo)
|
||||
|
||||
|
||||
# tray callbacks
|
||||
|
||||
|
||||
def _on_open_in_telegram(icon=None, item=None) -> None:
|
||||
url = tg_proxy_url(_config)
|
||||
log.info("Copying %s", url)
|
||||
try:
|
||||
pyperclip.copy(url)
|
||||
_show_info(
|
||||
f"Ссылка скопирована в буфер обмена, отправьте её в Telegram и нажмите по ней ЛКМ:\n{url}"
|
||||
)
|
||||
except Exception as exc:
|
||||
log.error("Clipboard copy failed: %s", exc)
|
||||
_show_error(f"Не удалось скопировать ссылку:\n{exc}")
|
||||
|
||||
|
||||
def _on_copy_link(icon=None, item=None) -> None:
|
||||
url = tg_proxy_url(_config)
|
||||
log.info("Copying link: %s", url)
|
||||
try:
|
||||
pyperclip.copy(url)
|
||||
except Exception as exc:
|
||||
log.error("Clipboard copy failed: %s", exc)
|
||||
_show_error(f"Не удалось скопировать ссылку:\n{exc}")
|
||||
|
||||
|
||||
def _on_restart(icon=None, item=None) -> None:
|
||||
threading.Thread(
|
||||
target=lambda: restart_proxy(_config, _show_error), daemon=True
|
||||
).start()
|
||||
|
||||
|
||||
def _on_edit_config(icon=None, item=None) -> None:
|
||||
threading.Thread(target=_edit_config_dialog, daemon=True).start()
|
||||
|
||||
|
||||
def _on_open_logs(icon=None, item=None) -> None:
|
||||
log.info("Opening log file: %s", LOG_FILE)
|
||||
if LOG_FILE.exists():
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("VIRTUAL_ENV", "PYTHONPATH", "PYTHONHOME")}
|
||||
subprocess.Popen(
|
||||
["xdg-open", str(LOG_FILE)], env=env,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
stdin=subprocess.DEVNULL, start_new_session=True,
|
||||
)
|
||||
else:
|
||||
_show_info("Файл логов ещё не создан.")
|
||||
|
||||
|
||||
def _on_exit(icon=None, item=None) -> None:
|
||||
global _exiting
|
||||
if _exiting:
|
||||
os._exit(0)
|
||||
return
|
||||
_exiting = True
|
||||
log.info("User requested exit")
|
||||
quit_ctk()
|
||||
threading.Thread(target=lambda: (time.sleep(3), os._exit(0)), daemon=True, name="force-exit").start()
|
||||
if icon:
|
||||
icon.stop()
|
||||
|
||||
|
||||
# settings dialog
|
||||
|
||||
|
||||
def _edit_config_dialog() -> None:
|
||||
if not ensure_ctk_thread(ctk):
|
||||
_show_error("customtkinter не установлен.")
|
||||
return
|
||||
|
||||
cfg = dict(_config)
|
||||
|
||||
def _build(done: threading.Event) -> None:
|
||||
theme = ctk_theme_for_platform()
|
||||
w, h = CONFIG_DIALOG_SIZE
|
||||
root = create_ctk_toplevel(
|
||||
ctk, title="TG WS Proxy — Настройки", width=w, height=h, theme=theme,
|
||||
after_create=_apply_window_icon,
|
||||
)
|
||||
fpx, fpy = CONFIG_DIALOG_FRAME_PAD
|
||||
frame = main_content_frame(ctk, root, theme, padx=fpx, pady=fpy)
|
||||
scroll, footer = tray_settings_scroll_and_footer(ctk, frame, theme)
|
||||
widgets = install_tray_config_form(ctk, scroll, theme, cfg, DEFAULT_CONFIG, show_autostart=False)
|
||||
|
||||
def _finish() -> None:
|
||||
root.destroy()
|
||||
done.set()
|
||||
|
||||
def on_save() -> None:
|
||||
from tkinter import messagebox
|
||||
merged = validate_config_form(widgets, DEFAULT_CONFIG, include_autostart=False)
|
||||
if isinstance(merged, str):
|
||||
messagebox.showerror("TG WS Proxy — Ошибка", merged, parent=root)
|
||||
return
|
||||
save_config(merged)
|
||||
_config.update(merged)
|
||||
log.info("Config saved: %s", merged)
|
||||
_tray_icon.menu = _build_menu()
|
||||
|
||||
do_restart = messagebox.askyesno(
|
||||
"Перезапустить?",
|
||||
"Настройки сохранены.\n\nПерезапустить прокси сейчас?",
|
||||
parent=root,
|
||||
)
|
||||
_finish()
|
||||
if do_restart:
|
||||
threading.Thread(target=lambda: restart_proxy(_config, _show_error), daemon=True).start()
|
||||
|
||||
root.protocol("WM_DELETE_WINDOW", _finish)
|
||||
install_tray_config_buttons(ctk, footer, theme, on_save=on_save, on_cancel=_finish)
|
||||
|
||||
ctk_run_dialog(_build)
|
||||
|
||||
|
||||
# first run
|
||||
|
||||
|
||||
def _show_first_run() -> None:
|
||||
ensure_dirs()
|
||||
if FIRST_RUN_MARKER.exists():
|
||||
return
|
||||
if not ensure_ctk_thread(ctk):
|
||||
FIRST_RUN_MARKER.touch()
|
||||
return
|
||||
|
||||
host = _config.get("host", DEFAULT_CONFIG["host"])
|
||||
port = _config.get("port", DEFAULT_CONFIG["port"])
|
||||
secret = _config.get("secret", DEFAULT_CONFIG["secret"])
|
||||
|
||||
def _build(done: threading.Event) -> None:
|
||||
theme = ctk_theme_for_platform()
|
||||
w, h = FIRST_RUN_SIZE
|
||||
root = create_ctk_toplevel(
|
||||
ctk, title="TG WS Proxy", width=w, height=h, theme=theme,
|
||||
after_create=_apply_window_icon,
|
||||
)
|
||||
|
||||
def on_done(open_tg: bool) -> None:
|
||||
FIRST_RUN_MARKER.touch()
|
||||
root.destroy()
|
||||
done.set()
|
||||
if open_tg:
|
||||
_on_open_in_telegram()
|
||||
|
||||
populate_first_run_window(ctk, root, theme, host=host, port=port, secret=secret, on_done=on_done)
|
||||
|
||||
ctk_run_dialog(_build)
|
||||
|
||||
|
||||
# tray menu
|
||||
|
||||
|
||||
def _build_menu():
|
||||
host = _config.get("host", DEFAULT_CONFIG["host"])
|
||||
port = _config.get("port", DEFAULT_CONFIG["port"])
|
||||
link_host = tg_ws_proxy.get_link_host(host)
|
||||
return pystray.Menu(
|
||||
pystray.MenuItem(f"Открыть в Telegram ({link_host}:{port})", _on_open_in_telegram, default=True),
|
||||
pystray.MenuItem("Скопировать ссылку", _on_copy_link),
|
||||
pystray.Menu.SEPARATOR,
|
||||
pystray.MenuItem("Перезапустить прокси", _on_restart),
|
||||
pystray.MenuItem("Настройки...", _on_edit_config),
|
||||
pystray.MenuItem("Открыть логи", _on_open_logs),
|
||||
pystray.Menu.SEPARATOR,
|
||||
pystray.MenuItem("Выход", _on_exit),
|
||||
)
|
||||
|
||||
|
||||
# entry point
|
||||
|
||||
|
||||
def run_tray() -> None:
|
||||
global _tray_icon, _config
|
||||
|
||||
_config = load_config()
|
||||
bootstrap(_config)
|
||||
|
||||
if pystray is None or Image is None:
|
||||
log.error("pystray or Pillow not installed; running in console mode")
|
||||
start_proxy(_config, _show_error)
|
||||
try:
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
stop_proxy()
|
||||
return
|
||||
|
||||
start_proxy(_config, _show_error)
|
||||
maybe_notify_update(_config, lambda: _exiting, _ask_yes_no)
|
||||
_show_first_run()
|
||||
check_ipv6_warning(_show_info)
|
||||
|
||||
_tray_icon = pystray.Icon(APP_NAME, load_icon(), "TG WS Proxy", menu=_build_menu())
|
||||
log.info("Tray icon running")
|
||||
_tray_icon.run()
|
||||
|
||||
stop_proxy()
|
||||
log.info("Tray app exited")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if not acquire_lock("linux.py"):
|
||||
_show_info("Приложение уже запущено.", os.path.basename(sys.argv[0]))
|
||||
return
|
||||
try:
|
||||
run_tray()
|
||||
finally:
|
||||
release_lock()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
600
macos.py
600
macos.py
@ -1,600 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import webbrowser
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
try:
|
||||
import rumps
|
||||
except ImportError:
|
||||
rumps = None
|
||||
|
||||
try:
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
except ImportError:
|
||||
Image = ImageDraw = ImageFont = None
|
||||
|
||||
try:
|
||||
import pyperclip
|
||||
except ImportError:
|
||||
pyperclip = None
|
||||
|
||||
import proxy.tg_ws_proxy as tg_ws_proxy
|
||||
from proxy import __version__
|
||||
|
||||
from utils.tray_common import (
|
||||
APP_DIR, APP_NAME, DEFAULT_CONFIG, FIRST_RUN_MARKER, IPV6_WARN_MARKER,
|
||||
LOG_FILE, acquire_lock, apply_proxy_config, ensure_dirs, load_config,
|
||||
log, release_lock, save_config, setup_logging, stop_proxy, tg_proxy_url,
|
||||
)
|
||||
|
||||
MENUBAR_ICON_PATH = APP_DIR / "menubar_icon.png"
|
||||
|
||||
_proxy_thread: Optional[threading.Thread] = None
|
||||
_async_stop: Optional[object] = None
|
||||
_app: Optional[object] = None
|
||||
_config: dict = {}
|
||||
_exiting: bool = False
|
||||
|
||||
# osascript dialogs
|
||||
|
||||
|
||||
def _esc(text: str) -> str:
|
||||
return text.replace("\\", "\\\\").replace('"', '\\"')
|
||||
|
||||
|
||||
def _osascript(script: str) -> str:
|
||||
r = subprocess.run(["osascript", "-e", script], capture_output=True, text=True)
|
||||
return r.stdout.strip()
|
||||
|
||||
|
||||
def _show_error(text: str, title: str = "TG WS Proxy") -> None:
|
||||
_osascript(
|
||||
f'display dialog "{_esc(text)}" with title "{_esc(title)}" '
|
||||
f'buttons {{"OK"}} default button "OK" with icon stop'
|
||||
)
|
||||
|
||||
|
||||
def _show_info(text: str, title: str = "TG WS Proxy") -> None:
|
||||
_osascript(
|
||||
f'display dialog "{_esc(text)}" with title "{_esc(title)}" '
|
||||
f'buttons {{"OK"}} default button "OK" with icon note'
|
||||
)
|
||||
|
||||
|
||||
def _ask_yes_no(text: str, title: str = "TG WS Proxy") -> bool:
|
||||
return _ask_yes_no_close(text, title) is True
|
||||
|
||||
|
||||
def _ask_yes_no_close(text: str, title: str = "TG WS Proxy") -> Optional[bool]:
|
||||
r = subprocess.run(
|
||||
[
|
||||
"osascript", "-e",
|
||||
f'button returned of (display dialog "{_esc(text)}" '
|
||||
f'with title "{_esc(title)}" '
|
||||
f'buttons {{"Закрыть", "Нет", "Да"}} '
|
||||
f'default button "Да" cancel button "Закрыть" with icon note)',
|
||||
],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
if r.returncode != 0:
|
||||
return None
|
||||
btn = r.stdout.strip()
|
||||
if btn == "Да":
|
||||
return True
|
||||
if btn == "Нет":
|
||||
return False
|
||||
return None
|
||||
|
||||
|
||||
def _osascript_input(prompt: str, default: str, title: str = "TG WS Proxy") -> Optional[str]:
|
||||
r = subprocess.run(
|
||||
[
|
||||
"osascript", "-e",
|
||||
f'text returned of (display dialog "{_esc(prompt)}" '
|
||||
f'default answer "{_esc(default)}" '
|
||||
f'with title "{_esc(title)}" '
|
||||
f'buttons {{"Закрыть", "OK"}} '
|
||||
f'default button "OK" cancel button "Закрыть")',
|
||||
],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
if r.returncode != 0:
|
||||
return None
|
||||
return r.stdout.rstrip("\r\n")
|
||||
|
||||
|
||||
# menubar icon
|
||||
|
||||
|
||||
def _make_menubar_icon(size: int = 44):
|
||||
if Image is None:
|
||||
return None
|
||||
img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
|
||||
draw = ImageDraw.Draw(img)
|
||||
margin = size // 11
|
||||
draw.ellipse([margin, margin, size - margin, size - margin], fill=(0, 0, 0, 255))
|
||||
try:
|
||||
font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", size=int(size * 0.55))
|
||||
except Exception:
|
||||
font = ImageFont.load_default()
|
||||
bbox = draw.textbbox((0, 0), "T", font=font)
|
||||
tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
|
||||
draw.text(
|
||||
((size - tw) // 2 - bbox[0], (size - th) // 2 - bbox[1]),
|
||||
"T", fill=(255, 255, 255, 255), font=font,
|
||||
)
|
||||
return img
|
||||
|
||||
|
||||
def _ensure_menubar_icon() -> None:
|
||||
if MENUBAR_ICON_PATH.exists():
|
||||
return
|
||||
ensure_dirs()
|
||||
img = _make_menubar_icon(44)
|
||||
if img:
|
||||
img.save(str(MENUBAR_ICON_PATH), "PNG")
|
||||
|
||||
|
||||
# proxy lifecycle (macOS-local)
|
||||
|
||||
import asyncio as _asyncio
|
||||
|
||||
|
||||
def _run_proxy_thread() -> None:
|
||||
global _async_stop
|
||||
loop = _asyncio.new_event_loop()
|
||||
_asyncio.set_event_loop(loop)
|
||||
stop_ev = _asyncio.Event()
|
||||
_async_stop = (loop, stop_ev)
|
||||
try:
|
||||
loop.run_until_complete(tg_ws_proxy._run(stop_event=stop_ev))
|
||||
except Exception as exc:
|
||||
log.error("Proxy thread crashed: %s", exc)
|
||||
if "Address already in use" in str(exc):
|
||||
_show_error(
|
||||
"Не удалось запустить прокси:\n"
|
||||
"Порт уже используется другим приложением.\n\n"
|
||||
"Закройте приложение, использующее этот порт, "
|
||||
"или измените порт в настройках прокси и перезапустите."
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
_async_stop = None
|
||||
|
||||
|
||||
def _start_proxy() -> None:
|
||||
global _proxy_thread
|
||||
if _proxy_thread and _proxy_thread.is_alive():
|
||||
log.info("Proxy already running")
|
||||
return
|
||||
if not apply_proxy_config(_config):
|
||||
_show_error("Ошибка конфигурации DC → IP.")
|
||||
return
|
||||
pc = tg_ws_proxy.proxy_config
|
||||
log.info("Starting proxy on %s:%d ...", pc.host, pc.port)
|
||||
_proxy_thread = threading.Thread(target=_run_proxy_thread, daemon=True, name="proxy")
|
||||
_proxy_thread.start()
|
||||
|
||||
|
||||
def _stop_proxy() -> None:
|
||||
global _proxy_thread, _async_stop
|
||||
if _async_stop:
|
||||
loop, stop_ev = _async_stop
|
||||
loop.call_soon_threadsafe(stop_ev.set)
|
||||
if _proxy_thread:
|
||||
_proxy_thread.join(timeout=2)
|
||||
_proxy_thread = None
|
||||
log.info("Proxy stopped")
|
||||
|
||||
|
||||
def _restart_proxy() -> None:
|
||||
log.info("Restarting proxy...")
|
||||
_stop_proxy()
|
||||
time.sleep(0.3)
|
||||
_start_proxy()
|
||||
|
||||
|
||||
# menu callbacks
|
||||
|
||||
|
||||
def _on_open_in_telegram(_=None) -> None:
|
||||
url = tg_proxy_url(_config)
|
||||
log.info("Opening %s", url)
|
||||
try:
|
||||
result = subprocess.call(["open", url])
|
||||
if result != 0:
|
||||
raise RuntimeError("open command failed")
|
||||
except Exception:
|
||||
log.info("open command failed, trying webbrowser")
|
||||
try:
|
||||
if not webbrowser.open(url):
|
||||
raise RuntimeError("webbrowser.open returned False")
|
||||
except Exception:
|
||||
log.info("Browser open failed, copying to clipboard")
|
||||
try:
|
||||
if pyperclip:
|
||||
pyperclip.copy(url)
|
||||
else:
|
||||
subprocess.run(["pbcopy"], input=url.encode(), check=True)
|
||||
_show_info(
|
||||
"Не удалось открыть Telegram автоматически.\n\n"
|
||||
f"Ссылка скопирована в буфер обмена:\n{url}"
|
||||
)
|
||||
except Exception as exc:
|
||||
log.error("Clipboard copy failed: %s", exc)
|
||||
_show_error(f"Не удалось скопировать ссылку:\n{exc}")
|
||||
|
||||
|
||||
def _on_copy_link(_=None) -> None:
|
||||
url = tg_proxy_url(_config)
|
||||
log.info("Copying link: %s", url)
|
||||
try:
|
||||
if pyperclip:
|
||||
pyperclip.copy(url)
|
||||
else:
|
||||
subprocess.run(["pbcopy"], input=url.encode(), check=True)
|
||||
except Exception as exc:
|
||||
log.error("Clipboard copy failed: %s", exc)
|
||||
_show_error(f"Не удалось скопировать ссылку:\n{exc}")
|
||||
|
||||
|
||||
def _on_restart(_=None) -> None:
|
||||
def _do():
|
||||
global _config
|
||||
_config = load_config()
|
||||
if _app:
|
||||
_app.update_menu_title()
|
||||
_restart_proxy()
|
||||
|
||||
threading.Thread(target=_do, daemon=True).start()
|
||||
|
||||
|
||||
def _on_open_logs(_=None) -> None:
|
||||
log.info("Opening log file: %s", LOG_FILE)
|
||||
if LOG_FILE.exists():
|
||||
subprocess.call(["open", str(LOG_FILE)])
|
||||
else:
|
||||
_show_info("Файл логов ещё не создан.")
|
||||
|
||||
|
||||
def _on_edit_config(_=None) -> None:
|
||||
threading.Thread(target=_edit_config_dialog, daemon=True).start()
|
||||
|
||||
|
||||
def _check_updates_menu_title() -> str:
|
||||
on = bool(_config.get("check_updates", True))
|
||||
return "✓ Проверять обновления при запуске" if on else "Проверять обновления при запуске (выкл)"
|
||||
|
||||
|
||||
def _toggle_check_updates(_=None) -> None:
|
||||
global _config
|
||||
_config["check_updates"] = not bool(_config.get("check_updates", True))
|
||||
save_config(_config)
|
||||
if _app is not None:
|
||||
_app._check_updates_item.title = _check_updates_menu_title()
|
||||
|
||||
|
||||
def _on_open_release_page(_=None) -> None:
|
||||
from utils.update_check import RELEASES_PAGE_URL
|
||||
webbrowser.open(RELEASES_PAGE_URL)
|
||||
|
||||
|
||||
# update check
|
||||
|
||||
|
||||
def _maybe_notify_update_async() -> None:
|
||||
def _work():
|
||||
time.sleep(1.5)
|
||||
if _exiting:
|
||||
return
|
||||
if not _config.get("check_updates", True):
|
||||
return
|
||||
try:
|
||||
from utils.update_check import RELEASES_PAGE_URL, get_status, run_check
|
||||
run_check(__version__)
|
||||
st = get_status()
|
||||
if not st.get("has_update"):
|
||||
return
|
||||
url = (st.get("html_url") or "").strip() or RELEASES_PAGE_URL
|
||||
ver = st.get("latest") or "?"
|
||||
if _ask_yes_no(
|
||||
f"Доступна новая версия: {ver}\n\nОткрыть страницу релиза в браузере?",
|
||||
"TG WS Proxy — обновление",
|
||||
):
|
||||
webbrowser.open(url)
|
||||
except Exception as exc:
|
||||
log.debug("Update check failed: %s", exc)
|
||||
|
||||
threading.Thread(target=_work, daemon=True, name="update-check").start()
|
||||
|
||||
|
||||
# settings dialog
|
||||
|
||||
|
||||
def _edit_config_dialog() -> None:
|
||||
cfg = load_config()
|
||||
|
||||
host = _osascript_input("IP-адрес прокси:", cfg.get("host", DEFAULT_CONFIG["host"]))
|
||||
if host is None:
|
||||
return
|
||||
host = host.strip()
|
||||
import socket as _sock
|
||||
try:
|
||||
_sock.inet_aton(host)
|
||||
except OSError:
|
||||
_show_error("Некорректный IP-адрес.")
|
||||
return
|
||||
|
||||
port_str = _osascript_input("Порт прокси:", str(cfg.get("port", DEFAULT_CONFIG["port"])))
|
||||
if port_str is None:
|
||||
return
|
||||
try:
|
||||
port = int(port_str.strip())
|
||||
if not (1 <= port <= 65535):
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
_show_error("Порт должен быть числом 1-65535")
|
||||
return
|
||||
|
||||
secret_str = _osascript_input(
|
||||
"MTProto Secret (32 hex символа):", cfg.get("secret", DEFAULT_CONFIG["secret"])
|
||||
)
|
||||
if secret_str is None:
|
||||
return
|
||||
secret_str = secret_str.strip().lower()
|
||||
if len(secret_str) != 32 or not all(c in "0123456789abcdef" for c in secret_str):
|
||||
_show_error("Secret должен быть строкой из 32 шестнадцатеричных символов.")
|
||||
return
|
||||
|
||||
dc_default = ", ".join(cfg.get("dc_ip", DEFAULT_CONFIG["dc_ip"]))
|
||||
dc_str = _osascript_input(
|
||||
"DC → IP маппинги (через запятую, формат DC:IP):\n"
|
||||
"Например: 2:149.154.167.220, 4:149.154.167.220",
|
||||
dc_default,
|
||||
)
|
||||
if dc_str is None:
|
||||
return
|
||||
dc_lines = [s.strip() for s in dc_str.replace(",", "\n").splitlines() if s.strip()]
|
||||
try:
|
||||
tg_ws_proxy.parse_dc_ip_list(dc_lines)
|
||||
except ValueError as e:
|
||||
_show_error(str(e))
|
||||
return
|
||||
|
||||
verbose = _ask_yes_no_close("Включить подробное логирование (verbose)?")
|
||||
if verbose is None:
|
||||
return
|
||||
|
||||
adv_str = _osascript_input(
|
||||
"Расширенные настройки (буфер KB, WS пул, лог MB):\n"
|
||||
"Формат: buf_kb,pool_size,log_max_mb",
|
||||
f"{cfg.get('buf_kb', DEFAULT_CONFIG['buf_kb'])},"
|
||||
f"{cfg.get('pool_size', DEFAULT_CONFIG['pool_size'])},"
|
||||
f"{cfg.get('log_max_mb', DEFAULT_CONFIG['log_max_mb'])}",
|
||||
)
|
||||
if adv_str is None:
|
||||
return
|
||||
|
||||
adv = {}
|
||||
if adv_str:
|
||||
parts = [s.strip() for s in adv_str.split(",")]
|
||||
keys = [("buf_kb", int), ("pool_size", int), ("log_max_mb", float)]
|
||||
for i, (k, typ) in enumerate(keys):
|
||||
if i < len(parts):
|
||||
try:
|
||||
adv[k] = typ(parts[i])
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
new_cfg = {
|
||||
"host": host,
|
||||
"port": port,
|
||||
"secret": secret_str,
|
||||
"dc_ip": dc_lines,
|
||||
"verbose": verbose,
|
||||
"buf_kb": adv.get("buf_kb", cfg.get("buf_kb", DEFAULT_CONFIG["buf_kb"])),
|
||||
"pool_size": adv.get("pool_size", cfg.get("pool_size", DEFAULT_CONFIG["pool_size"])),
|
||||
"log_max_mb": adv.get("log_max_mb", cfg.get("log_max_mb", DEFAULT_CONFIG["log_max_mb"])),
|
||||
"check_updates": cfg.get("check_updates", True),
|
||||
}
|
||||
save_config(new_cfg)
|
||||
log.info("Config saved: %s", new_cfg)
|
||||
|
||||
global _config
|
||||
_config = new_cfg
|
||||
if _app:
|
||||
_app.update_menu_title()
|
||||
|
||||
if _ask_yes_no_close("Настройки сохранены.\n\nПерезапустить прокси сейчас?"):
|
||||
_restart_proxy()
|
||||
|
||||
|
||||
# first run & ipv6
|
||||
|
||||
|
||||
def _show_first_run() -> None:
|
||||
ensure_dirs()
|
||||
if FIRST_RUN_MARKER.exists():
|
||||
return
|
||||
|
||||
host = _config.get("host", DEFAULT_CONFIG["host"])
|
||||
port = _config.get("port", DEFAULT_CONFIG["port"])
|
||||
secret = _config.get("secret", DEFAULT_CONFIG["secret"])
|
||||
tg_url = tg_proxy_url(_config)
|
||||
link_host = tg_ws_proxy.get_link_host(host)
|
||||
|
||||
text = (
|
||||
f"Прокси запущен и работает в строке меню.\n\n"
|
||||
f"Как подключить Telegram Desktop:\n\n"
|
||||
f"Автоматически:\n"
|
||||
f" Нажмите «Открыть в Telegram» в меню\n"
|
||||
f" Или ссылка: {tg_url}\n\n"
|
||||
f"Вручную:\n"
|
||||
f" Настройки → Продвинутые → Тип подключения → Прокси\n"
|
||||
f" MTProto → {link_host} : {port} \n"
|
||||
f" Secret: dd{secret} \n\n"
|
||||
f"Открыть прокси в Telegram сейчас?"
|
||||
)
|
||||
|
||||
FIRST_RUN_MARKER.touch()
|
||||
if _ask_yes_no(text, "TG WS Proxy"):
|
||||
_on_open_in_telegram()
|
||||
|
||||
|
||||
def _check_ipv6_warning() -> None:
|
||||
ensure_dirs()
|
||||
if IPV6_WARN_MARKER.exists():
|
||||
return
|
||||
|
||||
import socket as _sock
|
||||
has = False
|
||||
try:
|
||||
for addr in _sock.getaddrinfo(_sock.gethostname(), None, _sock.AF_INET6):
|
||||
ip = addr[4][0]
|
||||
if ip and not ip.startswith("::1") and not ip.startswith("fe80::1"):
|
||||
has = True
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
if not has:
|
||||
try:
|
||||
s = _sock.socket(_sock.AF_INET6, _sock.SOCK_STREAM)
|
||||
s.bind(("::1", 0))
|
||||
s.close()
|
||||
has = True
|
||||
except Exception:
|
||||
pass
|
||||
if not has:
|
||||
return
|
||||
|
||||
IPV6_WARN_MARKER.touch()
|
||||
_show_info(
|
||||
"На вашем компьютере включена поддержка подключения по IPv6.\n\n"
|
||||
"Telegram может пытаться подключаться через IPv6, "
|
||||
"что не поддерживается и может привести к ошибкам.\n\n"
|
||||
"Если прокси не работает, попробуйте отключить "
|
||||
"попытку соединения по IPv6 в настройках прокси Telegram.\n\n"
|
||||
"Это предупреждение будет показано только один раз."
|
||||
)
|
||||
|
||||
|
||||
# rumps app
|
||||
|
||||
_TgWsProxyAppBase = rumps.App if rumps else object
|
||||
|
||||
|
||||
class TgWsProxyApp(_TgWsProxyAppBase):
|
||||
def __init__(self):
|
||||
_ensure_menubar_icon()
|
||||
icon_path = str(MENUBAR_ICON_PATH) if MENUBAR_ICON_PATH.exists() else None
|
||||
|
||||
host = _config.get("host", DEFAULT_CONFIG["host"])
|
||||
port = _config.get("port", DEFAULT_CONFIG["port"])
|
||||
link_host = tg_ws_proxy.get_link_host(host)
|
||||
|
||||
self._open_tg_item = rumps.MenuItem(
|
||||
f"Открыть в Telegram ({link_host}:{port})", callback=_on_open_in_telegram
|
||||
)
|
||||
self._copy_link_item = rumps.MenuItem("Скопировать ссылку", callback=_on_copy_link)
|
||||
self._restart_item = rumps.MenuItem("Перезапустить прокси", callback=_on_restart)
|
||||
self._settings_item = rumps.MenuItem("Настройки...", callback=_on_edit_config)
|
||||
self._logs_item = rumps.MenuItem("Открыть логи", callback=_on_open_logs)
|
||||
self._release_page_item = rumps.MenuItem(
|
||||
"Страница релиза на GitHub…", callback=_on_open_release_page
|
||||
)
|
||||
self._check_updates_item = rumps.MenuItem(
|
||||
_check_updates_menu_title(), callback=_toggle_check_updates
|
||||
)
|
||||
self._version_item = rumps.MenuItem(f"Версия {__version__}", callback=lambda _: None)
|
||||
|
||||
super().__init__(
|
||||
"TG WS Proxy",
|
||||
icon=icon_path,
|
||||
template=False,
|
||||
quit_button="Выход",
|
||||
menu=[
|
||||
self._open_tg_item,
|
||||
self._copy_link_item,
|
||||
None,
|
||||
self._restart_item,
|
||||
self._settings_item,
|
||||
self._logs_item,
|
||||
None,
|
||||
self._release_page_item,
|
||||
self._check_updates_item,
|
||||
None,
|
||||
self._version_item,
|
||||
],
|
||||
)
|
||||
|
||||
def update_menu_title(self) -> None:
|
||||
host = _config.get("host", DEFAULT_CONFIG["host"])
|
||||
port = _config.get("port", DEFAULT_CONFIG["port"])
|
||||
link_host = tg_ws_proxy.get_link_host(host)
|
||||
self._open_tg_item.title = f"Открыть в Telegram ({link_host}:{port})"
|
||||
|
||||
|
||||
# entry point
|
||||
|
||||
|
||||
def run_menubar() -> None:
|
||||
global _app, _config
|
||||
|
||||
_config = load_config()
|
||||
save_config(_config)
|
||||
|
||||
if LOG_FILE.exists():
|
||||
try:
|
||||
LOG_FILE.unlink()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
setup_logging(
|
||||
_config.get("verbose", False),
|
||||
log_max_mb=_config.get("log_max_mb", DEFAULT_CONFIG["log_max_mb"]),
|
||||
)
|
||||
log.info("TG WS Proxy версия %s, menubar app starting", __version__)
|
||||
log.info("Config: %s", _config)
|
||||
log.info("Log file: %s", LOG_FILE)
|
||||
|
||||
if rumps is None or Image is None:
|
||||
log.error("rumps or Pillow not installed; running in console mode")
|
||||
_start_proxy()
|
||||
try:
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
_stop_proxy()
|
||||
return
|
||||
|
||||
_start_proxy()
|
||||
_maybe_notify_update_async()
|
||||
_show_first_run()
|
||||
_check_ipv6_warning()
|
||||
|
||||
_app = TgWsProxyApp()
|
||||
log.info("Menubar app running")
|
||||
_app.run()
|
||||
|
||||
_stop_proxy()
|
||||
log.info("Menubar app exited")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if not acquire_lock("macos.py"):
|
||||
_show_info("Приложение уже запущено.")
|
||||
return
|
||||
try:
|
||||
run_menubar()
|
||||
finally:
|
||||
release_lock()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -1,80 +0,0 @@
|
||||
# -*- mode: python ; coding: utf-8 -*-
|
||||
|
||||
import sys
|
||||
import os
|
||||
import glob
|
||||
|
||||
from PyInstaller.utils.hooks import collect_submodules, collect_data_files
|
||||
|
||||
block_cipher = None
|
||||
|
||||
# customtkinter ships JSON themes + assets that must be bundled
|
||||
import customtkinter
|
||||
ctk_path = os.path.dirname(customtkinter.__file__)
|
||||
|
||||
# Collect gi (PyGObject) submodules and data so pystray._appindicator works
|
||||
gi_hiddenimports = collect_submodules('gi')
|
||||
gi_datas = collect_data_files('gi')
|
||||
|
||||
# Collect GObject typelib files from the system
|
||||
typelib_dirs = glob.glob('/usr/lib/*/girepository-1.0')
|
||||
typelib_datas = []
|
||||
for d in typelib_dirs:
|
||||
typelib_datas.append((d, 'gi_typelibs'))
|
||||
|
||||
a = Analysis(
|
||||
[os.path.join(os.path.dirname(SPEC), os.pardir, 'linux.py')],
|
||||
pathex=[],
|
||||
binaries=[],
|
||||
datas=[(ctk_path, 'customtkinter/')] + gi_datas + typelib_datas,
|
||||
hiddenimports=[
|
||||
'pystray._appindicator',
|
||||
'PIL._tkinter_finder',
|
||||
'customtkinter',
|
||||
'cryptography.hazmat.primitives.ciphers',
|
||||
'cryptography.hazmat.primitives.ciphers.algorithms',
|
||||
'cryptography.hazmat.primitives.ciphers.modes',
|
||||
'cryptography.hazmat.backends.openssl',
|
||||
'gi',
|
||||
'_gi',
|
||||
'gi.repository.GLib',
|
||||
'gi.repository.GObject',
|
||||
'gi.repository.Gtk',
|
||||
'gi.repository.Gdk',
|
||||
'gi.repository.AyatanaAppIndicator3',
|
||||
] + gi_hiddenimports,
|
||||
hookspath=[],
|
||||
hooksconfig={},
|
||||
runtime_hooks=[],
|
||||
excludes=[],
|
||||
noarchive=False,
|
||||
cipher=block_cipher,
|
||||
)
|
||||
|
||||
icon_path = os.path.join(os.path.dirname(SPEC), os.pardir, 'icon.ico')
|
||||
if os.path.exists(icon_path):
|
||||
a.datas += [('icon.ico', icon_path, 'DATA')]
|
||||
|
||||
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
|
||||
|
||||
exe = EXE(
|
||||
pyz,
|
||||
a.scripts,
|
||||
a.binaries,
|
||||
a.zipfiles,
|
||||
a.datas,
|
||||
[],
|
||||
name='TgWsProxy',
|
||||
debug=False,
|
||||
bootloader_ignore_signals=False,
|
||||
strip=True,
|
||||
upx=True,
|
||||
upx_exclude=[],
|
||||
runtime_tmpdir=None,
|
||||
console=False,
|
||||
disable_windowed_traceback=False,
|
||||
argv_emulation=False,
|
||||
target_arch=None,
|
||||
codesign_identity=None,
|
||||
entitlements_file=None,
|
||||
)
|
||||
@ -1,83 +0,0 @@
|
||||
# -*- mode: python ; coding: utf-8 -*-
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
block_cipher = None
|
||||
|
||||
a = Analysis(
|
||||
[os.path.join(os.path.dirname(SPEC), os.pardir, 'macos.py')],
|
||||
pathex=[],
|
||||
binaries=[],
|
||||
datas=[],
|
||||
hiddenimports=[
|
||||
'rumps',
|
||||
'objc',
|
||||
'Foundation',
|
||||
'AppKit',
|
||||
'PyObjCTools',
|
||||
'PyObjCTools.AppHelper',
|
||||
'cryptography.hazmat.primitives.ciphers',
|
||||
'cryptography.hazmat.primitives.ciphers.algorithms',
|
||||
'cryptography.hazmat.primitives.ciphers.modes',
|
||||
'cryptography.hazmat.backends.openssl',
|
||||
],
|
||||
hookspath=[],
|
||||
hooksconfig={},
|
||||
runtime_hooks=[],
|
||||
excludes=[],
|
||||
noarchive=False,
|
||||
cipher=block_cipher,
|
||||
)
|
||||
|
||||
icon_path = os.path.join(os.path.dirname(SPEC), os.pardir, 'icon.icns')
|
||||
if not os.path.exists(icon_path):
|
||||
icon_path = None
|
||||
|
||||
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
|
||||
|
||||
exe = EXE(
|
||||
pyz,
|
||||
a.scripts,
|
||||
[],
|
||||
exclude_binaries=True,
|
||||
name='TgWsProxy',
|
||||
debug=False,
|
||||
bootloader_ignore_signals=False,
|
||||
strip=False,
|
||||
upx=False,
|
||||
console=False,
|
||||
argv_emulation=False,
|
||||
target_arch='universal2',
|
||||
codesign_identity=None,
|
||||
entitlements_file=None,
|
||||
)
|
||||
|
||||
coll = COLLECT(
|
||||
exe,
|
||||
a.binaries,
|
||||
a.zipfiles,
|
||||
a.datas,
|
||||
strip=False,
|
||||
upx=False,
|
||||
upx_exclude=[],
|
||||
name='TgWsProxy',
|
||||
)
|
||||
|
||||
app = BUNDLE(
|
||||
coll,
|
||||
name='TG WS Proxy.app',
|
||||
icon=icon_path,
|
||||
bundle_identifier='com.tgwsproxy.app',
|
||||
info_plist={
|
||||
'CFBundleName': 'TG WS Proxy',
|
||||
'CFBundleDisplayName': 'TG WS Proxy',
|
||||
'CFBundleShortVersionString': '1.0.0',
|
||||
'CFBundleVersion': '1.0.0',
|
||||
'LSMinimumSystemVersion': '10.15',
|
||||
'LSUIElement': True,
|
||||
'NSHighResolutionCapable': True,
|
||||
'NSAppleEventsUsageDescription':
|
||||
'TG WS Proxy needs to display dialogs.',
|
||||
},
|
||||
)
|
||||
@ -1,63 +0,0 @@
|
||||
# -*- mode: python ; coding: utf-8 -*-
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
block_cipher = None
|
||||
|
||||
# customtkinter ships JSON themes + assets that must be bundled
|
||||
import customtkinter
|
||||
ctk_path = os.path.dirname(customtkinter.__file__)
|
||||
|
||||
a = Analysis(
|
||||
[os.path.join(os.path.dirname(SPEC), os.pardir, 'windows.py')],
|
||||
pathex=[],
|
||||
binaries=[],
|
||||
datas=[(ctk_path, 'customtkinter/')],
|
||||
hiddenimports=[
|
||||
'pystray._win32',
|
||||
'PIL._tkinter_finder',
|
||||
'customtkinter',
|
||||
'cryptography.hazmat.primitives.ciphers',
|
||||
'cryptography.hazmat.primitives.ciphers.algorithms',
|
||||
'cryptography.hazmat.primitives.ciphers.modes',
|
||||
'cryptography.hazmat.backends.openssl',
|
||||
],
|
||||
hookspath=[],
|
||||
hooksconfig={},
|
||||
runtime_hooks=[],
|
||||
excludes=[],
|
||||
win_no_prefer_redirects=False,
|
||||
win_private_assemblies=False,
|
||||
cipher=block_cipher,
|
||||
noarchive=False,
|
||||
)
|
||||
|
||||
icon_path = os.path.join(os.path.dirname(SPEC), os.pardir, 'icon.ico')
|
||||
if os.path.exists(icon_path):
|
||||
a.datas += [('icon.ico', icon_path, 'DATA')]
|
||||
|
||||
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
|
||||
|
||||
exe = EXE(
|
||||
pyz,
|
||||
a.scripts,
|
||||
a.binaries,
|
||||
a.zipfiles,
|
||||
a.datas,
|
||||
[],
|
||||
name='TgWsProxy',
|
||||
debug=False,
|
||||
bootloader_ignore_signals=False,
|
||||
strip=False,
|
||||
upx=True,
|
||||
upx_exclude=[],
|
||||
runtime_tmpdir=None,
|
||||
console=False,
|
||||
disable_windowed_traceback=False,
|
||||
argv_emulation=False,
|
||||
target_arch=None,
|
||||
codesign_identity=None,
|
||||
entitlements_file=None,
|
||||
icon=icon_path if os.path.exists(icon_path) else None,
|
||||
)
|
||||
@ -1 +0,0 @@
|
||||
__version__ = "1.4.0"
|
||||
1204
proxy/tg_ws_proxy.py
1204
proxy/tg_ws_proxy.py
File diff suppressed because it is too large
Load Diff
@ -1,73 +0,0 @@
|
||||
[build-system]
|
||||
requires = ["hatchling>=1.25.0"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "tg-ws-proxy"
|
||||
dynamic=["version"]
|
||||
|
||||
description = "Telegram Desktop WebSocket Bridge Proxy"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.8"
|
||||
|
||||
license = { name = "MIT", file = "LICENSE" }
|
||||
|
||||
authors = [
|
||||
{ name = "Flowseal" }
|
||||
]
|
||||
|
||||
keywords = [
|
||||
"telegram",
|
||||
"tdesktop",
|
||||
"proxy",
|
||||
"bypass",
|
||||
"websocket",
|
||||
"mtproto",
|
||||
]
|
||||
classifiers = [
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"Environment :: Console",
|
||||
"Intended Audience :: Customer Service",
|
||||
"Programming Language :: Python :: 3",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Operating System :: OS Independent",
|
||||
"Topic :: System :: Networking :: Firewalls",
|
||||
]
|
||||
|
||||
dependencies = [
|
||||
"pyperclip==1.9.0",
|
||||
|
||||
"psutil==5.9.8; platform_system == 'Windows' and python_version < '3.9'",
|
||||
"cryptography==41.0.7; platform_system == 'Windows' and python_version < '3.9'",
|
||||
"Pillow==10.4.0; platform_system == 'Windows' and python_version < '3.9'",
|
||||
|
||||
"psutil==7.0.0; platform_system != 'Windows' or python_version >= '3.9'",
|
||||
"cryptography==46.0.5; platform_system != 'Windows' or python_version >= '3.9'",
|
||||
"Pillow==12.1.1; (platform_system != 'Windows' or python_version >= '3.9') and platform_system != 'Darwin'",
|
||||
|
||||
"customtkinter==5.2.2; platform_system != 'Darwin'",
|
||||
"pystray==0.19.5; platform_system != 'Darwin'",
|
||||
"rumps==0.4.0; platform_system == 'Darwin'",
|
||||
"Pillow==12.1.0; platform_system == 'Darwin'",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
tg-ws-proxy = "proxy.tg_ws_proxy:main"
|
||||
tg-ws-proxy-tray-win = "windows:main"
|
||||
tg-ws-proxy-tray-macos = "macos:main"
|
||||
tg-ws-proxy-tray-linux = "linux:main"
|
||||
|
||||
[project.urls]
|
||||
Source = "https://github.com/Flowseal/tg-ws-proxy"
|
||||
Issues = "https://github.com/Flowseal/tg-ws-proxy/issues"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["proxy", "ui", "utils"]
|
||||
|
||||
[tool.hatch.build.force-include]
|
||||
"windows.py" = "windows.py"
|
||||
"macos.py" = "macos.py"
|
||||
"linux.py" = "linux.py"
|
||||
|
||||
[tool.hatch.version]
|
||||
path = "proxy/__init__.py"
|
||||
164
src/config.go
Normal file
164
src/config.go
Normal file
@ -0,0 +1,164 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func parseFlags() (*Config, error) {
|
||||
host := flag.String("host", "127.0.0.1", "Listen host")
|
||||
port := flag.Int("port", 1443, "Listen port")
|
||||
secret := flag.String("secret", "", "MTProto secret (32 hex chars)")
|
||||
verbose := flag.Bool("v", false, "Verbose logs")
|
||||
logFile := flag.String("log-file", "", "Log file path")
|
||||
logMaxMB := flag.Float64("log-max-mb", 5, "Max log file size before rotate")
|
||||
logBackups := flag.Int("log-backups", 0, "Number of rotated backups")
|
||||
bufKB := flag.Int("buf-kb", 256, "Socket buffer size in KB")
|
||||
poolSize := flag.Int("pool-size", 4, "WS pool size per DC")
|
||||
maxConns := flag.Int("max-conns", defaultMaxConns, "Max concurrent client sessions")
|
||||
dcIPDefault := flag.String("dc-ip-default", "149.154.167.220", "Default WS target IP for all implicit DCs when --dc-ip is not provided")
|
||||
dcIPDefaultPool := flag.String("dc-ip-default-pool", "", "Default WS target IP pool for implicit DCs, comma-separated")
|
||||
pprofListen := flag.String("pprof-listen", "", "Optional pprof listen address (e.g. 127.0.0.1:6060)")
|
||||
|
||||
var dcIPs multiFlag
|
||||
var dcIPPools multiFlag
|
||||
flag.Var(&dcIPs, "dc-ip", "Target DC IP as DC:IP; repeatable")
|
||||
flag.Var(&dcIPPools, "dc-ip-pool", "Target pool as DC:IP1,IP2,...; repeatable")
|
||||
flag.Parse()
|
||||
|
||||
if *secret == "" {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
*secret = hex.EncodeToString(b)
|
||||
log.Printf("INFO Generated secret: %s", *secret)
|
||||
}
|
||||
if len(*secret) != 32 {
|
||||
return nil, errors.New("secret must be exactly 32 hex chars")
|
||||
}
|
||||
if _, err := hex.DecodeString(*secret); err != nil {
|
||||
return nil, errors.New("secret must be valid hex")
|
||||
}
|
||||
|
||||
defaultTargetIP := strings.TrimSpace(*dcIPDefault)
|
||||
if net.ParseIP(defaultTargetIP) == nil {
|
||||
return nil, fmt.Errorf("invalid --dc-ip-default: %s", defaultTargetIP)
|
||||
}
|
||||
|
||||
defaultPool := []string{defaultTargetIP}
|
||||
if strings.TrimSpace(*dcIPDefaultPool) != "" {
|
||||
poolIPs, err := parseIPCSV(*dcIPDefaultPool)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid --dc-ip-default-pool: %w", err)
|
||||
}
|
||||
defaultPool = poolIPs
|
||||
}
|
||||
|
||||
dcMap := map[int]string{}
|
||||
dcPool := map[int][]string{}
|
||||
for _, dc := range []int{2, 4} {
|
||||
dcPool[dc] = append([]string(nil), defaultPool...)
|
||||
dcMap[dc] = defaultPool[0]
|
||||
}
|
||||
|
||||
for _, item := range dcIPs {
|
||||
parts := strings.SplitN(item, ":", 2)
|
||||
if len(parts) != 2 {
|
||||
return nil, fmt.Errorf("invalid --dc-ip: %s", item)
|
||||
}
|
||||
dc, err := strconv.Atoi(parts[0])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid dc: %s", parts[0])
|
||||
}
|
||||
if net.ParseIP(parts[1]) == nil {
|
||||
return nil, fmt.Errorf("invalid ip: %s", parts[1])
|
||||
}
|
||||
ip := parts[1]
|
||||
dcPool[dc] = []string{ip}
|
||||
dcMap[dc] = ip
|
||||
}
|
||||
|
||||
for _, item := range dcIPPools {
|
||||
parts := strings.SplitN(item, ":", 2)
|
||||
if len(parts) != 2 {
|
||||
return nil, fmt.Errorf("invalid --dc-ip-pool: %s", item)
|
||||
}
|
||||
dc, err := strconv.Atoi(parts[0])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid dc in --dc-ip-pool: %s", parts[0])
|
||||
}
|
||||
poolIPs, err := parseIPCSV(parts[1])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid --dc-ip-pool for dc %d: %w", dc, err)
|
||||
}
|
||||
dcPool[dc] = append([]string(nil), poolIPs...)
|
||||
dcMap[dc] = dcPool[dc][0]
|
||||
}
|
||||
|
||||
return &Config{
|
||||
Host: *host,
|
||||
Port: *port,
|
||||
SecretHex: *secret,
|
||||
DCMap: dcMap,
|
||||
DCPool: dcPool,
|
||||
Verbose: *verbose,
|
||||
BufKB: maxInt(*bufKB, 4),
|
||||
PoolSize: maxInt(*poolSize, 0),
|
||||
MaxConns: maxInt(*maxConns, 1),
|
||||
LogFile: *logFile,
|
||||
LogMaxMB: *logMaxMB,
|
||||
LogBackups: maxInt(*logBackups, 0),
|
||||
PprofListen: strings.TrimSpace(*pprofListen),
|
||||
}, nil
|
||||
}
|
||||
|
||||
type multiFlag []string
|
||||
|
||||
func (m *multiFlag) String() string { return strings.Join(*m, ",") }
|
||||
func (m *multiFlag) Set(v string) error {
|
||||
*m = append(*m, v)
|
||||
return nil
|
||||
}
|
||||
|
||||
func maxInt(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func parseIPCSV(raw string) ([]string, error) {
|
||||
parts := strings.Split(raw, ",")
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
ip := strings.TrimSpace(p)
|
||||
if ip == "" {
|
||||
continue
|
||||
}
|
||||
if net.ParseIP(ip) == nil {
|
||||
return nil, fmt.Errorf("invalid ip: %s", ip)
|
||||
}
|
||||
out = appendUniqueIP(out, ip)
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil, errors.New("empty ip pool")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func appendUniqueIP(dst []string, ip string) []string {
|
||||
for _, v := range dst {
|
||||
if v == ip {
|
||||
return dst
|
||||
}
|
||||
}
|
||||
return append(dst, ip)
|
||||
}
|
||||
54
src/constants.go
Normal file
54
src/constants.go
Normal file
@ -0,0 +1,54 @@
|
||||
package main
|
||||
|
||||
import "time"
|
||||
|
||||
const (
|
||||
handshakeLen = 64
|
||||
skipLen = 8
|
||||
prekeyLen = 32
|
||||
keyLen = 32
|
||||
ivLen = 16
|
||||
protoTagPos = 56
|
||||
dcIdxPos = 60
|
||||
|
||||
protoAbridgedInt = 0xEFEFEFEF
|
||||
protoIntermediateInt = 0xEEEEEEEE
|
||||
protoPaddedIntermediateInt = 0xDDDDDDDD
|
||||
|
||||
wsPoolMaxAge = 120 * time.Second
|
||||
dcFailCooldown = 30 * time.Second
|
||||
ioIdleTimeout = 90 * time.Second
|
||||
wsWriteTimeout = 15 * time.Second
|
||||
statsFlushBytes = 256 * 1024
|
||||
acceptPollTimeout = 1 * time.Second
|
||||
acceptBackoffMin = 5 * time.Millisecond
|
||||
acceptBackoffMax = 1 * time.Second
|
||||
defaultMaxConns = 1024
|
||||
)
|
||||
|
||||
var (
|
||||
protoTagAbridged = []byte{0xef, 0xef, 0xef, 0xef}
|
||||
protoTagIntermediate = []byte{0xee, 0xee, 0xee, 0xee}
|
||||
protoTagSecure = []byte{0xdd, 0xdd, 0xdd, 0xdd}
|
||||
|
||||
reservedFirst = map[byte]bool{0xef: true}
|
||||
reservedStart = [][]byte{
|
||||
[]byte("HEAD"),
|
||||
[]byte("POST"),
|
||||
[]byte("GET "),
|
||||
{0xee, 0xee, 0xee, 0xee},
|
||||
{0xdd, 0xdd, 0xdd, 0xdd},
|
||||
{0x16, 0x03, 0x01, 0x02},
|
||||
}
|
||||
|
||||
dcFallbackDefaults = map[int]string{
|
||||
1: "149.154.175.50",
|
||||
2: "149.154.167.51",
|
||||
3: "149.154.175.100",
|
||||
4: "149.154.167.91",
|
||||
5: "149.154.171.5",
|
||||
203: "91.105.192.100",
|
||||
}
|
||||
|
||||
dcOverrides = map[int]int{203: 2}
|
||||
)
|
||||
188
src/crypto.go
Normal file
188
src/crypto.go
Normal file
@ -0,0 +1,188 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"math"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func tryHandshake(handshake, secret []byte) (*handshakeInfo, bool) {
|
||||
if len(handshake) != handshakeLen {
|
||||
return nil, false
|
||||
}
|
||||
decPrekeyAndIV := handshake[skipLen : skipLen+prekeyLen+ivLen]
|
||||
decPrekey := decPrekeyAndIV[:prekeyLen]
|
||||
decIV := decPrekeyAndIV[prekeyLen:]
|
||||
|
||||
h := keyFromPrekeyAndSecret(decPrekey, secret)
|
||||
block, err := aes.NewCipher(h[:])
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
dec := cipher.NewCTR(block, decIV)
|
||||
decrypted := make([]byte, len(handshake))
|
||||
dec.XORKeyStream(decrypted, handshake)
|
||||
|
||||
protoTag := decrypted[protoTagPos : protoTagPos+4]
|
||||
if !bytes.Equal(protoTag, protoTagAbridged) && !bytes.Equal(protoTag, protoTagIntermediate) && !bytes.Equal(protoTag, protoTagSecure) {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
dcIdx := int16(binary.LittleEndian.Uint16(decrypted[dcIdxPos : dcIdxPos+2]))
|
||||
dc := int(math.Abs(float64(dcIdx)))
|
||||
isMedia := dcIdx < 0
|
||||
|
||||
pt := make([]byte, 4)
|
||||
copy(pt, protoTag)
|
||||
civ := make([]byte, len(decPrekeyAndIV))
|
||||
copy(civ, decPrekeyAndIV)
|
||||
return &handshakeInfo{DC: dc, IsMedia: isMedia, ProtoTag: pt, ClientDecI: civ}, true
|
||||
}
|
||||
|
||||
func generateRelayInit(protoTag []byte, dcIdx int16) []byte {
|
||||
rnd := make([]byte, handshakeLen)
|
||||
for {
|
||||
_, _ = rand.Read(rnd)
|
||||
if reservedFirst[rnd[0]] {
|
||||
continue
|
||||
}
|
||||
bad := false
|
||||
for _, rs := range reservedStart {
|
||||
if bytes.Equal(rnd[:4], rs) {
|
||||
bad = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if bad {
|
||||
continue
|
||||
}
|
||||
if bytes.Equal(rnd[4:8], []byte{0, 0, 0, 0}) {
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
encKey := rnd[skipLen : skipLen+prekeyLen]
|
||||
encIV := rnd[skipLen+prekeyLen : skipLen+prekeyLen+ivLen]
|
||||
block, _ := aes.NewCipher(encKey)
|
||||
enc := cipher.NewCTR(block, encIV)
|
||||
encryptedFull := make([]byte, handshakeLen)
|
||||
enc.XORKeyStream(encryptedFull, rnd)
|
||||
|
||||
tailPlain := make([]byte, 8)
|
||||
copy(tailPlain[:4], protoTag)
|
||||
binary.LittleEndian.PutUint16(tailPlain[4:6], uint16(dcIdx))
|
||||
_, _ = rand.Read(tailPlain[6:8])
|
||||
|
||||
result := make([]byte, handshakeLen)
|
||||
copy(result, rnd)
|
||||
for i := 0; i < 8; i++ {
|
||||
keystream := encryptedFull[56+i] ^ rnd[56+i]
|
||||
result[56+i] = tailPlain[i] ^ keystream
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func buildCiphers(clientDecPrekeyAndIV, relayInit, secret []byte) (cltDec, cltEnc, tgEnc, tgDec cipher.Stream, err error) {
|
||||
cltDecPrekey := clientDecPrekeyAndIV[:prekeyLen]
|
||||
cltDecIV := clientDecPrekeyAndIV[prekeyLen:]
|
||||
k1 := keyFromPrekeyAndSecret(cltDecPrekey, secret)
|
||||
b1, err := aes.NewCipher(k1[:])
|
||||
if err != nil {
|
||||
return nil, nil, nil, nil, err
|
||||
}
|
||||
cltDec = cipher.NewCTR(b1, cltDecIV)
|
||||
|
||||
rev := reverseBytes(clientDecPrekeyAndIV)
|
||||
encPrekey := rev[:prekeyLen]
|
||||
encIV := rev[prekeyLen:]
|
||||
k2 := keyFromPrekeyAndSecret(encPrekey, secret)
|
||||
b2, err := aes.NewCipher(k2[:])
|
||||
if err != nil {
|
||||
return nil, nil, nil, nil, err
|
||||
}
|
||||
cltEnc = cipher.NewCTR(b2, encIV)
|
||||
|
||||
relayEncKey := relayInit[8:40]
|
||||
relayEncIV := relayInit[40:56]
|
||||
b3, err := aes.NewCipher(relayEncKey)
|
||||
if err != nil {
|
||||
return nil, nil, nil, nil, err
|
||||
}
|
||||
tgEnc = cipher.NewCTR(b3, relayEncIV)
|
||||
|
||||
relayDecPI := reverseBytes(relayInit[8:56])
|
||||
relayDecKey := relayDecPI[:keyLen]
|
||||
relayDecIV := relayDecPI[keyLen:]
|
||||
b4, err := aes.NewCipher(relayDecKey)
|
||||
if err != nil {
|
||||
return nil, nil, nil, nil, err
|
||||
}
|
||||
tgDec = cipher.NewCTR(b4, relayDecIV)
|
||||
|
||||
zeros := make([]byte, handshakeLen)
|
||||
tmp := make([]byte, handshakeLen)
|
||||
cltDec.XORKeyStream(tmp, zeros)
|
||||
tgEnc.XORKeyStream(tmp, zeros)
|
||||
|
||||
return cltDec, cltEnc, tgEnc, tgDec, nil
|
||||
}
|
||||
|
||||
func keyFromPrekeyAndSecret(prekey, secret []byte) [32]byte {
|
||||
b := make([]byte, 0, len(prekey)+len(secret))
|
||||
b = append(b, prekey...)
|
||||
b = append(b, secret...)
|
||||
return sha256.Sum256(b)
|
||||
}
|
||||
|
||||
func reverseBytes(in []byte) []byte {
|
||||
out := make([]byte, len(in))
|
||||
for i := range in {
|
||||
out[len(in)-1-i] = in[i]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func protoFromTag(tag []byte) uint32 {
|
||||
switch {
|
||||
case bytes.Equal(tag, protoTagAbridged):
|
||||
return protoAbridgedInt
|
||||
case bytes.Equal(tag, protoTagIntermediate):
|
||||
return protoIntermediateInt
|
||||
default:
|
||||
return protoPaddedIntermediateInt
|
||||
}
|
||||
}
|
||||
|
||||
func wsDomains(dc int, isMedia bool) []string {
|
||||
dcS := strconv.Itoa(dc)
|
||||
if isMedia {
|
||||
return []string{
|
||||
"kws" + dcS + "-1.web.telegram.org",
|
||||
"kws" + dcS + ".web.telegram.org",
|
||||
}
|
||||
}
|
||||
return []string{
|
||||
"kws" + dcS + ".web.telegram.org",
|
||||
"kws" + dcS + "-1.web.telegram.org",
|
||||
}
|
||||
}
|
||||
|
||||
func signedDC(dc int, media bool) int16 {
|
||||
if media {
|
||||
return int16(-dc)
|
||||
}
|
||||
return int16(dc)
|
||||
}
|
||||
|
||||
func fallbackIP(dc int) string {
|
||||
if ip, ok := dcFallbackDefaults[dc]; ok {
|
||||
return ip
|
||||
}
|
||||
return ""
|
||||
}
|
||||
5
src/errors.go
Normal file
5
src/errors.go
Normal file
@ -0,0 +1,5 @@
|
||||
package main
|
||||
|
||||
import "errors"
|
||||
|
||||
var errNoDomains = errors.New("no domains to connect")
|
||||
5
src/go.mod
Normal file
5
src/go.mod
Normal file
@ -0,0 +1,5 @@
|
||||
module tg-ws-proxy
|
||||
|
||||
go 1.22
|
||||
|
||||
require github.com/gorilla/websocket v1.5.3
|
||||
2
src/go.sum
Normal file
2
src/go.sum
Normal file
@ -0,0 +1,2 @@
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
98
src/logging.go
Normal file
98
src/logging.go
Normal file
@ -0,0 +1,98 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
_ "net/http/pprof"
|
||||
"os"
|
||||
"sync"
|
||||
)
|
||||
|
||||
func initLogger(cfg *Config) {
|
||||
log.SetFlags(log.Ltime)
|
||||
if cfg.LogFile == "" {
|
||||
return
|
||||
}
|
||||
f, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
|
||||
if err != nil {
|
||||
log.Printf("WARN failed to open log file %s: %v", cfg.LogFile, err)
|
||||
return
|
||||
}
|
||||
log.SetOutput(newRotatingWriter(f, cfg.LogFile, cfg.LogMaxMB, cfg.LogBackups))
|
||||
}
|
||||
|
||||
func startPprof(cfg *Config) {
|
||||
if cfg.PprofListen == "" {
|
||||
return
|
||||
}
|
||||
go func(addr string) {
|
||||
log.Printf("INFO pprof enabled on http://%s/debug/pprof/", addr)
|
||||
if err := http.ListenAndServe(addr, nil); err != nil {
|
||||
log.Printf("WARN pprof server stopped: %v", err)
|
||||
}
|
||||
}(cfg.PprofListen)
|
||||
}
|
||||
|
||||
type rotatingWriter struct {
|
||||
mu sync.Mutex
|
||||
f *os.File
|
||||
path string
|
||||
maxBytes int64
|
||||
backups int
|
||||
checkTick int
|
||||
}
|
||||
|
||||
func newRotatingWriter(f *os.File, path string, maxMB float64, backups int) *rotatingWriter {
|
||||
maxBytes := int64(maxMB * 1024 * 1024)
|
||||
if maxBytes < 32*1024 {
|
||||
maxBytes = 32 * 1024
|
||||
}
|
||||
return &rotatingWriter{f: f, path: path, maxBytes: maxBytes, backups: backups}
|
||||
}
|
||||
|
||||
func (w *rotatingWriter) Write(p []byte) (int, error) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
w.checkTick++
|
||||
if w.checkTick%32 == 0 {
|
||||
if st, err := w.f.Stat(); err == nil && st.Size() >= w.maxBytes {
|
||||
_ = w.rotate()
|
||||
}
|
||||
}
|
||||
return w.f.Write(p)
|
||||
}
|
||||
|
||||
func (w *rotatingWriter) rotate() error {
|
||||
_ = w.f.Close()
|
||||
if w.backups > 0 {
|
||||
for i := w.backups - 1; i >= 1; i-- {
|
||||
old := fmt.Sprintf("%s.%d", w.path, i)
|
||||
newp := fmt.Sprintf("%s.%d", w.path, i+1)
|
||||
_ = os.Rename(old, newp)
|
||||
}
|
||||
_ = os.Rename(w.path, fmt.Sprintf("%s.1", w.path))
|
||||
} else {
|
||||
_ = os.Remove(w.path)
|
||||
}
|
||||
f, err := os.OpenFile(w.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
w.f = f
|
||||
return nil
|
||||
}
|
||||
|
||||
func debugf(cfg *Config, format string, args ...any) {
|
||||
if cfg.Verbose {
|
||||
log.Printf("DEBUG "+format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func warnf(format string, args ...any) {
|
||||
log.Printf("WARNING "+format, args...)
|
||||
}
|
||||
|
||||
func logf(format string, args ...any) {
|
||||
log.Printf(format, args...)
|
||||
}
|
||||
107
src/pool.go
Normal file
107
src/pool.go
Normal file
@ -0,0 +1,107 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
type pooledWS struct {
|
||||
Conn *websocket.Conn
|
||||
Created time.Time
|
||||
}
|
||||
|
||||
type wsPool struct {
|
||||
mu sync.Mutex
|
||||
idle map[dcKey][]pooledWS
|
||||
refilling map[dcKey]bool
|
||||
}
|
||||
|
||||
func newWSPool() *wsPool {
|
||||
return &wsPool{
|
||||
idle: make(map[dcKey][]pooledWS),
|
||||
refilling: make(map[dcKey]bool),
|
||||
}
|
||||
}
|
||||
|
||||
func (p *wsPool) get(cfg *Config, key dcKey, targetIP string, domains []string, st *Stats) *websocket.Conn {
|
||||
now := time.Now()
|
||||
p.mu.Lock()
|
||||
bucket := p.idle[key]
|
||||
for len(bucket) > 0 {
|
||||
item := bucket[0]
|
||||
bucket = bucket[1:]
|
||||
if now.Sub(item.Created) > wsPoolMaxAge {
|
||||
_ = item.Conn.Close()
|
||||
continue
|
||||
}
|
||||
p.idle[key] = bucket
|
||||
p.scheduleRefill(cfg, key, targetIP, domains)
|
||||
p.mu.Unlock()
|
||||
atomic.AddInt64(&st.poolHits, 1)
|
||||
return item.Conn
|
||||
}
|
||||
p.idle[key] = bucket
|
||||
p.scheduleRefill(cfg, key, targetIP, domains)
|
||||
p.mu.Unlock()
|
||||
atomic.AddInt64(&st.poolMisses, 1)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *wsPool) scheduleRefill(cfg *Config, key dcKey, targetIP string, domains []string) {
|
||||
if cfg.PoolSize <= 0 || p.refilling[key] {
|
||||
return
|
||||
}
|
||||
p.refilling[key] = true
|
||||
go p.refill(cfg, key, targetIP, domains)
|
||||
}
|
||||
|
||||
func (p *wsPool) refill(cfg *Config, key dcKey, targetIP string, domains []string) {
|
||||
defer func() {
|
||||
p.mu.Lock()
|
||||
delete(p.refilling, key)
|
||||
p.mu.Unlock()
|
||||
}()
|
||||
|
||||
for {
|
||||
p.mu.Lock()
|
||||
cur := len(p.idle[key])
|
||||
p.mu.Unlock()
|
||||
if cur >= cfg.PoolSize {
|
||||
return
|
||||
}
|
||||
conn, _, err := wsConnect(targetIP, domains, 8*time.Second)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
p.mu.Lock()
|
||||
p.idle[key] = append(p.idle[key], pooledWS{Conn: conn, Created: time.Now()})
|
||||
p.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func warmupPool(cfg *Config) {
|
||||
if cfg.PoolSize <= 0 {
|
||||
return
|
||||
}
|
||||
for dc, targets := range cfg.DCPool {
|
||||
if len(targets) == 0 {
|
||||
continue
|
||||
}
|
||||
ip := targets[0]
|
||||
for _, media := range []bool{false, true} {
|
||||
dcw := dc
|
||||
if v, ok := dcOverrides[dcw]; ok {
|
||||
dcw = v
|
||||
}
|
||||
key := dcKey{DC: dc, IsMedia: media}
|
||||
domains := wsDomains(dcw, media)
|
||||
pool.mu.Lock()
|
||||
pool.scheduleRefill(cfg, key, ip, domains)
|
||||
pool.mu.Unlock()
|
||||
}
|
||||
}
|
||||
logf("INFO WS pool warmup started for %d DC(s)", len(cfg.DCMap))
|
||||
}
|
||||
263
src/server.go
Normal file
263
src/server.go
Normal file
@ -0,0 +1,263 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg, err := parseFlags()
|
||||
if err != nil {
|
||||
log.Fatalf("config error: %v", err)
|
||||
}
|
||||
|
||||
initLogger(cfg)
|
||||
startPprof(cfg)
|
||||
|
||||
linkHost := getLinkHost(cfg.Host)
|
||||
log.Printf("INFO %s", strings.Repeat("=", 60))
|
||||
log.Printf("INFO Telegram MTProto WS Bridge Proxy (Go)")
|
||||
log.Printf("INFO Listening on %s:%d", cfg.Host, cfg.Port)
|
||||
log.Printf("INFO Secret: %s", cfg.SecretHex)
|
||||
log.Printf("INFO Target DC IPs:")
|
||||
for _, item := range sortedDCMap(cfg.DCMap) {
|
||||
dc, ip := item.dc, item.ip
|
||||
log.Printf("INFO DC%d: %s", dc, ip)
|
||||
}
|
||||
log.Printf("INFO %s", strings.Repeat("=", 60))
|
||||
log.Printf("INFO Connect link:")
|
||||
log.Printf("INFO tg://proxy?server=%s&port=%d&secret=dd%s", linkHost, cfg.Port, cfg.SecretHex)
|
||||
log.Printf("INFO %s", strings.Repeat("=", 60))
|
||||
|
||||
go func() {
|
||||
for {
|
||||
time.Sleep(60 * time.Second)
|
||||
log.Printf("INFO stats: %s", stats.summary())
|
||||
}
|
||||
}()
|
||||
|
||||
warmupPool(cfg)
|
||||
|
||||
ln, err := net.Listen("tcp", net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)))
|
||||
if err != nil {
|
||||
log.Fatalf("listen error: %v", err)
|
||||
}
|
||||
defer ln.Close()
|
||||
|
||||
secret, _ := hex.DecodeString(cfg.SecretHex)
|
||||
sessionsSem := make(chan struct{}, cfg.MaxConns)
|
||||
|
||||
acceptBackoff := acceptBackoffMin
|
||||
tcpLn, _ := ln.(*net.TCPListener)
|
||||
|
||||
for {
|
||||
if tcpLn != nil {
|
||||
_ = tcpLn.SetDeadline(time.Now().Add(acceptPollTimeout))
|
||||
}
|
||||
c, err := ln.Accept()
|
||||
if err != nil {
|
||||
if ne, ok := err.(net.Error); ok && ne.Timeout() {
|
||||
acceptBackoff = acceptBackoffMin
|
||||
continue
|
||||
}
|
||||
log.Printf("WARN accept error: %v", err)
|
||||
time.Sleep(acceptBackoff)
|
||||
acceptBackoff *= 2
|
||||
if acceptBackoff > acceptBackoffMax {
|
||||
acceptBackoff = acceptBackoffMax
|
||||
}
|
||||
continue
|
||||
}
|
||||
acceptBackoff = acceptBackoffMin
|
||||
atomic.AddInt64(&stats.connectionsTotal, 1)
|
||||
|
||||
select {
|
||||
case sessionsSem <- struct{}{}:
|
||||
go func(conn net.Conn) {
|
||||
defer func() { <-sessionsSem }()
|
||||
handleClient(conn, cfg, secret)
|
||||
}(c)
|
||||
default:
|
||||
log.Printf("WARN max concurrent sessions reached (%d), dropping %s", cfg.MaxConns, c.RemoteAddr())
|
||||
_ = c.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func handleClient(client net.Conn, cfg *Config, secret []byte) {
|
||||
atomic.AddInt64(&stats.connectionsActive, 1)
|
||||
defer atomic.AddInt64(&stats.connectionsActive, -1)
|
||||
defer client.Close()
|
||||
label := client.RemoteAddr().String()
|
||||
|
||||
_ = setSockOpts(client, cfg.BufKB*1024)
|
||||
|
||||
_ = client.SetReadDeadline(time.Now().Add(10 * time.Second))
|
||||
hs := make([]byte, handshakeLen)
|
||||
if _, err := io.ReadFull(client, hs); err != nil {
|
||||
debugf(cfg, "[%s] client disconnected before handshake", label)
|
||||
return
|
||||
}
|
||||
_ = client.SetReadDeadline(time.Time{})
|
||||
|
||||
hi, ok := tryHandshake(hs, secret)
|
||||
if !ok {
|
||||
atomic.AddInt64(&stats.connectionsBad, 1)
|
||||
debugf(cfg, "[%s] bad handshake", label)
|
||||
return
|
||||
}
|
||||
|
||||
protoInt := protoFromTag(hi.ProtoTag)
|
||||
mediaTag := ""
|
||||
if hi.IsMedia {
|
||||
mediaTag = " media"
|
||||
}
|
||||
|
||||
relayInit := generateRelayInit(hi.ProtoTag, signedDC(hi.DC, hi.IsMedia))
|
||||
cltDec, cltEnc, tgEnc, tgDec, err := buildCiphers(hi.ClientDecI, relayInit, secret)
|
||||
if err != nil {
|
||||
log.Printf("ERROR [%s] cipher init failed: %v", label, err)
|
||||
return
|
||||
}
|
||||
|
||||
if isBlacklisted(hi.DC, hi.IsMedia) {
|
||||
fallback := fallbackIP(hi.DC)
|
||||
if fallback == "" {
|
||||
log.Printf("WARN [%s] DC%d%s WS blacklisted and no fallback", label, hi.DC, mediaTag)
|
||||
return
|
||||
}
|
||||
log.Printf("INFO [%s] DC%d%s WS blacklisted -> TCP fallback %s:443", label, hi.DC, mediaTag, fallback)
|
||||
_ = tcpFallback(client, fallback, relayInit, cltDec, cltEnc, tgEnc, tgDec)
|
||||
return
|
||||
}
|
||||
|
||||
targets, hasTarget := cfg.DCPool[hi.DC]
|
||||
if !hasTarget || len(targets) == 0 {
|
||||
fallback := fallbackIP(hi.DC)
|
||||
if fallback == "" {
|
||||
log.Printf("WARN [%s] DC%d%s no fallback available", label, hi.DC, mediaTag)
|
||||
return
|
||||
}
|
||||
log.Printf("INFO [%s] DC%d not in config -> TCP fallback %s:443", label, hi.DC, fallback)
|
||||
_ = tcpFallback(client, fallback, relayInit, cltDec, cltEnc, tgEnc, tgDec)
|
||||
return
|
||||
}
|
||||
primaryTarget := targets[0]
|
||||
|
||||
dcW := hi.DC
|
||||
if v, ok := dcOverrides[dcW]; ok {
|
||||
dcW = v
|
||||
}
|
||||
domains := wsDomains(dcW, hi.IsMedia)
|
||||
key := dcKey{DC: hi.DC, IsMedia: hi.IsMedia}
|
||||
connectWS := func(timeout time.Duration) (*websocket.Conn, bool, bool) {
|
||||
wsFailedRedirect := false
|
||||
allRedirect := true
|
||||
for _, target := range targets {
|
||||
for _, d := range domains {
|
||||
debugf(cfg, "[%s] DC%d%s -> wss://%s/apiws via %s", label, hi.DC, mediaTag, d, target)
|
||||
conn, resp, err := wsConnect(target, []string{d}, timeout)
|
||||
if err == nil {
|
||||
allRedirect = false
|
||||
return conn, wsFailedRedirect, allRedirect
|
||||
}
|
||||
atomic.AddInt64(&stats.wsErrors, 1)
|
||||
if resp != nil && isRedirect(resp.StatusCode) {
|
||||
wsFailedRedirect = true
|
||||
warnf("[%s] DC%d%s got %d from %s via %s", label, hi.DC, mediaTag, resp.StatusCode, d, target)
|
||||
continue
|
||||
}
|
||||
allRedirect = false
|
||||
warnf("[%s] DC%d%s WS connect failed via %s: %v", label, hi.DC, mediaTag, target, err)
|
||||
}
|
||||
}
|
||||
return nil, wsFailedRedirect, allRedirect
|
||||
}
|
||||
fallbackToTCP := func(wsFailedRedirect, allRedirect bool) {
|
||||
if wsFailedRedirect && allRedirect {
|
||||
setBlacklisted(key)
|
||||
warnf("[%s] DC%d%s blacklisted for WS (all redirects)", label, hi.DC, mediaTag)
|
||||
} else {
|
||||
setCooldown(key)
|
||||
}
|
||||
fallback := fallbackIP(hi.DC)
|
||||
if fallback == "" {
|
||||
fallback = primaryTarget
|
||||
}
|
||||
log.Printf("INFO [%s] DC%d%s -> TCP fallback to %s:443", label, hi.DC, mediaTag, fallback)
|
||||
err := tcpFallback(client, fallback, relayInit, cltDec, cltEnc, tgEnc, tgDec)
|
||||
if err == nil {
|
||||
log.Printf("INFO [%s] DC%d%s TCP fallback closed", label, hi.DC, mediaTag)
|
||||
}
|
||||
}
|
||||
|
||||
var ws *websocket.Conn
|
||||
fromPool := false
|
||||
if pooled := pool.get(cfg, key, primaryTarget, domains, &stats); pooled != nil {
|
||||
ws = pooled
|
||||
fromPool = true
|
||||
log.Printf("INFO [%s] DC%d%s -> pool hit via %s", label, hi.DC, mediaTag, primaryTarget)
|
||||
}
|
||||
|
||||
if ws == nil {
|
||||
timeout := 10 * time.Second
|
||||
if inCooldown(key) {
|
||||
timeout = 2 * time.Second
|
||||
}
|
||||
wsFailedRedirect := false
|
||||
allRedirect := true
|
||||
ws, wsFailedRedirect, allRedirect = connectWS(timeout)
|
||||
|
||||
if ws == nil {
|
||||
fallbackToTCP(wsFailedRedirect, allRedirect)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var splitter *msgSplitter
|
||||
if ms, err := newMsgSplitter(relayInit, protoInt); err == nil {
|
||||
splitter = ms
|
||||
}
|
||||
|
||||
if err := ws.WriteMessage(websocket.BinaryMessage, relayInit); err != nil {
|
||||
warnf("[%s] ws init write failed: %v", label, err)
|
||||
_ = ws.Close()
|
||||
if !fromPool {
|
||||
setCooldown(key)
|
||||
fallbackToTCP(false, false)
|
||||
return
|
||||
}
|
||||
|
||||
timeout := 10 * time.Second
|
||||
if inCooldown(key) {
|
||||
timeout = 2 * time.Second
|
||||
}
|
||||
wsFailedRedirect := false
|
||||
allRedirect := true
|
||||
ws, wsFailedRedirect, allRedirect = connectWS(timeout)
|
||||
if ws == nil {
|
||||
fallbackToTCP(wsFailedRedirect, allRedirect)
|
||||
return
|
||||
}
|
||||
if err := ws.WriteMessage(websocket.BinaryMessage, relayInit); err != nil {
|
||||
warnf("[%s] ws init write failed after pool retry: %v", label, err)
|
||||
_ = ws.Close()
|
||||
setCooldown(key)
|
||||
fallbackToTCP(false, false)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
clearCooldown(key)
|
||||
atomic.AddInt64(&stats.connectionsWS, 1)
|
||||
|
||||
bridgeWS(label, hi.DC, hi.IsMedia, client, ws, cltDec, cltEnc, tgEnc, tgDec, splitter)
|
||||
}
|
||||
122
src/splitter.go
Normal file
122
src/splitter.go
Normal file
@ -0,0 +1,122 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"encoding/binary"
|
||||
)
|
||||
|
||||
type msgSplitter struct {
|
||||
dec cipher.Stream
|
||||
proto uint32
|
||||
cipherBuf []byte
|
||||
plainBuf []byte
|
||||
disabled bool
|
||||
}
|
||||
|
||||
func newMsgSplitter(relayInit []byte, proto uint32) (*msgSplitter, error) {
|
||||
b, err := aes.NewCipher(relayInit[8:40])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dec := cipher.NewCTR(b, relayInit[40:56])
|
||||
zero := make([]byte, handshakeLen)
|
||||
tmp := make([]byte, handshakeLen)
|
||||
dec.XORKeyStream(tmp, zero)
|
||||
return &msgSplitter{dec: dec, proto: proto}, nil
|
||||
}
|
||||
|
||||
func (m *msgSplitter) split(chunk []byte) [][]byte {
|
||||
if len(chunk) == 0 {
|
||||
return nil
|
||||
}
|
||||
if m.disabled {
|
||||
return [][]byte{chunk}
|
||||
}
|
||||
|
||||
m.cipherBuf = append(m.cipherBuf, chunk...)
|
||||
plainStart := len(m.plainBuf)
|
||||
m.plainBuf = append(m.plainBuf, make([]byte, len(chunk))...)
|
||||
m.dec.XORKeyStream(m.plainBuf[plainStart:], chunk)
|
||||
|
||||
parts := make([][]byte, 0, 2)
|
||||
for len(m.cipherBuf) > 0 {
|
||||
next := m.nextPacketLen()
|
||||
if next < 0 {
|
||||
break
|
||||
}
|
||||
if next == 0 {
|
||||
parts = append(parts, m.cipherBuf)
|
||||
m.cipherBuf = m.cipherBuf[:0]
|
||||
m.plainBuf = m.plainBuf[:0]
|
||||
m.disabled = true
|
||||
break
|
||||
}
|
||||
parts = append(parts, m.cipherBuf[:next])
|
||||
m.cipherBuf = m.cipherBuf[next:]
|
||||
m.plainBuf = m.plainBuf[next:]
|
||||
}
|
||||
return parts
|
||||
}
|
||||
|
||||
func (m *msgSplitter) flush() [][]byte {
|
||||
if len(m.cipherBuf) == 0 {
|
||||
return nil
|
||||
}
|
||||
tail := m.cipherBuf
|
||||
m.cipherBuf = m.cipherBuf[:0]
|
||||
m.plainBuf = m.plainBuf[:0]
|
||||
return [][]byte{tail}
|
||||
}
|
||||
|
||||
func (m *msgSplitter) nextPacketLen() int {
|
||||
if len(m.plainBuf) == 0 {
|
||||
return -1
|
||||
}
|
||||
switch m.proto {
|
||||
case protoAbridgedInt:
|
||||
return m.nextAbridgedLen()
|
||||
case protoIntermediateInt, protoPaddedIntermediateInt:
|
||||
return m.nextIntermediateLen()
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func (m *msgSplitter) nextAbridgedLen() int {
|
||||
first := m.plainBuf[0]
|
||||
headerLen := 1
|
||||
payloadLen := 0
|
||||
if first == 0x7F || first == 0xFF {
|
||||
if len(m.plainBuf) < 4 {
|
||||
return -1
|
||||
}
|
||||
headerLen = 4
|
||||
payloadLen = int(uint32(m.plainBuf[1])|uint32(m.plainBuf[2])<<8|uint32(m.plainBuf[3])<<16) * 4
|
||||
} else {
|
||||
payloadLen = int(first&0x7F) * 4
|
||||
}
|
||||
if payloadLen <= 0 {
|
||||
return 0
|
||||
}
|
||||
packetLen := headerLen + payloadLen
|
||||
if len(m.plainBuf) < packetLen {
|
||||
return -1
|
||||
}
|
||||
return packetLen
|
||||
}
|
||||
|
||||
func (m *msgSplitter) nextIntermediateLen() int {
|
||||
if len(m.plainBuf) < 4 {
|
||||
return -1
|
||||
}
|
||||
payloadLen := int(binary.LittleEndian.Uint32(m.plainBuf[:4]) & 0x7FFFFFFF)
|
||||
if payloadLen <= 0 {
|
||||
return 0
|
||||
}
|
||||
packetLen := 4 + payloadLen
|
||||
if len(m.plainBuf) < packetLen {
|
||||
return -1
|
||||
}
|
||||
return packetLen
|
||||
}
|
||||
59
src/state.go
Normal file
59
src/state.go
Normal file
@ -0,0 +1,59 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
stats Stats
|
||||
pool = newWSPool()
|
||||
blacklist = make(map[dcKey]struct{})
|
||||
blMu sync.Mutex
|
||||
failUntil = make(map[dcKey]time.Time)
|
||||
fuMu sync.Mutex
|
||||
)
|
||||
|
||||
func setCooldown(k dcKey) {
|
||||
fuMu.Lock()
|
||||
failUntil[k] = time.Now().Add(dcFailCooldown)
|
||||
fuMu.Unlock()
|
||||
}
|
||||
|
||||
func inCooldown(k dcKey) bool {
|
||||
fuMu.Lock()
|
||||
t, ok := failUntil[k]
|
||||
fuMu.Unlock()
|
||||
return ok && time.Now().Before(t)
|
||||
}
|
||||
|
||||
func clearCooldown(k dcKey) {
|
||||
fuMu.Lock()
|
||||
delete(failUntil, k)
|
||||
fuMu.Unlock()
|
||||
}
|
||||
|
||||
func setBlacklisted(k dcKey) {
|
||||
blMu.Lock()
|
||||
blacklist[k] = struct{}{}
|
||||
blMu.Unlock()
|
||||
}
|
||||
|
||||
func isBlacklisted(dc int, media bool) bool {
|
||||
blMu.Lock()
|
||||
_, ok := blacklist[dcKey{DC: dc, IsMedia: media}]
|
||||
blMu.Unlock()
|
||||
return ok
|
||||
}
|
||||
|
||||
func sortedDCMap(m map[int]string) []dcMapItem {
|
||||
items := make([]dcMapItem, 0, len(m))
|
||||
for dc, ip := range m {
|
||||
items = append(items, dcMapItem{dc: dc, ip: ip})
|
||||
}
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
return items[i].dc < items[j].dc
|
||||
})
|
||||
return items
|
||||
}
|
||||
261
src/transport.go
Normal file
261
src/transport.go
Normal file
@ -0,0 +1,261 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/cipher"
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
var ioBufPool = sync.Pool{
|
||||
New: func() any {
|
||||
return make([]byte, 64*1024)
|
||||
},
|
||||
}
|
||||
|
||||
func dialWS(targetIP, domain string, timeout time.Duration) (*websocket.Conn, *http.Response, error) {
|
||||
u := url.URL{Scheme: "wss", Host: domain, Path: "/apiws"}
|
||||
dialer := websocket.Dialer{
|
||||
HandshakeTimeout: timeout,
|
||||
Subprotocols: []string{"binary"},
|
||||
TLSClientConfig: &tls.Config{
|
||||
ServerName: domain,
|
||||
InsecureSkipVerify: true,
|
||||
},
|
||||
NetDialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
d := &net.Dialer{Timeout: timeout}
|
||||
return d.DialContext(ctx, "tcp", net.JoinHostPort(targetIP, "443"))
|
||||
},
|
||||
}
|
||||
headers := http.Header{}
|
||||
headers.Set("Host", domain)
|
||||
headers.Set("Origin", "https://web.telegram.org")
|
||||
headers.Set("User-Agent", "Mozilla/5.0")
|
||||
return dialer.Dial(u.String(), headers)
|
||||
}
|
||||
|
||||
func bridgeWS(label string, dc int, isMedia bool, client net.Conn, ws *websocket.Conn, cltDec, cltEnc, tgEnc, tgDec cipher.Stream, splitter *msgSplitter) {
|
||||
mediaTag := ""
|
||||
if isMedia {
|
||||
mediaTag = "m"
|
||||
}
|
||||
start := time.Now()
|
||||
var upBytes, downBytes int64
|
||||
var upPkts, downPkts int64
|
||||
|
||||
done := make(chan struct{}, 2)
|
||||
|
||||
go func() {
|
||||
defer func() { done <- struct{}{} }()
|
||||
buf := ioBufPool.Get().([]byte)
|
||||
defer ioBufPool.Put(buf)
|
||||
var upPending int64
|
||||
defer func() {
|
||||
if upPending > 0 {
|
||||
atomic.AddInt64(&stats.bytesUp, upPending)
|
||||
}
|
||||
}()
|
||||
for {
|
||||
_ = client.SetReadDeadline(time.Now().Add(ioIdleTimeout))
|
||||
n, err := client.Read(buf)
|
||||
if n > 0 {
|
||||
upPending += int64(n)
|
||||
upBytes += int64(n)
|
||||
upPkts++
|
||||
if upPending >= statsFlushBytes {
|
||||
atomic.AddInt64(&stats.bytesUp, upPending)
|
||||
upPending = 0
|
||||
}
|
||||
chunk := buf[:n]
|
||||
cltDec.XORKeyStream(chunk, chunk)
|
||||
tgEnc.XORKeyStream(chunk, chunk)
|
||||
|
||||
if splitter != nil {
|
||||
parts := splitter.split(chunk)
|
||||
if len(parts) == 0 {
|
||||
continue
|
||||
}
|
||||
for _, p := range parts {
|
||||
_ = ws.SetWriteDeadline(time.Now().Add(wsWriteTimeout))
|
||||
if werr := ws.WriteMessage(websocket.BinaryMessage, p); werr != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
} else {
|
||||
_ = ws.SetWriteDeadline(time.Now().Add(wsWriteTimeout))
|
||||
if werr := ws.WriteMessage(websocket.BinaryMessage, chunk); werr != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
if splitter != nil {
|
||||
for _, p := range splitter.flush() {
|
||||
_ = ws.SetWriteDeadline(time.Now().Add(wsWriteTimeout))
|
||||
_ = ws.WriteMessage(websocket.BinaryMessage, p)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
defer func() { done <- struct{}{} }()
|
||||
var downPending int64
|
||||
defer func() {
|
||||
if downPending > 0 {
|
||||
atomic.AddInt64(&stats.bytesDown, downPending)
|
||||
}
|
||||
}()
|
||||
for {
|
||||
_ = ws.SetReadDeadline(time.Now().Add(ioIdleTimeout))
|
||||
mt, data, err := ws.ReadMessage()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if mt != websocket.BinaryMessage {
|
||||
continue
|
||||
}
|
||||
n := int64(len(data))
|
||||
downPending += n
|
||||
downBytes += n
|
||||
downPkts++
|
||||
if downPending >= statsFlushBytes {
|
||||
atomic.AddInt64(&stats.bytesDown, downPending)
|
||||
downPending = 0
|
||||
}
|
||||
|
||||
tgDec.XORKeyStream(data, data)
|
||||
cltEnc.XORKeyStream(data, data)
|
||||
_ = client.SetWriteDeadline(time.Now().Add(ioIdleTimeout))
|
||||
if _, werr := client.Write(data); werr != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
<-done
|
||||
_ = ws.Close()
|
||||
_ = client.Close()
|
||||
logf("INFO [%s] DC%d%s WS session closed: ^%s (%d pkts) v%s (%d pkts) in %.1fs",
|
||||
label,
|
||||
dc,
|
||||
mediaTag,
|
||||
humanBytes(upBytes),
|
||||
upPkts,
|
||||
humanBytes(downBytes),
|
||||
downPkts,
|
||||
time.Since(start).Seconds(),
|
||||
)
|
||||
}
|
||||
|
||||
func tcpFallback(client net.Conn, dst string, relayInit []byte, cltDec, cltEnc, tgEnc, tgDec cipher.Stream) error {
|
||||
r, err := net.DialTimeout("tcp", net.JoinHostPort(dst, "443"), 10*time.Second)
|
||||
if err != nil {
|
||||
logf("WARNING TCP fallback to %s:443 failed: %v", dst, err)
|
||||
return err
|
||||
}
|
||||
defer r.Close()
|
||||
atomic.AddInt64(&stats.connectionsTCP, 1)
|
||||
|
||||
if _, err := r.Write(relayInit); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
done := make(chan struct{}, 2)
|
||||
go func() {
|
||||
defer func() { done <- struct{}{} }()
|
||||
buf := ioBufPool.Get().([]byte)
|
||||
defer ioBufPool.Put(buf)
|
||||
var upPending int64
|
||||
defer func() {
|
||||
if upPending > 0 {
|
||||
atomic.AddInt64(&stats.bytesUp, upPending)
|
||||
}
|
||||
}()
|
||||
for {
|
||||
_ = client.SetReadDeadline(time.Now().Add(ioIdleTimeout))
|
||||
n, err := client.Read(buf)
|
||||
if n > 0 {
|
||||
upPending += int64(n)
|
||||
if upPending >= statsFlushBytes {
|
||||
atomic.AddInt64(&stats.bytesUp, upPending)
|
||||
upPending = 0
|
||||
}
|
||||
chunk := buf[:n]
|
||||
cltDec.XORKeyStream(chunk, chunk)
|
||||
tgEnc.XORKeyStream(chunk, chunk)
|
||||
_ = r.SetWriteDeadline(time.Now().Add(ioIdleTimeout))
|
||||
if _, werr := r.Write(chunk); werr != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
defer func() { done <- struct{}{} }()
|
||||
buf := ioBufPool.Get().([]byte)
|
||||
defer ioBufPool.Put(buf)
|
||||
var downPending int64
|
||||
defer func() {
|
||||
if downPending > 0 {
|
||||
atomic.AddInt64(&stats.bytesDown, downPending)
|
||||
}
|
||||
}()
|
||||
for {
|
||||
_ = r.SetReadDeadline(time.Now().Add(ioIdleTimeout))
|
||||
n, err := r.Read(buf)
|
||||
if n > 0 {
|
||||
downPending += int64(n)
|
||||
if downPending >= statsFlushBytes {
|
||||
atomic.AddInt64(&stats.bytesDown, downPending)
|
||||
downPending = 0
|
||||
}
|
||||
chunk := buf[:n]
|
||||
tgDec.XORKeyStream(chunk, chunk)
|
||||
cltEnc.XORKeyStream(chunk, chunk)
|
||||
_ = client.SetWriteDeadline(time.Now().Add(ioIdleTimeout))
|
||||
if _, werr := client.Write(chunk); werr != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
<-done
|
||||
_ = client.Close()
|
||||
_ = r.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func wsConnect(targetIP string, domains []string, timeout time.Duration) (*websocket.Conn, *http.Response, error) {
|
||||
var lastErr error
|
||||
var lastResp *http.Response
|
||||
for _, domain := range domains {
|
||||
conn, resp, err := dialWS(targetIP, domain, timeout)
|
||||
if err == nil {
|
||||
return conn, resp, nil
|
||||
}
|
||||
lastErr = err
|
||||
lastResp = resp
|
||||
}
|
||||
if lastErr == nil {
|
||||
lastErr = errNoDomains
|
||||
}
|
||||
return nil, lastResp, lastErr
|
||||
}
|
||||
74
src/types.go
Normal file
74
src/types.go
Normal file
@ -0,0 +1,74 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port int
|
||||
SecretHex string
|
||||
DCMap map[int]string
|
||||
DCPool map[int][]string
|
||||
Verbose bool
|
||||
BufKB int
|
||||
PoolSize int
|
||||
MaxConns int
|
||||
LogFile string
|
||||
LogMaxMB float64
|
||||
LogBackups int
|
||||
PprofListen string
|
||||
}
|
||||
|
||||
type Stats struct {
|
||||
connectionsTotal int64
|
||||
connectionsActive int64
|
||||
connectionsWS int64
|
||||
connectionsTCP int64
|
||||
connectionsBad int64
|
||||
wsErrors int64
|
||||
bytesUp int64
|
||||
bytesDown int64
|
||||
poolHits int64
|
||||
poolMisses int64
|
||||
}
|
||||
|
||||
func (s *Stats) summary() string {
|
||||
hits := atomic.LoadInt64(&s.poolHits)
|
||||
misses := atomic.LoadInt64(&s.poolMisses)
|
||||
poolTotal := hits + misses
|
||||
poolS := "n/a"
|
||||
if poolTotal > 0 {
|
||||
poolS = fmt.Sprintf("%d/%d", hits, poolTotal)
|
||||
}
|
||||
return fmt.Sprintf(
|
||||
"total=%d active=%d ws=%d tcp_fb=%d bad=%d err=%d pool=%s up=%s down=%s",
|
||||
atomic.LoadInt64(&s.connectionsTotal),
|
||||
atomic.LoadInt64(&s.connectionsActive),
|
||||
atomic.LoadInt64(&s.connectionsWS),
|
||||
atomic.LoadInt64(&s.connectionsTCP),
|
||||
atomic.LoadInt64(&s.connectionsBad),
|
||||
atomic.LoadInt64(&s.wsErrors),
|
||||
poolS,
|
||||
humanBytes(atomic.LoadInt64(&s.bytesUp)),
|
||||
humanBytes(atomic.LoadInt64(&s.bytesDown)),
|
||||
)
|
||||
}
|
||||
|
||||
type handshakeInfo struct {
|
||||
DC int
|
||||
IsMedia bool
|
||||
ProtoTag []byte
|
||||
ClientDecI []byte
|
||||
}
|
||||
|
||||
type dcKey struct {
|
||||
DC int
|
||||
IsMedia bool
|
||||
}
|
||||
|
||||
type dcMapItem struct {
|
||||
dc int
|
||||
ip string
|
||||
}
|
||||
53
src/utils.go
Normal file
53
src/utils.go
Normal file
@ -0,0 +1,53 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"net"
|
||||
)
|
||||
|
||||
func formatFloat(v float64) string {
|
||||
return fmt.Sprintf("%.1f", v)
|
||||
}
|
||||
|
||||
func humanBytes(n int64) string {
|
||||
v := float64(n)
|
||||
units := []string{"B", "KB", "MB", "GB", "TB"}
|
||||
u := 0
|
||||
for math.Abs(v) >= 1024 && u < len(units)-1 {
|
||||
v /= 1024
|
||||
u++
|
||||
}
|
||||
return formatFloat(v) + units[u]
|
||||
}
|
||||
|
||||
func getLinkHost(host string) string {
|
||||
if host != "0.0.0.0" {
|
||||
return host
|
||||
}
|
||||
c, err := net.Dial("udp", "8.8.8.8:80")
|
||||
if err != nil {
|
||||
return "127.0.0.1"
|
||||
}
|
||||
defer c.Close()
|
||||
la, ok := c.LocalAddr().(*net.UDPAddr)
|
||||
if !ok || la.IP == nil {
|
||||
return "127.0.0.1"
|
||||
}
|
||||
return la.IP.String()
|
||||
}
|
||||
|
||||
func isRedirect(code int) bool {
|
||||
return code == 301 || code == 302 || code == 303 || code == 307 || code == 308
|
||||
}
|
||||
|
||||
func setSockOpts(c net.Conn, bufSize int) error {
|
||||
tcp, ok := c.(*net.TCPConn)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
_ = tcp.SetNoDelay(true)
|
||||
_ = tcp.SetReadBuffer(bufSize)
|
||||
_ = tcp.SetWriteBuffer(bufSize)
|
||||
return nil
|
||||
}
|
||||
@ -1,4 +0,0 @@
|
||||
"""
|
||||
Интерфейс tray (CustomTkinter): тема, диалоги настроек, подсказки.
|
||||
Ядро прокси — пакет `proxy`.
|
||||
"""
|
||||
108
ui/ctk_theme.py
108
ui/ctk_theme.py
@ -1,108 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import tkinter
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable, Optional, Tuple
|
||||
|
||||
_tk_variable_del_guard_installed = False
|
||||
|
||||
|
||||
def install_tkinter_variable_del_guard() -> None:
|
||||
global _tk_variable_del_guard_installed
|
||||
if _tk_variable_del_guard_installed:
|
||||
return
|
||||
_orig = tkinter.Variable.__del__
|
||||
|
||||
def _safe_variable_del(self: Any, _orig: Any = _orig) -> None:
|
||||
try:
|
||||
_orig(self)
|
||||
except (RuntimeError, tkinter.TclError):
|
||||
pass
|
||||
|
||||
tkinter.Variable.__del__ = _safe_variable_del # type: ignore[assignment]
|
||||
_tk_variable_del_guard_installed = True
|
||||
|
||||
CONFIG_DIALOG_SIZE: Tuple[int, int] = (460, 560)
|
||||
CONFIG_DIALOG_FRAME_PAD: Tuple[int, int] = (20, 14)
|
||||
FIRST_RUN_SIZE: Tuple[int, int] = (520, 480)
|
||||
FIRST_RUN_FRAME_PAD: Tuple[int, int] = (28, 24)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CtkTheme:
|
||||
tg_blue: tuple = ("#3390ec", "#3390ec")
|
||||
tg_blue_hover: tuple = ("#2b7cd4", "#2b7cd4")
|
||||
|
||||
bg: tuple = ("#ffffff", "#1e1e1e")
|
||||
field_bg: tuple = ("#f0f2f5", "#2b2b2b")
|
||||
field_border: tuple = ("#d6d9dc", "#3a3a3a")
|
||||
|
||||
text_primary: tuple = ("#000000", "#ffffff")
|
||||
text_secondary: tuple = ("#707579", "#aaaaaa")
|
||||
|
||||
ui_font_family: str = "Sans"
|
||||
mono_font_family: str = "Monospace"
|
||||
|
||||
|
||||
def ctk_theme_for_platform() -> CtkTheme:
|
||||
if sys.platform == "win32":
|
||||
return CtkTheme(ui_font_family="Segoe UI", mono_font_family="Consolas")
|
||||
return CtkTheme()
|
||||
|
||||
|
||||
def apply_ctk_appearance(ctk: Any) -> None:
|
||||
ctk.set_appearance_mode("auto")
|
||||
ctk.set_default_color_theme("blue")
|
||||
|
||||
def center_ctk_geometry(root: Any, width: int, height: int) -> None:
|
||||
sw = root.winfo_screenwidth()
|
||||
sh = root.winfo_screenheight()
|
||||
root.geometry(f"{width}x{height}+{(sw - width) // 2}+{(sh - height) // 2}")
|
||||
|
||||
|
||||
def create_ctk_toplevel(
|
||||
ctk: Any,
|
||||
*,
|
||||
title: str,
|
||||
width: int,
|
||||
height: int,
|
||||
theme: CtkTheme,
|
||||
topmost: bool = True,
|
||||
after_create: Optional[Callable[[Any], None]] = None,
|
||||
) -> Any:
|
||||
root = ctk.CTkToplevel()
|
||||
root.title(title)
|
||||
root.resizable(False, False)
|
||||
center_ctk_geometry(root, width, height)
|
||||
root.configure(fg_color=theme.bg)
|
||||
if topmost:
|
||||
root.attributes("-topmost", True)
|
||||
root.lift()
|
||||
root.focus_force()
|
||||
if after_create:
|
||||
_after_id = root.after(300, lambda: after_create(root))
|
||||
_orig_destroy = root.destroy
|
||||
|
||||
def _safe_destroy():
|
||||
try:
|
||||
root.after_cancel(_after_id)
|
||||
except Exception:
|
||||
pass
|
||||
_orig_destroy()
|
||||
|
||||
root.destroy = _safe_destroy
|
||||
return root
|
||||
|
||||
|
||||
def main_content_frame(
|
||||
ctk: Any,
|
||||
root: Any,
|
||||
theme: CtkTheme,
|
||||
*,
|
||||
padx: int,
|
||||
pady: int,
|
||||
) -> Any:
|
||||
frame = ctk.CTkFrame(root, fg_color=theme.bg, corner_radius=0)
|
||||
frame.pack(fill="both", expand=True, padx=padx, pady=pady)
|
||||
return frame
|
||||
@ -1,109 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from typing import Any, List, Optional
|
||||
|
||||
|
||||
class CtkTooltip:
|
||||
def __init__(
|
||||
self,
|
||||
widget: Any,
|
||||
text: str,
|
||||
*,
|
||||
delay_ms: int = 450,
|
||||
wraplength: int = 320,
|
||||
) -> None:
|
||||
self.widget = widget
|
||||
self.text = text
|
||||
self.delay_ms = delay_ms
|
||||
self.wraplength = wraplength
|
||||
self._after_id: Optional[str] = None
|
||||
self._tip: Optional[tk.Toplevel] = None
|
||||
widget.bind("<Enter>", self._schedule, add="+")
|
||||
widget.bind("<Leave>", self._hide, add="+")
|
||||
widget.bind("<Button>", self._hide, add="+")
|
||||
widget.bind("<Destroy>", self._on_destroy, add="+")
|
||||
|
||||
def _schedule(self, _event: Any = None) -> None:
|
||||
if self.widget is None:
|
||||
return
|
||||
self._cancel_after()
|
||||
self._after_id = self.widget.after(self.delay_ms, self._show)
|
||||
|
||||
def _cancel_after(self) -> None:
|
||||
if self._after_id is not None:
|
||||
try:
|
||||
self.widget.after_cancel(self._after_id)
|
||||
except Exception:
|
||||
pass
|
||||
self._after_id = None
|
||||
|
||||
def _show(self) -> None:
|
||||
self._after_id = None
|
||||
if self._tip is not None:
|
||||
return
|
||||
try:
|
||||
if not self.widget.winfo_exists():
|
||||
return
|
||||
except Exception:
|
||||
return
|
||||
|
||||
tw = tk.Toplevel(self.widget.winfo_toplevel())
|
||||
tw.wm_overrideredirect(True)
|
||||
try:
|
||||
tw.wm_attributes("-topmost", True)
|
||||
except Exception:
|
||||
pass
|
||||
tw.configure(bg="#2b2b2b")
|
||||
lbl = tk.Label(
|
||||
tw,
|
||||
text=self.text,
|
||||
justify="left",
|
||||
wraplength=self.wraplength,
|
||||
background="#2b2b2b",
|
||||
foreground="#f0f0f0",
|
||||
relief="flat",
|
||||
borderwidth=0,
|
||||
padx=10,
|
||||
pady=8,
|
||||
font=("Segoe UI", 10) if _is_windows() else None,
|
||||
)
|
||||
lbl.pack()
|
||||
x = self.widget.winfo_rootx() + 12
|
||||
y = self.widget.winfo_rooty() + self.widget.winfo_height() + 4
|
||||
tw.wm_geometry(f"+{x}+{y}")
|
||||
self._tip = tw
|
||||
|
||||
def _hide(self, _event: Any = None) -> None:
|
||||
self._cancel_after()
|
||||
if self._tip is not None:
|
||||
try:
|
||||
self._tip.destroy()
|
||||
except Exception:
|
||||
pass
|
||||
self._tip = None
|
||||
|
||||
def _on_destroy(self, _event: Any = None) -> None:
|
||||
self._hide()
|
||||
self.widget = None
|
||||
|
||||
|
||||
def _is_windows() -> bool:
|
||||
import sys
|
||||
|
||||
return sys.platform == "win32"
|
||||
|
||||
|
||||
def attach_ctk_tooltip(
|
||||
widget: Any,
|
||||
text: str,
|
||||
*,
|
||||
delay_ms: int = 450,
|
||||
wraplength: int = 320,
|
||||
) -> None:
|
||||
CtkTooltip(widget, text, delay_ms=delay_ms, wraplength=wraplength)
|
||||
|
||||
|
||||
def attach_tooltip_to_widgets(widgets: List[Any], text: str, **kwargs: Any) -> None:
|
||||
for w in widgets:
|
||||
attach_ctk_tooltip(w, text, **kwargs)
|
||||
@ -1,516 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import webbrowser
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
||||
|
||||
import proxy.tg_ws_proxy as tg_ws_proxy
|
||||
from proxy import __version__
|
||||
from utils.update_check import RELEASES_PAGE_URL, get_status
|
||||
|
||||
from ui.ctk_theme import (
|
||||
FIRST_RUN_FRAME_PAD,
|
||||
CtkTheme,
|
||||
main_content_frame,
|
||||
)
|
||||
from ui.ctk_tooltip import attach_ctk_tooltip, attach_tooltip_to_widgets
|
||||
|
||||
_TIP_HOST = (
|
||||
"Адрес, на котором прокси принимает подключения.\n"
|
||||
"Обычно 127.0.0.1 — локальная сеть, 0.0.0.0 - все интерфейсы"
|
||||
)
|
||||
_TIP_PORT = (
|
||||
"Порт прокси. В Telegram Desktop в настройках прокси должен быть "
|
||||
"указан тот же порт"
|
||||
)
|
||||
_TIP_SECRET = "Секретный ключ для авторизации клиентов"
|
||||
_TIP_DC = (
|
||||
"Соответствие номера датацентра Telegram (DC) и IP-адреса сервера.\n"
|
||||
"Каждая строка: «номер:IP», например 2:149.154.167.220. "
|
||||
"Прокси по этим правилам направляет трафик к нужным серверам Telegram"
|
||||
)
|
||||
_TIP_VERBOSE = (
|
||||
"Если включено, в файл логов пишется больше подробностей — "
|
||||
"необходимо при поиске неполадок"
|
||||
)
|
||||
_TIP_BUF_KB = (
|
||||
"Размер буфера приёма/передачи в килобайтах.\n"
|
||||
"Больше значение — больше выделение памяти на сокет"
|
||||
)
|
||||
_TIP_POOL = (
|
||||
"Сколько параллельных WebSocket-сессий к одному датацентру можно держать.\n"
|
||||
"Увеличение может помочь при высокой нагрузке"
|
||||
)
|
||||
_TIP_LOG_MB = (
|
||||
"Максимальный размер файла лога; при достижении лимита файл перезаписывается"
|
||||
)
|
||||
_TIP_AUTOSTART = (
|
||||
"Запускать TG WS Proxy при входе в Windows. "
|
||||
"Если вы переместите программу в другую папку, автозапуск сбросится"
|
||||
)
|
||||
_TIP_CHECK_UPDATES = "При запуске проверять наличие обновлений"
|
||||
_TIP_SAVE = "Сохранить настройки"
|
||||
_TIP_CANCEL = "Закрыть окно без сохранения изменений"
|
||||
|
||||
_INNER_W = 396
|
||||
|
||||
|
||||
def _entry(ctk, parent, theme, *, var=None, width=0, height=36, radius=10, **kw):
|
||||
opts = dict(
|
||||
font=(theme.ui_font_family, 13), corner_radius=radius,
|
||||
fg_color=theme.bg, border_color=theme.field_border,
|
||||
border_width=1, text_color=theme.text_primary,
|
||||
)
|
||||
if var is not None:
|
||||
opts["textvariable"] = var
|
||||
if width:
|
||||
opts["width"] = width
|
||||
opts["height"] = height
|
||||
opts.update(kw)
|
||||
return ctk.CTkEntry(parent, **opts)
|
||||
|
||||
|
||||
def _checkbox(ctk, parent, theme, text, variable):
|
||||
return ctk.CTkCheckBox(
|
||||
parent, text=text, variable=variable,
|
||||
font=(theme.ui_font_family, 13), text_color=theme.text_primary,
|
||||
fg_color=theme.tg_blue, hover_color=theme.tg_blue_hover,
|
||||
corner_radius=6, border_width=2, border_color=theme.field_border,
|
||||
)
|
||||
|
||||
|
||||
def _label(ctk, parent, theme, text, *, size=12, bold=False, secondary=True, **kw):
|
||||
weight = "bold" if bold else "normal"
|
||||
return ctk.CTkLabel(
|
||||
parent, text=text,
|
||||
font=(theme.ui_font_family, size, weight),
|
||||
text_color=theme.text_secondary if secondary else theme.text_primary,
|
||||
anchor="w", **kw,
|
||||
)
|
||||
|
||||
|
||||
def _labeled_entry(ctk, parent, theme, label_text, value, *, tip="", width=0, pack_fill=False):
|
||||
col = ctk.CTkFrame(parent, fg_color="transparent")
|
||||
lbl = _label(ctk, col, theme, label_text)
|
||||
lbl.pack(anchor="w", pady=(0, 2))
|
||||
var = ctk.StringVar(value=str(value))
|
||||
ent = _entry(ctk, col, theme, var=var, width=width)
|
||||
if pack_fill:
|
||||
ent.pack(fill="x")
|
||||
else:
|
||||
ent.pack(anchor="w")
|
||||
if tip:
|
||||
attach_tooltip_to_widgets([lbl, ent, col], tip)
|
||||
return col, var
|
||||
|
||||
|
||||
def tray_settings_scroll_and_footer(
|
||||
ctk: Any,
|
||||
content_parent: Any,
|
||||
theme: CtkTheme,
|
||||
) -> Tuple[Any, Any]:
|
||||
footer = ctk.CTkFrame(content_parent, fg_color=theme.bg)
|
||||
footer.pack(side="bottom", fill="x")
|
||||
scroll = ctk.CTkScrollableFrame(
|
||||
content_parent,
|
||||
fg_color=theme.bg,
|
||||
corner_radius=0,
|
||||
scrollbar_button_color=theme.field_border,
|
||||
scrollbar_button_hover_color=theme.text_secondary,
|
||||
)
|
||||
scroll.pack(fill="both", expand=True)
|
||||
return scroll, footer
|
||||
|
||||
|
||||
def _config_section(
|
||||
ctk: Any,
|
||||
parent: Any,
|
||||
theme: CtkTheme,
|
||||
title: str,
|
||||
*,
|
||||
bottom_spacer: int = 6,
|
||||
) -> Any:
|
||||
wrap = ctk.CTkFrame(parent, fg_color="transparent")
|
||||
wrap.pack(fill="x", pady=(0, bottom_spacer))
|
||||
_label(ctk, wrap, theme, title, secondary=False, bold=True).pack(anchor="w", pady=(0, 2))
|
||||
card = ctk.CTkFrame(
|
||||
wrap, fg_color=theme.field_bg, corner_radius=10,
|
||||
border_width=1, border_color=theme.field_border,
|
||||
)
|
||||
card.pack(fill="x")
|
||||
inner = ctk.CTkFrame(card, fg_color="transparent")
|
||||
inner.pack(fill="x", padx=10, pady=8)
|
||||
return inner
|
||||
|
||||
|
||||
@dataclass
|
||||
class TrayConfigFormWidgets:
|
||||
host_var: Any
|
||||
port_var: Any
|
||||
secret_var: Any
|
||||
dc_textbox: Any
|
||||
verbose_var: Any
|
||||
adv_entries: List[Any]
|
||||
adv_keys: Tuple[str, ...]
|
||||
autostart_var: Optional[Any]
|
||||
check_updates_var: Optional[Any]
|
||||
|
||||
|
||||
def install_tray_config_form(
|
||||
ctk: Any,
|
||||
frame: Any,
|
||||
theme: CtkTheme,
|
||||
cfg: dict,
|
||||
default_config: dict,
|
||||
*,
|
||||
show_autostart: bool = False,
|
||||
autostart_value: bool = False,
|
||||
) -> TrayConfigFormWidgets:
|
||||
header = ctk.CTkFrame(frame, fg_color="transparent")
|
||||
header.pack(fill="x", pady=(0, 2))
|
||||
ctk.CTkLabel(
|
||||
header, text="Настройки прокси",
|
||||
font=(theme.ui_font_family, 17, "bold"),
|
||||
text_color=theme.text_primary, anchor="w",
|
||||
).pack(side="left")
|
||||
ctk.CTkLabel(
|
||||
header, text=f"v{__version__}",
|
||||
font=(theme.ui_font_family, 12),
|
||||
text_color=theme.text_secondary, anchor="e",
|
||||
).pack(side="right")
|
||||
|
||||
conn = _config_section(ctk, frame, theme, "Подключение MTProto")
|
||||
|
||||
host_row = ctk.CTkFrame(conn, fg_color="transparent")
|
||||
host_row.pack(fill="x")
|
||||
|
||||
host_col, host_var = _labeled_entry(
|
||||
ctk, host_row, theme, "IP-адрес",
|
||||
cfg.get("host", default_config["host"]),
|
||||
tip=_TIP_HOST, width=160, pack_fill=True,
|
||||
)
|
||||
host_col.pack(side="left", fill="x", expand=True, padx=(0, 10))
|
||||
|
||||
port_col, port_var = _labeled_entry(
|
||||
ctk, host_row, theme, "Порт",
|
||||
cfg.get("port", default_config["port"]),
|
||||
tip=_TIP_PORT, width=100,
|
||||
)
|
||||
port_col.pack(side="left")
|
||||
|
||||
secret_row = ctk.CTkFrame(conn, fg_color="transparent")
|
||||
secret_row.pack(fill="x")
|
||||
|
||||
secret_col, secret_var = _labeled_entry(
|
||||
ctk, secret_row, theme, "Secret",
|
||||
cfg.get("secret", default_config["secret"]),
|
||||
tip=_TIP_SECRET, width=160, pack_fill=True,
|
||||
)
|
||||
secret_col.pack(side="left", fill="x", expand=True, padx=(0, 10))
|
||||
|
||||
regen_col = ctk.CTkFrame(secret_row, fg_color="transparent")
|
||||
regen_col.pack(side="left", anchor="s")
|
||||
ctk.CTkLabel(regen_col, text="", font=(theme.ui_font_family, 12)).pack(pady=(0, 2))
|
||||
ctk.CTkButton(
|
||||
regen_col, text="↺", width=36, height=36,
|
||||
font=(theme.ui_font_family, 18), corner_radius=10,
|
||||
fg_color=theme.tg_blue, hover_color=theme.tg_blue_hover,
|
||||
text_color="#ffffff", border_width=1, border_color=theme.field_border,
|
||||
command=lambda: secret_var.set(os.urandom(16).hex()),
|
||||
).pack()
|
||||
|
||||
dc_inner = _config_section(ctk, frame, theme, "Датацентры Telegram (DC → IP)")
|
||||
dc_lbl = _label(ctk, dc_inner, theme, "По одному правилу на строку, формат: номер:IP", size=11)
|
||||
dc_lbl.pack(anchor="w", pady=(0, 4))
|
||||
dc_textbox = ctk.CTkTextbox(
|
||||
dc_inner, width=_INNER_W, height=88,
|
||||
font=(theme.mono_font_family, 12), corner_radius=10,
|
||||
fg_color=theme.bg, border_color=theme.field_border,
|
||||
border_width=1, text_color=theme.text_primary,
|
||||
)
|
||||
dc_textbox.pack(fill="x")
|
||||
dc_textbox.insert("1.0", "\n".join(cfg.get("dc_ip", default_config["dc_ip"])))
|
||||
attach_tooltip_to_widgets([dc_lbl, dc_textbox], _TIP_DC)
|
||||
|
||||
log_inner = _config_section(ctk, frame, theme, "Логи и производительность")
|
||||
|
||||
verbose_var = ctk.BooleanVar(value=cfg.get("verbose", False))
|
||||
verbose_cb = _checkbox(ctk, log_inner, theme, "Подробное логирование (verbose)", verbose_var)
|
||||
verbose_cb.pack(anchor="w", pady=(0, 6))
|
||||
attach_ctk_tooltip(verbose_cb, _TIP_VERBOSE)
|
||||
|
||||
adv_frame = ctk.CTkFrame(log_inner, fg_color="transparent")
|
||||
adv_frame.pack(fill="x")
|
||||
|
||||
adv_rows = [
|
||||
("Буфер, КБ (по умолчанию 256)", "buf_kb", _TIP_BUF_KB),
|
||||
("Пул WebSocket-сессий (по умолчанию 4)", "pool_size", _TIP_POOL),
|
||||
("Макс. размер лога, МБ (по умолчанию 5)", "log_max_mb", _TIP_LOG_MB),
|
||||
]
|
||||
for label_text, key, tip in adv_rows:
|
||||
col = ctk.CTkFrame(adv_frame, fg_color="transparent")
|
||||
col.pack(fill="x", pady=(0, 0 if key == "log_max_mb" else 5))
|
||||
adv_l = _label(ctk, col, theme, label_text, size=11)
|
||||
adv_l.pack(anchor="w", pady=(0, 2))
|
||||
adv_e = _entry(
|
||||
ctk, col, theme, width=_INNER_W, height=32, radius=8,
|
||||
textvariable=ctk.StringVar(value=str(cfg.get(key, default_config[key]))),
|
||||
)
|
||||
adv_e.pack(fill="x")
|
||||
attach_tooltip_to_widgets([adv_l, adv_e, col], tip)
|
||||
|
||||
adv_entries = list(adv_frame.winfo_children())
|
||||
adv_keys = ("buf_kb", "pool_size", "log_max_mb")
|
||||
|
||||
upd_inner = _config_section(ctk, frame, theme, "Обновления")
|
||||
st = get_status()
|
||||
check_updates_var = ctk.BooleanVar(
|
||||
value=bool(cfg.get("check_updates", default_config.get("check_updates", True)))
|
||||
)
|
||||
upd_cb = _checkbox(ctk, upd_inner, theme, "Проверять обновления при запуске", check_updates_var)
|
||||
upd_cb.pack(anchor="w", pady=(0, 6))
|
||||
attach_ctk_tooltip(upd_cb, _TIP_CHECK_UPDATES)
|
||||
|
||||
if st.get("error"):
|
||||
upd_status = "Не удалось связаться с GitHub. Проверьте сеть."
|
||||
elif not st.get("checked"):
|
||||
upd_status = "Статус появится после фоновой проверки при запуске."
|
||||
elif st.get("has_update") and st.get("latest"):
|
||||
upd_status = (
|
||||
f"На GitHub доступна версия {st['latest']} "
|
||||
f"(у вас {__version__})."
|
||||
)
|
||||
elif st.get("ahead_of_release") and st.get("latest"):
|
||||
upd_status = (
|
||||
f"У вас {__version__} — новее последнего релиза на GitHub "
|
||||
f"({st['latest']})."
|
||||
)
|
||||
else:
|
||||
upd_status = "Установлена последняя известная версия с GitHub."
|
||||
|
||||
_label(ctk, upd_inner, theme, upd_status, size=11,
|
||||
justify="left", wraplength=_INNER_W).pack(anchor="w", pady=(0, 8))
|
||||
|
||||
rel_url = (st.get("html_url") or "").strip() or RELEASES_PAGE_URL
|
||||
ctk.CTkButton(
|
||||
upd_inner, text="Открыть страницу релиза", height=32,
|
||||
font=(theme.ui_font_family, 13), corner_radius=8,
|
||||
fg_color=theme.field_bg, hover_color=theme.field_border,
|
||||
text_color=theme.text_primary, border_width=1,
|
||||
border_color=theme.field_border,
|
||||
command=lambda u=rel_url: webbrowser.open(u),
|
||||
).pack(anchor="w")
|
||||
|
||||
autostart_var = None
|
||||
if show_autostart:
|
||||
sys_inner = _config_section(ctk, frame, theme, "Запуск Windows", bottom_spacer=4)
|
||||
autostart_var = ctk.BooleanVar(value=autostart_value)
|
||||
as_cb = _checkbox(ctk, sys_inner, theme, "Автозапуск при включении компьютера", autostart_var)
|
||||
as_cb.pack(anchor="w", pady=(0, 4))
|
||||
as_hint = _label(
|
||||
ctk, sys_inner, theme,
|
||||
"Если переместить программу в другую папку, запись автозапуска может сброситься.",
|
||||
size=11, justify="left", wraplength=_INNER_W,
|
||||
)
|
||||
as_hint.pack(anchor="w")
|
||||
attach_tooltip_to_widgets([as_cb, as_hint], _TIP_AUTOSTART)
|
||||
|
||||
return TrayConfigFormWidgets(
|
||||
host_var=host_var, port_var=port_var, secret_var=secret_var,
|
||||
dc_textbox=dc_textbox, verbose_var=verbose_var,
|
||||
adv_entries=adv_entries, adv_keys=adv_keys,
|
||||
autostart_var=autostart_var, check_updates_var=check_updates_var,
|
||||
)
|
||||
|
||||
|
||||
def merge_adv_from_form(
|
||||
widgets: TrayConfigFormWidgets,
|
||||
base: Dict[str, Any],
|
||||
default_config: dict,
|
||||
) -> None:
|
||||
for i, key in enumerate(widgets.adv_keys):
|
||||
col_frame = widgets.adv_entries[i]
|
||||
entry = col_frame.winfo_children()[1]
|
||||
try:
|
||||
val = float(entry.get().strip())
|
||||
if key in ("buf_kb", "pool_size"):
|
||||
val = int(val)
|
||||
base[key] = val
|
||||
except ValueError:
|
||||
base[key] = default_config[key]
|
||||
|
||||
|
||||
def validate_config_form(
|
||||
widgets: TrayConfigFormWidgets,
|
||||
default_config: dict,
|
||||
*,
|
||||
include_autostart: bool,
|
||||
) -> Union[dict, str]:
|
||||
import socket as _sock
|
||||
|
||||
host_val = widgets.host_var.get().strip()
|
||||
try:
|
||||
_sock.inet_aton(host_val)
|
||||
except OSError:
|
||||
return "Некорректный IP-адрес."
|
||||
|
||||
try:
|
||||
port_val = int(widgets.port_var.get().strip())
|
||||
if not (1 <= port_val <= 65535):
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
return "Порт должен быть числом 1-65535"
|
||||
|
||||
lines = [
|
||||
l.strip()
|
||||
for l in widgets.dc_textbox.get("1.0", "end").strip().splitlines()
|
||||
if l.strip()
|
||||
]
|
||||
try:
|
||||
tg_ws_proxy.parse_dc_ip_list(lines)
|
||||
except ValueError as e:
|
||||
return str(e)
|
||||
|
||||
secret_val = widgets.secret_var.get().strip()
|
||||
if len(secret_val) != 32:
|
||||
return "Secret должен содержать ровно 32 hex-символа (16 байт)."
|
||||
try:
|
||||
bytes.fromhex(secret_val)
|
||||
except ValueError:
|
||||
return "Secret должен состоять только из hex-символов (0-9, a-f)."
|
||||
|
||||
new_cfg: Dict[str, Any] = {
|
||||
"host": host_val,
|
||||
"port": port_val,
|
||||
"secret": secret_val,
|
||||
"dc_ip": lines,
|
||||
"verbose": widgets.verbose_var.get(),
|
||||
}
|
||||
if include_autostart:
|
||||
new_cfg["autostart"] = (
|
||||
widgets.autostart_var.get()
|
||||
if widgets.autostart_var is not None
|
||||
else False
|
||||
)
|
||||
|
||||
merge_adv_from_form(widgets, new_cfg, default_config)
|
||||
if widgets.check_updates_var is not None:
|
||||
new_cfg["check_updates"] = bool(widgets.check_updates_var.get())
|
||||
return new_cfg
|
||||
|
||||
|
||||
def install_tray_config_buttons(
|
||||
ctk: Any,
|
||||
frame: Any,
|
||||
theme: CtkTheme,
|
||||
*,
|
||||
on_save: Callable[[], None],
|
||||
on_cancel: Callable[[], None],
|
||||
) -> None:
|
||||
ctk.CTkFrame(
|
||||
frame,
|
||||
fg_color=theme.field_border,
|
||||
height=1,
|
||||
corner_radius=0,
|
||||
).pack(fill="x", pady=(4, 10))
|
||||
btn_frame = ctk.CTkFrame(frame, fg_color="transparent")
|
||||
btn_frame.pack(fill="x", pady=(0, 0))
|
||||
save_btn = ctk.CTkButton(
|
||||
btn_frame, text="Сохранить", height=38,
|
||||
font=(theme.ui_font_family, 14, "bold"), corner_radius=10,
|
||||
fg_color=theme.tg_blue, hover_color=theme.tg_blue_hover,
|
||||
text_color="#ffffff",
|
||||
command=on_save)
|
||||
save_btn.pack(side="left", fill="x", expand=True, padx=(0, 8))
|
||||
attach_ctk_tooltip(save_btn, _TIP_SAVE)
|
||||
cancel_btn = ctk.CTkButton(
|
||||
btn_frame, text="Отмена", height=38,
|
||||
font=(theme.ui_font_family, 14), corner_radius=10,
|
||||
fg_color=theme.field_bg, hover_color=theme.field_border,
|
||||
text_color=theme.text_primary, border_width=1,
|
||||
border_color=theme.field_border,
|
||||
command=on_cancel)
|
||||
cancel_btn.pack(side="right", fill="x", expand=True)
|
||||
attach_ctk_tooltip(cancel_btn, _TIP_CANCEL)
|
||||
|
||||
|
||||
def populate_first_run_window(
|
||||
ctk: Any,
|
||||
root: Any,
|
||||
theme: CtkTheme,
|
||||
*,
|
||||
host: str,
|
||||
port: int,
|
||||
secret: str,
|
||||
on_done: Callable[[bool], None],
|
||||
) -> None:
|
||||
link_host = tg_ws_proxy.get_link_host(host)
|
||||
tg_url = f"tg://proxy?server={link_host}&port={port}&secret=dd{secret}"
|
||||
fpx, fpy = FIRST_RUN_FRAME_PAD
|
||||
frame = main_content_frame(ctk, root, theme, padx=fpx, pady=fpy)
|
||||
|
||||
title_frame = ctk.CTkFrame(frame, fg_color="transparent")
|
||||
title_frame.pack(anchor="w", pady=(0, 16), fill="x")
|
||||
|
||||
accent_bar = ctk.CTkFrame(title_frame, fg_color=theme.tg_blue,
|
||||
width=4, height=32, corner_radius=2)
|
||||
accent_bar.pack(side="left", padx=(0, 12))
|
||||
|
||||
ctk.CTkLabel(title_frame, text="Прокси запущен и работает в системном трее",
|
||||
font=(theme.ui_font_family, 17, "bold"),
|
||||
text_color=theme.text_primary).pack(side="left")
|
||||
|
||||
sections = [
|
||||
("Как подключить Telegram Desktop:", True),
|
||||
(" Автоматически:", True),
|
||||
(" ПКМ по иконке в трее → «Открыть в Telegram»", False),
|
||||
(f" Или скопировать ссылку, отправить её себе в TG и нажать по ней: {tg_url}", False),
|
||||
("\n Вручную:", True),
|
||||
(" Настройки → Продвинутые → Тип подключения → Прокси", False),
|
||||
(f" MTProto → {link_host} : {port}", False),
|
||||
(f" Secret: dd{secret}", False),
|
||||
]
|
||||
|
||||
textbox = ctk.CTkTextbox(
|
||||
frame,
|
||||
font=(theme.ui_font_family, 13),
|
||||
fg_color=theme.bg,
|
||||
border_width=0,
|
||||
text_color=theme.text_primary,
|
||||
activate_scrollbars=False,
|
||||
wrap="word",
|
||||
height=275,
|
||||
)
|
||||
textbox._textbox.tag_configure("bold", font=(theme.ui_font_family, 13, "bold"))
|
||||
textbox._textbox.configure(spacing1=1, spacing3=1)
|
||||
for text, bold in sections:
|
||||
if text.startswith("\n"):
|
||||
textbox.insert("end", "\n")
|
||||
text = text[1:]
|
||||
if bold:
|
||||
textbox.insert("end", text + "\n", "bold")
|
||||
else:
|
||||
textbox.insert("end", text + "\n")
|
||||
textbox.configure(state="disabled")
|
||||
textbox.pack(anchor="w", fill="x")
|
||||
|
||||
ctk.CTkFrame(frame, fg_color="transparent", height=16).pack()
|
||||
|
||||
ctk.CTkFrame(frame, fg_color=theme.field_border, height=1,
|
||||
corner_radius=0).pack(fill="x", pady=(0, 12))
|
||||
|
||||
auto_var = ctk.BooleanVar(value=True)
|
||||
_checkbox(ctk, frame, theme, "Открыть прокси в Telegram сейчас",
|
||||
auto_var).pack(anchor="w", pady=(0, 16))
|
||||
|
||||
def on_ok():
|
||||
on_done(auto_var.get())
|
||||
|
||||
ctk.CTkButton(frame, text="Начать", width=180, height=42,
|
||||
font=(theme.ui_font_family, 15, "bold"), corner_radius=10,
|
||||
fg_color=theme.tg_blue, hover_color=theme.tg_blue_hover,
|
||||
text_color="#ffffff",
|
||||
command=on_ok).pack(pady=(0, 0))
|
||||
|
||||
root.protocol("WM_DELETE_WINDOW", on_ok)
|
||||
@ -1,5 +0,0 @@
|
||||
"""Вспомогательные утилиты (проверка релизов и т.п.)."""
|
||||
|
||||
from utils.update_check import RELEASES_PAGE_URL, get_status, run_check
|
||||
|
||||
__all__ = ["RELEASES_PAGE_URL", "get_status", "run_check"]
|
||||
@ -1,30 +0,0 @@
|
||||
"""
|
||||
Общие значения по умолчанию для tray-приложений (Windows / Linux / macOS).
|
||||
Единственное отличие по платформе — ключ autostart только на Windows.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import os
|
||||
from typing import Any, Dict
|
||||
|
||||
_TRAY_DEFAULTS_COMMON: Dict[str, Any] = {
|
||||
"port": 1443,
|
||||
"host": "127.0.0.1",
|
||||
"dc_ip": ["2:149.154.167.220", "4:149.154.167.220"],
|
||||
"verbose": False,
|
||||
"check_updates": True,
|
||||
"log_max_mb": 5,
|
||||
"buf_kb": 256,
|
||||
"pool_size": 4,
|
||||
}
|
||||
|
||||
|
||||
def default_tray_config() -> Dict[str, Any]:
|
||||
cfg = dict(_TRAY_DEFAULTS_COMMON)
|
||||
cfg["secret"] = os.urandom(16).hex()
|
||||
|
||||
if sys.platform == "win32":
|
||||
cfg["autostart"] = False
|
||||
|
||||
return cfg
|
||||
@ -1,460 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import socket as _socket
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, Optional, Tuple
|
||||
|
||||
import psutil
|
||||
|
||||
import proxy.tg_ws_proxy as tg_ws_proxy
|
||||
from proxy import __version__
|
||||
from utils.default_config import default_tray_config
|
||||
|
||||
log = logging.getLogger("tg-ws-tray")
|
||||
|
||||
APP_NAME = "TgWsProxy"
|
||||
|
||||
|
||||
def _app_dir() -> Path:
|
||||
if sys.platform == "win32":
|
||||
return Path(os.environ.get("APPDATA", Path.home())) / APP_NAME
|
||||
if sys.platform == "darwin":
|
||||
return Path.home() / "Library" / "Application Support" / APP_NAME
|
||||
return Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / APP_NAME
|
||||
|
||||
|
||||
APP_DIR = _app_dir()
|
||||
CONFIG_FILE = APP_DIR / "config.json"
|
||||
LOG_FILE = APP_DIR / "proxy.log"
|
||||
FIRST_RUN_MARKER = APP_DIR / ".first_run_done_mtproto"
|
||||
IPV6_WARN_MARKER = APP_DIR / ".ipv6_warned"
|
||||
|
||||
DEFAULT_CONFIG: Dict[str, Any] = default_tray_config()
|
||||
|
||||
IS_FROZEN = bool(getattr(sys, "frozen", False))
|
||||
|
||||
|
||||
def ensure_dirs() -> None:
|
||||
APP_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
# single-instance lock
|
||||
|
||||
_lock_file_path: Optional[Path] = None
|
||||
|
||||
|
||||
def _same_process(meta: dict, proc: psutil.Process, script_hint: str) -> bool:
|
||||
try:
|
||||
lock_ct = float(meta.get("create_time", 0.0))
|
||||
if lock_ct > 0 and abs(lock_ct - proc.create_time()) > 1.0:
|
||||
return False
|
||||
except Exception:
|
||||
return False
|
||||
if IS_FROZEN:
|
||||
return APP_NAME.lower() in proc.name().lower()
|
||||
try:
|
||||
for arg in proc.cmdline():
|
||||
if script_hint in arg:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def acquire_lock(script_hint: str = "") -> bool:
|
||||
global _lock_file_path
|
||||
ensure_dirs()
|
||||
for f in list(APP_DIR.glob("*.lock")):
|
||||
try:
|
||||
pid = int(f.stem)
|
||||
except Exception:
|
||||
f.unlink(missing_ok=True)
|
||||
continue
|
||||
meta: dict = {}
|
||||
try:
|
||||
raw = f.read_text(encoding="utf-8").strip()
|
||||
if raw:
|
||||
meta = json.loads(raw)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if _same_process(meta, psutil.Process(pid), script_hint):
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
f.unlink(missing_ok=True)
|
||||
|
||||
lock_file = APP_DIR / f"{os.getpid()}.lock"
|
||||
try:
|
||||
proc = psutil.Process(os.getpid())
|
||||
lock_file.write_text(
|
||||
json.dumps({"create_time": proc.create_time()}, ensure_ascii=False),
|
||||
encoding="utf-8",
|
||||
)
|
||||
except Exception:
|
||||
lock_file.touch()
|
||||
_lock_file_path = lock_file
|
||||
return True
|
||||
|
||||
|
||||
def release_lock() -> None:
|
||||
global _lock_file_path
|
||||
if _lock_file_path:
|
||||
try:
|
||||
_lock_file_path.unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_lock_file_path = None
|
||||
|
||||
|
||||
# config
|
||||
|
||||
def load_config() -> dict:
|
||||
ensure_dirs()
|
||||
if CONFIG_FILE.exists():
|
||||
try:
|
||||
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
for k, v in DEFAULT_CONFIG.items():
|
||||
data.setdefault(k, v)
|
||||
return data
|
||||
except Exception as exc:
|
||||
log.warning("Failed to load config: %s", exc)
|
||||
return dict(DEFAULT_CONFIG)
|
||||
|
||||
|
||||
def save_config(cfg: dict) -> None:
|
||||
ensure_dirs()
|
||||
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(cfg, f, indent=2, ensure_ascii=False)
|
||||
|
||||
|
||||
# logging
|
||||
|
||||
_LOG_FMT_FILE = "%(asctime)s %(levelname)-5s %(name)s %(message)s"
|
||||
_LOG_FMT_CONSOLE = "%(asctime)s %(levelname)-5s %(message)s"
|
||||
|
||||
|
||||
def setup_logging(verbose: bool = False, log_max_mb: float = 5) -> None:
|
||||
ensure_dirs()
|
||||
level = logging.DEBUG if verbose else logging.INFO
|
||||
root = logging.getLogger()
|
||||
root.setLevel(level)
|
||||
|
||||
fh = logging.handlers.RotatingFileHandler(
|
||||
str(LOG_FILE),
|
||||
maxBytes=max(32 * 1024, int(log_max_mb * 1024 * 1024)),
|
||||
backupCount=0,
|
||||
encoding="utf-8",
|
||||
)
|
||||
fh.setLevel(logging.DEBUG)
|
||||
fh.setFormatter(logging.Formatter(_LOG_FMT_FILE, datefmt="%Y-%m-%d %H:%M:%S"))
|
||||
root.addHandler(fh)
|
||||
|
||||
if not IS_FROZEN:
|
||||
ch = logging.StreamHandler(sys.stdout)
|
||||
ch.setLevel(level)
|
||||
ch.setFormatter(logging.Formatter(_LOG_FMT_CONSOLE, datefmt="%H:%M:%S"))
|
||||
root.addHandler(ch)
|
||||
|
||||
|
||||
# icon
|
||||
|
||||
def make_icon_image(size: int = 64, *, color: Tuple[int, ...] = (0, 136, 204, 255)):
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
|
||||
draw = ImageDraw.Draw(img)
|
||||
margin = 2
|
||||
draw.ellipse([margin, margin, size - margin, size - margin], fill=color)
|
||||
|
||||
for path in _font_paths():
|
||||
try:
|
||||
font = ImageFont.truetype(path, size=int(size * 0.55))
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
else:
|
||||
font = ImageFont.load_default()
|
||||
|
||||
bbox = draw.textbbox((0, 0), "T", font=font)
|
||||
tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
|
||||
draw.text(
|
||||
((size - tw) // 2 - bbox[0], (size - th) // 2 - bbox[1]),
|
||||
"T",
|
||||
fill=(255, 255, 255, 255),
|
||||
font=font,
|
||||
)
|
||||
return img
|
||||
|
||||
|
||||
def _font_paths():
|
||||
if sys.platform == "win32":
|
||||
return ["arial.ttf"]
|
||||
if sys.platform == "darwin":
|
||||
return ["/System/Library/Fonts/Helvetica.ttc"]
|
||||
return [
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
|
||||
"/usr/share/fonts/TTF/DejaVuSans-Bold.ttf",
|
||||
]
|
||||
|
||||
|
||||
def load_icon():
|
||||
from PIL import Image
|
||||
|
||||
icon_path = Path(__file__).parents[1] / "icon.ico"
|
||||
if icon_path.exists():
|
||||
try:
|
||||
return Image.open(str(icon_path))
|
||||
except Exception:
|
||||
pass
|
||||
return make_icon_image(64)
|
||||
|
||||
|
||||
# proxy lifecycle
|
||||
|
||||
_proxy_thread: Optional[threading.Thread] = None
|
||||
_async_stop: Optional[Tuple[asyncio.AbstractEventLoop, asyncio.Event]] = None
|
||||
|
||||
|
||||
def _run_proxy_thread(on_port_busy: Callable[[str], None]) -> None:
|
||||
global _async_stop
|
||||
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
stop_ev = asyncio.Event()
|
||||
_async_stop = (loop, stop_ev)
|
||||
|
||||
try:
|
||||
loop.run_until_complete(tg_ws_proxy._run(stop_event=stop_ev))
|
||||
except Exception as exc:
|
||||
log.error("Proxy thread crashed: %s", exc)
|
||||
if "Address already in use" in str(exc) or "10048" in str(exc):
|
||||
on_port_busy(
|
||||
"Не удалось запустить прокси:\n"
|
||||
"Порт уже используется другим приложением.\n\n"
|
||||
"Закройте приложение, использующее этот порт, "
|
||||
"или измените порт в настройках прокси и перезапустите."
|
||||
)
|
||||
finally:
|
||||
loop.close()
|
||||
_async_stop = None
|
||||
|
||||
|
||||
def apply_proxy_config(cfg: dict) -> bool:
|
||||
dc_ip_list = cfg.get("dc_ip", DEFAULT_CONFIG["dc_ip"])
|
||||
try:
|
||||
dc_redirects = tg_ws_proxy.parse_dc_ip_list(dc_ip_list)
|
||||
except ValueError as e:
|
||||
log.error("Bad config dc_ip: %s", e)
|
||||
return False
|
||||
|
||||
pc = tg_ws_proxy.proxy_config
|
||||
pc.port = cfg.get("port", DEFAULT_CONFIG["port"])
|
||||
pc.host = cfg.get("host", DEFAULT_CONFIG["host"])
|
||||
pc.secret = cfg.get("secret", DEFAULT_CONFIG["secret"])
|
||||
pc.dc_redirects = dc_redirects
|
||||
pc.buffer_size = max(4, cfg.get("buf_kb", DEFAULT_CONFIG["buf_kb"])) * 1024
|
||||
pc.pool_size = max(0, cfg.get("pool_size", DEFAULT_CONFIG["pool_size"]))
|
||||
return True
|
||||
|
||||
|
||||
def start_proxy(cfg: dict, on_error: Callable[[str], None]) -> None:
|
||||
global _proxy_thread
|
||||
if _proxy_thread and _proxy_thread.is_alive():
|
||||
log.info("Proxy already running")
|
||||
return
|
||||
|
||||
if not apply_proxy_config(cfg):
|
||||
on_error("Ошибка конфигурации DC → IP.")
|
||||
return
|
||||
|
||||
pc = tg_ws_proxy.proxy_config
|
||||
log.info("Starting proxy on %s:%d ...", pc.host, pc.port)
|
||||
_proxy_thread = threading.Thread(
|
||||
target=_run_proxy_thread, args=(on_error,), daemon=True, name="proxy"
|
||||
)
|
||||
_proxy_thread.start()
|
||||
|
||||
|
||||
def stop_proxy() -> None:
|
||||
global _proxy_thread, _async_stop
|
||||
if _async_stop:
|
||||
loop, stop_ev = _async_stop
|
||||
loop.call_soon_threadsafe(stop_ev.set)
|
||||
if _proxy_thread:
|
||||
_proxy_thread.join(timeout=5)
|
||||
_proxy_thread = None
|
||||
log.info("Proxy stopped")
|
||||
|
||||
|
||||
def restart_proxy(cfg: dict, on_error: Callable[[str], None]) -> None:
|
||||
log.info("Restarting proxy...")
|
||||
stop_proxy()
|
||||
time.sleep(0.3)
|
||||
start_proxy(cfg, on_error)
|
||||
|
||||
|
||||
def tg_proxy_url(cfg: dict) -> str:
|
||||
host = cfg.get("host", DEFAULT_CONFIG["host"])
|
||||
port = cfg.get("port", DEFAULT_CONFIG["port"])
|
||||
secret = cfg.get("secret", DEFAULT_CONFIG["secret"])
|
||||
link_host = tg_ws_proxy.get_link_host(host)
|
||||
return f"tg://proxy?server={link_host}&port={port}&secret=dd{secret}"
|
||||
|
||||
|
||||
_IPV6_WARNING = (
|
||||
"На вашем компьютере включена поддержка подключения по IPv6.\n\n"
|
||||
"Telegram может пытаться подключаться через IPv6, "
|
||||
"что не поддерживается и может привести к ошибкам.\n\n"
|
||||
"Если прокси не работает или в логах присутствуют ошибки, "
|
||||
"связанные с попытками подключения по IPv6 - "
|
||||
"попробуйте отключить в настройках прокси Telegram попытку соединения "
|
||||
"по IPv6. Если данная мера не помогает, попробуйте отключить IPv6 "
|
||||
"в системе.\n\n"
|
||||
"Это предупреждение будет показано только один раз."
|
||||
)
|
||||
|
||||
|
||||
def _has_ipv6() -> bool:
|
||||
try:
|
||||
for addr in _socket.getaddrinfo(_socket.gethostname(), None, _socket.AF_INET6):
|
||||
ip = addr[4][0]
|
||||
if ip and not ip.startswith("::1") and not ip.startswith("fe80::1"):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
s = _socket.socket(_socket.AF_INET6, _socket.SOCK_STREAM)
|
||||
s.bind(("::1", 0))
|
||||
s.close()
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def check_ipv6_warning(show_info: Callable[[str, str], None]) -> None:
|
||||
ensure_dirs()
|
||||
if IPV6_WARN_MARKER.exists() or not _has_ipv6():
|
||||
return
|
||||
IPV6_WARN_MARKER.touch()
|
||||
threading.Thread(
|
||||
target=lambda: show_info(_IPV6_WARNING, "TG WS Proxy"),
|
||||
daemon=True,
|
||||
).start()
|
||||
|
||||
|
||||
# update check
|
||||
|
||||
def maybe_notify_update(
|
||||
cfg: dict,
|
||||
is_exiting: Callable[[], bool],
|
||||
ask_open: Callable[[str, str], bool],
|
||||
) -> None:
|
||||
if not cfg.get("check_updates", True):
|
||||
return
|
||||
|
||||
def _work():
|
||||
time.sleep(1.5)
|
||||
if is_exiting():
|
||||
return
|
||||
try:
|
||||
from utils.update_check import RELEASES_PAGE_URL, get_status, run_check
|
||||
import webbrowser
|
||||
|
||||
run_check(__version__)
|
||||
st = get_status()
|
||||
if not st.get("has_update"):
|
||||
return
|
||||
url = (st.get("html_url") or "").strip() or RELEASES_PAGE_URL
|
||||
ver = st.get("latest") or "?"
|
||||
if ask_open(
|
||||
f"Доступна новая версия: {ver}\n\nОткрыть страницу релиза в браузере?",
|
||||
"TG WS Proxy — обновление",
|
||||
):
|
||||
webbrowser.open(url)
|
||||
except Exception as exc:
|
||||
log.debug("Update check failed: %s", exc)
|
||||
|
||||
threading.Thread(target=_work, daemon=True, name="update-check").start()
|
||||
|
||||
|
||||
# ctk thread (windows / linux)
|
||||
|
||||
_ctk_root: Any = None
|
||||
_ctk_root_ready = threading.Event()
|
||||
|
||||
|
||||
def ensure_ctk_thread(ctk: Any) -> bool:
|
||||
global _ctk_root
|
||||
if ctk is None:
|
||||
return False
|
||||
if _ctk_root_ready.is_set():
|
||||
return True
|
||||
|
||||
def _run():
|
||||
global _ctk_root
|
||||
from ui.ctk_theme import apply_ctk_appearance, install_tkinter_variable_del_guard
|
||||
|
||||
install_tkinter_variable_del_guard()
|
||||
apply_ctk_appearance(ctk)
|
||||
_ctk_root = ctk.CTk()
|
||||
_ctk_root.withdraw()
|
||||
_ctk_root_ready.set()
|
||||
_ctk_root.mainloop()
|
||||
|
||||
threading.Thread(target=_run, daemon=True, name="ctk-root").start()
|
||||
_ctk_root_ready.wait(timeout=5.0)
|
||||
return _ctk_root is not None
|
||||
|
||||
|
||||
def ctk_run_dialog(build_fn: Callable[[threading.Event], None]) -> None:
|
||||
if _ctk_root is None:
|
||||
return
|
||||
done = threading.Event()
|
||||
|
||||
def _invoke():
|
||||
try:
|
||||
build_fn(done)
|
||||
except Exception:
|
||||
log.exception("CTk dialog failed")
|
||||
done.set()
|
||||
|
||||
_ctk_root.after(0, _invoke)
|
||||
done.wait()
|
||||
import gc
|
||||
gc.collect()
|
||||
|
||||
|
||||
def quit_ctk() -> None:
|
||||
if _ctk_root is not None:
|
||||
try:
|
||||
_ctk_root.after(0, _ctk_root.quit)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# common bootstrap
|
||||
|
||||
def bootstrap(cfg: dict) -> None:
|
||||
save_config(cfg)
|
||||
if LOG_FILE.exists():
|
||||
try:
|
||||
LOG_FILE.unlink()
|
||||
except Exception:
|
||||
pass
|
||||
setup_logging(
|
||||
cfg.get("verbose", False),
|
||||
log_max_mb=cfg.get("log_max_mb", DEFAULT_CONFIG["log_max_mb"]),
|
||||
)
|
||||
log.info("TG WS Proxy версия %s starting", __version__)
|
||||
log.info("Config: %s", cfg)
|
||||
log.info("Log file: %s", LOG_FILE)
|
||||
@ -1,223 +0,0 @@
|
||||
"""
|
||||
Минимальная проверка новой версии через GitHub Releases API (без сторонних зависимостей).
|
||||
|
||||
Ограничение частоты запросов: не чаще одного раза в час на машину (кэш в каталоге
|
||||
данных приложения). Поддерживается If-None-Match (ETag) для ответа 304.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from itertools import zip_longest
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
REPO = "Flowseal/tg-ws-proxy"
|
||||
RELEASES_LATEST_API = f"https://api.github.com/repos/{REPO}/releases/latest"
|
||||
RELEASES_PAGE_URL = f"https://github.com/{REPO}/releases/latest"
|
||||
|
||||
# Не чаще одного полного запроса к API в час (без учёта 304 с тем же ETag).
|
||||
_MIN_FETCH_INTERVAL_SEC = 3600.0
|
||||
|
||||
_state: Dict[str, Any] = {
|
||||
"checked": False,
|
||||
"has_update": False,
|
||||
"ahead_of_release": False,
|
||||
"latest": None,
|
||||
"html_url": None,
|
||||
"error": None,
|
||||
}
|
||||
|
||||
|
||||
def _cache_file() -> Optional[Path]:
|
||||
try:
|
||||
if sys.platform == "win32":
|
||||
root = Path(os.environ.get("APPDATA", str(Path.home()))) / "TgWsProxy"
|
||||
elif sys.platform == "darwin":
|
||||
root = Path.home() / "Library/Application Support/TgWsProxy"
|
||||
else:
|
||||
xdg = os.environ.get("XDG_CONFIG_HOME")
|
||||
root = (Path(xdg).expanduser() if xdg else Path.home() / ".config") / "TgWsProxy"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
return root / ".update_check_cache.json"
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def _load_cache(path: Optional[Path]) -> Dict[str, Any]:
|
||||
if not path or not path.is_file():
|
||||
return {}
|
||||
try:
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, json.JSONDecodeError):
|
||||
return {}
|
||||
|
||||
|
||||
def _save_cache(path: Optional[Path], data: Dict[str, Any]) -> None:
|
||||
if not path:
|
||||
return
|
||||
try:
|
||||
path.write_text(json.dumps(data), encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _parse_version_tuple(s: str) -> tuple:
|
||||
s = (s or "").strip().lstrip("vV")
|
||||
if not s:
|
||||
return (0,)
|
||||
parts = []
|
||||
for seg in s.split("."):
|
||||
digits = "".join(c for c in seg if c.isdigit())
|
||||
if digits:
|
||||
try:
|
||||
parts.append(int(digits))
|
||||
except ValueError:
|
||||
parts.append(0)
|
||||
else:
|
||||
parts.append(0)
|
||||
return tuple(parts) if parts else (0,)
|
||||
|
||||
|
||||
def _version_gt(a: str, b: str) -> bool:
|
||||
"""True, если версия a новее b (простое сравнение по сегментам)."""
|
||||
ta = _parse_version_tuple(a)
|
||||
tb = _parse_version_tuple(b)
|
||||
for x, y in zip_longest(ta, tb, fillvalue=0):
|
||||
if x > y:
|
||||
return True
|
||||
if x < y:
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
def _apply_release_tag(
|
||||
tag: str, html_url: str, current_version: str,
|
||||
) -> None:
|
||||
global _state
|
||||
if not tag:
|
||||
_state["has_update"] = False
|
||||
_state["ahead_of_release"] = False
|
||||
_state["latest"] = None
|
||||
_state["html_url"] = html_url.strip() or RELEASES_PAGE_URL
|
||||
return
|
||||
latest_clean = tag.lstrip("vV")
|
||||
cur = (current_version or "").strip().lstrip("vV")
|
||||
_state["latest"] = latest_clean
|
||||
_state["html_url"] = html_url.strip() or RELEASES_PAGE_URL
|
||||
_state["has_update"] = _version_gt(latest_clean, cur)
|
||||
_state["ahead_of_release"] = bool(latest_clean) and _version_gt(
|
||||
cur, latest_clean
|
||||
)
|
||||
|
||||
|
||||
def fetch_latest_release(
|
||||
timeout: float = 12.0,
|
||||
etag: Optional[str] = None,
|
||||
) -> Tuple[Optional[dict], Optional[str], int]:
|
||||
"""
|
||||
GET releases/latest. Возвращает (data или None при 304, etag или None, HTTP-код).
|
||||
"""
|
||||
headers = {
|
||||
"Accept": "application/vnd.github+json",
|
||||
"User-Agent": "tg-ws-proxy-update-check",
|
||||
}
|
||||
if etag:
|
||||
headers["If-None-Match"] = etag
|
||||
req = Request(
|
||||
RELEASES_LATEST_API,
|
||||
headers=headers,
|
||||
method="GET",
|
||||
)
|
||||
try:
|
||||
with urlopen(req, timeout=timeout) as resp:
|
||||
code = getattr(resp, "status", None) or resp.getcode()
|
||||
new_etag = resp.headers.get("ETag")
|
||||
raw = resp.read().decode("utf-8", errors="replace")
|
||||
return json.loads(raw), new_etag, int(code)
|
||||
except HTTPError as e:
|
||||
if e.code == 304:
|
||||
hdrs = e.headers
|
||||
new_etag = hdrs.get("ETag") if hdrs else None
|
||||
return None, new_etag or etag, 304
|
||||
raise
|
||||
|
||||
|
||||
def run_check(current_version: str) -> None:
|
||||
"""Запрашивает последний релиз и обновляет внутреннее состояние."""
|
||||
global _state
|
||||
_state["checked"] = True
|
||||
_state["error"] = None
|
||||
|
||||
cache_path = _cache_file()
|
||||
cache = _load_cache(cache_path)
|
||||
now = time.time()
|
||||
last_attempt = float(cache.get("last_attempt_at") or 0)
|
||||
|
||||
if last_attempt and (now - last_attempt) < _MIN_FETCH_INTERVAL_SEC:
|
||||
tag = (cache.get("tag_name") or "").strip()
|
||||
if tag:
|
||||
_apply_release_tag(tag, cache.get("html_url") or "", current_version)
|
||||
return
|
||||
err = cache.get("last_error")
|
||||
_state["error"] = (
|
||||
err if err else "Проверка обновлений отложена (интервал между запросами)."
|
||||
)
|
||||
_state["has_update"] = False
|
||||
_state["ahead_of_release"] = False
|
||||
_state["latest"] = None
|
||||
_state["html_url"] = RELEASES_PAGE_URL
|
||||
return
|
||||
|
||||
etag = (cache.get("etag") or "").strip() or None
|
||||
try:
|
||||
data, new_etag, code = fetch_latest_release(etag=etag)
|
||||
cache["last_attempt_at"] = now
|
||||
if code == 304:
|
||||
tag = (cache.get("tag_name") or "").strip()
|
||||
url = (cache.get("html_url") or "").strip() or RELEASES_PAGE_URL
|
||||
_apply_release_tag(tag, url, current_version)
|
||||
if new_etag:
|
||||
cache["etag"] = new_etag
|
||||
_save_cache(cache_path, cache)
|
||||
return
|
||||
|
||||
assert data is not None
|
||||
tag = (data.get("tag_name") or "").strip()
|
||||
html_url = (data.get("html_url") or "").strip() or RELEASES_PAGE_URL
|
||||
if not tag:
|
||||
_state["has_update"] = False
|
||||
_state["ahead_of_release"] = False
|
||||
_state["latest"] = None
|
||||
_state["html_url"] = html_url
|
||||
else:
|
||||
_apply_release_tag(tag, html_url, current_version)
|
||||
if new_etag:
|
||||
cache["etag"] = new_etag
|
||||
cache["tag_name"] = tag
|
||||
cache["html_url"] = html_url
|
||||
cache.pop("last_error", None)
|
||||
_save_cache(cache_path, cache)
|
||||
except (HTTPError, URLError, OSError, TimeoutError, ValueError, json.JSONDecodeError) as e:
|
||||
cache["last_attempt_at"] = now
|
||||
msg = str(e)
|
||||
if isinstance(e, HTTPError) and e.code == 403:
|
||||
msg = (
|
||||
"GitHub API вернул 403 (лимит или доступ). Повторите позже."
|
||||
)
|
||||
cache["last_error"] = msg
|
||||
_save_cache(cache_path, cache)
|
||||
_state["error"] = msg
|
||||
_state["has_update"] = False
|
||||
_state["ahead_of_release"] = False
|
||||
_state["latest"] = None
|
||||
_state["html_url"] = RELEASES_PAGE_URL
|
||||
|
||||
|
||||
def get_status() -> Dict[str, Any]:
|
||||
"""Снимок состояния после run_check (для подписей в настройках)."""
|
||||
return dict(_state)
|
||||
355
windows.py
355
windows.py
@ -1,355 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import webbrowser
|
||||
import winreg
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
try:
|
||||
import pyperclip
|
||||
except ImportError:
|
||||
pyperclip = None
|
||||
|
||||
try:
|
||||
import pystray
|
||||
except ImportError:
|
||||
pystray = None
|
||||
|
||||
try:
|
||||
import customtkinter as ctk
|
||||
except ImportError:
|
||||
ctk = None
|
||||
|
||||
try:
|
||||
from PIL import Image
|
||||
except ImportError:
|
||||
Image = None
|
||||
|
||||
import proxy.tg_ws_proxy as tg_ws_proxy
|
||||
|
||||
from utils.tray_common import (
|
||||
APP_NAME, DEFAULT_CONFIG, FIRST_RUN_MARKER, IS_FROZEN, LOG_FILE,
|
||||
acquire_lock, bootstrap, check_ipv6_warning, ctk_run_dialog,
|
||||
ensure_ctk_thread, ensure_dirs, load_config, load_icon, log,
|
||||
maybe_notify_update, quit_ctk, release_lock, restart_proxy,
|
||||
save_config, start_proxy, stop_proxy, tg_proxy_url,
|
||||
)
|
||||
from ui.ctk_tray_ui import (
|
||||
install_tray_config_buttons, install_tray_config_form,
|
||||
populate_first_run_window, tray_settings_scroll_and_footer,
|
||||
validate_config_form,
|
||||
)
|
||||
from ui.ctk_theme import (
|
||||
CONFIG_DIALOG_FRAME_PAD, CONFIG_DIALOG_SIZE, FIRST_RUN_SIZE,
|
||||
create_ctk_toplevel, ctk_theme_for_platform, main_content_frame,
|
||||
)
|
||||
|
||||
_tray_icon: Optional[object] = None
|
||||
_config: dict = {}
|
||||
_exiting = False
|
||||
|
||||
ICON_PATH = str(Path(__file__).parent / "icon.ico")
|
||||
|
||||
# win32 dialogs
|
||||
|
||||
_u32 = ctypes.windll.user32
|
||||
_u32.MessageBoxW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p, ctypes.c_wchar_p, ctypes.c_uint]
|
||||
_u32.MessageBoxW.restype = ctypes.c_int
|
||||
|
||||
_MB_OK_ERR = 0x10
|
||||
_MB_OK_INFO = 0x40
|
||||
_MB_YESNO_Q = 0x24
|
||||
_IDYES = 6
|
||||
|
||||
|
||||
def _show_error(text: str, title: str = "TG WS Proxy — Ошибка") -> None:
|
||||
_u32.MessageBoxW(None, text, title, _MB_OK_ERR)
|
||||
|
||||
|
||||
def _show_info(text: str, title: str = "TG WS Proxy") -> None:
|
||||
_u32.MessageBoxW(None, text, title, _MB_OK_INFO)
|
||||
|
||||
|
||||
def _ask_yes_no(text: str, title: str = "TG WS Proxy") -> bool:
|
||||
return _u32.MessageBoxW(None, text, title, _MB_YESNO_Q) == _IDYES
|
||||
|
||||
|
||||
# autostart (registry)
|
||||
|
||||
_RUN_KEY = r"Software\Microsoft\Windows\CurrentVersion\Run"
|
||||
|
||||
|
||||
def _supports_autostart() -> bool:
|
||||
return IS_FROZEN
|
||||
|
||||
|
||||
def _autostart_command() -> str:
|
||||
return f'"{sys.executable}"'
|
||||
|
||||
|
||||
def is_autostart_enabled() -> bool:
|
||||
try:
|
||||
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, _RUN_KEY, 0, winreg.KEY_READ) as k:
|
||||
val, _ = winreg.QueryValueEx(k, APP_NAME)
|
||||
return str(val).strip() == _autostart_command().strip()
|
||||
except (FileNotFoundError, OSError):
|
||||
return False
|
||||
|
||||
|
||||
def set_autostart_enabled(enabled: bool) -> None:
|
||||
try:
|
||||
with winreg.CreateKey(winreg.HKEY_CURRENT_USER, _RUN_KEY) as k:
|
||||
if enabled:
|
||||
winreg.SetValueEx(k, APP_NAME, 0, winreg.REG_SZ, _autostart_command())
|
||||
else:
|
||||
try:
|
||||
winreg.DeleteValue(k, APP_NAME)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except OSError as exc:
|
||||
log.error("Failed to update autostart: %s", exc)
|
||||
_show_error(
|
||||
"Не удалось изменить автозапуск.\n\n"
|
||||
"Попробуйте запустить приложение от имени пользователя "
|
||||
f"с правами на реестр.\n\nОшибка: {exc}"
|
||||
)
|
||||
|
||||
|
||||
# tray callbacks
|
||||
|
||||
def _on_open_in_telegram(icon=None, item=None) -> None:
|
||||
url = tg_proxy_url(_config)
|
||||
log.info("Opening %s", url)
|
||||
try:
|
||||
if not webbrowser.open(url):
|
||||
raise RuntimeError
|
||||
except Exception:
|
||||
log.info("Browser open failed, copying to clipboard")
|
||||
if pyperclip is None:
|
||||
_show_error(
|
||||
"Не удалось открыть Telegram автоматически.\n\n"
|
||||
f"Установите пакет pyperclip для копирования в буфер или откройте вручную:\n{url}"
|
||||
)
|
||||
return
|
||||
try:
|
||||
pyperclip.copy(url)
|
||||
_show_info(
|
||||
"Не удалось открыть Telegram автоматически.\n\n"
|
||||
f"Ссылка скопирована в буфер обмена, отправьте её в Telegram и нажмите по ней ЛКМ:\n{url}"
|
||||
)
|
||||
except Exception as exc:
|
||||
log.error("Clipboard copy failed: %s", exc)
|
||||
_show_error(f"Не удалось скопировать ссылку:\n{exc}")
|
||||
|
||||
|
||||
def _on_copy_link(icon=None, item=None) -> None:
|
||||
url = tg_proxy_url(_config)
|
||||
log.info("Copying link: %s", url)
|
||||
if pyperclip is None:
|
||||
_show_error(
|
||||
"Установите пакет pyperclip для копирования в буфер обмена."
|
||||
)
|
||||
return
|
||||
try:
|
||||
pyperclip.copy(url)
|
||||
except Exception as exc:
|
||||
log.error("Clipboard copy failed: %s", exc)
|
||||
_show_error(f"Не удалось скопировать ссылку:\n{exc}")
|
||||
|
||||
|
||||
def _on_restart(icon=None, item=None) -> None:
|
||||
threading.Thread(
|
||||
target=lambda: restart_proxy(_config, _show_error), daemon=True
|
||||
).start()
|
||||
|
||||
|
||||
def _on_edit_config(icon=None, item=None) -> None:
|
||||
threading.Thread(target=_edit_config_dialog, daemon=True).start()
|
||||
|
||||
|
||||
def _on_open_logs(icon=None, item=None) -> None:
|
||||
log.info("Opening log file: %s", LOG_FILE)
|
||||
if LOG_FILE.exists():
|
||||
os.startfile(str(LOG_FILE))
|
||||
else:
|
||||
_show_info("Файл логов ещё не создан.")
|
||||
|
||||
|
||||
def _on_exit(icon=None, item=None) -> None:
|
||||
global _exiting
|
||||
if _exiting:
|
||||
os._exit(0)
|
||||
return
|
||||
_exiting = True
|
||||
log.info("User requested exit")
|
||||
quit_ctk()
|
||||
threading.Thread(target=lambda: (time.sleep(3), os._exit(0)), daemon=True, name="force-exit").start()
|
||||
if icon:
|
||||
icon.stop()
|
||||
|
||||
|
||||
# settings dialog
|
||||
|
||||
def _edit_config_dialog() -> None:
|
||||
if not ensure_ctk_thread(ctk):
|
||||
_show_error("customtkinter не установлен.")
|
||||
return
|
||||
|
||||
cfg = dict(_config)
|
||||
cfg["autostart"] = is_autostart_enabled()
|
||||
if _supports_autostart() and not cfg["autostart"]:
|
||||
set_autostart_enabled(False)
|
||||
|
||||
def _build(done: threading.Event) -> None:
|
||||
theme = ctk_theme_for_platform()
|
||||
w, h = CONFIG_DIALOG_SIZE
|
||||
if _supports_autostart():
|
||||
h += 100
|
||||
|
||||
root = create_ctk_toplevel(
|
||||
ctk, title="TG WS Proxy — Настройки", width=w, height=h, theme=theme,
|
||||
after_create=lambda r: r.iconbitmap(ICON_PATH),
|
||||
)
|
||||
fpx, fpy = CONFIG_DIALOG_FRAME_PAD
|
||||
frame = main_content_frame(ctk, root, theme, padx=fpx, pady=fpy)
|
||||
scroll, footer = tray_settings_scroll_and_footer(ctk, frame, theme)
|
||||
widgets = install_tray_config_form(
|
||||
ctk, scroll, theme, cfg, DEFAULT_CONFIG,
|
||||
show_autostart=_supports_autostart(),
|
||||
autostart_value=cfg.get("autostart", False),
|
||||
)
|
||||
|
||||
def _finish() -> None:
|
||||
root.destroy()
|
||||
done.set()
|
||||
|
||||
def on_save() -> None:
|
||||
from tkinter import messagebox
|
||||
merged = validate_config_form(widgets, DEFAULT_CONFIG, include_autostart=_supports_autostart())
|
||||
if isinstance(merged, str):
|
||||
messagebox.showerror("TG WS Proxy — Ошибка", merged, parent=root)
|
||||
return
|
||||
save_config(merged)
|
||||
_config.update(merged)
|
||||
log.info("Config saved: %s", merged)
|
||||
if _supports_autostart():
|
||||
set_autostart_enabled(bool(merged.get("autostart", False)))
|
||||
_tray_icon.menu = _build_menu()
|
||||
|
||||
do_restart = messagebox.askyesno(
|
||||
"Перезапустить?",
|
||||
"Настройки сохранены.\n\nПерезапустить прокси сейчас?",
|
||||
parent=root,
|
||||
)
|
||||
_finish()
|
||||
if do_restart:
|
||||
threading.Thread(target=lambda: restart_proxy(_config, _show_error), daemon=True).start()
|
||||
|
||||
root.protocol("WM_DELETE_WINDOW", _finish)
|
||||
install_tray_config_buttons(ctk, footer, theme, on_save=on_save, on_cancel=_finish)
|
||||
|
||||
ctk_run_dialog(_build)
|
||||
|
||||
|
||||
# first run
|
||||
|
||||
def _show_first_run() -> None:
|
||||
ensure_dirs()
|
||||
if FIRST_RUN_MARKER.exists():
|
||||
return
|
||||
if not ensure_ctk_thread(ctk):
|
||||
FIRST_RUN_MARKER.touch()
|
||||
return
|
||||
|
||||
host = _config.get("host", DEFAULT_CONFIG["host"])
|
||||
port = _config.get("port", DEFAULT_CONFIG["port"])
|
||||
secret = _config.get("secret", DEFAULT_CONFIG["secret"])
|
||||
|
||||
def _build(done: threading.Event) -> None:
|
||||
theme = ctk_theme_for_platform()
|
||||
w, h = FIRST_RUN_SIZE
|
||||
root = create_ctk_toplevel(
|
||||
ctk, title="TG WS Proxy", width=w, height=h, theme=theme,
|
||||
after_create=lambda r: r.iconbitmap(ICON_PATH),
|
||||
)
|
||||
|
||||
def on_done(open_tg: bool) -> None:
|
||||
FIRST_RUN_MARKER.touch()
|
||||
root.destroy()
|
||||
done.set()
|
||||
if open_tg:
|
||||
_on_open_in_telegram()
|
||||
|
||||
populate_first_run_window(ctk, root, theme, host=host, port=port, secret=secret, on_done=on_done)
|
||||
|
||||
ctk_run_dialog(_build)
|
||||
|
||||
|
||||
# tray menu
|
||||
|
||||
def _build_menu():
|
||||
if pystray is None:
|
||||
return None
|
||||
host = _config.get("host", DEFAULT_CONFIG["host"])
|
||||
port = _config.get("port", DEFAULT_CONFIG["port"])
|
||||
link_host = tg_ws_proxy.get_link_host(host)
|
||||
return pystray.Menu(
|
||||
pystray.MenuItem(f"Открыть в Telegram ({link_host}:{port})", _on_open_in_telegram, default=True),
|
||||
pystray.MenuItem("Скопировать ссылку", _on_copy_link),
|
||||
pystray.Menu.SEPARATOR,
|
||||
pystray.MenuItem("Перезапустить прокси", _on_restart),
|
||||
pystray.MenuItem("Настройки...", _on_edit_config),
|
||||
pystray.MenuItem("Открыть логи", _on_open_logs),
|
||||
pystray.Menu.SEPARATOR,
|
||||
pystray.MenuItem("Выход", _on_exit),
|
||||
)
|
||||
|
||||
|
||||
# entry point
|
||||
|
||||
def run_tray() -> None:
|
||||
global _tray_icon, _config
|
||||
|
||||
_config = load_config()
|
||||
bootstrap(_config)
|
||||
|
||||
if pystray is None or Image is None or ctk is None:
|
||||
log.error("pystray, Pillow or customtkinter not installed; running in console mode")
|
||||
start_proxy(_config, _show_error)
|
||||
try:
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
stop_proxy()
|
||||
return
|
||||
|
||||
start_proxy(_config, _show_error)
|
||||
maybe_notify_update(_config, lambda: _exiting, _ask_yes_no)
|
||||
_show_first_run()
|
||||
check_ipv6_warning(_show_info)
|
||||
|
||||
_tray_icon = pystray.Icon(APP_NAME, load_icon(), "TG WS Proxy", menu=_build_menu())
|
||||
log.info("Tray icon running")
|
||||
_tray_icon.run()
|
||||
|
||||
stop_proxy()
|
||||
log.info("Tray app exited")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
if not acquire_lock("windows.py"):
|
||||
_show_info("Приложение уже запущено.", os.path.basename(sys.argv[0]))
|
||||
return
|
||||
try:
|
||||
run_tray()
|
||||
finally:
|
||||
release_lock()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user