Initial commit
This commit is contained in:
commit
71712b07db
263 files changed
+83991
No files matched your search
+119
@@ -0,0 +1,119 @@
|
||||
# CSQTT v2.1.9
|
||||
|
||||
## Коротко
|
||||
|
||||
- Добавлена поддержка Linux-серверов `arm64` и `armv7` (32-bit ARM) наряду с `amd64`.
|
||||
- Android-клиент теперь выпускается и для `x86_64`.
|
||||
- В web-панель добавлен большой набор DNS-профилей: Yandex, Cloudflare, Google, AdGuard, Xbox, Comms, Geohide, Quad9, OpenDNS, Rostelecom, NextDNS, BI.ZONE и НСДИ.
|
||||
- DNS меняется горячо: без остановки TURN-потоков и без ручного переподключения к серверу.
|
||||
- Улучшена стабильность клиентского и серверного пути, регистрации потоков, восстановления сессий, systemd/Docker-деплоя и повторной установки.
|
||||
- Исправлены известные на момент выпуска проблемы, включая ситуацию «байты RX/TX идут, но активных потоков 0», конфликты старых runtime и блокировку UDP-порта после переключения systemd/Docker.
|
||||
|
||||
## Подключение и активные потоки
|
||||
|
||||
- Исправлена рассинхронизация клиентского и серверного пути, из-за которой TURN мог успешно создать ChannelBind и передавать байты, но сервер не создавал активные сессии.
|
||||
- Протокольный путь проверен реальным E2E-сценарием: клиент, 72 криптосессии, TURN-подобный relay, systemd-сервер, TUN и обратный трафик.
|
||||
- Проверено отсутствие пропусков и дублей при регистрации множества потоков.
|
||||
- Улучшено завершение и отмена сессий: дочерние reader/writer-задачи корректно дожидаются или отменяются при остановке.
|
||||
- Старые сессии не должны мешать новым при повторном старте, восстановлении или смене runtime.
|
||||
- Исправлены повреждённые русские строки сессий вида `[СЕССРРЇ …]`. Теперь выводится нормальный UTF-8:
|
||||
|
||||
```text
|
||||
[СЕССИЯ #65] Завершена
|
||||
[ВОРКЕР #12] Конфиг получен
|
||||
[ВОРКЕР #12] [READY] Поток готов ✓
|
||||
```
|
||||
|
||||
## Новый быстрый диспетчер
|
||||
|
||||
- Переработано распределение пакетов по потокам.
|
||||
- Убран тяжёлый fallback с постоянным поиском «наименее загруженного» потока на горячем пути.
|
||||
- Используется чистый class-aware Round Robin: поток получает непрерывный chunk, затем очередь передаётся следующему потоку.
|
||||
- Введены классы трафика:
|
||||
|
||||
| Класс | Пакеты | Chunk | UDP batch |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| Small | DNS, ICMP, TCP SYN/FIN/RST/ACK, UDP/TCP до 164 B | 4 | 16 |
|
||||
| Medium | 165–999 B | 16 | 64 |
|
||||
| Bulk | от 1000 B | 32 | 128 |
|
||||
|
||||
- Маленький трафик получает приоритет и не должен стоять за крупными пакетами загрузки.
|
||||
- Потоки распределяются равномерно, без фиксации всего flow на одном канале.
|
||||
- Сохранена защита от reorder на обратном направлении: поздний TCP-пакет и ретрансмит не теряются из-за того, что соседние пакеты пришли по разным потокам.
|
||||
- Улучшено batched I/O через `sendmmsg` и `recvmmsg`; инициализируются только фактически используемые элементы batch.
|
||||
- Уменьшено давление на allocator и атомики packet pool.
|
||||
- Запись возвратного трафика в TUN повторно использует уже готовый TUN-дескриптор для burst до 64 пакетов, вместо нового ожидания готовности на каждый пакет.
|
||||
- Очереди возвратного трафика, packet pool и логгер имеют фиксированные лимиты, чтобы не разрастаться бесконечно при перегрузке.
|
||||
|
||||
## Результат производительности
|
||||
|
||||
- 72-поточный Linux E2E держит 159.92 Мбит/с upload и 159.92 Мбит/с download.
|
||||
- Минимум 2.30 / 2.31 Мбит/с на каждый поток.
|
||||
- Серверный dataplane в этом тесте потреблял около 18% одного логического ядра.
|
||||
- Клиентский fast path после оптимизации потреблял примерно 45–47% одного логического ядра на 160 Мбит/с в локальном 72-поточном сценарии.
|
||||
- Новый диспетчер способен использовать кратковременный burst внешнего TURN или маршрута: реальные 9–18 потоков могут выходить выше прежнего устойчивого потолка.
|
||||
- Пинг стал ниже за счёт приоритета small-пакетов, устранения лишнего выбора потока и сокращения локальных очередей.
|
||||
|
||||
## Деплой и редеплой
|
||||
|
||||
- Усилена очистка старого runtime перед установкой.
|
||||
- Установщик корректно работает при занятых путях CSQTT и занятом UDP-порту CSQTT.
|
||||
- Если порт, выбранный для CSQTT, удерживает мешающий runtime, установщик освобождает его перед запуском нового релиза.
|
||||
- Исправлена проблема, при которой старый Docker-контейнер CSQTT мог пережить переход на systemd и после рестарта блокировать UDP-порт.
|
||||
- Исправлена проблема перезапуска `csqtt.service`, когда TUN-recover видел старый Docker-процесс на порту и ошибочно считал его чужим runtime.
|
||||
- Установщик останавливает и удаляет прежние CSQTT runtime: systemd service, Docker-контейнер и старые процессы по используемым путям и порту.
|
||||
- Состояние CSQTT сохраняется при переключении runtime: SQLite и legacy JSON не должны удаляться вместе со старой службой.
|
||||
- Укреплена чистая установка: нужные каталоги создаются до записи environment/config файлов.
|
||||
- Добавлены проверки кандидата до остановки рабочего сервиса: бинарник, конфигурация, TLS и Docker preflight.
|
||||
- Добавлены проверки Docker image до переключения runtime.
|
||||
- Переключения Docker ↔ systemd проверяются автоматически, чтобы не оставался второй runtime.
|
||||
- После перезагрузки systemd-служба должна корректно поднимать TUN и сервер без конфликта со старым контейнером.
|
||||
|
||||
## Совместимость и сервер
|
||||
|
||||
- Подтверждена работа amd64 server asset как статически слинкованного ELF: нет зависимости от новой `glibc`, которая могла бы сломать запуск на старом Ubuntu.
|
||||
- `deploy.sh` определяет дистрибутив через `/etc/os-release` и использует соответствующий пакетный менеджер.
|
||||
- Реально проверены Ubuntu 22.04, Ubuntu 24.04, Ubuntu 26.04 и Debian 13.
|
||||
- На каждой из этих систем проверены первый systemd-деплой, systemd-редеплой, очистка занятого UDP-порта, Docker-деплой, Docker-редеплой, Docker → systemd и systemd → Docker.
|
||||
- Ubuntu 20.04 и Debian 12 логически поддерживаются и не имеют проблемы с glibc у текущего amd64-бинарника, но именно в этой тестовой матрице они не запускались.
|
||||
|
||||
## Тестирование и устойчивость
|
||||
|
||||
- Пройдены Windows-тесты сессий: 31/31.
|
||||
- Пройдены Linux-тесты диспетчера: 28/28.
|
||||
- Проверены гонки регистрации и снятия воркеров, suspend/resume, закрытие receiver, перегрузка очередей, строго ограниченная packet memory, сохранение порядка TCP, отмена и аварийное завершение session reader/writer, replay-защита и границы окна, priority lane для small/medium/bulk, частичные TUN-записи и `WouldBlock`.
|
||||
- Исправлен E2E-скрипт: он больше не может случайно запускать старый `client-*` бинарник из `target/deps`; выбирается свежий release executable.
|
||||
|
||||
## Рекомендации по использованию
|
||||
|
||||
- Ровная устойчивая скорость важнее краткого burst-пика.
|
||||
- Burst выше обычной скорости — нормальное поведение TURN или сети, если пинг под нагрузкой остаётся приемлемым.
|
||||
- Для игр лучше выбирать число потоков по устойчивой скорости и пингу под нагрузкой, а не по максимальной цифре speedtest.
|
||||
- Для скачиваний и торрентов burst допустим: TCP выровняет поток, файл не пострадает.
|
||||
|
||||
## DNS-профили и горячая смена DNS
|
||||
|
||||
- В web-панели добавлен единый список DNS-профилей: Yandex DNS, Cloudflare DNS, Google DNS, AdGuard DNS, Xbox DNS, Comms DNS, Geohide DNS, Quad9 DNS, OpenDNS, Rostelecom DNS, NextDNS, BI.ZONE DNS и НСДИ DNS.
|
||||
- Выбранный профиль сохраняется в SQLite и переживает перезапуск сервера, systemd-редеплой и переключение runtime.
|
||||
- При редеплое известный профиль распознаётся по паре адресов и сохраняется; неизвестная или неполная DNS-конфигурация нормализуется к Yandex DNS.
|
||||
- Смена DNS в панели применяется без остановки TURN-потоков: сервер сохраняет настройку, рассылает новое `TUNCONF` активным путям, а Android заменяет DNS VPN-интерфейса без переподключения к серверу.
|
||||
- DNS-профиль относится к трафику внутри VPN, а не к системному resolver VPS: запрос приложений идёт внутри CSQTT через VK TURN, выходит из сервера и только затем направляется к выбранному DNS-провайдеру.
|
||||
- Для стартового разрешения TURN-адресов нативный клиент использует Yandex DNS `77.88.8.8` и `77.88.8.1`. До поднятия VPN остаётся только аварийный fallback к системному resolver при тайм-ауте Yandex; после поднятия туннеля такой fallback не используется.
|
||||
- Удалены ложные проверки доступности и задержки DNS-провайдеров из панели. Проверка UDP/53 с VPS не доказывает доступность DNS для конкретного клиента и давала вводящие в заблуждение статусы.
|
||||
|
||||
## Идентификаторы устройств и пароли
|
||||
|
||||
- Сохранён главный инвариант безопасности: пароль, уже привязанный к устройству при первом успешном подключении, нельзя использовать с другим `device_id`.
|
||||
- Убран обратный глобальный запрет «одно устройство — только один пароль». Одно и то же устройство может корректно использовать несколько собственных паролей, не теряя ранее созданные привязки.
|
||||
- Сохраняется общий лимит паролей сервера, включая главный пароль; изменение не расширяет квоту пользователей.
|
||||
- Существующие SQLite-базы совместимы с новой схемой: устаревшее обратное поле привязки больше не участвует в решении доступа, а повреждённые ссылки пароль → отсутствующее устройство очищаются при загрузке.
|
||||
- Добавлен протокольный тест: одно устройство привязывает несколько паролей, тогда как попытка другого устройства использовать любой из этих занятых паролей отклоняется.
|
||||
|
||||
## Поставка и архитектуры
|
||||
|
||||
- Серверная поставка включает отдельные Linux-ресурсы для `amd64`, `arm64` и `armv7`; установщик выбирает подходящий ресурс по архитектуре VPS.
|
||||
- В Android-поставку добавлена нативная библиотека `x86_64` наряду с `arm64-v8a` и `armeabi-v7a`.
|
||||
- Выпускаются четыре APK: universal, arm64-v8a, armeabi-v7a и x86_64.
|
||||
- Нативные библиотеки всех Android ABI собираются параллельно. Для клиентских и серверных артефактов записывается и проверяется provenance-файл.
|
||||
- Перед публикацией каждого APK проверяется, что встроенный `assets/deploy.sh` совпадает с исходным сценарием; проверяется и наличие нужных server assets и ABI-библиотек.
|
||||
- Docker-сборка при временной проблеме DNS VPS повторяется с резервными DNS Яндекса только внутри build-контейнера. Это не меняет DNS профиля VPN и не меняет resolver запущенного сервера.
|
||||
@@ -0,0 +1,136 @@
|
||||
# PolyForm Noncommercial License 1.0.0
|
||||
|
||||
<https://polyformproject.org/licenses/noncommercial/1.0.0>
|
||||
|
||||
Required Notice: Copyright 2026 amurcanov.
|
||||
Required Notice: Commercial use of CSQTT requires a separate written license from the licensor.
|
||||
Required Notice: Redistributions and derivative works must retain attribution to the original CSQTT project and these notices.
|
||||
|
||||
|
||||
## Acceptance
|
||||
|
||||
In order to get any license under these terms, you must agree
|
||||
to them as both strict obligations and conditions to all
|
||||
your licenses.
|
||||
|
||||
## Copyright License
|
||||
|
||||
The licensor grants you a copyright license for the
|
||||
software to do everything you might do with the software
|
||||
that would otherwise infringe the licensor's copyright
|
||||
in it for any permitted purpose. However, you may
|
||||
only distribute the software according to [Distribution
|
||||
License](#distribution-license) and make changes or new works
|
||||
based on the software according to [Changes and New Works
|
||||
License](#changes-and-new-works-license).
|
||||
|
||||
## Distribution License
|
||||
|
||||
The licensor grants you an additional copyright license
|
||||
to distribute copies of the software. Your license
|
||||
to distribute covers distributing the software with
|
||||
changes and new works permitted by [Changes and New Works
|
||||
License](#changes-and-new-works-license).
|
||||
|
||||
## Notices
|
||||
|
||||
You must ensure that anyone who gets a copy of any part of
|
||||
the software from you also gets a copy of these terms or the
|
||||
URL for them above, as well as copies of any plain-text lines
|
||||
beginning with `Required Notice:` that the licensor provided
|
||||
with the software. For example:
|
||||
|
||||
> Required Notice: Copyright 2026 amurcanov (https://github.com/amurcanov)
|
||||
|
||||
## Changes and New Works License
|
||||
|
||||
The licensor grants you an additional copyright license to
|
||||
make changes and new works based on the software for any
|
||||
permitted purpose.
|
||||
|
||||
## Patent License
|
||||
|
||||
The licensor grants you a patent license for the software that
|
||||
covers patent claims the licensor can license, or becomes able
|
||||
to license, that you would infringe by using the software.
|
||||
|
||||
## Noncommercial Purposes
|
||||
|
||||
Any noncommercial purpose is a permitted purpose.
|
||||
|
||||
## Personal Uses
|
||||
|
||||
Personal use for research, experiment, and testing for
|
||||
the benefit of public knowledge, personal study, private
|
||||
entertainment, hobby projects, amateur pursuits, or religious
|
||||
observance, without any anticipated commercial application,
|
||||
is use for a permitted purpose.
|
||||
|
||||
## Noncommercial Organizations
|
||||
|
||||
Use by any charitable organization, educational institution,
|
||||
public research organization, public safety or health
|
||||
organization, environmental protection organization,
|
||||
or government institution is use for a permitted purpose
|
||||
regardless of the source of funding or obligations resulting
|
||||
from the funding.
|
||||
|
||||
## Fair Use
|
||||
|
||||
You may have "fair use" rights for the software under the
|
||||
law. These terms do not limit them.
|
||||
|
||||
## No Other Rights
|
||||
|
||||
These terms do not allow you to sublicense or transfer any of
|
||||
your licenses to anyone else, or prevent the licensor from
|
||||
granting licenses to anyone else. These terms do not imply
|
||||
any other licenses.
|
||||
|
||||
## Patent Defense
|
||||
|
||||
If you make any written claim that the software infringes or
|
||||
contributes to infringement of any patent, your patent license
|
||||
for the software granted under these terms ends immediately. If
|
||||
your company makes such a claim, your patent license ends
|
||||
immediately for work on behalf of your company.
|
||||
|
||||
## Violations
|
||||
|
||||
The first time you are notified in writing that you have
|
||||
violated any of these terms, or done anything with the software
|
||||
not covered by your licenses, your licenses can nonetheless
|
||||
continue if you come into full compliance with these terms,
|
||||
and take practical steps to correct past violations, within
|
||||
32 days of receiving notice. Otherwise, all your licenses
|
||||
end immediately.
|
||||
|
||||
## No Liability
|
||||
|
||||
***As far as the law allows, the software comes as is, without
|
||||
any warranty or condition, and the licensor will not be liable
|
||||
to you for any damages arising out of these terms or the use
|
||||
or nature of the software, under any kind of legal claim.***
|
||||
|
||||
## Definitions
|
||||
|
||||
The **licensor** is the individual or entity offering these
|
||||
terms, and the **software** is the software the licensor makes
|
||||
available under these terms.
|
||||
|
||||
**You** refers to the individual or entity agreeing to these
|
||||
terms.
|
||||
|
||||
**Your company** is any legal entity, sole proprietorship,
|
||||
or other kind of organization that you work for, plus all
|
||||
organizations that have control over, are under the control of,
|
||||
or are under common control with that organization. **Control**
|
||||
means ownership of substantially all the assets of an entity,
|
||||
or the power to direct its management and policies by vote,
|
||||
contract, or otherwise. Control can be direct or indirect.
|
||||
|
||||
**Your licenses** are all the licenses granted to you for the
|
||||
software under these terms.
|
||||
|
||||
**Use** means anything you do with the software requiring one
|
||||
of your licenses.
|
||||
@@ -0,0 +1,39 @@
|
||||
<div align="center">
|
||||
|
||||
# CSQTT
|
||||
|
||||
<br>
|
||||
|
||||
<img src="https://img.shields.io/badge/Android-SDK_28--37-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Android SDK" />
|
||||
<img src="https://img.shields.io/badge/Rust-2024-000000?style=for-the-badge&logo=rust&logoColor=white" alt="Rust Core" />
|
||||
<img src="https://img.shields.io/badge/Kotlin-Compose-7F52FF?style=for-the-badge&logo=kotlin&logoColor=white" alt="Kotlin" />
|
||||
<a href="https://github.com/amurcanov/csqtt/stargazers">
|
||||
<img src="https://img.shields.io/github/stars/amurcanov/csqtt?style=for-the-badge&logo=github&color=ffca28&labelColor=24292e" alt="Stars" />
|
||||
</a>
|
||||
|
||||
[CSQTT Telegram Community](https://t.me/wdttcommunity)
|
||||
|
||||
</div>
|
||||
|
||||
<br>
|
||||
|
||||
**CSQTT** — Android-приложение и высокопроизводительный сервер для создания защищённого туннеля поверх TURN/RTP. Клиент поднимает локальный интерфейс на устройстве, маскируя транспорт под зашифрованный медиатрафик звонка.
|
||||
|
||||
**Кросс., проекты с поддержкой CSQTT**:
|
||||
- Windows & Linux порт - [luminescq/focsq](https://github.com/luminescq/focsq)
|
||||
- ios совместимый клиент - [anton48/vk-turn-proxy-ios](https://github.com/anton48/vk-turn-proxy-ios)
|
||||
|
||||
> [!WARNING]
|
||||
> **Некоммерческий статус и запрет коммерческого использования**
|
||||
> Проект является строго некоммерческим исследовательским инструментом и не преследует извлечения выгоды.
|
||||
>
|
||||
> Я (**amurcanov**) прямо запрещаю любое использование исходного кода данного репозитория ([github.com/amurcanov/csqtt](https://github.com/amurcanov/csqtt)) в коммерческих целях в соответствии с условиями лицензии **PolyForm Noncommercial License 1.0.0**. Любая продажа, перепродажа, интеграция в платные сервисы или извлечение прибыли на базе данного кода запрещены.
|
||||
|
||||
> [!NOTE]
|
||||
> Подробная техническая информация и документация по архитектуре **CSQTT** будут опубликованы позже в отдельном окне заметок.
|
||||
|
||||
---
|
||||
|
||||
## Лицензия
|
||||
|
||||
Этот проект распространяется под лицензией **PolyForm Noncommercial License 1.0.0 (PolyForm-Noncommercial-1.0.0)**.
|
||||
@@ -0,0 +1,208 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.plugin.compose")
|
||||
}
|
||||
|
||||
val localProperties = Properties()
|
||||
val localPropertiesFile = rootProject.file("local.properties")
|
||||
if (localPropertiesFile.isFile) {
|
||||
localPropertiesFile.inputStream().use { input -> localProperties.load(input) }
|
||||
}
|
||||
|
||||
fun releaseSigningValue(name: String): String? =
|
||||
providers.gradleProperty(name).orNull
|
||||
?: providers.environmentVariable(name).orNull
|
||||
?: localProperties.getProperty(name)
|
||||
|
||||
fun requiredReleaseSigningValue(name: String): String? =
|
||||
releaseSigningValue(name)?.takeIf { it.isNotBlank() }
|
||||
|
||||
val releaseKeystorePath = requiredReleaseSigningValue("KEYSTORE_FILE")?.trim()
|
||||
val releaseKeystoreFile = releaseKeystorePath?.let { path ->
|
||||
// Keep supporting the existing ../release.keystore convention relative to
|
||||
// the repository root, while also accepting absolute and root-relative paths.
|
||||
if (path.startsWith("../") || path.startsWith("..\\")) {
|
||||
rootProject.file(path.substring(3))
|
||||
} else {
|
||||
rootProject.file(path)
|
||||
}
|
||||
}
|
||||
val releaseStorePassword = requiredReleaseSigningValue("KEYSTORE_PASSWORD")
|
||||
val releaseKeyAlias = requiredReleaseSigningValue("KEY_ALIAS")
|
||||
val releaseKeyPassword = requiredReleaseSigningValue("KEY_PASSWORD")
|
||||
val releaseSigningProblems = mutableListOf<String>().apply {
|
||||
when {
|
||||
releaseKeystoreFile == null -> add("KEYSTORE_FILE is not configured")
|
||||
!releaseKeystoreFile.isFile -> add("the configured release keystore is unavailable")
|
||||
!releaseKeystoreFile.canRead() -> add("the configured release keystore is not readable")
|
||||
}
|
||||
if (releaseStorePassword == null) add("KEYSTORE_PASSWORD is not configured")
|
||||
if (releaseKeyAlias == null) add("KEY_ALIAS is not configured")
|
||||
if (releaseKeyPassword == null) add("KEY_PASSWORD is not configured")
|
||||
}
|
||||
val releaseSigningReady = releaseSigningProblems.isEmpty()
|
||||
|
||||
val verifyReleaseSigning = tasks.register("verifyReleaseSigning") {
|
||||
group = "verification"
|
||||
description = "Verifies that a release build has an explicit, readable signing configuration."
|
||||
inputs.property("releaseSigningProblems", releaseSigningProblems.joinToString("; "))
|
||||
doLast {
|
||||
val signingProblems = inputs.properties["releaseSigningProblems"] as String
|
||||
check(signingProblems.isEmpty()) {
|
||||
"Release signing is not configured: $signingProblems. " +
|
||||
"Provide the required values through Gradle properties, environment variables, " +
|
||||
"or an untracked local.properties file."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.csqtt.client"
|
||||
compileSdk = 37
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "csqtt.quic.amurcanov"
|
||||
minSdk = 26
|
||||
targetSdk = 37
|
||||
versionCode = 221
|
||||
versionName = "2.1.9"
|
||||
|
||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||
vectorDrawables {
|
||||
useSupportLibrary = true
|
||||
}
|
||||
|
||||
ndk {
|
||||
abiFilters.addAll(listOf("arm64-v8a", "armeabi-v7a", "x86_64"))
|
||||
}
|
||||
}
|
||||
|
||||
splits {
|
||||
abi {
|
||||
isEnable = true
|
||||
reset()
|
||||
include("arm64-v8a", "armeabi-v7a", "x86_64")
|
||||
isUniversalApk = true
|
||||
}
|
||||
}
|
||||
|
||||
signingConfigs {
|
||||
create("release") {
|
||||
if (releaseSigningReady) {
|
||||
storeFile = requireNotNull(releaseKeystoreFile)
|
||||
storePassword = releaseStorePassword
|
||||
keyAlias = releaseKeyAlias
|
||||
keyPassword = releaseKeyPassword
|
||||
}
|
||||
enableV1Signing = true
|
||||
enableV2Signing = true
|
||||
enableV3Signing = true
|
||||
}
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
getByName("release") {
|
||||
isMinifyEnabled = true
|
||||
isShrinkResources = true
|
||||
proguardFiles(
|
||||
getDefaultProguardFile("proguard-android-optimize.txt"),
|
||||
"proguard-rules.pro"
|
||||
)
|
||||
if (releaseSigningReady) {
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
packaging {
|
||||
jniLibs {
|
||||
useLegacyPackaging = true
|
||||
keepDebugSymbols += "**/libclient.so"
|
||||
keepDebugSymbols += "**/libandroidx.graphics.path.so"
|
||||
keepDebugSymbols += "**/libdatastore_shared_counter.so"
|
||||
}
|
||||
resources {
|
||||
excludes += "/META-INF/{AL2.0,LGPL2.1}"
|
||||
excludes += "/META-INF/INDEX.LIST"
|
||||
excludes += "/META-INF/DEPENDENCIES"
|
||||
excludes += "/META-INF/LICENSE.md"
|
||||
excludes += "/META-INF/NOTICE.md"
|
||||
}
|
||||
}
|
||||
|
||||
buildFeatures {
|
||||
compose = true
|
||||
buildConfig = true
|
||||
}
|
||||
|
||||
lint {
|
||||
checkReleaseBuilds = true
|
||||
abortOnError = true
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
getByName("main") {
|
||||
jniLibs.directories.add("src/main/jniLibs")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tasks.configureEach {
|
||||
val taskName = name.lowercase()
|
||||
val preparesReleaseBuild = taskName == "prereleasebuild"
|
||||
val producesReleaseArtifact = taskName.contains("release") &&
|
||||
(taskName.startsWith("assemble") ||
|
||||
taskName.startsWith("bundle") ||
|
||||
taskName.startsWith("package") ||
|
||||
taskName.startsWith("sign") ||
|
||||
taskName.startsWith("install") ||
|
||||
taskName.startsWith("publish") ||
|
||||
taskName.startsWith("upload"))
|
||||
if (preparesReleaseBuild || producesReleaseArtifact) {
|
||||
dependsOn(verifyReleaseSigning)
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("androidx.core:core-ktx:1.19.0")
|
||||
implementation(platform("androidx.compose:compose-bom:2026.08.00"))
|
||||
implementation("androidx.compose.ui:ui")
|
||||
implementation("androidx.compose.ui:ui-graphics")
|
||||
implementation("androidx.compose.ui:ui-tooling-preview")
|
||||
implementation("androidx.compose.foundation:foundation")
|
||||
implementation("androidx.compose.material3:material3")
|
||||
implementation("androidx.compose.material:material-icons-extended")
|
||||
implementation("androidx.activity:activity-compose:1.13.0")
|
||||
implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.11.0")
|
||||
implementation("androidx.lifecycle:lifecycle-runtime-compose:2.11.0")
|
||||
implementation("androidx.datastore:datastore-preferences:1.2.1")
|
||||
implementation("com.hierynomus:sshj:0.38.0") {
|
||||
exclude(group = "org.bouncycastle", module = "bcprov-jdk18on")
|
||||
exclude(group = "org.bouncycastle", module = "bcpkix-jdk18on")
|
||||
exclude(group = "org.bouncycastle", module = "bcutil-jdk18on")
|
||||
}
|
||||
implementation("org.bouncycastle:bcprov-jdk18on:1.85")
|
||||
implementation("org.bouncycastle:bcpkix-jdk18on:1.85")
|
||||
implementation("org.bouncycastle:bcutil-jdk18on:1.85")
|
||||
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.11.0")
|
||||
testImplementation("org.mockito:mockito-core:5.23.0")
|
||||
testImplementation("org.json:json:20260814")
|
||||
|
||||
androidTestImplementation("androidx.test.ext:junit:1.3.0")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
|
||||
androidTestImplementation(platform("androidx.compose:compose-bom:2026.08.00"))
|
||||
androidTestImplementation("androidx.compose.ui:ui-test-junit4")
|
||||
debugImplementation("androidx.compose.ui:ui-test-manifest")
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- SPDX-FileCopyrightText: 2026 amurcanov -->
|
||||
<!-- SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 -->
|
||||
|
||||
<lint>
|
||||
<issue id="AndroidGradlePluginVersion" severity="ignore" />
|
||||
<issue id="UnsafeNativeCodeLocation">
|
||||
<ignore path="src/main/assets/csqtt-linux-amd64" />
|
||||
<ignore path="src/main/assets/csqtt-linux-arm64" />
|
||||
<ignore path="src/main/assets/csqtt-linux-armv7" />
|
||||
</issue>
|
||||
</lint>
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
# SPDX-FileCopyrightText: 2026 amurcanov
|
||||
# SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
-keep class net.schmizz.sshj.** { *; }
|
||||
-dontwarn net.schmizz.sshj.**
|
||||
-keep class org.bouncycastle.** { *; }
|
||||
-dontwarn org.bouncycastle.**
|
||||
-keep class org.slf4j.** { *; }
|
||||
-dontwarn org.slf4j.**
|
||||
-keep class net.i2p.crypto.eddsa.** { *; }
|
||||
-dontwarn net.i2p.crypto.eddsa.**
|
||||
-dontwarn sun.security.x509.**
|
||||
-dontwarn com.hierynomus.**
|
||||
@@ -0,0 +1,124 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- SPDX-FileCopyrightText: 2026 amurcanov -->
|
||||
<!-- SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 -->
|
||||
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
|
||||
<uses-feature
|
||||
android:name="android.software.leanback"
|
||||
android:required="false" />
|
||||
<uses-feature
|
||||
android:name="android.hardware.touchscreen"
|
||||
android:required="false" />
|
||||
<uses-feature
|
||||
android:name="android.hardware.wifi"
|
||||
android:required="false" />
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" tools:ignore="QueryAllPackagesPermission" />
|
||||
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
|
||||
|
||||
<application
|
||||
android:name=".CsqttApplication"
|
||||
android:allowBackup="false"
|
||||
android:banner="@drawable/tv_banner"
|
||||
android:dataExtractionRules="@xml/data_extraction_rules"
|
||||
android:fullBackupContent="false"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="CSQTT"
|
||||
android:roundIcon="@mipmap/ic_launcher_round"
|
||||
android:supportsRtl="true"
|
||||
android:theme="@style/Theme.CSQTTClient">
|
||||
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:configChanges="orientation|screenSize"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTop">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.service.quicksettings.ACTION_QS_TILE_PREFERENCES" />
|
||||
</intent-filter>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="csqtt" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<service
|
||||
android:name=".TunnelService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="specialUse"
|
||||
android:stopWithTask="false">
|
||||
<property
|
||||
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="persistent_vpn_tunnel_transport" />
|
||||
</service>
|
||||
|
||||
<service
|
||||
android:name=".QuickToggleTileService"
|
||||
android:exported="true"
|
||||
android:icon="@drawable/ic_c_logo"
|
||||
android:label="CSQTT"
|
||||
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
|
||||
<intent-filter>
|
||||
<action android:name="android.service.quicksettings.action.QS_TILE" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<service
|
||||
android:name=".TunVpnService"
|
||||
android:exported="false"
|
||||
android:permission="android.permission.BIND_VPN_SERVICE"
|
||||
android:foregroundServiceType="specialUse">
|
||||
<intent-filter>
|
||||
<action android:name="android.net.VpnService" />
|
||||
</intent-filter>
|
||||
<property
|
||||
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="csqtt_peer_vpn_tunnel" />
|
||||
<meta-data
|
||||
android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON"
|
||||
android:value="false" />
|
||||
</service>
|
||||
|
||||
<activity
|
||||
android:name=".ManlCaptchaActivity"
|
||||
android:theme="@android:style/Theme.Translucent.NoTitleBar"
|
||||
android:launchMode="singleTask"
|
||||
android:windowSoftInputMode="adjustResize"
|
||||
android:exported="false" />
|
||||
|
||||
<receiver
|
||||
android:name=".CaptchaCancelReceiver"
|
||||
android:exported="false" />
|
||||
|
||||
<receiver
|
||||
android:name=".VpnWidgetProvider"
|
||||
android:label="CSQTT ВПН Виджет"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||
<action android:name="com.csqtt.client.ACTION_WIDGET_TOGGLE" />
|
||||
</intent-filter>
|
||||
<meta-data
|
||||
android:name="android.appwidget.provider"
|
||||
android:resource="@xml/vpn_widget_info" />
|
||||
</receiver>
|
||||
|
||||
</application>
|
||||
|
||||
</manifest>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,5 @@
|
||||
PolyForm Noncommercial License 1.0.0
|
||||
https://polyformproject.org/licenses/noncommercial/1.0.0
|
||||
Required Notice: Copyright 2026 amurcanov.
|
||||
Required Notice: Commercial use of CSQTT requires a separate written license from the licensor.
|
||||
Required Notice: Redistributions and derivative works must retain attribution to the original CSQTT project and these notices.
|
||||
@@ -0,0 +1,24 @@
|
||||
primp
|
||||
Copyright (c) deedy5 and primp contributors
|
||||
Upstream source: https://github.com/deedy5/primp
|
||||
License: MIT (as declared in the crate manifest, license = "MIT")
|
||||
|
||||
MIT License
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,279 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
const val UPDATE_CHECK_NEVER = CsqttConstants.Update.CHECK_NEVER
|
||||
const val DEFAULT_UPDATE_CHECK_INTERVAL_HOURS = CsqttConstants.Update.DEFAULT_CHECK_INTERVAL_HOURS
|
||||
const val UPDATE_DIALOG_ACTION_POSTPONED = CsqttConstants.Update.ACTION_POSTPONED
|
||||
const val UPDATE_DIALOG_ACTION_UPDATE = CsqttConstants.Update.ACTION_UPDATE
|
||||
|
||||
private const val UPDATE_LOG_TAG = CsqttConstants.General.APP_NAME
|
||||
private const val GITHUB_RELEASES_URL = CsqttConstants.Update.GITHUB_RELEASES_URL
|
||||
private const val GITHUB_LATEST_RELEASE_URL = CsqttConstants.Update.GITHUB_LATEST_RELEASE_URL
|
||||
private const val GITHUB_LATEST_RELEASE_WEB_URL = CsqttConstants.Update.GITHUB_LATEST_RELEASE_WEB_URL
|
||||
private const val GITHUB_RELEASE_TAG_URL_PREFIX = CsqttConstants.Update.GITHUB_RELEASE_TAG_URL_PREFIX
|
||||
private const val GITHUB_TAGS_URL = CsqttConstants.Update.GITHUB_TAGS_URL
|
||||
private const val GITHUB_TAG_TREE_URL_PREFIX = CsqttConstants.Update.GITHUB_TAG_TREE_URL_PREFIX
|
||||
private const val GITHUB_API_RATE_LIMIT_FALLBACK_MS = CsqttConstants.Timeouts.UPDATE_RATE_LIMIT_COOLDOWN_MS
|
||||
private val VERSION_NUMBER_REGEX = CsqttConstants.Patterns.VERSION_NUMBER
|
||||
|
||||
@Volatile
|
||||
private var githubApiCooldownUntilMs = 0L
|
||||
|
||||
fun updateIntervalHoursToMillis(hours: Int): Long? = when {
|
||||
hours <= 0 -> null
|
||||
else -> hours * 60L * 60L * 1000L
|
||||
}
|
||||
|
||||
data class AppReleaseInfo(
|
||||
val versionTag: String,
|
||||
val releaseUrl: String,
|
||||
val source: RemoteVersionSource
|
||||
)
|
||||
|
||||
enum class RemoteVersionSource {
|
||||
Release,
|
||||
Tag
|
||||
}
|
||||
|
||||
suspend fun fetchLatestReleaseInfo(localVersion: String? = null): AppReleaseInfo? = withContext(Dispatchers.IO) {
|
||||
val latestRelease = fetchReleaseFromLatestWebRedirect()
|
||||
?: fetchReleaseFromLatestEndpoint()
|
||||
?: fetchLatestStableReleaseFromList()
|
||||
val latestTag = fetchLatestTagFromList()
|
||||
|
||||
when {
|
||||
latestRelease == null -> latestTag
|
||||
latestTag == null -> latestRelease
|
||||
isNewerVersion(latestRelease.versionTag, latestTag.versionTag) -> latestTag
|
||||
else -> latestRelease
|
||||
}
|
||||
}
|
||||
|
||||
fun isNewerVersion(local: String, remote: String): Boolean {
|
||||
val localParts = versionParts(local)
|
||||
val remoteParts = versionParts(remote)
|
||||
if (remoteParts.isEmpty()) return false
|
||||
|
||||
val maxLen = maxOf(localParts.size, remoteParts.size)
|
||||
for (i in 0 until maxLen) {
|
||||
val localPart = localParts.getOrElse(i) { 0 }
|
||||
val remotePart = remoteParts.getOrElse(i) { 0 }
|
||||
if (remotePart > localPart) return true
|
||||
if (remotePart < localPart) return false
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private fun fetchLatestStableReleaseFromList(): AppReleaseInfo? {
|
||||
val response = fetchGitHubApi(GITHUB_RELEASES_URL) ?: return null
|
||||
val releases = try {
|
||||
JSONArray(response)
|
||||
} catch (e: Exception) {
|
||||
Log.w(UPDATE_LOG_TAG, "[WARN] Update check: failed to parse releases list", e)
|
||||
return null
|
||||
}
|
||||
|
||||
var bestRelease: AppReleaseInfo? = null
|
||||
for (i in 0 until releases.length()) {
|
||||
val json = releases.optJSONObject(i) ?: continue
|
||||
if (json.optBoolean("draft") || json.optBoolean("prerelease")) continue
|
||||
val release = json.toAppReleaseInfo() ?: continue
|
||||
if (bestRelease == null || isNewerVersion(bestRelease.versionTag, release.versionTag)) {
|
||||
bestRelease = release
|
||||
}
|
||||
}
|
||||
return bestRelease
|
||||
}
|
||||
|
||||
private fun fetchLatestTagFromList(): AppReleaseInfo? {
|
||||
val response = fetchGitHubApi(GITHUB_TAGS_URL) ?: return null
|
||||
val tags = try {
|
||||
JSONArray(response)
|
||||
} catch (e: Exception) {
|
||||
Log.w(UPDATE_LOG_TAG, "[WARN] Update check: failed to parse tags list", e)
|
||||
return null
|
||||
}
|
||||
|
||||
var bestTag: AppReleaseInfo? = null
|
||||
for (i in 0 until tags.length()) {
|
||||
val json = tags.optJSONObject(i) ?: continue
|
||||
val tagName = normalizeVersionTag(json.optString("name"))
|
||||
if (tagName.isBlank()) continue
|
||||
val tag = AppReleaseInfo(
|
||||
versionTag = tagName,
|
||||
releaseUrl = "$GITHUB_TAG_TREE_URL_PREFIX$tagName",
|
||||
source = RemoteVersionSource.Tag
|
||||
)
|
||||
if (bestTag == null || isNewerVersion(bestTag.versionTag, tag.versionTag)) {
|
||||
bestTag = tag
|
||||
}
|
||||
}
|
||||
return bestTag
|
||||
}
|
||||
|
||||
private fun fetchReleaseFromLatestEndpoint(): AppReleaseInfo? {
|
||||
val response = fetchGitHubApi(GITHUB_LATEST_RELEASE_URL) ?: return null
|
||||
val json = try {
|
||||
JSONObject(response)
|
||||
} catch (e: Exception) {
|
||||
Log.w(UPDATE_LOG_TAG, "[WARN] Update check: failed to parse latest release", e)
|
||||
return null
|
||||
}
|
||||
return json.toAppReleaseInfo()
|
||||
}
|
||||
|
||||
private fun fetchReleaseFromLatestWebRedirect(): AppReleaseInfo? {
|
||||
var conn: HttpURLConnection? = null
|
||||
return try {
|
||||
conn = URL(GITHUB_LATEST_RELEASE_WEB_URL).openConnection() as HttpURLConnection
|
||||
applyNoCacheHeaders(conn)
|
||||
conn.instanceFollowRedirects = false
|
||||
conn.requestMethod = "GET"
|
||||
conn.setRequestProperty("Accept", "text/html,*/*")
|
||||
conn.setRequestProperty("User-Agent", "CSQTTAndroid/${BuildConfig.VERSION_NAME}")
|
||||
conn.connectTimeout = 8_000
|
||||
conn.readTimeout = 8_000
|
||||
|
||||
val responseCode = conn.responseCode
|
||||
val location = conn.getHeaderField("Location")
|
||||
if (!location.isNullOrBlank()) {
|
||||
val releaseUrl = URL(URL(GITHUB_LATEST_RELEASE_WEB_URL), location).toString()
|
||||
val versionTag = extractTagFromReleaseUrl(releaseUrl)
|
||||
if (!versionTag.isNullOrBlank()) {
|
||||
return AppReleaseInfo(versionTag, releaseUrl, RemoteVersionSource.Release)
|
||||
}
|
||||
}
|
||||
|
||||
if (responseCode in 200..299) {
|
||||
val response = conn.inputStream.bufferedReader().use { it.readText() }
|
||||
val versionTag = Regex("/releases/tag/([^\"?#<]+)").find(response)?.groupValues?.getOrNull(1)
|
||||
if (!versionTag.isNullOrBlank()) {
|
||||
return AppReleaseInfo(versionTag, "$GITHUB_RELEASE_TAG_URL_PREFIX$versionTag", RemoteVersionSource.Release)
|
||||
}
|
||||
}
|
||||
|
||||
Log.w(UPDATE_LOG_TAG, "[WARN] Update check: GitHub web fallback returned $responseCode")
|
||||
null
|
||||
} catch (e: Exception) {
|
||||
Log.w(UPDATE_LOG_TAG, "[WARN] Update check: GitHub web fallback failed", e)
|
||||
null
|
||||
} finally {
|
||||
conn?.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun fetchGitHubApi(url: String): String? {
|
||||
val now = System.currentTimeMillis()
|
||||
if (now < githubApiCooldownUntilMs) return null
|
||||
return fetchHttpText(
|
||||
url = url,
|
||||
sourceLabel = "GitHub API",
|
||||
accept = "application/vnd.github+json",
|
||||
isGitHubApi = true
|
||||
)
|
||||
}
|
||||
|
||||
private fun fetchHttpText(
|
||||
url: String,
|
||||
sourceLabel: String,
|
||||
accept: String,
|
||||
isGitHubApi: Boolean = false
|
||||
): String? {
|
||||
var conn: HttpURLConnection? = null
|
||||
return try {
|
||||
conn = URL(url).openConnection() as HttpURLConnection
|
||||
applyNoCacheHeaders(conn)
|
||||
conn.requestMethod = "GET"
|
||||
conn.setRequestProperty("Accept", accept)
|
||||
if (isGitHubApi) {
|
||||
conn.setRequestProperty("X-GitHub-Api-Version", "2022-11-28")
|
||||
}
|
||||
conn.setRequestProperty("User-Agent", "CSQTTAndroid/${BuildConfig.VERSION_NAME}")
|
||||
conn.connectTimeout = 8_000
|
||||
conn.readTimeout = 8_000
|
||||
|
||||
val responseCode = conn.responseCode
|
||||
val stream = if (responseCode in 200..299) conn.inputStream else conn.errorStream
|
||||
val response = stream?.bufferedReader()?.use { it.readText() }.orEmpty()
|
||||
|
||||
if (responseCode in 200..299) {
|
||||
if (isGitHubApi) githubApiCooldownUntilMs = 0L
|
||||
response
|
||||
} else {
|
||||
if (isGitHubApi) noteGitHubApiCooldown(conn, responseCode, response)
|
||||
Log.w(
|
||||
UPDATE_LOG_TAG,
|
||||
"[WARN] Update check: $sourceLabel returned $responseCode ${response.take(300)}"
|
||||
)
|
||||
null
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(UPDATE_LOG_TAG, "[WARN] Update check: $sourceLabel request failed", e)
|
||||
null
|
||||
} finally {
|
||||
conn?.disconnect()
|
||||
}
|
||||
}
|
||||
|
||||
private fun applyNoCacheHeaders(conn: HttpURLConnection) {
|
||||
conn.useCaches = false
|
||||
conn.setRequestProperty("Cache-Control", "no-cache, no-store, max-age=0")
|
||||
conn.setRequestProperty("Pragma", "no-cache")
|
||||
conn.setRequestProperty("Expires", "0")
|
||||
}
|
||||
|
||||
private fun noteGitHubApiCooldown(conn: HttpURLConnection, responseCode: Int, response: String) {
|
||||
if (responseCode != HttpURLConnection.HTTP_FORBIDDEN && responseCode != 429) return
|
||||
val now = System.currentTimeMillis()
|
||||
val retryAfterUntil = conn.getHeaderField("Retry-After")?.trim()?.toLongOrNull()?.takeIf { it > 0L }?.let { now + it * 1000L }
|
||||
val rateLimitResetUntil = conn.getHeaderField("X-RateLimit-Reset")?.trim()?.toLongOrNull()?.takeIf { it > 0L }?.let { it * 1000L }
|
||||
val fallbackUntil = now + if (response.contains("rate limit", ignoreCase = true)) GITHUB_API_RATE_LIMIT_FALLBACK_MS else 5L * 60L * 1000L
|
||||
val cooldownUntil = listOfNotNull(retryAfterUntil, rateLimitResetUntil).filter { it > now }.minOrNull() ?: fallbackUntil
|
||||
if (cooldownUntil > githubApiCooldownUntilMs) {
|
||||
githubApiCooldownUntilMs = cooldownUntil
|
||||
Log.w(
|
||||
UPDATE_LOG_TAG,
|
||||
"[WARN] Update check: GitHub API cooldown ${(cooldownUntil - now) / 1000}s after HTTP $responseCode"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun JSONObject.toAppReleaseInfo(): AppReleaseInfo? {
|
||||
val versionTag = normalizeVersionTag(optString("tag_name"))
|
||||
val releaseUrl = optString("html_url").trim()
|
||||
if (versionTag.isBlank() || releaseUrl.isBlank()) return null
|
||||
return AppReleaseInfo(versionTag, releaseUrl, RemoteVersionSource.Release)
|
||||
}
|
||||
|
||||
private fun versionParts(version: String): List<Int> {
|
||||
val normalized = VERSION_NUMBER_REGEX.find(version.trim())?.value ?: return emptyList()
|
||||
return normalized.split(".").mapNotNull { it.toIntOrNull() }
|
||||
}
|
||||
|
||||
internal fun normalizeVersionTag(version: String): String {
|
||||
val trimmed = version.trim()
|
||||
if (trimmed.isBlank()) return ""
|
||||
return if (trimmed.startsWith("v", ignoreCase = true)) trimmed else "v$trimmed"
|
||||
}
|
||||
|
||||
private fun extractTagFromReleaseUrl(releaseUrl: String): String? {
|
||||
val marker = "/releases/tag/"
|
||||
val index = releaseUrl.indexOf(marker)
|
||||
if (index < 0) return null
|
||||
return releaseUrl.substring(index + marker.length)
|
||||
.substringBefore("?")
|
||||
.substringBefore("#")
|
||||
.substringBefore("/")
|
||||
.takeIf { it.isNotBlank() }
|
||||
?.let(::normalizeVersionTag)
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
internal fun shouldRequestBatteryOptimizationExemption(
|
||||
promptHandled: Boolean,
|
||||
alreadyExempt: Boolean,
|
||||
): Boolean = !promptHandled && !alreadyExempt
|
||||
@@ -0,0 +1,18 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.app.NotificationManager
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
|
||||
class CaptchaCancelReceiver : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
TunnelManager.stop()
|
||||
ManlCaptchaWebViewManager.activeActivity?.finish()
|
||||
val notifMgr = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
notifMgr.cancel(CsqttConstants.Notifications.CAPTCHA_NOTIFICATION_ID)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import java.net.URI
|
||||
|
||||
object CaptchaUriPolicy {
|
||||
private val allowedDomains = setOf("vk.com", "vk.ru", "ok.ru", "okcdn.ru")
|
||||
|
||||
fun isAllowed(value: String): Boolean {
|
||||
val uri = runCatching { URI(value) }.getOrNull() ?: return false
|
||||
if (!uri.scheme.equals("https", ignoreCase = true)) return false
|
||||
val host = uri.host?.lowercase()?.trimEnd('.') ?: return false
|
||||
return allowedDomains.any { host == it || host.endsWith(".$it") }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,531 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import android.util.Log
|
||||
import android.view.MotionEvent
|
||||
import android.view.View
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebResourceResponse
|
||||
import android.webkit.WebChromeClient
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import java.lang.ref.WeakReference
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
import kotlin.coroutines.cancellation.CancellationException
|
||||
import kotlin.random.Random
|
||||
|
||||
@SuppressLint("StaticFieldLeak")
|
||||
object CaptchaWebViewManager {
|
||||
private const val TAG = "CaptchaWV"
|
||||
private const val CAPTCHA_TIMEOUT_MS = CsqttConstants.Timeouts.CAPTCHA_AUTO_TIMEOUT_MS
|
||||
private const val WV_CREATE_TIMEOUT_MS = CsqttConstants.Timeouts.CAPTCHA_WV_CREATE_TIMEOUT_MS
|
||||
const val ERROR_SLIDER_DETECTED = CsqttConstants.Captcha.ERROR_SLIDER_DETECTED
|
||||
|
||||
private val VIEWPORT_WIDTHS = CsqttConstants.Captcha.AUTO_VIEWPORT_WIDTHS
|
||||
private val VIEWPORT_HEIGHTS = CsqttConstants.Captcha.AUTO_VIEWPORT_HEIGHTS
|
||||
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
private val captchaMutex = Mutex()
|
||||
|
||||
@Volatile
|
||||
private var isTunnelActive = false
|
||||
|
||||
@Volatile
|
||||
private var appContext: WeakReference<Context>? = null
|
||||
|
||||
private val pendingResult = AtomicReference<CompletableDeferred<Result<String>>?>(null)
|
||||
private val postClickSliderWatcher = AtomicReference<Runnable?>(null)
|
||||
|
||||
@Volatile
|
||||
private var currentWebView: WebView? = null
|
||||
|
||||
private fun activeWebView(): WebView? = currentWebView
|
||||
|
||||
private val interceptorJSCode = """
|
||||
(function() {
|
||||
if (window.__csqtt_interceptor_installed) return;
|
||||
window.__csqtt_interceptor_installed = true;
|
||||
|
||||
const origFetch = window.fetch;
|
||||
window.fetch = async function() {
|
||||
const args = arguments;
|
||||
const url = args[0] || '';
|
||||
if (typeof url === 'string' && url.includes('captchaNotRobot.check')) {
|
||||
const response = await origFetch.apply(this, args);
|
||||
const clone = response.clone();
|
||||
try {
|
||||
const data = await clone.json();
|
||||
if (data.response && data.response.success_token) {
|
||||
window.CsqttCaptcha.onSuccess(data.response.success_token);
|
||||
} else if (
|
||||
data.response &&
|
||||
data.response.show_captcha_type === 'slider'
|
||||
) {
|
||||
window.CsqttCaptcha.onSliderDetected('check_response');
|
||||
} else if (data.error) {
|
||||
window.CsqttCaptcha.onError(JSON.stringify(data.error));
|
||||
}
|
||||
} catch(e) {}
|
||||
return response;
|
||||
}
|
||||
return origFetch.apply(this, args);
|
||||
};
|
||||
|
||||
const origXHROpen = XMLHttpRequest.prototype.open;
|
||||
const origXHRSend = XMLHttpRequest.prototype.send;
|
||||
XMLHttpRequest.prototype.open = function(method, url) {
|
||||
this._csqtt_url = url;
|
||||
return origXHROpen.apply(this, arguments);
|
||||
};
|
||||
XMLHttpRequest.prototype.send = function() {
|
||||
const xhr = this;
|
||||
if (xhr._csqtt_url && xhr._csqtt_url.includes('captchaNotRobot.check')) {
|
||||
xhr.addEventListener('load', function() {
|
||||
try {
|
||||
const data = JSON.parse(xhr.responseText);
|
||||
if (data.response && data.response.success_token) {
|
||||
window.CsqttCaptcha.onSuccess(data.response.success_token);
|
||||
} else if (
|
||||
data.response &&
|
||||
data.response.show_captcha_type === 'slider'
|
||||
) {
|
||||
window.CsqttCaptcha.onSliderDetected('check_response');
|
||||
} else if (data.error) {
|
||||
window.CsqttCaptcha.onError(JSON.stringify(data.error));
|
||||
}
|
||||
} catch(e) {}
|
||||
});
|
||||
}
|
||||
return origXHRSend.apply(this, arguments);
|
||||
};
|
||||
})();
|
||||
""".trimIndent()
|
||||
|
||||
fun onTunnelStart(context: Context) {
|
||||
appContext = WeakReference(context.applicationContext)
|
||||
isTunnelActive = true
|
||||
Log.d(TAG, "Туннель активен")
|
||||
}
|
||||
|
||||
fun onTunnelStop() {
|
||||
isTunnelActive = false
|
||||
cancelPendingResult("tunnel stopped")
|
||||
destroyCurrentWebView()
|
||||
appContext = null
|
||||
Log.d(TAG, "Туннель остановлен")
|
||||
}
|
||||
|
||||
suspend fun solveCaptchaAsync(redirectUri: String, sessionToken: String, onStep: (String) -> Unit = {}): String {
|
||||
if (!isTunnelActive) throw IllegalStateException("WV не готов — туннель не активен")
|
||||
if (!CaptchaUriPolicy.isAllowed(redirectUri)) throw IllegalArgumentException("Недопустимый адрес captcha")
|
||||
val ctx = appContext?.get() ?: throw IllegalStateException("WV не готов — контекст null")
|
||||
|
||||
return captchaMutex.withLock {
|
||||
try {
|
||||
withTimeout(CAPTCHA_TIMEOUT_MS) {
|
||||
doSolveCaptcha(ctx, redirectUri, onStep)
|
||||
}
|
||||
} finally {
|
||||
pendingResult.set(null)
|
||||
destroyCurrentWebView()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun doSolveCaptcha(context: Context, redirectUri: String, onStep: (String) -> Unit): String {
|
||||
val deferred = CompletableDeferred<Result<String>>()
|
||||
pendingResult.set(deferred)
|
||||
|
||||
val webView = createWebViewSync(context, onStep)
|
||||
?: throw IllegalStateException("Не удалось создать WebView")
|
||||
|
||||
Log.d(TAG, "WebView создан ✓")
|
||||
|
||||
withContext(Dispatchers.Main) {
|
||||
webView.evaluateJavascript(interceptorJSCode, null)
|
||||
kotlinx.coroutines.delay(80)
|
||||
webView.loadUrl(redirectUri)
|
||||
}
|
||||
|
||||
try {
|
||||
val token = deferred.await().getOrThrow()
|
||||
Log.d(TAG, "Капча решена ✓")
|
||||
return token
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Ошибка: ${e::class.simpleName} — ${e.message}")
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
private fun createWebViewSync(context: Context, onStep: (String) -> Unit): WebView? {
|
||||
val vw = VIEWPORT_WIDTHS[Random.Default.nextInt(VIEWPORT_WIDTHS.size)]
|
||||
val vh = VIEWPORT_HEIGHTS[Random.Default.nextInt(VIEWPORT_HEIGHTS.size)]
|
||||
Log.d(TAG, "WebView viewport: ${vw}x${vh}")
|
||||
|
||||
val latch = CountDownLatch(1)
|
||||
var webView: WebView? = null
|
||||
|
||||
val createAction = Runnable {
|
||||
try {
|
||||
val wv = WebView(context.applicationContext)
|
||||
wv.apply {
|
||||
settings.apply {
|
||||
javaScriptEnabled = true
|
||||
domStorageEnabled = true
|
||||
mediaPlaybackRequiresUserGesture = false
|
||||
loadWithOverviewMode = true
|
||||
useWideViewPort = true
|
||||
blockNetworkLoads = false
|
||||
cacheMode = android.webkit.WebSettings.LOAD_NO_CACHE
|
||||
}
|
||||
|
||||
Log.d(TAG, "WebView UA: ${settings.userAgentString}")
|
||||
|
||||
addJavascriptInterface(CaptchaJSBridge(), "CsqttCaptcha")
|
||||
|
||||
webViewClient = object : WebViewClient() {
|
||||
override fun onPageStarted(
|
||||
view: WebView, url: String?, favicon: android.graphics.Bitmap?
|
||||
) {
|
||||
super.onPageStarted(view, url, favicon)
|
||||
view.evaluateJavascript(interceptorJSCode, null)
|
||||
}
|
||||
|
||||
override fun onPageFinished(view: WebView, url: String?) {
|
||||
super.onPageFinished(view, url)
|
||||
|
||||
val isCaptchaPage = url?.let {
|
||||
it.contains("not_robot_captcha") ||
|
||||
it.contains("id.vk.ru/captcha") ||
|
||||
it.contains("not_robot")
|
||||
} ?: false
|
||||
|
||||
if (isCaptchaPage) {
|
||||
Log.d(TAG, "Страница капчи загружена")
|
||||
view.evaluateJavascript(interceptorJSCode, null)
|
||||
|
||||
if (activeWebView() === view && isTunnelActive) {
|
||||
val pageLoadDelay = 650L + Random.Default.nextLong(0, 550)
|
||||
mainHandler.postDelayed({
|
||||
if (activeWebView() === view && isTunnelActive) {
|
||||
solveCaptchaAutomatedSync(view)
|
||||
}
|
||||
}, pageLoadDelay)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun shouldInterceptRequest(
|
||||
view: WebView, request: WebResourceRequest
|
||||
): WebResourceResponse? {
|
||||
return super.shouldInterceptRequest(view, request)
|
||||
}
|
||||
|
||||
override fun shouldOverrideUrlLoading(
|
||||
view: WebView,
|
||||
request: WebResourceRequest
|
||||
): Boolean = !CaptchaUriPolicy.isAllowed(request.url.toString())
|
||||
|
||||
override fun onReceivedSslError(
|
||||
view: WebView,
|
||||
handler: android.webkit.SslErrorHandler,
|
||||
error: android.net.http.SslError
|
||||
) {
|
||||
handler.cancel()
|
||||
Log.w(TAG, "SSL error rejected for: ${error.url.orEmpty()}")
|
||||
}
|
||||
}
|
||||
|
||||
webChromeClient = WebChromeClient()
|
||||
|
||||
measure(
|
||||
View.MeasureSpec.makeMeasureSpec(vw, View.MeasureSpec.EXACTLY),
|
||||
View.MeasureSpec.makeMeasureSpec(vh, View.MeasureSpec.EXACTLY)
|
||||
)
|
||||
layout(0, 0, vw, vh)
|
||||
onResume()
|
||||
}
|
||||
webView = wv
|
||||
currentWebView = wv
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Ошибка создания WebView: ${e.message}")
|
||||
webView = null
|
||||
} finally {
|
||||
latch.countDown()
|
||||
}
|
||||
}
|
||||
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||
createAction.run()
|
||||
} else {
|
||||
mainHandler.post(createAction)
|
||||
}
|
||||
|
||||
val ok = latch.await(WV_CREATE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
|
||||
if (!ok) {
|
||||
Log.e(TAG, "Таймаут создания WebView")
|
||||
mainHandler.post {
|
||||
if (webView != null && currentWebView === webView) {
|
||||
destroyCurrentWebView()
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
return webView
|
||||
}
|
||||
|
||||
private fun destroyCurrentWebView() {
|
||||
val wv = activeWebView() ?: return
|
||||
currentWebView = null
|
||||
postClickSliderWatcher.getAndSet(null)?.let { mainHandler.removeCallbacks(it) }
|
||||
|
||||
val destroyAction = Runnable {
|
||||
try {
|
||||
wv.stopLoading()
|
||||
wv.loadUrl("about:blank")
|
||||
try { wv.removeJavascriptInterface("CsqttCaptcha") } catch (_: Exception) {}
|
||||
wv.webViewClient = WebViewClient()
|
||||
wv.webChromeClient = null
|
||||
wv.onPause()
|
||||
wv.removeAllViews()
|
||||
wv.destroy()
|
||||
Log.d(TAG, "WebView уничтожен ✓")
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Ошибка уничтожения: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||
destroyAction.run()
|
||||
} else {
|
||||
val latch = CountDownLatch(1)
|
||||
mainHandler.post {
|
||||
try { destroyAction.run() } finally { latch.countDown() }
|
||||
}
|
||||
latch.await(2000, TimeUnit.MILLISECONDS)
|
||||
}
|
||||
}
|
||||
|
||||
private fun solveCaptchaAutomatedSync(webView: WebView) {
|
||||
if (activeWebView() !== webView || !isTunnelActive) return
|
||||
|
||||
val findLabelJS = """
|
||||
(function() {
|
||||
var slider = document.querySelector(
|
||||
'[class*="SliderCaptcha"], [class*="Kaleidoscope"], ' +
|
||||
'.vkc__SliderCaptcha-module__description, ' +
|
||||
'.vkc__KaleidoscopeScreen-module__captchaId'
|
||||
);
|
||||
if (slider) return '${ERROR_SLIDER_DETECTED}';
|
||||
|
||||
var el = document.querySelector('label.vkc__Checkbox-module__Checkbox');
|
||||
if (!el) el = document.querySelector('label[for="not-robot-captcha-checkbox"]');
|
||||
if (!el) el = document.getElementById('not-robot-captcha-checkbox');
|
||||
if (!el) return 'not_found';
|
||||
|
||||
var rect = el.getBoundingClientRect();
|
||||
var style = window.getComputedStyle(el);
|
||||
if (rect.width < 5 || rect.height < 5 ||
|
||||
style.display === 'none' || style.visibility === 'hidden') {
|
||||
return 'not_found';
|
||||
}
|
||||
return rect.left + ',' + rect.top + ',' + rect.width + ',' + rect.height;
|
||||
})();
|
||||
""".trimIndent()
|
||||
|
||||
webView.evaluateJavascript(findLabelJS) { rawValue ->
|
||||
val result = rawValue?.replace("\"", "") ?: ""
|
||||
Log.d(TAG, "Label чекбокса: $result")
|
||||
|
||||
if (activeWebView() !== webView || !isTunnelActive) return@evaluateJavascript
|
||||
|
||||
if (result == ERROR_SLIDER_DETECTED) {
|
||||
Log.i(TAG, "Обнаружен слайдер — fallback на ручной WebView")
|
||||
notifyResult(Result.failure(IllegalStateException(ERROR_SLIDER_DETECTED)))
|
||||
return@evaluateJavascript
|
||||
}
|
||||
|
||||
if (result == "not_found" || result.split(",").size < 4) {
|
||||
Log.w(TAG, "Label не найден — JS-клик (fallback)")
|
||||
val jsClick = """
|
||||
(function() {
|
||||
var el = document.querySelector('label.vkc__Checkbox-module__Checkbox');
|
||||
if (!el) el = document.getElementById('not-robot-captcha-checkbox');
|
||||
if (el) { el.click(); return 'clicked'; }
|
||||
return 'nothing';
|
||||
})();
|
||||
""".trimIndent()
|
||||
webView.evaluateJavascript(jsClick) { clickResult ->
|
||||
if ((clickResult ?: "").replace("\"", "") == "clicked") {
|
||||
startPostClickSliderWatcher(webView)
|
||||
}
|
||||
}
|
||||
return@evaluateJavascript
|
||||
}
|
||||
|
||||
val parts = result.split(",")
|
||||
val left = parts[0].toFloatOrNull() ?: return@evaluateJavascript
|
||||
val top = parts[1].toFloatOrNull() ?: return@evaluateJavascript
|
||||
val width = parts[2].toFloatOrNull() ?: return@evaluateJavascript
|
||||
val height = parts[3].toFloatOrNull() ?: return@evaluateJavascript
|
||||
|
||||
val randX = left + width * (0.15f + Random.Default.nextFloat() * 0.7f)
|
||||
val randY = top + height * (0.25f + Random.Default.nextFloat() * 0.5f)
|
||||
|
||||
Log.d(TAG, "Клик: (${randX.toInt()}, ${randY.toInt()}) в зоне ${width.toInt()}x${height.toInt()}")
|
||||
|
||||
val thinkDelay = 420L + Random.Default.nextLong(0, 260)
|
||||
|
||||
mainHandler.postDelayed({
|
||||
if (activeWebView() === webView && isTunnelActive) {
|
||||
simulateHumanTouch(webView, randX, randY)
|
||||
startPostClickSliderWatcher(webView)
|
||||
}
|
||||
}, thinkDelay)
|
||||
}
|
||||
}
|
||||
|
||||
private fun startPostClickSliderWatcher(webView: WebView) {
|
||||
postClickSliderWatcher.getAndSet(null)?.let { mainHandler.removeCallbacks(it) }
|
||||
|
||||
var attemptsLeft = 14
|
||||
val watcher = object : Runnable {
|
||||
override fun run() {
|
||||
if (activeWebView() !== webView || !isTunnelActive) return
|
||||
|
||||
val detectSliderJS = """
|
||||
(function() {
|
||||
var slider = document.querySelector(
|
||||
'[class*="SliderCaptcha"], [class*="Kaleidoscope"], ' +
|
||||
'.vkc__SliderCaptcha-module__description, ' +
|
||||
'.vkc__KaleidoscopeScreen-module__captchaId, ' +
|
||||
'.vkc__SwipeButton-module__track'
|
||||
);
|
||||
if (slider) return 'slider';
|
||||
|
||||
var success = document.querySelector(
|
||||
'[class*="success"], [class*="Success"], [class*="passed"], [class*="Passed"]'
|
||||
);
|
||||
if (success) return 'success_ui';
|
||||
|
||||
return 'none';
|
||||
})();
|
||||
""".trimIndent()
|
||||
|
||||
webView.evaluateJavascript(detectSliderJS) { rawValue ->
|
||||
if (activeWebView() !== webView || !isTunnelActive) return@evaluateJavascript
|
||||
|
||||
val result = rawValue?.replace("\"", "") ?: "none"
|
||||
when (result) {
|
||||
"slider" -> {
|
||||
Log.i(TAG, "После checkbox появился слайдер — fallback на ручной WebView")
|
||||
notifyResult(Result.failure(IllegalStateException(ERROR_SLIDER_DETECTED)))
|
||||
}
|
||||
"success_ui" -> {
|
||||
postClickSliderWatcher.set(null)
|
||||
}
|
||||
else -> {
|
||||
attemptsLeft--
|
||||
if (attemptsLeft > 0) {
|
||||
mainHandler.postDelayed(this, 350L)
|
||||
} else {
|
||||
postClickSliderWatcher.set(null)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
postClickSliderWatcher.set(watcher)
|
||||
mainHandler.postDelayed(watcher, 450L)
|
||||
}
|
||||
|
||||
private fun simulateHumanTouch(webView: WebView, cssX: Float, cssY: Float) {
|
||||
if (activeWebView() !== webView) return
|
||||
|
||||
val density = webView.resources.displayMetrics.density
|
||||
val physX = cssX * density
|
||||
val physY = cssY * density
|
||||
val downTime = SystemClock.uptimeMillis()
|
||||
|
||||
val pressure = 0.5f + Random.Default.nextFloat() * 0.4f
|
||||
|
||||
val downEvent = MotionEvent.obtain(
|
||||
downTime, downTime, MotionEvent.ACTION_DOWN, physX, physY, pressure, 1f, 0, 1f, 1f, 0, 0
|
||||
)
|
||||
downEvent.source = android.view.InputDevice.SOURCE_TOUCHSCREEN
|
||||
webView.dispatchTouchEvent(downEvent)
|
||||
downEvent.recycle()
|
||||
|
||||
val holdTime = 80L + Random.Default.nextLong(0, 100)
|
||||
|
||||
mainHandler.postDelayed({
|
||||
if (activeWebView() === webView) {
|
||||
val jitterX = physX + (-1f + Random.Default.nextFloat() * 2f) * density
|
||||
val jitterY = physY + (-0.5f + Random.Default.nextFloat() * 1f) * density
|
||||
|
||||
val upEvent = MotionEvent.obtain(
|
||||
downTime, SystemClock.uptimeMillis(), MotionEvent.ACTION_UP,
|
||||
jitterX, jitterY, 0f, 1f, 0, 1f, 1f, 0, 0
|
||||
)
|
||||
upEvent.source = android.view.InputDevice.SOURCE_TOUCHSCREEN
|
||||
webView.dispatchTouchEvent(upEvent)
|
||||
upEvent.recycle()
|
||||
}
|
||||
}, holdTime)
|
||||
}
|
||||
|
||||
private class CaptchaJSBridge {
|
||||
@JavascriptInterface
|
||||
fun onSuccess(token: String) {
|
||||
Log.d(TAG, "JS: success_token получен (${token.length} символов)")
|
||||
notifyResult(Result.success(token))
|
||||
}
|
||||
|
||||
@JavascriptInterface
|
||||
fun onSliderDetected(source: String) {
|
||||
Log.i(TAG, "JS: обнаружен slider после auto-step ($source)")
|
||||
notifyResult(Result.failure(IllegalStateException(ERROR_SLIDER_DETECTED)))
|
||||
}
|
||||
|
||||
@JavascriptInterface
|
||||
fun onError(error: String) {
|
||||
Log.e(TAG, "JS: ошибка — $error")
|
||||
notifyResult(Result.failure(Exception("VK: $error")))
|
||||
}
|
||||
}
|
||||
|
||||
private fun notifyResult(result: Result<String>) {
|
||||
val deferred = pendingResult.getAndSet(null) ?: return
|
||||
if (!deferred.isCompleted) {
|
||||
deferred.complete(result)
|
||||
}
|
||||
}
|
||||
|
||||
private fun cancelPendingResult(reason: String) {
|
||||
val deferred = pendingResult.getAndSet(null) ?: return
|
||||
if (!deferred.isCompleted) {
|
||||
deferred.complete(Result.failure(CancellationException(reason)))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import com.csqtt.client.ui.utils.parseCsqttLink
|
||||
import com.csqtt.client.ui.utils.peerAddress
|
||||
import kotlinx.coroutines.flow.first
|
||||
|
||||
data class ConnectionSource(
|
||||
val peer: String,
|
||||
val password: String,
|
||||
val hashes: String,
|
||||
val hashesFromLink: Boolean,
|
||||
)
|
||||
|
||||
suspend fun resolveConnectionSource(store: SettingsStore): ConnectionSource? {
|
||||
val invalidHashes = VkHashValidationCodec.decode(store.vkHashCheckResults.first())
|
||||
fun activeHashes(raw: String): String = VkHashValidationCodec.active(
|
||||
raw.split(Regex("[,\\s\\n]+")),
|
||||
invalidHashes,
|
||||
).joinToString(",")
|
||||
|
||||
if (store.csqttLinkMode.first()) {
|
||||
val link = parseCsqttLink(store.csqttLink.first()) ?: return null
|
||||
val linkHashes = activeHashes(link.hashes.joinToString(","))
|
||||
return ConnectionSource(
|
||||
peer = link.peerAddress(),
|
||||
password = link.password,
|
||||
hashes = linkHashes.ifEmpty { activeHashes(store.vkHashes.first()) },
|
||||
hashesFromLink = linkHashes.isNotEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
val basePeer = store.peer.first()
|
||||
val passwordState = store.connectionPasswordState.first()
|
||||
val password = passwordState.value
|
||||
if (passwordState.state == StoredSecretState.Unreadable) return null
|
||||
if (basePeer.isBlank() || password.isBlank()) return null
|
||||
val serverPeerPort = if (store.manualPortsEnabled.first()) {
|
||||
store.serverPeerPort.first()
|
||||
} else {
|
||||
CsqttConstants.Network.DEFAULT_SERVER_PEER_PORT
|
||||
}
|
||||
val peer = if (basePeer.contains(':')) basePeer else "$basePeer:$serverPeerPort"
|
||||
return ConnectionSource(
|
||||
peer = peer,
|
||||
password = password,
|
||||
hashes = activeHashes(store.vkHashes.first()),
|
||||
hashesFromLink = false,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.csqtt.client
|
||||
|
||||
internal enum class ConnectionStartBlocker(val message: String) {
|
||||
Link("нужна корректная ссылка CSQTT"),
|
||||
Server("не указан корректный адрес сервера"),
|
||||
Port("указан некорректный порт сервера"),
|
||||
Password("не указан пароль подключения"),
|
||||
StoredSecret("не удалось прочитать сохранённый пароль подключения; введите его заново"),
|
||||
Hashes("нет действующих VK хешей или VK токена"),
|
||||
}
|
||||
|
||||
internal object ConnectionStartPolicy {
|
||||
fun blocker(
|
||||
linkMode: Boolean,
|
||||
linkValid: Boolean,
|
||||
peerValid: Boolean,
|
||||
peerPortValid: Boolean,
|
||||
connectionPasswordSet: Boolean,
|
||||
connectionPasswordReadable: Boolean = true,
|
||||
hashesReady: Boolean,
|
||||
): ConnectionStartBlocker? {
|
||||
if (!hashesReady) return ConnectionStartBlocker.Hashes
|
||||
if (linkMode) return if (linkValid) null else ConnectionStartBlocker.Link
|
||||
if (!peerValid) return ConnectionStartBlocker.Server
|
||||
if (!peerPortValid) return ConnectionStartBlocker.Port
|
||||
if (!connectionPasswordReadable) return ConnectionStartBlocker.StoredSecret
|
||||
if (!connectionPasswordSet) return ConnectionStartBlocker.Password
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
object CsqttConstants {
|
||||
object General {
|
||||
const val APP_NAME = "CSQTT"
|
||||
const val PACKAGE_VK = "com.vkontakte.android"
|
||||
const val PACKAGE_VK_CALLS = "com.vk.calls"
|
||||
const val CSQTT_EVENT_PREFIX = "__CSQTT_EVENT__|"
|
||||
const val ACTION_RESTART_WHEN_VK_REACHABLE = "com.csqtt.client.RESTART_WHEN_VK_REACHABLE"
|
||||
const val ACTION_VERIFY_VK_REACHABILITY = "com.csqtt.client.VERIFY_VK_REACHABILITY"
|
||||
const val ACTION_RECOVER_VK_CALL = "com.csqtt.client.RECOVER_VK_CALL"
|
||||
const val EXTRA_UNAVAILABLE_VK_HASH = "unavailable_vk_hash"
|
||||
}
|
||||
|
||||
object Profiles {
|
||||
const val MIN_INDEX = 0
|
||||
const val MAX_INDEX = 3
|
||||
}
|
||||
|
||||
object Network {
|
||||
const val LOCAL_LISTEN_HOST = "127.0.0.1"
|
||||
const val DEFAULT_LOCAL_PORT = 0
|
||||
const val DEFAULT_SERVER_PEER_PORT = 46000
|
||||
const val DEFAULT_SSH_PORT = 22
|
||||
const val DEFAULT_SERVER_WEB_PORT = 46002
|
||||
}
|
||||
|
||||
object Tunnel {
|
||||
const val BINARY_NAME = "libclient.so"
|
||||
const val PROCESS_ENV_EVENTS = "CSQTT_EVENTS"
|
||||
|
||||
const val DEFAULT_FINGERPRINT = "firefox"
|
||||
const val DEFAULT_CLIENT_IDS = "8202606,6287487"
|
||||
const val DEFAULT_OBFS_MODE = "video"
|
||||
const val DEFAULT_TURN_TRANSPORT = "udp"
|
||||
const val TURN_TRANSPORT_TCP_TLS = "tcp_tls"
|
||||
|
||||
const val WORKERS_PER_GROUP = 9
|
||||
const val GROUPS_PER_VK_HASH = 3
|
||||
const val MAX_VK_HASHES = 6
|
||||
const val DEFAULT_MAX_WORKERS = 72
|
||||
const val MAX_WORKERS = 126
|
||||
}
|
||||
|
||||
object VkAuth {
|
||||
const val MODE_CALLS = "vkcalls"
|
||||
const val MODE_CAPTCHA = "legacy"
|
||||
const val MODE_AUTO_JS = "auto_js"
|
||||
}
|
||||
|
||||
object Timeouts {
|
||||
const val CAPTCHA_AUTO_TIMEOUT_MS = 10_000L
|
||||
const val CAPTCHA_MANUAL_TIMEOUT_MS = 60_000L
|
||||
const val CAPTCHA_WV_CREATE_TIMEOUT_MS = 3_000L
|
||||
|
||||
const val WATCHDOG_INTERVAL_MS = 5_000L
|
||||
const val LOG_READER_RESET_INTERVAL_MS = 60_000L
|
||||
|
||||
const val VPN_PERMISSION_COOLDOWN_MS = 300L
|
||||
|
||||
const val DEPLOY_CMD_TIMEOUT_MS = 900_000L
|
||||
const val DEPLOY_STALL_TIMEOUT_MS = 30 * 60 * 1000L
|
||||
|
||||
const val UPDATE_RATE_LIMIT_COOLDOWN_MS = 30L * 60L * 1000L
|
||||
}
|
||||
|
||||
object Thresholds {
|
||||
const val FLOOD_CONTROL_THRESHOLD = 5
|
||||
const val IP_MISMATCH_THRESHOLD = 5
|
||||
const val CONNECTION_REFUSED_THRESHOLD = 400
|
||||
const val HASH_ERROR_THRESHOLD = 10
|
||||
}
|
||||
|
||||
object Update {
|
||||
const val DEFAULT_CHECK_INTERVAL_HOURS = 12
|
||||
const val CHECK_NEVER = -1
|
||||
const val ACTION_POSTPONED = "postponed"
|
||||
const val ACTION_UPDATE = "update"
|
||||
|
||||
const val GITHUB_RELEASES_URL =
|
||||
"https://api.github.com/repos/amurcanov/csqtt/releases?per_page=30"
|
||||
const val GITHUB_LATEST_RELEASE_URL =
|
||||
"https://api.github.com/repos/amurcanov/csqtt/releases/latest"
|
||||
const val GITHUB_LATEST_RELEASE_WEB_URL =
|
||||
"https://github.com/amurcanov/csqtt/releases/latest"
|
||||
const val GITHUB_RELEASE_TAG_URL_PREFIX =
|
||||
"https://github.com/amurcanov/csqtt/releases/tag/"
|
||||
const val GITHUB_TAGS_URL =
|
||||
"https://api.github.com/repos/amurcanov/csqtt/tags?per_page=100"
|
||||
const val GITHUB_TAG_TREE_URL_PREFIX =
|
||||
"https://github.com/amurcanov/csqtt/tree/"
|
||||
}
|
||||
|
||||
object Notifications {
|
||||
const val TUNNEL_CHANNEL_ID = "csqtt_tunnel_v4"
|
||||
const val TUNNEL_NOTIFICATION_ID = 1
|
||||
|
||||
const val CAPTCHA_CHANNEL_ID = "captcha_channel"
|
||||
const val CAPTCHA_NOTIFICATION_ID = 9001
|
||||
}
|
||||
|
||||
object Widget {
|
||||
const val ACTION_TOGGLE = "com.csqtt.client.ACTION_WIDGET_TOGGLE"
|
||||
}
|
||||
|
||||
object Captcha {
|
||||
const val ERROR_SLIDER_DETECTED = "slider_detected"
|
||||
val AUTO_VIEWPORT_WIDTHS = intArrayOf(356, 358, 360, 362, 364, 366, 368)
|
||||
val AUTO_VIEWPORT_HEIGHTS = intArrayOf(376, 378, 380, 382, 384, 386, 388)
|
||||
}
|
||||
|
||||
object SecureStore {
|
||||
const val KEY_ALIAS = "csqtt.settings.secrets"
|
||||
const val ANDROID_KEYSTORE = "AndroidKeyStore"
|
||||
const val TRANSFORMATION = "AES/GCM/NoPadding"
|
||||
const val GCM_TAG_BITS = 128
|
||||
const val VERSION_PREFIX = "v1:"
|
||||
}
|
||||
|
||||
object VkAutoHash {
|
||||
const val MODE_MANUAL = "manual"
|
||||
const val MODE_AUTO_API = "auto_api"
|
||||
const val MODE_AUTO_JS = "auto_js"
|
||||
const val MAX_OAUTH_HOPS = 15
|
||||
|
||||
const val VK_APP_ID = 7793118
|
||||
const val VK_OAUTH_SCOPE = 1073737727
|
||||
const val VK_OAUTH_REDIRECT_URI = "https://oauth.vk.ru/blank.html"
|
||||
const val VK_OAUTH_AUTH_URL =
|
||||
"https://oauth.vk.ru/authorize" +
|
||||
"?client_id=7793118" +
|
||||
"&scope=1073737727" +
|
||||
"&redirect_uri=https%3A%2F%2Foauth.vk.ru%2Fblank.html" +
|
||||
"&display=page" +
|
||||
"&response_type=token" +
|
||||
"&revoke=1" +
|
||||
"&v=5.199"
|
||||
const val VK_LOGIN_URL = "https://vk.ru/"
|
||||
const val API_METHOD_BASE_URL = "https://api.vk.ru/method/"
|
||||
const val API_VERSION = "5.199"
|
||||
|
||||
const val AUTH_TIMEOUT_MS = 300_000L
|
||||
const val AUTH_MONITOR_INTERVAL_MS = 200L
|
||||
const val AUTH_SILENT_RETRY_DELAY_MS = 1_500L
|
||||
|
||||
const val AUTO_CALL_SMALL_DELAY_MS = 80L
|
||||
const val AUTO_CALL_LARGE_DELAY_MS = 202L
|
||||
const val AUTO_CALL_MAX_ATTEMPTS = 3
|
||||
const val FINISH_CALL_STEP_MS = 150L
|
||||
const val FINISH_CALLS_TIMEOUT_MS = 8_000L
|
||||
}
|
||||
|
||||
object Vpn {
|
||||
const val DEFAULT_MTU = 1300
|
||||
const val EMPTY_WHITELIST_MESSAGE = "В режиме БС выберите хотя бы одно приложение"
|
||||
}
|
||||
|
||||
object Theme {
|
||||
const val MODE_SYSTEM = "system"
|
||||
const val MODE_DARK = "dark"
|
||||
const val MODE_LIGHT = "light"
|
||||
const val PALETTE_INDIGO = "indigo"
|
||||
const val PALETTE_ESPRESSO = "espresso"
|
||||
const val PALETTE_FOREST = "forest"
|
||||
}
|
||||
|
||||
object Links {
|
||||
const val RELEASES = "https://github.com/amurcanov/csqtt/releases"
|
||||
const val ISSUES = "https://github.com/amurcanov/csqtt/issues/new"
|
||||
const val DEVELOPER_PROFILE = "https://github.com/amurcanov"
|
||||
const val REPOSITORY = "https://github.com/amurcanov/csqtt"
|
||||
const val DONATE = ""
|
||||
}
|
||||
|
||||
object Patterns {
|
||||
val VERSION_NUMBER = kotlin.text.Regex("\\d+(?:\\.\\d+)*")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.app.Application
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
class CsqttApplication : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
DeployManager.init(this)
|
||||
|
||||
CoroutineScope(SupervisorJob() + Dispatchers.Main).launch {
|
||||
try {
|
||||
TunnelManager.running.collect {
|
||||
VpnWidgetProvider.updateAllWidgets(this@CsqttApplication)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e("CsqttApp", "Не удалось обновить виджеты: ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
val settingsStore = SettingsStore(this)
|
||||
CoroutineScope(SupervisorJob() + Dispatchers.Main).launch {
|
||||
try {
|
||||
settingsStore.loggingEnabled.collect { enabled ->
|
||||
TunnelManager.isLoggingEnabled = enabled
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e("CsqttApp", "Не удалось отслеживать флаг логирования: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.content.Context
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.CoroutineExceptionHandler
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import java.io.File
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
|
||||
object DeployManager {
|
||||
private val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
|
||||
val message = throwable.message?.take(160) ?: throwable.javaClass.simpleName
|
||||
writeError(
|
||||
"Uncaught deploy coroutine error: $message\n" +
|
||||
throwable.stackTraceToString().take(1200)
|
||||
)
|
||||
TunnelManager.addDeployErrorLog("Необработанная ошибка установки: $message")
|
||||
stopDeploy("Ошибка установки: $message")
|
||||
}
|
||||
val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO + exceptionHandler)
|
||||
|
||||
val isDeploying = MutableStateFlow(false)
|
||||
val deployProgress = MutableStateFlow(0f)
|
||||
val currentStep = MutableStateFlow("")
|
||||
val lastResult = MutableStateFlow("")
|
||||
|
||||
@Volatile
|
||||
var activeSession: java.io.Closeable? = null
|
||||
private var deployStartTime = 0L
|
||||
private var errorsFile: File? = null
|
||||
|
||||
fun init(context: Context) {
|
||||
val dir = context.getExternalFilesDir(null) ?: context.filesDir
|
||||
errorsFile = File(dir, "errors.log")
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun writeError(msg: String) {
|
||||
val file = errorsFile ?: return
|
||||
try {
|
||||
val timestamp = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())
|
||||
file.appendText("[$timestamp] $msg\n")
|
||||
|
||||
if (file.length() > 500_000) {
|
||||
val text = file.readText()
|
||||
file.writeText(text.takeLast(200_000))
|
||||
}
|
||||
} catch (_: Exception) { }
|
||||
}
|
||||
|
||||
fun startDeploy() {
|
||||
if (isDeploying.value && deployStartTime > 0 &&
|
||||
System.currentTimeMillis() - deployStartTime > 30 * 60 * 1000) {
|
||||
writeError("Автосброс: предыдущий деплой завис >30 мин")
|
||||
forceReset()
|
||||
}
|
||||
TunnelManager.clearLogs()
|
||||
isDeploying.value = true
|
||||
deployStartTime = System.currentTimeMillis()
|
||||
deployProgress.value = 0f
|
||||
currentStep.value = "Инициализация..."
|
||||
lastResult.value = ""
|
||||
}
|
||||
|
||||
fun stopDeploy(result: String = "") {
|
||||
isDeploying.value = false
|
||||
deployStartTime = 0L
|
||||
if (result.isNotBlank()) lastResult.value = result
|
||||
val session = activeSession
|
||||
activeSession = null
|
||||
try { session?.close() } catch (_: Exception) {}
|
||||
}
|
||||
|
||||
fun forceReset() {
|
||||
val session = activeSession
|
||||
activeSession = null
|
||||
try { session?.close() } catch (_: Exception) {}
|
||||
isDeploying.value = false
|
||||
deployStartTime = 0L
|
||||
deployProgress.value = 0f
|
||||
currentStep.value = ""
|
||||
}
|
||||
|
||||
fun updateProgress(progress: Float, step: String) {
|
||||
deployProgress.value = progress
|
||||
currentStep.value = step
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,753 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.VpnService
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.PowerManager
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import android.view.HapticFeedbackConstants
|
||||
import android.widget.Toast
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.core.net.toUri
|
||||
import androidx.compose.animation.core.Animatable
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.selection.selectableGroup
|
||||
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import kotlinx.coroutines.launch
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Cloud
|
||||
import androidx.compose.material.icons.filled.FilterList
|
||||
import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.PowerSettingsNew
|
||||
import androidx.compose.material.icons.filled.Terminal
|
||||
import androidx.compose.material.icons.filled.VpnKey
|
||||
import androidx.compose.material.icons.outlined.Cloud
|
||||
import androidx.compose.material.icons.outlined.FilterList
|
||||
import androidx.compose.material.icons.outlined.Info
|
||||
import androidx.compose.material.icons.outlined.Terminal
|
||||
import androidx.compose.material.icons.outlined.VpnKey
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.saveable.rememberSaveableStateHolder
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.lerp
|
||||
import androidx.compose.ui.graphics.luminance
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.unit.Density
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.core.content.ContextCompat
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import androidx.lifecycle.lifecycleScope
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import com.csqtt.client.ui.AppUpdateDialog
|
||||
import com.csqtt.client.ui.ConnectionTab
|
||||
import com.csqtt.client.ui.FloatingToolbar
|
||||
import com.csqtt.client.ui.LogsTab
|
||||
import com.csqtt.client.ui.SettingsTab
|
||||
import com.csqtt.client.CsqttConstants
|
||||
import com.csqtt.client.ui.DeployTab
|
||||
import com.csqtt.client.ui.ExceptionsTab
|
||||
import com.csqtt.client.ui.InfoTab
|
||||
import com.csqtt.client.ui.components.LocalCsqttHeaderActions
|
||||
import com.csqtt.client.ui.design.CsqttMotion
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.dialogs.VkAuthDialog
|
||||
import com.csqtt.client.ui.utils.parseCsqttLink
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlin.math.abs
|
||||
|
||||
class MainActivity : ComponentActivity() {
|
||||
private val appSettingsStore by lazy { SettingsStore(applicationContext) }
|
||||
private var renderUi by mutableStateOf(false)
|
||||
private var showVkAuthDialog by mutableStateOf(false)
|
||||
private var batteryPromptInFlight = false
|
||||
|
||||
private val batteryLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
|
||||
batteryPromptInFlight = false
|
||||
lifecycleScope.launch {
|
||||
appSettingsStore.markBatteryOptimizationPromptHandled()
|
||||
}
|
||||
}
|
||||
|
||||
private val notificationLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
|
||||
checkAndRequestBattery()
|
||||
}
|
||||
|
||||
companion object {
|
||||
@Volatile
|
||||
var activeActivities = 0
|
||||
val isForeground: Boolean
|
||||
get() = activeActivities > 0
|
||||
}
|
||||
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
activeActivities++
|
||||
renderUi = true
|
||||
ManlCaptchaWebViewManager.checkAndShowPendingCaptcha(this)
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
renderUi = false
|
||||
activeActivities = (activeActivities - 1).coerceAtLeast(0)
|
||||
super.onStop()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
val discardStaleUiState = UpdateLaunchGuard.consumeStaleSavedState(this)
|
||||
super.onCreate(if (discardStaleUiState) null else savedInstanceState)
|
||||
|
||||
importCsqttLink(intent)
|
||||
|
||||
TunnelManager.initObservers(this)
|
||||
|
||||
enableEdgeToEdge()
|
||||
|
||||
checkAndRequestNotifications()
|
||||
|
||||
setContent {
|
||||
val authContext = LocalContext.current.applicationContext
|
||||
val authScope = rememberCoroutineScope()
|
||||
val uiStateHolder = rememberSaveableStateHolder()
|
||||
if (renderUi) {
|
||||
uiStateHolder.SaveableStateProvider("main_ui") {
|
||||
val settingsStore = remember { appSettingsStore }
|
||||
val themeMode by settingsStore.themeMode.collectAsStateWithLifecycle(initialValue = CsqttConstants.Theme.MODE_SYSTEM)
|
||||
val activeFingerprint by settingsStore.selectedFingerprint.collectAsStateWithLifecycle(initialValue = CsqttConstants.Tunnel.DEFAULT_FINGERPRINT)
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
val baseDensity = LocalDensity.current
|
||||
val fixedDensity = remember(baseDensity.density) { Density(baseDensity.density, 1f) }
|
||||
|
||||
CompositionLocalProvider(LocalDensity provides fixedDensity) {
|
||||
CSQTTTheme(themeMode = themeMode) {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
color = MaterialTheme.colorScheme.background,
|
||||
) {
|
||||
MainScreen(
|
||||
settingsStore = settingsStore,
|
||||
themeMode = themeMode,
|
||||
onThemeChange = { mode ->
|
||||
scope.launch {
|
||||
settingsStore.saveThemeMode(mode)
|
||||
}
|
||||
},
|
||||
activeFingerprint = activeFingerprint,
|
||||
onFingerprintChange = { fp ->
|
||||
scope.launch { settingsStore.saveFingerprint(fp) }
|
||||
},
|
||||
onVkAuthRequested = { showVkAuthDialog = true },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (showVkAuthDialog) {
|
||||
VkAuthDialog(
|
||||
onToken = { payload ->
|
||||
showVkAuthDialog = false
|
||||
authScope.launch {
|
||||
appSettingsStore.saveVkAccessToken(payload.token, payload.userId)
|
||||
authContext.showRaisedToast("Вечный VK access token сохранен", Toast.LENGTH_SHORT)
|
||||
}
|
||||
},
|
||||
onDismiss = { showVkAuthDialog = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
importCsqttLink(intent)
|
||||
}
|
||||
|
||||
private fun importCsqttLink(intent: Intent?) {
|
||||
if (intent?.action != Intent.ACTION_VIEW) return
|
||||
val link = intent.dataString?.takeIf { parseCsqttLink(it) != null } ?: return
|
||||
lifecycleScope.launch {
|
||||
appSettingsStore.saveCsqttLink(link)
|
||||
appSettingsStore.saveCsqttLinkMode(true)
|
||||
}
|
||||
}
|
||||
|
||||
private fun checkAndRequestNotifications() {
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
||||
notificationLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
} else {
|
||||
checkAndRequestBattery()
|
||||
}
|
||||
} else {
|
||||
checkAndRequestBattery()
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("BatteryLife")
|
||||
private fun checkAndRequestBattery() {
|
||||
if (batteryPromptInFlight) return
|
||||
val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||
lifecycleScope.launch {
|
||||
val shouldRequest = shouldRequestBatteryOptimizationExemption(
|
||||
promptHandled = appSettingsStore.isBatteryOptimizationPromptHandled(),
|
||||
alreadyExempt = powerManager.isIgnoringBatteryOptimizations(packageName),
|
||||
)
|
||||
if (!shouldRequest) {
|
||||
if (powerManager.isIgnoringBatteryOptimizations(packageName)) {
|
||||
appSettingsStore.markBatteryOptimizationPromptHandled()
|
||||
}
|
||||
return@launch
|
||||
}
|
||||
|
||||
batteryPromptInFlight = true
|
||||
val launched = runCatching {
|
||||
batteryLauncher.launch(
|
||||
Intent(
|
||||
Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
|
||||
"package:$packageName".toUri(),
|
||||
),
|
||||
)
|
||||
true
|
||||
}.getOrDefault(false)
|
||||
if (!launched) {
|
||||
batteryPromptInFlight = false
|
||||
appSettingsStore.markBatteryOptimizationPromptHandled()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private data class NavItem(
|
||||
val id: Int,
|
||||
val labelRes: Int,
|
||||
val selectedIcon: ImageVector,
|
||||
val unselectedIcon: ImageVector,
|
||||
)
|
||||
|
||||
private val navItems = listOf(
|
||||
NavItem(0, R.string.nav_connection, Icons.Filled.PowerSettingsNew, Icons.Filled.PowerSettingsNew),
|
||||
NavItem(1, R.string.nav_tunnel, Icons.Filled.VpnKey, Icons.Outlined.VpnKey),
|
||||
NavItem(2, R.string.nav_deploy, Icons.Filled.Cloud, Icons.Outlined.Cloud),
|
||||
NavItem(3, R.string.nav_exceptions, Icons.Filled.FilterList, Icons.Outlined.FilterList),
|
||||
NavItem(4, R.string.nav_logs, Icons.Filled.Terminal, Icons.Outlined.Terminal),
|
||||
NavItem(5, R.string.nav_info, Icons.Filled.Info, Icons.Outlined.Info),
|
||||
)
|
||||
|
||||
internal fun navigationSwipeProgress(totalDrag: Float, containerWidth: Int): Float =
|
||||
if (containerWidth <= 0) 0f else (abs(totalDrag) / (containerWidth.toFloat() * 0.25f)).coerceIn(0f, 1f)
|
||||
|
||||
internal fun shouldCommitNavigationSwipe(progress: Float): Boolean = progress > 0.4f
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun MainScreen(
|
||||
settingsStore: SettingsStore,
|
||||
themeMode: String = CsqttConstants.Theme.MODE_SYSTEM,
|
||||
onThemeChange: (String) -> Unit = {},
|
||||
activeFingerprint: String = CsqttConstants.Tunnel.DEFAULT_FINGERPRINT,
|
||||
onFingerprintChange: (String) -> Unit = {},
|
||||
onVkAuthRequested: () -> Unit = {},
|
||||
) {
|
||||
val unreadErrors by TunnelManager.unreadErrorCount.collectAsStateWithLifecycle()
|
||||
val tunnelRunning by TunnelManager.running.collectAsStateWithLifecycle()
|
||||
val tunnelAutoPausedForWifi by TunnelManager.autoPausedForWifi.collectAsStateWithLifecycle()
|
||||
val view = LocalView.current
|
||||
val context = LocalContext.current
|
||||
val density = LocalDensity.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val activeProfile by settingsStore.activeProfile.collectAsStateWithLifecycle(initialValue = 0)
|
||||
val deploySettings by settingsStore.deploySettingsSnapshot.collectAsStateWithLifecycle(
|
||||
initialValue = DeploySettingsSnapshot()
|
||||
)
|
||||
val tunnelAuthSettings by settingsStore.tunnelAuthSnapshot.collectAsStateWithLifecycle(
|
||||
initialValue = TunnelAuthSnapshot()
|
||||
)
|
||||
val csqttLinkMode by settingsStore.csqttLinkMode.collectAsStateWithLifecycle(initialValue = false)
|
||||
val autoPauseOnWifi by settingsStore.autoPauseOnWifi.collectAsStateWithLifecycle(initialValue = false)
|
||||
val excludedApps by settingsStore.excludedApps.collectAsStateWithLifecycle(initialValue = "")
|
||||
val showSystemApps by settingsStore.showSystemApps.collectAsStateWithLifecycle(initialValue = false)
|
||||
val isWhitelist by settingsStore.isWhitelist.collectAsStateWithLifecycle(initialValue = false)
|
||||
val infoActionsExpanded by settingsStore.infoActionsExpanded.collectAsStateWithLifecycle(initialValue = false)
|
||||
val infoProjectExpanded by settingsStore.infoProjectExpanded.collectAsStateWithLifecycle(initialValue = false)
|
||||
var selectedTab by rememberSaveable { mutableIntStateOf(0) }
|
||||
var tunnelValidationRequest by rememberSaveable { mutableIntStateOf(0) }
|
||||
// Held as State objects and read only inside ProxyNavigationBar: a swipe
|
||||
// writes these on every pointer event, and delegating reads here would
|
||||
// recompose the whole MainScreen (tabs included) per event.
|
||||
val dragTargetIndex = remember { mutableIntStateOf(-1) }
|
||||
val dragProgress = remember { mutableFloatStateOf(0f) }
|
||||
var wasRunning by remember { mutableStateOf(tunnelRunning) }
|
||||
val updateCheckIntervalHours by settingsStore.updateCheckIntervalHours.collectAsStateWithLifecycle(
|
||||
initialValue = DEFAULT_UPDATE_CHECK_INTERVAL_HOURS
|
||||
)
|
||||
var pendingRelease by remember { mutableStateOf<AppReleaseInfo?>(null) }
|
||||
val currentVersion = remember { "v${BuildConfig.VERSION_NAME.removePrefix("v")}" }
|
||||
val safeBottomInset = with(density) { WindowInsets.safeDrawing.getBottom(density).toDp() }
|
||||
val navToolbarHeight = 66.dp
|
||||
val navToolbarBottomMargin = 10.dp
|
||||
val navContentGap = 5.dp
|
||||
val navOverlayReserve = safeBottomInset + navToolbarBottomMargin + navToolbarHeight + navContentGap
|
||||
val navigationDragSlop = with(density) { 6.dp.toPx() }
|
||||
|
||||
val activeNavItems = remember(csqttLinkMode) {
|
||||
if (csqttLinkMode) {
|
||||
navItems.filter { it.id != 2 }
|
||||
} else {
|
||||
navItems
|
||||
}
|
||||
}
|
||||
val tabStateHolder = rememberSaveableStateHolder()
|
||||
LaunchedEffect(csqttLinkMode) {
|
||||
if (csqttLinkMode && selectedTab == 2) {
|
||||
selectedTab = 0
|
||||
}
|
||||
}
|
||||
|
||||
LaunchedEffect(tunnelRunning, tunnelAutoPausedForWifi) {
|
||||
if (wasRunning && !tunnelRunning && !tunnelAutoPausedForWifi) {
|
||||
TunnelManager.startCooldown(CsqttConstants.Timeouts.VPN_PERMISSION_COOLDOWN_MS)
|
||||
}
|
||||
wasRunning = tunnelRunning
|
||||
}
|
||||
|
||||
LaunchedEffect(selectedTab) {
|
||||
if (selectedTab == 4) TunnelManager.clearUnreadErrors()
|
||||
}
|
||||
|
||||
LaunchedEffect(updateCheckIntervalHours) {
|
||||
if (updateCheckIntervalHours == UPDATE_CHECK_NEVER) return@LaunchedEffect
|
||||
|
||||
val intervalMillis = updateIntervalHoursToMillis(updateCheckIntervalHours)
|
||||
?: updateIntervalHoursToMillis(DEFAULT_UPDATE_CHECK_INTERVAL_HOURS)
|
||||
?: 12L * 60L * 60L * 1000L
|
||||
|
||||
suspend fun runUpdateCheck(reason: String) {
|
||||
val checkedAt = System.currentTimeMillis()
|
||||
val release = fetchLatestReleaseInfo(currentVersion)
|
||||
settingsStore.saveUpdateState(
|
||||
lastCheckAt = checkedAt,
|
||||
latestVersion = release?.versionTag ?: "",
|
||||
error = if (release == null) "Не удалось проверить" else ""
|
||||
)
|
||||
|
||||
if (release == null) {
|
||||
Log.w("CSQTT", "[WARN] Update check: no release info, local=$currentVersion reason=$reason")
|
||||
return
|
||||
}
|
||||
|
||||
val hasUpdate = isNewerVersion(currentVersion, release.versionTag)
|
||||
val postponeVer = settingsStore.updatePostponeVersion.first()
|
||||
val postponeUntil = settingsStore.updatePostponeUntil.first()
|
||||
val isPostponed = postponeVer == release.versionTag && checkedAt < postponeUntil
|
||||
Log.i(
|
||||
"CSQTT",
|
||||
"Update check: local=$currentVersion remote=${release.versionTag} newer=$hasUpdate postponed=$isPostponed reason=$reason"
|
||||
)
|
||||
|
||||
if (hasUpdate && !isPostponed) {
|
||||
settingsStore.saveUpdateDialogShown(release.versionTag, checkedAt)
|
||||
pendingRelease = release
|
||||
}
|
||||
}
|
||||
|
||||
runUpdateCheck("startup")
|
||||
|
||||
while (isActive) {
|
||||
val now = System.currentTimeMillis()
|
||||
val lastCheck = settingsStore.updateLastCheckAt.first()
|
||||
val nextCheckAt = lastCheck + intervalMillis
|
||||
val waitMs = (nextCheckAt - now).coerceAtLeast(intervalMillis)
|
||||
delay(waitMs)
|
||||
if (isActive) {
|
||||
runUpdateCheck("periodic")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
AppBackdrop(modifier = Modifier.matchParentSize())
|
||||
|
||||
CompositionLocalProvider(
|
||||
LocalCsqttHeaderActions provides {
|
||||
FloatingToolbar(
|
||||
settingsStore = settingsStore,
|
||||
csqttLinkMode = csqttLinkMode,
|
||||
activeProfile = activeProfile,
|
||||
onActiveProfileChange = { profile ->
|
||||
scope.launch { settingsStore.saveActiveProfile(profile) }
|
||||
},
|
||||
currentTheme = themeMode,
|
||||
onThemeChange = onThemeChange,
|
||||
activeFingerprint = activeFingerprint,
|
||||
onFingerprintChange = onFingerprintChange,
|
||||
autoPauseOnWifi = autoPauseOnWifi,
|
||||
onAutoPauseOnWifiChange = { enabled ->
|
||||
scope.launch { settingsStore.saveAutoPauseOnWifi(enabled) }
|
||||
},
|
||||
)
|
||||
},
|
||||
) {
|
||||
Scaffold(
|
||||
contentWindowInsets = WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Top),
|
||||
containerColor = Color.Transparent,
|
||||
) { padding ->
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(padding)
|
||||
.consumeWindowInsets(padding)
|
||||
.pointerInput(selectedTab, csqttLinkMode) {
|
||||
var totalDrag = 0f
|
||||
detectHorizontalDragGestures(
|
||||
onDragStart = {
|
||||
totalDrag = 0f
|
||||
dragTargetIndex.intValue = -1
|
||||
dragProgress.floatValue = 0f
|
||||
},
|
||||
onDragCancel = {
|
||||
dragTargetIndex.intValue = -1
|
||||
dragProgress.floatValue = 0f
|
||||
},
|
||||
onDragEnd = {
|
||||
if (dragTargetIndex.intValue in activeNavItems.indices && shouldCommitNavigationSwipe(dragProgress.floatValue)) {
|
||||
selectedTab = activeNavItems[dragTargetIndex.intValue].id
|
||||
if (selectedTab == 4) TunnelManager.clearUnreadErrors()
|
||||
}
|
||||
dragTargetIndex.intValue = -1
|
||||
dragProgress.floatValue = 0f
|
||||
}
|
||||
) { change, dragAmount ->
|
||||
change.consume()
|
||||
totalDrag += dragAmount
|
||||
if (abs(totalDrag) < navigationDragSlop) {
|
||||
dragTargetIndex.intValue = -1
|
||||
dragProgress.floatValue = 0f
|
||||
return@detectHorizontalDragGestures
|
||||
}
|
||||
|
||||
val currentActiveIndex = activeNavItems.indexOfFirst { it.id == selectedTab }
|
||||
val candidate = if (totalDrag < 0f) currentActiveIndex + 1 else currentActiveIndex - 1
|
||||
if (candidate !in activeNavItems.indices) {
|
||||
dragTargetIndex.intValue = -1
|
||||
dragProgress.floatValue = 0f
|
||||
return@detectHorizontalDragGestures
|
||||
}
|
||||
|
||||
dragTargetIndex.intValue = candidate
|
||||
dragProgress.floatValue = navigationSwipeProgress(totalDrag, size.width)
|
||||
}
|
||||
}
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(bottom = navOverlayReserve),
|
||||
) {
|
||||
key(selectedTab) {
|
||||
val tab = selectedTab
|
||||
val tabStateKey: Any = when (tab) {
|
||||
0 -> "connection:${tunnelAuthSettings.profile}"
|
||||
1 -> "tunnel:${tunnelAuthSettings.profile}"
|
||||
2 -> "deploy:${deploySettings.profile}"
|
||||
else -> tab
|
||||
}
|
||||
tabStateHolder.SaveableStateProvider(tabStateKey) {
|
||||
when (tab) {
|
||||
0 -> if (tunnelAuthSettings.isLoaded) {
|
||||
ConnectionTab(
|
||||
settingsStore = settingsStore,
|
||||
tunnelAuthSettings = tunnelAuthSettings,
|
||||
onInvalidConfiguration = {
|
||||
selectedTab = 1
|
||||
tunnelValidationRequest += 1
|
||||
},
|
||||
)
|
||||
} else {
|
||||
Spacer(modifier = Modifier.fillMaxSize())
|
||||
}
|
||||
1 -> if (tunnelAuthSettings.isLoaded) {
|
||||
SettingsTab(
|
||||
settingsStore = settingsStore,
|
||||
tunnelAuthSettings = tunnelAuthSettings,
|
||||
validationRequest = tunnelValidationRequest,
|
||||
onVkAuthRequested = onVkAuthRequested,
|
||||
)
|
||||
} else {
|
||||
Spacer(modifier = Modifier.fillMaxSize())
|
||||
}
|
||||
2 -> if (!csqttLinkMode) {
|
||||
DeployTab(settingsStore, deploySettings)
|
||||
} else {
|
||||
Spacer(modifier = Modifier.fillMaxSize())
|
||||
}
|
||||
3 -> ExceptionsTab(
|
||||
settingsStore = settingsStore,
|
||||
savedExcluded = excludedApps,
|
||||
showSystemApps = showSystemApps,
|
||||
isWhitelist = isWhitelist,
|
||||
)
|
||||
4 -> LogsTab(settingsStore)
|
||||
5 -> InfoTab(
|
||||
settingsStore = settingsStore,
|
||||
actionsExpanded = infoActionsExpanded,
|
||||
projectExpanded = infoProjectExpanded,
|
||||
onActionsToggle = {
|
||||
scope.launch {
|
||||
settingsStore.saveInfoActionsExpanded(!infoActionsExpanded)
|
||||
}
|
||||
},
|
||||
onProjectToggle = {
|
||||
scope.launch {
|
||||
settingsStore.saveInfoProjectExpanded(!infoProjectExpanded)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ProxyNavigationBar(
|
||||
navItems = activeNavItems,
|
||||
selectedTab = selectedTab,
|
||||
dragTargetIndex = dragTargetIndex,
|
||||
dragProgress = dragProgress,
|
||||
unreadErrors = unreadErrors,
|
||||
tunnelRunning = tunnelRunning,
|
||||
onTabSelected = { index ->
|
||||
if (selectedTab != index) {
|
||||
view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
|
||||
selectedTab = index
|
||||
if (index == 4) TunnelManager.clearUnreadErrors()
|
||||
}
|
||||
dragTargetIndex.intValue = -1
|
||||
dragProgress.floatValue = 0f
|
||||
},
|
||||
modifier = Modifier.align(Alignment.BottomCenter)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pendingRelease?.let { release ->
|
||||
AppUpdateDialog(
|
||||
release = release,
|
||||
onPostpone = {
|
||||
pendingRelease = null
|
||||
context.showRaisedToast("Обновление отложено на 24 часа.", Toast.LENGTH_SHORT)
|
||||
scope.launch {
|
||||
val now = System.currentTimeMillis()
|
||||
settingsStore.saveUpdatePostpone(
|
||||
version = release.versionTag,
|
||||
until = now + 24L * 60L * 60L * 1000L
|
||||
)
|
||||
settingsStore.saveUpdateDialogAction(
|
||||
version = release.versionTag,
|
||||
action = UPDATE_DIALOG_ACTION_POSTPONED,
|
||||
actedAt = now
|
||||
)
|
||||
}
|
||||
},
|
||||
onUpdate = {
|
||||
pendingRelease = null
|
||||
scope.launch {
|
||||
settingsStore.saveUpdateDialogAction(
|
||||
version = release.versionTag,
|
||||
action = UPDATE_DIALOG_ACTION_UPDATE,
|
||||
actedAt = System.currentTimeMillis()
|
||||
)
|
||||
openReleaseUrl(context, release.releaseUrl)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ProxyNavigationBar(
|
||||
navItems: List<NavItem>,
|
||||
selectedTab: Int,
|
||||
dragTargetIndex: IntState,
|
||||
dragProgress: FloatState,
|
||||
unreadErrors: Int,
|
||||
tunnelRunning: Boolean,
|
||||
onTabSelected: (Int) -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val isDark = colors.background.luminance() < 0.22f
|
||||
val selectedColor = colors.onPrimary
|
||||
val unselectedColor = colors.onSurfaceVariant.copy(alpha = 0.55f)
|
||||
val indicatorShape = RoundedCornerShape(22.dp)
|
||||
val shellColor = if (isDark) {
|
||||
lerp(colors.background, colors.surface, 0.86f)
|
||||
} else {
|
||||
lerp(colors.surface, colors.surfaceVariant, 0.48f).copy(alpha = 0.95f)
|
||||
}
|
||||
val shellBorder = if (isDark) {
|
||||
colors.outlineVariant.copy(alpha = 0.42f)
|
||||
} else {
|
||||
colors.outline.copy(alpha = 0.16f)
|
||||
}
|
||||
val indicatorColor = colors.primary
|
||||
val selectedVisualIndex = remember(selectedTab, navItems) {
|
||||
navItems.indexOfFirst { it.id == selectedTab }.coerceAtLeast(0)
|
||||
}
|
||||
val indicatorIndex = remember { Animatable(selectedVisualIndex.toFloat()) }
|
||||
val isDragging = dragTargetIndex.intValue in navItems.indices
|
||||
val requestedIndicatorIndex = if (isDragging) {
|
||||
selectedVisualIndex.toFloat() +
|
||||
(dragTargetIndex.intValue - selectedVisualIndex) * dragProgress.floatValue
|
||||
} else {
|
||||
selectedVisualIndex.toFloat()
|
||||
}
|
||||
|
||||
LaunchedEffect(isDragging, requestedIndicatorIndex) {
|
||||
if (isDragging) {
|
||||
indicatorIndex.snapTo(requestedIndicatorIndex)
|
||||
} else {
|
||||
indicatorIndex.animateTo(
|
||||
targetValue = requestedIndicatorIndex,
|
||||
animationSpec = tween(
|
||||
durationMillis = CsqttMotion.Fast,
|
||||
easing = CsqttMotion.StandardEasing,
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
val dragVisualIndex = indicatorIndex.value
|
||||
|
||||
BoxWithConstraints(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.windowInsetsPadding(WindowInsets.safeDrawing.only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom))
|
||||
.padding(horizontal = 22.dp, vertical = 10.dp)
|
||||
) {
|
||||
val trackPadding = 6.dp
|
||||
val itemWidth = (maxWidth - trackPadding * 2) / navItems.size
|
||||
val indicatorOffset = trackPadding + itemWidth * dragVisualIndex
|
||||
|
||||
Surface(
|
||||
shape = CsqttShapes.Card,
|
||||
color = shellColor,
|
||||
border = BorderStroke(1.dp, shellBorder),
|
||||
tonalElevation = if (isDark) 0.dp else 1.dp,
|
||||
shadowElevation = if (isDark) 4.dp else 6.dp,
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(66.dp)
|
||||
) {
|
||||
Surface(
|
||||
shape = indicatorShape,
|
||||
color = indicatorColor,
|
||||
modifier = Modifier
|
||||
.offset(x = indicatorOffset)
|
||||
.padding(vertical = 7.dp)
|
||||
.width(itemWidth)
|
||||
.fillMaxHeight()
|
||||
) {}
|
||||
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.padding(horizontal = trackPadding, vertical = 7.dp)
|
||||
.selectableGroup()
|
||||
) {
|
||||
navItems.forEachIndexed { index, item ->
|
||||
val emphasis = (1f - abs(index - dragVisualIndex)).coerceIn(0f, 1f)
|
||||
val iconColor = lerp(unselectedColor, selectedColor, emphasis)
|
||||
val label = stringResource(item.labelRes)
|
||||
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.fillMaxHeight()
|
||||
.clip(CsqttShapes.Control)
|
||||
.selectable(
|
||||
selected = item.id == selectedTab,
|
||||
role = Role.Tab,
|
||||
onClick = { onTabSelected(item.id) },
|
||||
),
|
||||
verticalArrangement = Arrangement.Center,
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
Box(contentAlignment = Alignment.TopEnd) {
|
||||
Icon(
|
||||
imageVector = if (emphasis > 0.55f) item.selectedIcon else item.unselectedIcon,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(22.dp),
|
||||
tint = iconColor
|
||||
)
|
||||
if (item.id == 4 && unreadErrors > 0) {
|
||||
Badge(
|
||||
containerColor = if (tunnelRunning) colors.primary else CSQTTColors.warning,
|
||||
contentColor = colors.onPrimary,
|
||||
modifier = Modifier.offset(x = 12.dp, y = (-8).dp)
|
||||
) {
|
||||
Text("$unreadErrors")
|
||||
}
|
||||
}
|
||||
}
|
||||
Spacer(Modifier.height(4.dp))
|
||||
Text(
|
||||
text = label,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontWeight = if (emphasis > 0.55f) FontWeight.SemiBold else FontWeight.Medium,
|
||||
color = iconColor,
|
||||
maxLines = 1
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun openReleaseUrl(context: Context, url: String) {
|
||||
try {
|
||||
val intent = Intent(Intent.ACTION_VIEW, url.toUri()).apply {
|
||||
addCategory(Intent.CATEGORY_BROWSABLE)
|
||||
}
|
||||
context.startActivity(intent)
|
||||
} catch (_: Exception) {
|
||||
context.showRaisedToast("Не удалось открыть ссылку", Toast.LENGTH_SHORT)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import android.view.ViewGroup
|
||||
import android.webkit.*
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
|
||||
class ManlCaptchaActivity : ComponentActivity() {
|
||||
private var captchaWebView: WebView? = null
|
||||
private val interceptorJSCode = """
|
||||
(function() {
|
||||
if (window.__csqtt_interceptor_installed) return;
|
||||
window.__csqtt_interceptor_installed = true;
|
||||
|
||||
const origFetch = window.fetch;
|
||||
window.fetch = async function() {
|
||||
const args = arguments;
|
||||
const url = args[0] || '';
|
||||
if (typeof url === 'string' && url.includes('captchaNotRobot.check')) {
|
||||
const response = await origFetch.apply(this, args);
|
||||
const clone = response.clone();
|
||||
try {
|
||||
const data = await clone.json();
|
||||
if (data.response && data.response.success_token) {
|
||||
window.CsqttCaptcha.onSuccess(data.response.success_token);
|
||||
} else if (data.error) {
|
||||
window.CsqttCaptcha.onError(JSON.stringify(data.error));
|
||||
}
|
||||
} catch(e) {}
|
||||
return response;
|
||||
}
|
||||
return origFetch.apply(this, args);
|
||||
};
|
||||
|
||||
const origXHROpen = XMLHttpRequest.prototype.open;
|
||||
const origXHRSend = XMLHttpRequest.prototype.send;
|
||||
XMLHttpRequest.prototype.open = function(method, url) {
|
||||
this._csqtt_url = url;
|
||||
return origXHROpen.apply(this, arguments);
|
||||
};
|
||||
XMLHttpRequest.prototype.send = function() {
|
||||
const xhr = this;
|
||||
if (xhr._csqtt_url && xhr._csqtt_url.includes('captchaNotRobot.check')) {
|
||||
xhr.addEventListener('load', function() {
|
||||
try {
|
||||
const data = JSON.parse(xhr.responseText);
|
||||
if (data.response && data.response.success_token) {
|
||||
window.CsqttCaptcha.onSuccess(data.response.success_token);
|
||||
} else if (data.error) {
|
||||
window.CsqttCaptcha.onError(JSON.stringify(data.error));
|
||||
}
|
||||
} catch(e) {}
|
||||
});
|
||||
}
|
||||
return origXHRSend.apply(this, arguments);
|
||||
};
|
||||
})();
|
||||
""".trimIndent()
|
||||
|
||||
private val hideElementsJSCode = """
|
||||
(function() {
|
||||
document.addEventListener('click', function(e) {
|
||||
if (e.target.closest('.vkc__ModalCardBase-module__dismiss')) {
|
||||
window.CsqttCaptcha.onCancelAndStop();
|
||||
}
|
||||
});
|
||||
|
||||
const style = document.createElement('style');
|
||||
style.innerHTML = `
|
||||
.vkc__VisuallyHiddenModalOverlay-module__host,
|
||||
.vkc__ModalOverlay-module__host,
|
||||
.vkc__KaleidoscopeScreen-module__logoBlock,
|
||||
.vkc__KaleidoscopeScreen-module__captchaId,
|
||||
.vkc__SliderCaptcha-module__descriptionLink,
|
||||
.vkc__SliderCaptcha-module__changeTypeButton {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
body, html, .vkc__ModalCard-module__host, .vkc__AppRoot-module__host, .vkui__root {
|
||||
background: transparent !important;
|
||||
box-shadow: none !important;
|
||||
}
|
||||
|
||||
.vkc__ModalCardBase-module__container {
|
||||
background: #000000 !important;
|
||||
box-shadow: none !important;
|
||||
}
|
||||
|
||||
.vkc__ModalCardBase-module__dismiss {
|
||||
color: #ef4444 !important;
|
||||
transform: scale(0.8) translateX(-12px) !important;
|
||||
}
|
||||
.vkc__ModalCardBase-module__dismiss svg {
|
||||
fill: #ef4444 !important;
|
||||
}
|
||||
|
||||
.vkc__RefreshButton-module__text,
|
||||
.vkc__SliderCaptcha-module__description {
|
||||
color: #ffffff !important;
|
||||
}
|
||||
|
||||
.vkc__SwipeButton-module__track {
|
||||
background-color: #ffffff !important;
|
||||
}
|
||||
|
||||
.vkc__SwipeButton-module__track span {
|
||||
color: #0000FF !important;
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
})();
|
||||
""".trimIndent()
|
||||
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
val discardStaleUiState = UpdateLaunchGuard.consumeStaleSavedState(this)
|
||||
super.onCreate(if (discardStaleUiState) null else savedInstanceState)
|
||||
ManlCaptchaWebViewManager.activeActivity = this
|
||||
val redirectUri = intent.getStringExtra("redirectUri") ?: return finish()
|
||||
if (!CaptchaUriPolicy.isAllowed(redirectUri)) {
|
||||
ManlCaptchaWebViewManager.notifyResult(Result.failure(IllegalArgumentException("Недопустимый адрес captcha")))
|
||||
return finish()
|
||||
}
|
||||
|
||||
setContent {
|
||||
MaterialTheme(colorScheme = if (isSystemInDarkTheme()) darkColorScheme() else lightColorScheme()) {
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
Column(
|
||||
modifier = Modifier.align(Alignment.Center),
|
||||
horizontalAlignment = Alignment.CenterHorizontally
|
||||
) {
|
||||
var isLoading by rememberSaveable { mutableStateOf(true) }
|
||||
|
||||
Box {
|
||||
Surface(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
color = Color.Transparent,
|
||||
tonalElevation = 0.dp,
|
||||
shadowElevation = 0.dp
|
||||
) {
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { ctx ->
|
||||
WebView(ctx).apply {
|
||||
captchaWebView = this
|
||||
setBackgroundColor(android.graphics.Color.TRANSPARENT)
|
||||
layoutParams = ViewGroup.LayoutParams(
|
||||
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||
ViewGroup.LayoutParams.MATCH_PARENT
|
||||
)
|
||||
settings.apply {
|
||||
javaScriptEnabled = true
|
||||
domStorageEnabled = true
|
||||
mediaPlaybackRequiresUserGesture = false
|
||||
loadWithOverviewMode = true
|
||||
useWideViewPort = true
|
||||
blockNetworkLoads = false
|
||||
cacheMode = WebSettings.LOAD_DEFAULT
|
||||
}
|
||||
|
||||
addJavascriptInterface(object {
|
||||
@JavascriptInterface
|
||||
fun onSuccess(token: String) {
|
||||
Log.d("ManlCaptchaWV", "Token received")
|
||||
ManlCaptchaWebViewManager.notifyResult(Result.success(token))
|
||||
finish()
|
||||
}
|
||||
@JavascriptInterface
|
||||
fun onError(err: String) {
|
||||
Log.e("ManlCaptchaWV", "Error: $err")
|
||||
ManlCaptchaWebViewManager.notifyResult(Result.failure(Exception("VK Captcha error: $err")))
|
||||
finish()
|
||||
}
|
||||
@JavascriptInterface
|
||||
fun onCancelAndStop() {
|
||||
Log.d("ManlCaptchaWV", "User clicked VK Close. Stopping tunnel.")
|
||||
TunnelManager.stop()
|
||||
ManlCaptchaWebViewManager.notifyResult(Result.failure(Exception("Cancelled and stopped by user")))
|
||||
finish()
|
||||
}
|
||||
}, "CsqttCaptcha")
|
||||
|
||||
webViewClient = object : WebViewClient() {
|
||||
override fun shouldOverrideUrlLoading(
|
||||
view: WebView,
|
||||
request: WebResourceRequest
|
||||
): Boolean = !CaptchaUriPolicy.isAllowed(request.url.toString())
|
||||
|
||||
override fun onPageStarted(view: WebView?, url: String?, favicon: android.graphics.Bitmap?) {
|
||||
super.onPageStarted(view, url, favicon)
|
||||
view?.evaluateJavascript(interceptorJSCode, null)
|
||||
}
|
||||
override fun onPageFinished(view: WebView?, url: String?) {
|
||||
super.onPageFinished(view, url)
|
||||
view?.evaluateJavascript(interceptorJSCode, null)
|
||||
view?.evaluateJavascript(hideElementsJSCode, null)
|
||||
isLoading = false
|
||||
}
|
||||
}
|
||||
webChromeClient = WebChromeClient()
|
||||
loadUrl(redirectUri)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.align(Alignment.Center).size(48.dp),
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
captchaWebView?.let { webView ->
|
||||
runCatching {
|
||||
webView.stopLoading()
|
||||
webView.removeJavascriptInterface("CsqttCaptcha")
|
||||
webView.webViewClient = WebViewClient()
|
||||
webView.webChromeClient = null
|
||||
webView.loadUrl("about:blank")
|
||||
webView.removeAllViews()
|
||||
webView.destroy()
|
||||
}
|
||||
}
|
||||
captchaWebView = null
|
||||
super.onDestroy()
|
||||
if (ManlCaptchaWebViewManager.activeActivity === this) {
|
||||
ManlCaptchaWebViewManager.activeActivity = null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.util.Log
|
||||
import androidx.core.app.NotificationCompat
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeout
|
||||
import java.lang.ref.WeakReference
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
object ManlCaptchaWebViewManager {
|
||||
private const val TAG = "ManlCaptchaWV"
|
||||
private const val CAPTCHA_TIMEOUT_MS = CsqttConstants.Timeouts.CAPTCHA_MANUAL_TIMEOUT_MS
|
||||
|
||||
val captchaMutex = Mutex()
|
||||
val pendingResult = AtomicReference<CompletableDeferred<Result<String>>?>(null)
|
||||
private val activeActivityRef = AtomicReference<WeakReference<ManlCaptchaActivity>?>(null)
|
||||
var activeActivity: ManlCaptchaActivity?
|
||||
get() = activeActivityRef.get()?.get()
|
||||
set(value) {
|
||||
activeActivityRef.set(value?.let(::WeakReference))
|
||||
}
|
||||
@Volatile
|
||||
var pendingIntentToStart: Intent? = null
|
||||
@Volatile
|
||||
var isCaptchaPending = false
|
||||
|
||||
fun checkAndShowPendingCaptcha(context: Context) {
|
||||
val intent = pendingIntentToStart
|
||||
if (intent != null && activeActivity == null) {
|
||||
context.startActivity(intent)
|
||||
}
|
||||
}
|
||||
|
||||
fun cancelCaptcha() {
|
||||
pendingResult.get()?.completeExceptionally(CancellationException("Cancelled by system"))
|
||||
}
|
||||
|
||||
private const val NOTIFICATION_ID = CsqttConstants.Notifications.CAPTCHA_NOTIFICATION_ID
|
||||
private const val CHANNEL_ID = CsqttConstants.Notifications.CAPTCHA_CHANNEL_ID
|
||||
|
||||
private fun showCaptchaNotification(context: Context, redirectUri: String) {
|
||||
if (MainActivity.isForeground) return
|
||||
|
||||
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
|
||||
val channel = NotificationChannel(
|
||||
CHANNEL_ID,
|
||||
"Уведомления защиты (Капча)",
|
||||
NotificationManager.IMPORTANCE_HIGH
|
||||
)
|
||||
notificationManager.createNotificationChannel(channel)
|
||||
|
||||
val openIntent = Intent(context, ManlCaptchaActivity::class.java).apply {
|
||||
putExtra("redirectUri", redirectUri)
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
|
||||
}
|
||||
|
||||
val openPendingIntent = PendingIntent.getActivity(
|
||||
context, 0, openIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
|
||||
)
|
||||
|
||||
val cancelIntent = Intent(context, CaptchaCancelReceiver::class.java)
|
||||
val cancelPendingIntent = PendingIntent.getBroadcast(
|
||||
context, 1, cancelIntent, PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
|
||||
.setSmallIcon(android.R.drawable.ic_dialog_alert)
|
||||
.setContentTitle("Требуется подтверждение капчи")
|
||||
.setContentText("ВК запросил проверку безопасности. Нажмите для решения.")
|
||||
.setPriority(NotificationCompat.PRIORITY_HIGH)
|
||||
.setContentIntent(openPendingIntent)
|
||||
.setAutoCancel(true)
|
||||
.addAction(0, "Отменить и выключить", cancelPendingIntent)
|
||||
.build()
|
||||
|
||||
notificationManager.notify(NOTIFICATION_ID, notification)
|
||||
}
|
||||
|
||||
private fun clearCaptchaNotification(context: Context) {
|
||||
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
|
||||
notificationManager.cancel(NOTIFICATION_ID)
|
||||
}
|
||||
|
||||
suspend fun solveCaptchaAsync(context: Context, redirectUri: String, sessionToken: String): String {
|
||||
if (sessionToken.isBlank()) throw IllegalArgumentException("Пустой session token captcha")
|
||||
return captchaMutex.withLock {
|
||||
isCaptchaPending = true
|
||||
val deferred = CompletableDeferred<Result<String>>()
|
||||
|
||||
pendingResult.getAndSet(deferred)?.cancel()
|
||||
|
||||
showCaptchaNotification(context, redirectUri)
|
||||
|
||||
val intent = Intent(context, ManlCaptchaActivity::class.java).apply {
|
||||
putExtra("redirectUri", redirectUri)
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
|
||||
}
|
||||
pendingIntentToStart = intent
|
||||
|
||||
if (MainActivity.isForeground) {
|
||||
context.startActivity(intent)
|
||||
}
|
||||
|
||||
try {
|
||||
withTimeout(CAPTCHA_TIMEOUT_MS) {
|
||||
deferred.await().getOrThrow()
|
||||
}
|
||||
} finally {
|
||||
isCaptchaPending = false
|
||||
pendingResult.set(null)
|
||||
pendingIntentToStart = null
|
||||
clearCaptchaNotification(context)
|
||||
withContext(NonCancellable + Dispatchers.Main.immediate) {
|
||||
try {
|
||||
activeActivity?.finish()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Error finishing activity: ${e.message}")
|
||||
}
|
||||
activeActivity = null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun notifyResult(result: Result<String>) {
|
||||
val deferred = pendingResult.getAndSet(null) ?: return
|
||||
if (!deferred.isCompleted) {
|
||||
deferred.complete(result)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
internal class NetworkPauseGate {
|
||||
private val paused = AtomicBoolean(false)
|
||||
|
||||
fun pause(): Boolean = paused.compareAndSet(false, true)
|
||||
|
||||
fun resume(): Boolean = paused.compareAndSet(true, false)
|
||||
|
||||
fun isPaused(): Boolean = paused.get()
|
||||
|
||||
fun reset() {
|
||||
paused.set(false)
|
||||
}
|
||||
|
||||
fun restore() {
|
||||
paused.set(true)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
internal enum class PhysicalNetworkTransition {
|
||||
NONE,
|
||||
AVAILABLE,
|
||||
CHANGED,
|
||||
UNAVAILABLE,
|
||||
}
|
||||
|
||||
internal enum class PhysicalNetworkPauseReason {
|
||||
AIRPLANE_MODE,
|
||||
OFFLINE,
|
||||
}
|
||||
|
||||
internal fun physicalNetworkPauseReason(airplaneModeOn: Boolean): PhysicalNetworkPauseReason =
|
||||
if (airplaneModeOn) PhysicalNetworkPauseReason.AIRPLANE_MODE else PhysicalNetworkPauseReason.OFFLINE
|
||||
|
||||
internal fun isEligiblePhysicalNetwork(
|
||||
hasInternet: Boolean,
|
||||
notVpn: Boolean,
|
||||
wifi: Boolean,
|
||||
cellular: Boolean,
|
||||
): Boolean = hasInternet && notVpn && (wifi || cellular)
|
||||
|
||||
internal class PhysicalNetworkTracker<T> {
|
||||
private val active = mutableSetOf<T>()
|
||||
|
||||
@Synchronized
|
||||
fun update(network: T, usable: Boolean): PhysicalNetworkTransition {
|
||||
val wasAvailable = active.isNotEmpty()
|
||||
val changed = if (usable) active.add(network) else active.remove(network)
|
||||
val isAvailable = active.isNotEmpty()
|
||||
return when {
|
||||
!wasAvailable && isAvailable -> PhysicalNetworkTransition.AVAILABLE
|
||||
wasAvailable && !isAvailable -> PhysicalNetworkTransition.UNAVAILABLE
|
||||
changed && wasAvailable && isAvailable -> PhysicalNetworkTransition.CHANGED
|
||||
else -> PhysicalNetworkTransition.NONE
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun clear() {
|
||||
active.clear()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun hasUsableNetwork(): Boolean = active.isNotEmpty()
|
||||
|
||||
@Synchronized
|
||||
fun isUsable(network: T): Boolean = network in active
|
||||
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.PendingIntent
|
||||
import android.content.Intent
|
||||
import android.graphics.drawable.Icon
|
||||
import android.net.VpnService
|
||||
import android.os.Build
|
||||
import android.service.quicksettings.Tile
|
||||
import android.service.quicksettings.TileService
|
||||
import android.util.Log
|
||||
import android.widget.Toast
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import com.csqtt.client.CsqttConstants
|
||||
|
||||
class QuickToggleTileService : TileService() {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||||
private var stateJob: Job? = null
|
||||
|
||||
override fun onStartListening() {
|
||||
super.onStartListening()
|
||||
|
||||
stateJob?.cancel()
|
||||
stateJob = scope.launch {
|
||||
try {
|
||||
TunnelManager.running.collect { running ->
|
||||
updateTile(running)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e("QuickToggleTile", "Error collecting running state", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onStopListening() {
|
||||
stateJob?.cancel()
|
||||
super.onStopListening()
|
||||
}
|
||||
|
||||
override fun onClick() {
|
||||
super.onClick()
|
||||
runCatching {
|
||||
if (TunnelManager.running.value) {
|
||||
val stopIntent = Intent(this, TunnelService::class.java).apply { action = "STOP" }
|
||||
startService(stopIntent)
|
||||
return
|
||||
}
|
||||
|
||||
if (VpnService.prepare(this) != null) {
|
||||
this.showRaisedToast("Откройте CSQTT и выдайте VPN-разрешение", Toast.LENGTH_LONG)
|
||||
openMainActivity()
|
||||
return
|
||||
}
|
||||
|
||||
scope.launch {
|
||||
try {
|
||||
val intent = buildStartIntent()
|
||||
if (intent == null) {
|
||||
this@QuickToggleTileService.showRaisedToast("Заполните настройки подключения в CSQTT", Toast.LENGTH_LONG)
|
||||
openMainActivity()
|
||||
return@launch
|
||||
}
|
||||
|
||||
startForegroundService(intent)
|
||||
} catch (e: Exception) {
|
||||
Log.e("QuickToggleTile", "Failed to start tunnel via QS tile", e)
|
||||
this@QuickToggleTileService.showRaisedToast("Ошибка запуска: ${e.localizedMessage}", Toast.LENGTH_SHORT)
|
||||
}
|
||||
}
|
||||
}.onFailure { e ->
|
||||
Log.e("QuickToggleTile", "Crash prevented in onClick", e)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
scope.cancel()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private suspend fun buildStartIntent(): Intent? {
|
||||
return runCatching {
|
||||
val store = SettingsStore(applicationContext)
|
||||
val source = resolveConnectionSource(store) ?: return null
|
||||
|
||||
Intent(this, TunnelService::class.java).apply {
|
||||
action = "START"
|
||||
putExtra("peer", source.peer)
|
||||
putExtra("vk_hashes", source.hashes)
|
||||
putExtra("vk_hashes_from_link", source.hashesFromLink)
|
||||
putExtra("secondary_vk_hash", store.secondaryVkHash.first())
|
||||
putExtra("workers_per_hash", store.workersPerHash.first())
|
||||
putExtra("port", 0)
|
||||
putExtra("sni", store.sni.first())
|
||||
putExtra("connection_password", source.password)
|
||||
putExtra("protocol", store.protocol.first())
|
||||
putExtra("vk_auth_mode", store.vkAuthMode.first())
|
||||
putExtra("captcha_mode", store.captchaMode.first())
|
||||
putExtra("captcha_solve_method", store.captchaSolveMethod.first())
|
||||
putExtra("fingerprint", store.selectedFingerprint.first())
|
||||
putExtra("client_ids", store.activeClientIds.first())
|
||||
putExtra("obfs_mode", store.obfsMode.first())
|
||||
putExtra("turn_transport", store.turnTransport.first())
|
||||
}
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
private fun updateTile(running: Boolean) {
|
||||
runCatching {
|
||||
qsTile?.apply {
|
||||
label = CsqttConstants.General.APP_NAME
|
||||
icon = Icon.createWithResource(this@QuickToggleTileService, R.drawable.ic_c_logo)
|
||||
state = if (running) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
|
||||
if (Build.VERSION.SDK_INT >= 29) {
|
||||
subtitle = if (running) "Подключено" else "Отключено"
|
||||
}
|
||||
updateTile()
|
||||
}
|
||||
}.onFailure { e ->
|
||||
Log.e("QuickToggleTile", "Failed to update QS tile state", e)
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("StartActivityAndCollapseDeprecated")
|
||||
private fun openMainActivity() {
|
||||
runCatching {
|
||||
val intent = Intent(this, MainActivity::class.java).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= 34) {
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
this,
|
||||
100,
|
||||
intent,
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
|
||||
)
|
||||
startActivityAndCollapse(pendingIntent)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
startActivityAndCollapse(intent)
|
||||
}
|
||||
}.onFailure { e ->
|
||||
Log.e("QuickToggleTile", "Failed to open MainActivity", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.content.Context
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import android.util.Base64
|
||||
import java.security.KeyStore
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
class SecureStringStore(context: Context) {
|
||||
private val appContext = context.applicationContext
|
||||
|
||||
companion object {
|
||||
private const val KEY_ALIAS = CsqttConstants.SecureStore.KEY_ALIAS
|
||||
private const val ANDROID_KEYSTORE = CsqttConstants.SecureStore.ANDROID_KEYSTORE
|
||||
private const val TRANSFORMATION = CsqttConstants.SecureStore.TRANSFORMATION
|
||||
private const val GCM_TAG_BITS = CsqttConstants.SecureStore.GCM_TAG_BITS
|
||||
private const val VERSION_PREFIX = CsqttConstants.SecureStore.VERSION_PREFIX
|
||||
}
|
||||
|
||||
private val keyStore: KeyStore by lazy {
|
||||
KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
|
||||
}
|
||||
|
||||
// Keystore crypto costs an IPC round-trip; DataStore re-emits the whole
|
||||
// preferences object on every edit, so unchanged ciphertexts are memoized.
|
||||
private val decryptCache = java.util.concurrent.ConcurrentHashMap<String, String>()
|
||||
|
||||
fun encrypt(value: String): String {
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||
cipher.init(Cipher.ENCRYPT_MODE, getOrCreateKey())
|
||||
val encrypted = cipher.doFinal(value.toByteArray(Charsets.UTF_8))
|
||||
return VERSION_PREFIX +
|
||||
Base64.encodeToString(cipher.iv, Base64.NO_WRAP) +
|
||||
":" +
|
||||
Base64.encodeToString(encrypted, Base64.NO_WRAP)
|
||||
}
|
||||
|
||||
fun decrypt(value: String?): String? {
|
||||
if (value.isNullOrBlank() || !value.startsWith(VERSION_PREFIX)) return null
|
||||
decryptCache[value]?.let { return it }
|
||||
val payload = value.removePrefix(VERSION_PREFIX)
|
||||
val parts = payload.split(":", limit = 2)
|
||||
if (parts.size != 2) return null
|
||||
|
||||
val result = runCatching {
|
||||
val iv = Base64.decode(parts[0], Base64.NO_WRAP)
|
||||
val encrypted = Base64.decode(parts[1], Base64.NO_WRAP)
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||
cipher.init(Cipher.DECRYPT_MODE, getOrCreateKey(), GCMParameterSpec(GCM_TAG_BITS, iv))
|
||||
cipher.doFinal(encrypted).toString(Charsets.UTF_8)
|
||||
}.getOrNull()
|
||||
if (result != null) {
|
||||
if (decryptCache.size > 64) decryptCache.clear()
|
||||
decryptCache[value] = result
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private fun getOrCreateKey(): SecretKey {
|
||||
synchronized(appContext) {
|
||||
val existing = keyStore.getKey(KEY_ALIAS, null) as? SecretKey
|
||||
if (existing != null) return existing
|
||||
|
||||
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)
|
||||
val spec = KeyGenParameterSpec.Builder(
|
||||
KEY_ALIAS,
|
||||
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
|
||||
)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setKeySize(256)
|
||||
.setRandomizedEncryptionRequired(true)
|
||||
.build()
|
||||
generator.init(spec)
|
||||
return generator.generateKey()
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,29 @@
|
||||
package com.csqtt.client
|
||||
|
||||
internal enum class StoredSecretState {
|
||||
Readable,
|
||||
Missing,
|
||||
Unreadable,
|
||||
}
|
||||
|
||||
internal data class StoredSecret(
|
||||
val value: String,
|
||||
val state: StoredSecretState,
|
||||
)
|
||||
|
||||
internal fun resolveStoredSecret(
|
||||
encryptedValue: String?,
|
||||
legacyValue: String?,
|
||||
decrypt: (String?) -> String?,
|
||||
): StoredSecret {
|
||||
if (encryptedValue.isNullOrBlank()) {
|
||||
return legacyValue?.takeIf { it.isNotBlank() }
|
||||
?.let { StoredSecret(it, StoredSecretState.Readable) }
|
||||
?: StoredSecret("", StoredSecretState.Missing)
|
||||
}
|
||||
val decrypted = decrypt(encryptedValue)
|
||||
if (decrypted != null) return StoredSecret(decrypted, StoredSecretState.Readable)
|
||||
return legacyValue?.takeIf { it.isNotBlank() }
|
||||
?.let { StoredSecret(it, StoredSecretState.Readable) }
|
||||
?: StoredSecret("", StoredSecretState.Unreadable)
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.os.Build
|
||||
import android.app.Activity
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Typography
|
||||
import androidx.compose.material3.darkColorScheme
|
||||
import androidx.compose.material3.lightColorScheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.CompositionLocalProvider
|
||||
import androidx.compose.runtime.SideEffect
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.lerp
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
import androidx.compose.ui.text.TextStyle
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.Density
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.core.view.WindowCompat
|
||||
import com.csqtt.client.CsqttConstants
|
||||
import com.csqtt.client.ui.design.CsqttDarkExtendedColors
|
||||
import com.csqtt.client.ui.design.CsqttLightExtendedColors
|
||||
import com.csqtt.client.ui.design.CsqttMaterialShapes
|
||||
import com.csqtt.client.ui.design.LocalCsqttExtendedColors
|
||||
|
||||
val CSQTTTypography = Typography(
|
||||
displayLarge = TextStyle(fontFamily = FontFamily.Default, fontWeight = FontWeight.Bold, fontSize = 57.sp, lineHeight = 64.sp),
|
||||
displayMedium = TextStyle(fontFamily = FontFamily.Default, fontWeight = FontWeight.Bold, fontSize = 45.sp, lineHeight = 52.sp),
|
||||
displaySmall = TextStyle(fontFamily = FontFamily.Default, fontWeight = FontWeight.Bold, fontSize = 36.sp, lineHeight = 44.sp),
|
||||
headlineLarge = TextStyle(fontFamily = FontFamily.Default, fontWeight = FontWeight.SemiBold, fontSize = 32.sp, lineHeight = 40.sp),
|
||||
headlineMedium = TextStyle(fontFamily = FontFamily.Default, fontWeight = FontWeight.SemiBold, fontSize = 28.sp, lineHeight = 36.sp),
|
||||
headlineSmall = TextStyle(fontFamily = FontFamily.Default, fontWeight = FontWeight.SemiBold, fontSize = 24.sp, lineHeight = 32.sp),
|
||||
titleLarge = TextStyle(fontFamily = FontFamily.Default, fontWeight = FontWeight.SemiBold, fontSize = 22.sp, lineHeight = 28.sp),
|
||||
titleMedium = TextStyle(fontFamily = FontFamily.Default, fontWeight = FontWeight.SemiBold, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.15.sp),
|
||||
titleSmall = TextStyle(fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = 0.1.sp),
|
||||
bodyLarge = TextStyle(fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp),
|
||||
bodyMedium = TextStyle(fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = 0.25.sp),
|
||||
bodySmall = TextStyle(fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp, lineHeight = 16.sp, letterSpacing = 0.4.sp),
|
||||
labelLarge = TextStyle(fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 14.sp, lineHeight = 20.sp, letterSpacing = 0.1.sp),
|
||||
labelMedium = TextStyle(fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 12.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp),
|
||||
labelSmall = TextStyle(fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp),
|
||||
)
|
||||
|
||||
private val LightColorScheme = lightColorScheme(
|
||||
primary = Color(0xFF6D4C41),
|
||||
onPrimary = Color(0xFFFFFFFF),
|
||||
primaryContainer = Color(0xFFD7CCC8),
|
||||
onPrimaryContainer = Color(0xFF3E2723),
|
||||
secondary = Color(0xFF8D6E63),
|
||||
onSecondary = Color(0xFFFFFFFF),
|
||||
secondaryContainer = Color(0xFFEFEBE9),
|
||||
onSecondaryContainer = Color(0xFF4E342E),
|
||||
tertiary = Color(0xFF795548),
|
||||
onTertiary = Color(0xFFFFFFFF),
|
||||
tertiaryContainer = Color(0xFFBCAAA4),
|
||||
onTertiaryContainer = Color(0xFF3E2723),
|
||||
background = Color(0xFFF2F0EC),
|
||||
onBackground = Color(0xFF1C1B1A),
|
||||
surface = Color(0xFFFAF8F4),
|
||||
onSurface = Color(0xFF1C1B1A),
|
||||
surfaceVariant = Color(0xFFEFEBE9),
|
||||
onSurfaceVariant = Color(0xFF5D4037),
|
||||
outline = Color(0xFFBCAAA4),
|
||||
outlineVariant = Color(0xFFD7CCC8),
|
||||
error = Color(0xFFBA1A1A),
|
||||
onError = Color(0xFFFFFFFF),
|
||||
errorContainer = Color(0xFFFFDAD6),
|
||||
onErrorContainer = Color(0xFF410002),
|
||||
inverseSurface = Color(0xFF322F2D),
|
||||
inverseOnSurface = Color(0xFFF5F0EB),
|
||||
inversePrimary = Color(0xFFD7CCC8),
|
||||
surfaceTint = Color(0xFF6D4C41),
|
||||
)
|
||||
|
||||
private val DarkColorScheme = darkColorScheme(
|
||||
primary = Color(0xFFD7CCC8),
|
||||
onPrimary = Color(0xFF3E2723),
|
||||
primaryContainer = Color(0xFF5D4037),
|
||||
onPrimaryContainer = Color(0xFFEFEBE9),
|
||||
secondary = Color(0xFFBCAAA4),
|
||||
onSecondary = Color(0xFF3E2723),
|
||||
secondaryContainer = Color(0xFF4E342E),
|
||||
onSecondaryContainer = Color(0xFFEFEBE9),
|
||||
tertiary = Color(0xFFA1887F),
|
||||
onTertiary = Color(0xFF3E2723),
|
||||
tertiaryContainer = Color(0xFF5D4037),
|
||||
onTertiaryContainer = Color(0xFFEFEBE9),
|
||||
background = Color(0xFF1A1614),
|
||||
onBackground = Color(0xFFEDE0D4),
|
||||
surface = Color(0xFF211D1B),
|
||||
onSurface = Color(0xFFEDE0D4),
|
||||
surfaceVariant = Color(0xFF2C2624),
|
||||
onSurfaceVariant = Color(0xFFD7CCC8),
|
||||
outline = Color(0xFF8D6E63),
|
||||
outlineVariant = Color(0xFF4E342E),
|
||||
error = Color(0xFFFFB4AB),
|
||||
onError = Color(0xFF690005),
|
||||
errorContainer = Color(0xFF93000A),
|
||||
onErrorContainer = Color(0xFFFFDAD6),
|
||||
inverseSurface = Color(0xFFEDE0D4),
|
||||
inverseOnSurface = Color(0xFF322F2D),
|
||||
inversePrimary = Color(0xFF6D4C41),
|
||||
surfaceTint = Color(0xFFD7CCC8),
|
||||
)
|
||||
|
||||
private val IndigoLightColorScheme = lightColorScheme(
|
||||
primary = Color(0xFF5B588D),
|
||||
onPrimary = Color(0xFFFFFFFF),
|
||||
primaryContainer = Color(0xFFE2DFFF),
|
||||
onPrimaryContainer = Color(0xFF1A1744),
|
||||
secondary = Color(0xFF5B588D),
|
||||
onSecondary = Color(0xFFFFFFFF),
|
||||
secondaryContainer = Color(0xFFE2DFFF),
|
||||
onSecondaryContainer = Color(0xFF1A1744),
|
||||
background = Color(0xFFFBF8FF),
|
||||
onBackground = Color(0xFF1B1B1F),
|
||||
surface = Color(0xFFF6F3FA),
|
||||
onSurface = Color(0xFF1B1B1F),
|
||||
surfaceVariant = Color(0xFFE4E1EC),
|
||||
onSurfaceVariant = Color(0xFF47464F),
|
||||
outline = Color(0xFF787680),
|
||||
outlineVariant = Color(0xFFC8C5D0),
|
||||
)
|
||||
|
||||
private val IndigoDarkColorScheme = darkColorScheme(
|
||||
primary = Color(0xFFC4C0FF),
|
||||
onPrimary = Color(0xFF2D2A5B),
|
||||
primaryContainer = Color(0xFF434073),
|
||||
onPrimaryContainer = Color(0xFFE2DFFF),
|
||||
secondary = Color(0xFFC4C0FF),
|
||||
onSecondary = Color(0xFF2D2A5B),
|
||||
secondaryContainer = Color(0xFF434073),
|
||||
onSecondaryContainer = Color(0xFFE2DFFF),
|
||||
background = Color(0xFF131316),
|
||||
onBackground = Color(0xFFE4E1E6),
|
||||
surface = Color(0xFF1B1B1F),
|
||||
onSurface = Color(0xFFC8C5D0),
|
||||
surfaceVariant = Color(0xFF47464F),
|
||||
onSurfaceVariant = Color(0xFFC8C5D0),
|
||||
outline = Color(0xFF918F9A),
|
||||
outlineVariant = Color(0xFF47464F),
|
||||
)
|
||||
|
||||
private val ForestLightColorScheme = lightColorScheme(
|
||||
primary = Color(0xFF5F5D68),
|
||||
onPrimary = Color(0xFFFFFFFF),
|
||||
primaryContainer = Color(0xFFE5E0F0),
|
||||
onPrimaryContainer = Color(0xFF1C1A23),
|
||||
secondary = Color(0xFF5F5D68),
|
||||
onSecondary = Color(0xFFFFFFFF),
|
||||
secondaryContainer = Color(0xFFE5E0F0),
|
||||
onSecondaryContainer = Color(0xFF1C1A23),
|
||||
background = Color(0xFFFCF8FF),
|
||||
onBackground = Color(0xFF1D1B20),
|
||||
surface = Color(0xFFF7F2FA),
|
||||
onSurface = Color(0xFF1D1B20),
|
||||
surfaceVariant = Color(0xFFE6E0E9),
|
||||
onSurfaceVariant = Color(0xFF48454E),
|
||||
outline = Color(0xFF79747E),
|
||||
outlineVariant = Color(0xFFCAC4D0),
|
||||
)
|
||||
|
||||
private val ForestDarkColorScheme = darkColorScheme(
|
||||
primary = Color(0xFFC8C4D3),
|
||||
onPrimary = Color(0xFF312F38),
|
||||
primaryContainer = Color(0xFF474550),
|
||||
onPrimaryContainer = Color(0xFFE5E0F0),
|
||||
secondary = Color(0xFFC8C4D3),
|
||||
onSecondary = Color(0xFF312F38),
|
||||
secondaryContainer = Color(0xFF474550),
|
||||
onSecondaryContainer = Color(0xFFE5E0F0),
|
||||
background = Color(0xFF141318),
|
||||
onBackground = Color(0xFFE6E1E5),
|
||||
surface = Color(0xFF1D1B20),
|
||||
onSurface = Color(0xFFCAC4D0),
|
||||
surfaceVariant = Color(0xFF48454E),
|
||||
onSurfaceVariant = Color(0xFFCAC4D0),
|
||||
outline = Color(0xFF938F99),
|
||||
outlineVariant = Color(0xFF48454E),
|
||||
)
|
||||
|
||||
private val BrandLightColorScheme = lightColorScheme(
|
||||
primary = Color(0xFF1A73E8),
|
||||
onPrimary = Color(0xFFFFFFFF),
|
||||
primaryContainer = Color(0xFFE8F0FE),
|
||||
onPrimaryContainer = Color(0xFF111215),
|
||||
secondary = Color(0xFF1A73E8),
|
||||
onSecondary = Color(0xFFFFFFFF),
|
||||
secondaryContainer = Color(0xFFE8F0FE),
|
||||
onSecondaryContainer = Color(0xFF111215),
|
||||
tertiary = Color(0xFFD27D00),
|
||||
onTertiary = Color(0xFFFFFFFF),
|
||||
tertiaryContainer = Color(0xFFFFE4B7),
|
||||
onTertiaryContainer = Color(0xFF241400),
|
||||
background = Color(0xFFFDFDFE),
|
||||
onBackground = Color(0xFF111215),
|
||||
surface = Color(0xFFFFFFFF),
|
||||
onSurface = Color(0xFF111215),
|
||||
surfaceVariant = Color(0xFFF2F2F4),
|
||||
onSurfaceVariant = Color(0xFF5F6067),
|
||||
outline = Color(0xFF898B92),
|
||||
outlineVariant = Color(0xFFD7D8DD),
|
||||
surfaceTint = Color.Transparent,
|
||||
)
|
||||
|
||||
private val BrandDarkColorScheme = darkColorScheme(
|
||||
primary = Color(0xFF1565D8),
|
||||
onPrimary = Color(0xFFFFFFFF),
|
||||
primaryContainer = Color(0xFF173B72),
|
||||
onPrimaryContainer = Color(0xFFFFFFFF),
|
||||
secondary = Color(0xFF1565D8),
|
||||
onSecondary = Color(0xFFFFFFFF),
|
||||
secondaryContainer = Color(0xFF173B72),
|
||||
onSecondaryContainer = Color(0xFFFFFFFF),
|
||||
tertiary = Color(0xFFFFB74D),
|
||||
onTertiary = Color(0xFF271500),
|
||||
tertiaryContainer = Color(0xFF5A3900),
|
||||
onTertiaryContainer = Color(0xFFFFE5BD),
|
||||
background = Color(0xFF09090A),
|
||||
onBackground = Color(0xFFFAFAFA),
|
||||
surface = Color(0xFF121214),
|
||||
onSurface = Color(0xFFFAFAFA),
|
||||
surfaceVariant = Color(0xFF202024),
|
||||
onSurfaceVariant = Color(0xFFC9C9CF),
|
||||
outline = Color(0xFF8C8C94),
|
||||
outlineVariant = Color(0xFF35353A),
|
||||
surfaceTint = Color.Transparent,
|
||||
)
|
||||
|
||||
private fun getAppColorScheme(isDark: Boolean): androidx.compose.material3.ColorScheme =
|
||||
if (isDark) BrandDarkColorScheme else BrandLightColorScheme
|
||||
|
||||
object CSQTTColors {
|
||||
val connected = Color(0xFF4CAF50)
|
||||
val brand = Color(0xFF00E5C0)
|
||||
val brandDeep = Color(0xFF00B8A3)
|
||||
|
||||
val warning = Color(0xFFFFA726)
|
||||
|
||||
val terminalBg = Color(0xFF1A1A2E)
|
||||
val terminalBgDark = Color(0xFF0D0D1A)
|
||||
val terminalText = Color(0xFFE0E0E0)
|
||||
val terminalGreen = Color(0xFF4CAF50)
|
||||
val terminalBlue = Color(0xFF42A5F5)
|
||||
val terminalCyan = Color(0xFF00BCD4)
|
||||
val terminalRed = Color(0xFFEF5350)
|
||||
val terminalCounter = Color(0xFF1E88E5)
|
||||
|
||||
val donate = Color(0xFF8B3FFD)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun CSQTTTheme(
|
||||
themeMode: String = "system",
|
||||
content: @Composable () -> Unit
|
||||
) {
|
||||
val darkTheme = when (themeMode) {
|
||||
CsqttConstants.Theme.MODE_DARK -> true
|
||||
CsqttConstants.Theme.MODE_LIGHT -> false
|
||||
else -> isSystemInDarkTheme()
|
||||
}
|
||||
|
||||
val colorScheme = remember(darkTheme) {
|
||||
getAppColorScheme(darkTheme)
|
||||
}
|
||||
|
||||
val view = LocalView.current
|
||||
if (!view.isInEditMode) {
|
||||
@Suppress("DEPRECATION")
|
||||
SideEffect {
|
||||
val window = (view.context as Activity).window
|
||||
val navigationBarColor = if (darkTheme) {
|
||||
Color.Transparent
|
||||
} else {
|
||||
lerp(colorScheme.background, colorScheme.surface, 0.55f)
|
||||
}
|
||||
window.statusBarColor = Color.Transparent.toArgb()
|
||||
window.navigationBarColor = navigationBarColor.toArgb()
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
window.isNavigationBarContrastEnforced = false
|
||||
window.isStatusBarContrastEnforced = false
|
||||
}
|
||||
WindowCompat.getInsetsController(window, view).apply {
|
||||
isAppearanceLightStatusBars = !darkTheme
|
||||
isAppearanceLightNavigationBars = !darkTheme
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val currentDensity = LocalDensity.current
|
||||
val fixedDensity = remember(currentDensity.density) {
|
||||
Density(density = currentDensity.density, fontScale = 1f)
|
||||
}
|
||||
|
||||
CompositionLocalProvider(
|
||||
LocalCsqttExtendedColors provides if (darkTheme) CsqttDarkExtendedColors else CsqttLightExtendedColors,
|
||||
LocalDensity provides fixedDensity,
|
||||
) {
|
||||
MaterialTheme(
|
||||
colorScheme = colorScheme,
|
||||
typography = CSQTTTypography,
|
||||
shapes = CsqttMaterialShapes,
|
||||
content = content,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.content.Context
|
||||
import android.view.Gravity
|
||||
import android.widget.Toast
|
||||
|
||||
fun Context.showRaisedToast(message: String, length: Int = Toast.LENGTH_SHORT) {
|
||||
val toast = Toast.makeText(this.applicationContext, message, length)
|
||||
val yOffset = (180 * resources.displayMetrics.density).toInt()
|
||||
toast.setGravity(Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL, 0, yOffset)
|
||||
toast.show()
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
internal object TunRecoveryPolicy {
|
||||
fun shouldReuse(
|
||||
hasInterface: Boolean,
|
||||
descriptorValid: Boolean,
|
||||
serviceDestroyed: Boolean,
|
||||
forceRebuild: Boolean,
|
||||
activeClientIp: String?,
|
||||
activeDns: String?,
|
||||
requestedClientIp: String,
|
||||
requestedDns: String,
|
||||
): Boolean =
|
||||
hasInterface &&
|
||||
descriptorValid &&
|
||||
!serviceDestroyed &&
|
||||
!forceRebuild &&
|
||||
activeClientIp == requestedClientIp &&
|
||||
activeDns == requestedDns
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.VpnService
|
||||
import android.os.ParcelFileDescriptor
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
|
||||
class TunVpnService : VpnService() {
|
||||
private val serviceJob = SupervisorJob()
|
||||
private val serviceScope = CoroutineScope(serviceJob + Dispatchers.IO)
|
||||
private val vpnMutex = Mutex()
|
||||
private val interfaceLock = Any()
|
||||
private var vpnInterface: ParcelFileDescriptor? = null
|
||||
private var sendJob: Job? = null
|
||||
private var activeClientIp: String? = null
|
||||
private var activeDns: String? = null
|
||||
private var recoveryAttempts = 0
|
||||
private var stopRequested = false
|
||||
@Volatile
|
||||
private var serviceDestroyed = false
|
||||
|
||||
companion object {
|
||||
private const val TAG = "TunVPN"
|
||||
|
||||
@Volatile
|
||||
var instance: TunVpnService? = null
|
||||
private set
|
||||
|
||||
@Volatile
|
||||
var tunFd: Int = -1
|
||||
private set
|
||||
}
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
instance = this
|
||||
Log.d(TAG, "TunVpnService created")
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (intent == null) {
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
when (intent.action) {
|
||||
"START" -> {
|
||||
stopRequested = false
|
||||
val clientIp = intent.getStringExtra("client_ip") ?: "10.66.66.2"
|
||||
val dns = intent.getStringExtra("dns") ?: "1.1.1.1"
|
||||
val forceRebuild = intent.getBooleanExtra("force_rebuild", false)
|
||||
if (!forceRebuild) recoveryAttempts = 0
|
||||
serviceScope.launch {
|
||||
startVpn(clientIp, dns, forceRebuild)
|
||||
}
|
||||
}
|
||||
"STOP" -> {
|
||||
stopRequested = true
|
||||
serviceScope.launch {
|
||||
vpnMutex.withLock { stopVpn() }
|
||||
stopSelf()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
private suspend fun startVpn(clientIp: String, dns: String, forceRebuild: Boolean) {
|
||||
vpnMutex.withLock {
|
||||
try {
|
||||
val existing = synchronized(interfaceLock) {
|
||||
vpnInterface?.takeIf {
|
||||
TunRecoveryPolicy.shouldReuse(
|
||||
hasInterface = true,
|
||||
descriptorValid = it.fileDescriptor.valid(),
|
||||
serviceDestroyed = serviceDestroyed,
|
||||
forceRebuild = forceRebuild,
|
||||
activeClientIp = activeClientIp,
|
||||
activeDns = activeDns,
|
||||
requestedClientIp = clientIp,
|
||||
requestedDns = dns,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (existing != null) {
|
||||
sendTunFd(existing)
|
||||
return
|
||||
}
|
||||
|
||||
if (VpnService.prepare(this) != null) {
|
||||
failVpn("разрешение Android VPN не выдано")
|
||||
return
|
||||
}
|
||||
|
||||
val settingsStore = SettingsStore(applicationContext)
|
||||
val savedExcluded = settingsStore.excludedApps.first()
|
||||
val isWhitelist = settingsStore.isWhitelist.first()
|
||||
val userSelected = savedExcluded.split(",").filter { it.isNotEmpty() }.toSet()
|
||||
val transportPackages = setOf(
|
||||
applicationContext.packageName,
|
||||
CsqttConstants.General.PACKAGE_VK,
|
||||
CsqttConstants.General.PACKAGE_VK_CALLS
|
||||
)
|
||||
|
||||
val builder = Builder()
|
||||
.setSession("CSQTT")
|
||||
.setMtu(CsqttConstants.Vpn.DEFAULT_MTU)
|
||||
.addAddress(clientIp, 32)
|
||||
.addRoute("0.0.0.0", 0)
|
||||
|
||||
var validDnsServers = 0
|
||||
dns.split(",").map { it.trim() }.filter { it.isNotEmpty() }.forEach { dnsServer ->
|
||||
try {
|
||||
builder.addDnsServer(dnsServer)
|
||||
validDnsServers++
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Invalid DNS server: $dnsServer")
|
||||
}
|
||||
}
|
||||
if (validDnsServers == 0) {
|
||||
failVpn("сервер передал некорректный DNS: $dns")
|
||||
return
|
||||
}
|
||||
|
||||
if (isWhitelist) {
|
||||
val installedIncluded = userSelected
|
||||
.filter { pkg ->
|
||||
pkg !in transportPackages && isPackageInstalled(pkg)
|
||||
}
|
||||
.toSet()
|
||||
if (installedIncluded.isEmpty()) {
|
||||
failVpn("Whitelist пуст: выберите хотя бы одно установленное приложение")
|
||||
return
|
||||
} else {
|
||||
var includedCount = 0
|
||||
installedIncluded.forEach { pkg ->
|
||||
try {
|
||||
builder.addAllowedApplication(pkg)
|
||||
includedCount++
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "Unable to include $pkg in VPN", error)
|
||||
}
|
||||
}
|
||||
if (includedCount == 0) {
|
||||
failVpn("Android не разрешил добавить выбранные приложения в whitelist")
|
||||
return
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
builder.addDisallowedApplication(applicationContext.packageName)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Unable to exclude CSQTT UID from its VPN", e)
|
||||
failVpn("Android не разрешил исключить CSQTT из собственного VPN")
|
||||
return
|
||||
}
|
||||
val excluded = transportPackages.toMutableSet()
|
||||
excluded.addAll(userSelected)
|
||||
excluded
|
||||
.filter { it != applicationContext.packageName && isPackageInstalled(it) }
|
||||
.forEach { pkg ->
|
||||
try { builder.addDisallowedApplication(pkg) } catch (_: Exception) {}
|
||||
}
|
||||
}
|
||||
|
||||
val pfd = builder.establish()
|
||||
if (pfd == null) {
|
||||
Log.e(TAG, "VPN permission not granted")
|
||||
failVpn("Android не создал VPN-интерфейс; проверьте разрешение VPN и Always-on VPN")
|
||||
return
|
||||
}
|
||||
|
||||
var previousInterface: ParcelFileDescriptor? = null
|
||||
val accepted = synchronized(interfaceLock) {
|
||||
if (serviceDestroyed) {
|
||||
false
|
||||
} else {
|
||||
previousInterface = vpnInterface
|
||||
vpnInterface = pfd
|
||||
tunFd = pfd.fd
|
||||
activeClientIp = clientIp
|
||||
activeDns = dns
|
||||
true
|
||||
}
|
||||
}
|
||||
if (!accepted) {
|
||||
pfd.close()
|
||||
return
|
||||
}
|
||||
sendJob?.cancel()
|
||||
if (previousInterface !== pfd) {
|
||||
runCatching { previousInterface?.close() }
|
||||
}
|
||||
Log.d(TAG, "VPN interface established: IP=$clientIp DNS=$dns fd=$tunFd")
|
||||
|
||||
sendTunFd(pfd, dns)
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to start VPN: ${e.message}", e)
|
||||
failVpn(e.message ?: e.javaClass.simpleName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun sendTunFd(pfd: ParcelFileDescriptor, dns: String? = null) {
|
||||
sendJob?.cancel()
|
||||
sendJob = serviceScope.launch {
|
||||
var success = false
|
||||
for (i in 1..20) {
|
||||
val socket = android.net.LocalSocket()
|
||||
try {
|
||||
socket.connect(android.net.LocalSocketAddress("csqtt_tun_uds", android.net.LocalSocketAddress.Namespace.ABSTRACT))
|
||||
socket.setFileDescriptorsForSend(arrayOf(pfd.fileDescriptor))
|
||||
socket.outputStream.write(1)
|
||||
socket.outputStream.flush()
|
||||
socket.soTimeout = 3_000
|
||||
if (socket.inputStream.read() != 1) {
|
||||
throw IllegalStateException("Rust-клиент не подтвердил TUN-интерфейс")
|
||||
}
|
||||
Log.d(TAG, "Sent TUN fd to Rust client successfully")
|
||||
success = true
|
||||
recoveryAttempts = 0
|
||||
TunnelManager.onVpnInterfaceReady(dns)
|
||||
break
|
||||
} catch (e: Exception) {
|
||||
Log.d(TAG, "Failed to connect to Rust client UDS, retrying: ${e.message}")
|
||||
delay(500)
|
||||
} finally {
|
||||
runCatching { socket.close() }
|
||||
}
|
||||
}
|
||||
if (!success) {
|
||||
Log.e(TAG, "Could not send TUN fd to Rust client after 20 retries")
|
||||
if (!dns.isNullOrBlank()) {
|
||||
TunnelManager.updateLog(
|
||||
"vpn_dns_delivery_error_$dns",
|
||||
"[SERVER] DNS не применён: ${dnsProfileName(dns)} — Rust-клиент не принял TUN-интерфейс",
|
||||
99,
|
||||
true,
|
||||
)
|
||||
}
|
||||
recoverAfterFdFailure(pfd)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun recoverAfterFdFailure(failedInterface: ParcelFileDescriptor) {
|
||||
val recoveryConfig = synchronized(interfaceLock) {
|
||||
if (vpnInterface !== failedInterface || serviceDestroyed) {
|
||||
null
|
||||
} else {
|
||||
runCatching { vpnInterface?.close() }
|
||||
vpnInterface = null
|
||||
tunFd = -1
|
||||
val config = activeClientIp?.let { ip -> activeDns?.let { dns -> ip to dns } }
|
||||
activeClientIp = null
|
||||
activeDns = null
|
||||
config
|
||||
}
|
||||
} ?: return
|
||||
TunnelManager.onVpnInterfaceStopped()
|
||||
if (recoveryAttempts >= 2) {
|
||||
failVpn("не удалось передать TUN fd Rust-клиенту после повторных попыток")
|
||||
return
|
||||
}
|
||||
recoveryAttempts++
|
||||
delay(500L * recoveryAttempts)
|
||||
startVpn(recoveryConfig.first, recoveryConfig.second, forceRebuild = true)
|
||||
}
|
||||
|
||||
private fun failVpn(message: String) {
|
||||
stopRequested = true
|
||||
stopVpn()
|
||||
TunnelManager.onVpnTerminalFailure(message)
|
||||
}
|
||||
|
||||
private fun stopVpn() {
|
||||
sendJob?.cancel()
|
||||
sendJob = null
|
||||
synchronized(interfaceLock) {
|
||||
try {
|
||||
vpnInterface?.close()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "Error closing VPN interface: ${e.message}")
|
||||
}
|
||||
vpnInterface = null
|
||||
tunFd = -1
|
||||
activeClientIp = null
|
||||
activeDns = null
|
||||
}
|
||||
TunnelManager.onVpnInterfaceStopped()
|
||||
Log.d(TAG, "VPN interface closed")
|
||||
}
|
||||
|
||||
private fun isPackageInstalled(packageName: String): Boolean {
|
||||
return try {
|
||||
packageManager.getPackageInfo(packageName, 0)
|
||||
true
|
||||
} catch (_: Exception) {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
val unexpected = !stopRequested && TunnelManager.running.value
|
||||
serviceDestroyed = true
|
||||
serviceJob.cancel()
|
||||
stopVpn()
|
||||
instance = null
|
||||
if (unexpected) {
|
||||
TunnelManager.onVpnTerminalFailure("VPN-сервис был остановлен Android")
|
||||
}
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onRevoke() {
|
||||
stopRequested = true
|
||||
serviceDestroyed = true
|
||||
serviceJob.cancel()
|
||||
stopVpn()
|
||||
instance = null
|
||||
TunnelManager.onVpnTerminalFailure("разрешение Android VPN было отозвано")
|
||||
stopSelf()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import org.json.JSONObject
|
||||
|
||||
object TunnelEventParser {
|
||||
private const val PREFIX = CsqttConstants.General.CSQTT_EVENT_PREFIX
|
||||
|
||||
sealed class Event {
|
||||
data class Started(val message: String = "") : Event()
|
||||
data class Stopped(val message: String = "") : Event()
|
||||
data class Process(val pid: Int) : Event()
|
||||
data class Ready(val worker: Int, val message: String = "") : Event()
|
||||
data class ActiveZero(val message: String = "") : Event()
|
||||
data class CallUnavailable(val hash: String, val code: Int) : Event()
|
||||
data object NetworkSuspect : Event()
|
||||
data object ServerRestart : Event()
|
||||
data class Config(val config: String) : Event()
|
||||
data class Stats(
|
||||
val active: Int,
|
||||
val bytesUp: Long,
|
||||
val bytesDown: Long
|
||||
) : Event()
|
||||
|
||||
data class Error(
|
||||
val code: String,
|
||||
val message: String,
|
||||
val fatal: Boolean
|
||||
) : Event()
|
||||
|
||||
data class CaptchaRequest(
|
||||
val mode: String,
|
||||
val redirectUri: String,
|
||||
val sessionToken: String
|
||||
) : Event()
|
||||
|
||||
data class CaptchaDone(
|
||||
val success: Boolean,
|
||||
val error: String?
|
||||
) : Event()
|
||||
|
||||
data class Progress(val kind: String) : Event()
|
||||
}
|
||||
|
||||
fun parse(line: String): Event? {
|
||||
if (!line.startsWith(PREFIX)) return null
|
||||
val withoutPrefix = line.substring(PREFIX.length)
|
||||
val typeEnd = withoutPrefix.indexOf('|')
|
||||
if (typeEnd == -1) return null
|
||||
|
||||
val type = withoutPrefix.substring(0, typeEnd)
|
||||
val payload = try {
|
||||
JSONObject(withoutPrefix.substring(typeEnd + 1))
|
||||
} catch (_: Exception) {
|
||||
return null
|
||||
}
|
||||
|
||||
return when (type) {
|
||||
"STARTED" -> Event.Started(payload.optString("message", ""))
|
||||
"STOPPED" -> Event.Stopped(payload.optString("message", ""))
|
||||
"PROCESS" -> payload.optInt("pid", 0)
|
||||
.takeIf { it > 0 }
|
||||
?.let { Event.Process(it) }
|
||||
"READY" -> Event.Ready(
|
||||
worker = payload.optInt("worker", 0).coerceIn(0, CsqttConstants.Tunnel.MAX_WORKERS),
|
||||
message = payload.optString("message", ""),
|
||||
)
|
||||
"ACTIVE_ZERO" -> Event.ActiveZero(payload.optString("message", ""))
|
||||
"CALL_UNAVAILABLE" -> {
|
||||
val hash = payload.optString("hash", "").trim()
|
||||
if (hash.isBlank()) null else Event.CallUnavailable(
|
||||
hash = hash,
|
||||
code = payload.optInt("code", 951).coerceAtLeast(0),
|
||||
)
|
||||
}
|
||||
"NETWORK_SUSPECT" -> Event.NetworkSuspect
|
||||
"SERVER_RESTART" -> if (payload.optString("source", "") == "panel") {
|
||||
Event.ServerRestart
|
||||
} else {
|
||||
null
|
||||
}
|
||||
"CONFIG" -> Event.Config(payload.optString("config", ""))
|
||||
"STATS" -> Event.Stats(
|
||||
active = payload.optInt("active", 0).coerceAtLeast(0),
|
||||
bytesUp = payload.optLong("bytes_up", 0L).coerceAtLeast(0L),
|
||||
bytesDown = payload.optLong("bytes_down", 0L).coerceAtLeast(0L)
|
||||
)
|
||||
"ERROR" -> Event.Error(
|
||||
code = payload.optString("code", ""),
|
||||
message = payload.optString("message", ""),
|
||||
fatal = payload.optBoolean("fatal", false)
|
||||
)
|
||||
"CAPTCHA_REQUEST" -> Event.CaptchaRequest(
|
||||
mode = payload.optString("mode", "auto"),
|
||||
redirectUri = payload.optString("redirect_uri", ""),
|
||||
sessionToken = payload.optString("session_token", "")
|
||||
)
|
||||
"CAPTCHA_DONE" -> Event.CaptchaDone(
|
||||
success = payload.optBoolean("success", false),
|
||||
error = payload.optString("error", "").takeIf { it.isNotBlank() }
|
||||
)
|
||||
"PROGRESS" -> {
|
||||
val kind = payload.strictString("kind") ?: return null
|
||||
if (kind != "credentials") return null
|
||||
Event.Progress(kind)
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
private fun JSONObject.strictString(key: String): String? {
|
||||
if (!has(key) || isNull(key)) return null
|
||||
return get(key) as? String
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
internal fun nextTunnelGenerationId(nowSeconds: Long, current: Long): Long = maxOf(
|
||||
nowSeconds,
|
||||
if (current == Long.MAX_VALUE) Long.MAX_VALUE else current + 1,
|
||||
)
|
||||
|
||||
internal fun reserveTunnelGenerationId(
|
||||
nowSeconds: Long,
|
||||
proposed: Long,
|
||||
persisted: Long,
|
||||
): Long = nextTunnelGenerationId(maxOf(nowSeconds, proposed), persisted)
|
||||
|
||||
internal data class TunnelLifecycleTicket(
|
||||
val epoch: Long,
|
||||
val sequence: Long,
|
||||
)
|
||||
|
||||
internal class TunnelLifecycleState {
|
||||
private var epoch = 0L
|
||||
private var sequence = 0L
|
||||
private var desiredRunning = false
|
||||
private var active: TunnelLifecycleTicket? = null
|
||||
|
||||
@Synchronized
|
||||
fun requestStart(): Long {
|
||||
epoch = next(epoch)
|
||||
desiredRunning = true
|
||||
active = null
|
||||
return epoch
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun requestRestart(): Long? {
|
||||
if (!desiredRunning) return null
|
||||
epoch = next(epoch)
|
||||
active = null
|
||||
return epoch
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun requestStop(): Long {
|
||||
epoch = next(epoch)
|
||||
desiredRunning = false
|
||||
active = null
|
||||
return epoch
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun reserveProcess(expectedEpoch: Long, processIsNull: Boolean): TunnelLifecycleTicket? {
|
||||
if (!processIsNull || !canStart(expectedEpoch) || active != null) return null
|
||||
sequence = next(sequence)
|
||||
return TunnelLifecycleTicket(expectedEpoch, sequence).also { active = it }
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun releaseReservation(ticket: TunnelLifecycleTicket) {
|
||||
if (active == ticket) active = null
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun processEnded(ticket: TunnelLifecycleTicket): Boolean {
|
||||
if (active != ticket) return false
|
||||
active = null
|
||||
return desiredRunning && epoch == ticket.epoch
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun accepts(ticket: TunnelLifecycleTicket): Boolean =
|
||||
desiredRunning && epoch == ticket.epoch && active == ticket
|
||||
|
||||
@Synchronized
|
||||
fun canStart(expectedEpoch: Long): Boolean =
|
||||
desiredRunning && epoch == expectedEpoch
|
||||
|
||||
@Synchronized
|
||||
fun isDesiredRunning(): Boolean = desiredRunning
|
||||
|
||||
private fun next(value: Long): Long = if (value == Long.MAX_VALUE) 1L else value + 1L
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
object TunnelLogPolicy {
|
||||
fun isAllowedWhenInactiveLogging(key: String, isError: Boolean, level: LogLevel?): Boolean {
|
||||
return isError || level == LogLevel.ERR || key == "ready" || key == "stats"
|
||||
}
|
||||
|
||||
fun isInternalRecovery(line: String): Boolean {
|
||||
if (line.contains("FATAL_", ignoreCase = true)) return false
|
||||
return line.contains("GETCONF", ignoreCase = true) ||
|
||||
line.contains("[СЕТЬ][RETRY]", ignoreCase = true) ||
|
||||
line.contains("PEER_LIVENESS_TIMEOUT", ignoreCase = true)
|
||||
}
|
||||
|
||||
fun isTurnStreamFailure(line: String): Boolean {
|
||||
return line.contains("[TURN][DOWN]", ignoreCase = true) ||
|
||||
(
|
||||
line.contains("[ВОРКЕР", ignoreCase = true) &&
|
||||
line.contains("[TURN]", ignoreCase = true) &&
|
||||
(
|
||||
line.contains("ошибка", ignoreCase = true) ||
|
||||
line.contains("failed", ignoreCase = true) ||
|
||||
line.contains("exhausted", ignoreCase = true)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,25 @@
|
||||
package com.csqtt.client
|
||||
|
||||
internal fun resolveTunnelPasswordStorage(
|
||||
persistentValue: String?,
|
||||
legacyValue: String?,
|
||||
encryptedValue: String?,
|
||||
decrypt: (String?) -> String?,
|
||||
): StoredSecret {
|
||||
if (!persistentValue.isNullOrBlank()) {
|
||||
return StoredSecret(persistentValue, StoredSecretState.Readable)
|
||||
}
|
||||
return resolveStoredSecret(encryptedValue, legacyValue, decrypt)
|
||||
}
|
||||
|
||||
internal fun shouldResetUnreadableTunnelPassword(
|
||||
persistentValue: String?,
|
||||
legacyValue: String?,
|
||||
encryptedValue: String?,
|
||||
decrypt: (String?) -> String?,
|
||||
): Boolean = resolveTunnelPasswordStorage(
|
||||
persistentValue,
|
||||
legacyValue,
|
||||
encryptedValue,
|
||||
decrypt,
|
||||
).state == StoredSecretState.Unreadable
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,14 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
internal object TunnelServicePolicy {
|
||||
const val STARTUP_GRACE_MS = 60_000L
|
||||
|
||||
fun shouldStop(
|
||||
wasEverRunning: Boolean,
|
||||
running: Boolean,
|
||||
elapsedMs: Long,
|
||||
): Boolean = !running && (wasEverRunning || elapsedMs >= STARTUP_GRACE_MS)
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.csqtt.client
|
||||
|
||||
import java.security.SecureRandom
|
||||
|
||||
internal fun newTunnelSessionId(fillBytes: (ByteArray) -> Unit = SecureRandom()::nextBytes): String {
|
||||
val bytes = ByteArray(16)
|
||||
fillBytes(bytes)
|
||||
return bytes.joinToString(separator = "") { byte -> "%02x".format(byte.toInt() and 0xff) }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
internal enum class TunnelStartupStage {
|
||||
WAITING_FOR_CREDENTIALS,
|
||||
WAITING_FOR_TURN_OR_PEER,
|
||||
READY,
|
||||
}
|
||||
|
||||
internal class TunnelStartupProgress {
|
||||
private val credentials = AtomicInteger()
|
||||
private val ready = AtomicBoolean(false)
|
||||
|
||||
fun credentialReceived(): Int = credentials.incrementAndGet()
|
||||
|
||||
fun streamReady() {
|
||||
ready.set(true)
|
||||
}
|
||||
|
||||
fun stage(): TunnelStartupStage = when {
|
||||
ready.get() -> TunnelStartupStage.READY
|
||||
credentials.get() > 0 -> TunnelStartupStage.WAITING_FOR_TURN_OR_PEER
|
||||
else -> TunnelStartupStage.WAITING_FOR_CREDENTIALS
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
internal fun shouldConfirmTcpTransport(
|
||||
currentTransport: String,
|
||||
requestedTransport: String,
|
||||
warningAcknowledged: Boolean,
|
||||
): Boolean =
|
||||
!warningAcknowledged &&
|
||||
currentTransport != CsqttConstants.Tunnel.TURN_TRANSPORT_TCP_TLS &&
|
||||
requestedTransport == CsqttConstants.Tunnel.TURN_TRANSPORT_TCP_TLS
|
||||
@@ -0,0 +1,25 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.res.Configuration
|
||||
|
||||
internal object TvDevicePolicy {
|
||||
fun isTelevision(context: Context): Boolean = isTelevision(
|
||||
uiMode = context.resources.configuration.uiMode,
|
||||
hasTelevisionFeature = context.packageManager.hasSystemFeature("android.hardware.type.television"),
|
||||
hasLeanbackFeature = context.packageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK),
|
||||
)
|
||||
|
||||
internal fun isTelevision(
|
||||
uiMode: Int,
|
||||
hasTelevisionFeature: Boolean,
|
||||
hasLeanbackFeature: Boolean,
|
||||
): Boolean =
|
||||
(uiMode and Configuration.UI_MODE_TYPE_MASK) == Configuration.UI_MODE_TYPE_TELEVISION ||
|
||||
hasTelevisionFeature ||
|
||||
hasLeanbackFeature
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageInfo
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import androidx.core.content.edit
|
||||
|
||||
/** Drops only stale Activity/Compose state on the first launch after package replace. */
|
||||
internal object UpdateLaunchGuard {
|
||||
private const val TAG = "CSQTT"
|
||||
private const val PREFS = "update_launch_guard"
|
||||
private const val LAST_TOKEN = "last_package_token"
|
||||
|
||||
fun consumeStaleSavedState(context: Context): Boolean = runCatching {
|
||||
val packageInfo = context.currentPackageInfo()
|
||||
val token = "${packageInfo.versionCodeCompat()}:${packageInfo.lastUpdateTime}"
|
||||
val preferences = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
val previous = preferences.getString(LAST_TOKEN, null)
|
||||
val discard = shouldDiscardStaleSavedState(
|
||||
previousToken = previous,
|
||||
currentToken = token,
|
||||
packageWasUpdated = packageInfo.lastUpdateTime > packageInfo.firstInstallTime,
|
||||
)
|
||||
if (previous != token) {
|
||||
preferences.edit(commit = true) { putString(LAST_TOKEN, token) }
|
||||
}
|
||||
discard
|
||||
}.getOrElse { error ->
|
||||
Log.w(TAG, "Unable to inspect package-update launch state", error)
|
||||
false
|
||||
}
|
||||
|
||||
private fun Context.currentPackageInfo(): PackageInfo =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
packageManager.getPackageInfo(packageName, android.content.pm.PackageManager.PackageInfoFlags.of(0))
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
packageManager.getPackageInfo(packageName, 0)
|
||||
}
|
||||
|
||||
private fun PackageInfo.versionCodeCompat(): Long =
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||
longVersionCode
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
versionCode.toLong()
|
||||
}
|
||||
}
|
||||
|
||||
internal fun shouldDiscardStaleSavedState(
|
||||
previousToken: String?,
|
||||
currentToken: String,
|
||||
packageWasUpdated: Boolean,
|
||||
): Boolean =
|
||||
previousToken != currentToken && (previousToken != null || packageWasUpdated)
|
||||
@@ -0,0 +1,99 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import org.json.JSONObject
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
|
||||
internal sealed class VkApiResult<out T> {
|
||||
data class Ok<T>(val value: T) : VkApiResult<T>()
|
||||
data class ApiError(val code: Int, val message: String) : VkApiResult<Nothing>()
|
||||
data class Failed(val reason: String) : VkApiResult<Nothing>()
|
||||
}
|
||||
|
||||
internal object VkApi {
|
||||
private const val CONNECT_TIMEOUT_MS = 8_000
|
||||
private const val READ_TIMEOUT_MS = 8_000
|
||||
|
||||
private val TOKEN_INVALID_CODES = setOf(4, 5, 27, 28)
|
||||
|
||||
fun isTokenInvalid(error: VkApiResult.ApiError): Boolean = error.code in TOKEN_INVALID_CODES
|
||||
|
||||
data class StartedCall(
|
||||
val callId: String,
|
||||
val hash: String,
|
||||
val joinLink: String,
|
||||
)
|
||||
|
||||
fun startCall(token: String): VkApiResult<StartedCall> = request("calls.start", token, emptyMap()) { json ->
|
||||
val response = json.optJSONObject("response")
|
||||
val callId = response?.optString("call_id").orEmpty()
|
||||
val joinLink = response?.optString("join_link").orEmpty()
|
||||
val hash = response?.optString("ok_join_link")
|
||||
?.takeIf { it.isNotBlank() }
|
||||
?: joinLink.substringAfterLast('/').trimEnd('/')
|
||||
check(callId.isNotBlank() && hash.isNotBlank()) { "пустой call_id/hash в ответе calls.start" }
|
||||
StartedCall(callId = callId, hash = hash, joinLink = joinLink)
|
||||
}
|
||||
|
||||
fun forceFinishCall(token: String, callId: String): VkApiResult<Int> = request(
|
||||
"calls.forceFinish",
|
||||
token,
|
||||
mapOf("call_id" to callId),
|
||||
) { json ->
|
||||
json.optInt("response", 0)
|
||||
}
|
||||
|
||||
private fun <T> request(
|
||||
method: String,
|
||||
token: String,
|
||||
params: Map<String, String>,
|
||||
parse: (JSONObject) -> T,
|
||||
): VkApiResult<T> {
|
||||
var conn: HttpURLConnection? = null
|
||||
return try {
|
||||
conn = URL(CsqttConstants.VkAutoHash.API_METHOD_BASE_URL + method).openConnection() as HttpURLConnection
|
||||
conn.requestMethod = "POST"
|
||||
conn.connectTimeout = CONNECT_TIMEOUT_MS
|
||||
conn.readTimeout = READ_TIMEOUT_MS
|
||||
conn.doOutput = true
|
||||
conn.useCaches = false
|
||||
conn.setRequestProperty("Authorization", "Bearer $token")
|
||||
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
val body = buildString {
|
||||
params.forEach { (key, value) ->
|
||||
append(URLEncoder.encode(key, "UTF-8"))
|
||||
append('=')
|
||||
append(URLEncoder.encode(value, "UTF-8"))
|
||||
append('&')
|
||||
}
|
||||
append("v=")
|
||||
append(CsqttConstants.VkAutoHash.API_VERSION)
|
||||
}
|
||||
conn.outputStream.use { it.write(body.toByteArray(Charsets.UTF_8)) }
|
||||
|
||||
val code = conn.responseCode
|
||||
val stream = if (code >= 400) conn.errorStream else conn.inputStream
|
||||
val text = stream?.bufferedReader()?.readText().orEmpty()
|
||||
val json = JSONObject(text)
|
||||
|
||||
val errorObj = json.optJSONObject("error")
|
||||
if (errorObj != null) {
|
||||
VkApiResult.ApiError(
|
||||
code = errorObj.optInt("error_code", 1),
|
||||
message = errorObj.optString("error_msg"),
|
||||
)
|
||||
} else {
|
||||
VkApiResult.Ok(parse(json))
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
VkApiResult.Failed(e.message ?: e.javaClass.simpleName)
|
||||
} finally {
|
||||
runCatching { conn?.disconnect() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,576 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.KeyEvent
|
||||
import android.view.ViewGroup
|
||||
import android.webkit.CookieManager
|
||||
import android.webkit.WebResourceError
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebResourceResponse
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.core.net.toUri
|
||||
import kotlinx.coroutines.launch
|
||||
import org.json.JSONObject
|
||||
import java.io.ByteArrayInputStream
|
||||
import java.net.URLDecoder
|
||||
|
||||
internal data class VkAuthPayload(
|
||||
val token: String,
|
||||
val userId: String,
|
||||
val expiresIn: Long,
|
||||
)
|
||||
|
||||
internal enum class VkAuthPhase { LOGIN, TOKEN }
|
||||
|
||||
internal object VkAuthWebViewManager {
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
fun acquire(context: Context): WebView = createWebView(context)
|
||||
|
||||
fun clearVkSessionCookies() {
|
||||
mainHandler.post {
|
||||
runCatching {
|
||||
val manager = CookieManager.getInstance()
|
||||
manager.removeAllCookies(null)
|
||||
manager.flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun release(view: WebView) {
|
||||
mainHandler.post {
|
||||
runCatching { CookieManager.getInstance().flush() }
|
||||
runCatching {
|
||||
(view.parent as? ViewGroup)?.removeView(view)
|
||||
view.stopLoading()
|
||||
view.webViewClient = WebViewClient()
|
||||
view.loadUrl("about:blank")
|
||||
view.clearHistory()
|
||||
view.destroy()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
private fun createWebView(context: Context): WebView {
|
||||
val view = WebView(context)
|
||||
view.settings.apply {
|
||||
javaScriptEnabled = true
|
||||
domStorageEnabled = true
|
||||
javaScriptCanOpenWindowsAutomatically = true
|
||||
useWideViewPort = true
|
||||
loadWithOverviewMode = true
|
||||
setSupportZoom(false)
|
||||
builtInZoomControls = false
|
||||
}
|
||||
if (TvDevicePolicy.isTelevision(context)) {
|
||||
configureTelevisionInput(view)
|
||||
}
|
||||
runCatching {
|
||||
CookieManager.getInstance().setAcceptCookie(true)
|
||||
CookieManager.getInstance().setAcceptThirdPartyCookies(view, true)
|
||||
}
|
||||
return view
|
||||
}
|
||||
|
||||
private fun configureTelevisionInput(view: WebView) {
|
||||
view.isFocusable = true
|
||||
view.isFocusableInTouchMode = false
|
||||
view.setOnFocusChangeListener { _, hasFocus ->
|
||||
if (hasFocus) {
|
||||
view.post { view.evaluateJavascript(TV_FOCUS_FIRST_ELEMENT_JS, null) }
|
||||
}
|
||||
}
|
||||
view.setOnKeyListener { _, keyCode, event ->
|
||||
if (event.action != KeyEvent.ACTION_DOWN) return@setOnKeyListener false
|
||||
val command = when (keyCode) {
|
||||
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_LEFT -> "previous"
|
||||
KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_RIGHT -> "next"
|
||||
KeyEvent.KEYCODE_DPAD_CENTER,
|
||||
KeyEvent.KEYCODE_ENTER,
|
||||
KeyEvent.KEYCODE_NUMPAD_ENTER -> "activate"
|
||||
else -> null
|
||||
} ?: return@setOnKeyListener false
|
||||
|
||||
view.evaluateJavascript("window.__csqttTvInput && window.__csqttTvInput('$command');", null)
|
||||
true
|
||||
}
|
||||
view.post { view.requestFocus() }
|
||||
}
|
||||
|
||||
private const val TV_FOCUS_FIRST_ELEMENT_JS = """
|
||||
(function() {
|
||||
if (window.__csqttTvInput) {
|
||||
window.__csqttTvInput('ensure-focus');
|
||||
return;
|
||||
}
|
||||
var selector = 'a[href],button,input:not([type=hidden]),select,textarea,[role=button],[tabindex]:not([tabindex="-1"])';
|
||||
function elements() {
|
||||
return Array.prototype.filter.call(document.querySelectorAll(selector), function(node) {
|
||||
var style = window.getComputedStyle(node);
|
||||
return !node.disabled && style.display !== 'none' && style.visibility !== 'hidden' && node.getClientRects().length > 0;
|
||||
});
|
||||
}
|
||||
function focus(node) {
|
||||
if (!node) return false;
|
||||
node.focus({preventScroll: true});
|
||||
node.scrollIntoView({block: 'center', inline: 'nearest'});
|
||||
return true;
|
||||
}
|
||||
window.__csqttTvInput = function(command) {
|
||||
var items = elements();
|
||||
var active = document.activeElement;
|
||||
var index = items.indexOf(active);
|
||||
if (command === 'ensure-focus') {
|
||||
return index >= 0 || focus(items[0]);
|
||||
}
|
||||
if (command === 'next' || command === 'previous') {
|
||||
if (!items.length) return false;
|
||||
var direction = command === 'next' ? 1 : -1;
|
||||
var next = index < 0 ? (direction > 0 ? 0 : items.length - 1) : (index + direction + items.length) % items.length;
|
||||
return focus(items[next]);
|
||||
}
|
||||
if (command === 'activate') {
|
||||
if (index < 0 && !focus(items[0])) return false;
|
||||
active = document.activeElement;
|
||||
if (!active) return false;
|
||||
if (active.matches('button,a[href],input[type=button],input[type=submit],input[type=checkbox],input[type=radio],[role=button]')) {
|
||||
active.click();
|
||||
return true;
|
||||
}
|
||||
active.click();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
window.__csqttTvInput('ensure-focus');
|
||||
})();
|
||||
"""
|
||||
}
|
||||
|
||||
@SuppressLint("SetJavaScriptEnabled")
|
||||
internal class VkAuthSession(
|
||||
private val onUiReady: () -> Unit,
|
||||
private val onToken: (VkAuthPayload) -> Unit,
|
||||
private val onError: (String) -> Unit,
|
||||
private val onPhaseChange: (VkAuthPhase) -> Unit = {},
|
||||
) {
|
||||
private val mainHandler = Handler(Looper.getMainLooper())
|
||||
|
||||
private var webView: WebView? = null
|
||||
private var finished = false
|
||||
private var silentRetried = false
|
||||
private var nonPermanentRetried = false
|
||||
private var lastUrl: String? = null
|
||||
private var startedAt = 0L
|
||||
private var pausedAt = 0L
|
||||
private var uiReadyReported = false
|
||||
private var phase = VkAuthPhase.LOGIN
|
||||
private var paused = false
|
||||
private var pendingAuthorizationRetry = false
|
||||
|
||||
fun attach(view: WebView) {
|
||||
webView = view
|
||||
startedAt = System.currentTimeMillis()
|
||||
view.webViewClient = object : WebViewClient() {
|
||||
override fun onPageFinished(v: WebView, url: String) {
|
||||
installTelevisionNavigation(v)
|
||||
if (!uiReadyReported) {
|
||||
uiReadyReported = true
|
||||
onUiReady()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onPageCommitVisible(v: WebView, url: String) {
|
||||
installTelevisionNavigation(v)
|
||||
if (!uiReadyReported) {
|
||||
uiReadyReported = true
|
||||
onUiReady()
|
||||
}
|
||||
}
|
||||
|
||||
override fun shouldOverrideUrlLoading(v: WebView, request: WebResourceRequest): Boolean {
|
||||
val path = request.url.path ?: ""
|
||||
if (phase == VkAuthPhase.LOGIN && (path.startsWith("/feed") || isVkLoggedIn())) {
|
||||
switchToTokenPhase(v)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
override fun shouldInterceptRequest(v: WebView, request: WebResourceRequest): WebResourceResponse? {
|
||||
val uri = request.url
|
||||
if (uri.lastPathSegment == "blank.html") {
|
||||
return WebResourceResponse(
|
||||
"text/html",
|
||||
"utf-8",
|
||||
200,
|
||||
"OK",
|
||||
mapOf("Cache-Control" to "no-store"),
|
||||
ByteArrayInputStream(TOKEN_WAITING_HTML.toByteArray(Charsets.UTF_8)),
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
override fun onReceivedError(v: WebView, request: WebResourceRequest, error: WebResourceError) {
|
||||
if (!request.isForMainFrame) return
|
||||
if (finished) return
|
||||
finishWithError("Не удалось открыть страницу авторизации VK — проверьте интернет")
|
||||
}
|
||||
}
|
||||
|
||||
if (view.progress == 100 && !uiReadyReported) {
|
||||
uiReadyReported = true
|
||||
onUiReady()
|
||||
}
|
||||
|
||||
if (isVkLoggedIn()) {
|
||||
switchToTokenPhase(view)
|
||||
} else {
|
||||
phase = VkAuthPhase.LOGIN
|
||||
onPhaseChange(phase)
|
||||
if (view.url.isNullOrBlank() || view.url == "about:blank") {
|
||||
view.loadUrl(CsqttConstants.VkAutoHash.VK_LOGIN_URL)
|
||||
}
|
||||
}
|
||||
scheduleMonitor()
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
finished = true
|
||||
mainHandler.removeCallbacksAndMessages(null)
|
||||
webView = null
|
||||
}
|
||||
|
||||
fun pause() {
|
||||
if (finished || paused) return
|
||||
paused = true
|
||||
pausedAt = System.currentTimeMillis()
|
||||
mainHandler.removeCallbacks(monitorTick)
|
||||
webView?.onPause()
|
||||
}
|
||||
|
||||
fun resume() {
|
||||
if (finished || !paused) return
|
||||
val resumedAt = System.currentTimeMillis()
|
||||
if (pausedAt != 0L) {
|
||||
startedAt += (resumedAt - pausedAt).coerceAtLeast(0L)
|
||||
pausedAt = 0L
|
||||
}
|
||||
paused = false
|
||||
webView?.onResume()
|
||||
if (pendingAuthorizationRetry) {
|
||||
pendingAuthorizationRetry = false
|
||||
repeatAuthorization()
|
||||
}
|
||||
scheduleMonitor()
|
||||
}
|
||||
|
||||
private fun scheduleMonitor() {
|
||||
mainHandler.removeCallbacks(monitorTick)
|
||||
if (!finished && !paused) {
|
||||
mainHandler.postDelayed(monitorTick, CsqttConstants.VkAutoHash.AUTH_MONITOR_INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
|
||||
private fun installTelevisionNavigation(view: WebView) {
|
||||
if (TvDevicePolicy.isTelevision(view.context)) {
|
||||
view.evaluateJavascript(TV_FOCUS_FIRST_ELEMENT_JS, null)
|
||||
view.post { view.requestFocus() }
|
||||
}
|
||||
}
|
||||
|
||||
private fun switchToTokenPhase(view: WebView) {
|
||||
phase = VkAuthPhase.TOKEN
|
||||
onPhaseChange(phase)
|
||||
lastUrl = null
|
||||
view.stopLoading()
|
||||
view.loadDataWithBaseURL(null, TOKEN_WAITING_HTML, "text/html", "UTF-8", null)
|
||||
|
||||
val context = view.context.applicationContext
|
||||
val cookieManager = CookieManager.getInstance()
|
||||
val cookies = StringBuilder()
|
||||
val domains = listOf(
|
||||
"https://vk.com/", "https://vk.ru/", "https://id.vk.ru/", "https://id.vk.com/",
|
||||
"https://login.vk.com/", "https://login.vk.ru/", "https://m.vk.com/", "https://m.vk.ru/"
|
||||
)
|
||||
domains.forEach { domain ->
|
||||
val domainCookies = runCatching { cookieManager.getCookie(domain) }.getOrNull()
|
||||
if (!domainCookies.isNullOrBlank()) {
|
||||
if (cookies.isNotEmpty()) cookies.append("; ")
|
||||
cookies.append(domainCookies)
|
||||
}
|
||||
}
|
||||
|
||||
val cookieString = cookies.toString()
|
||||
val userAgent = view.settings.userAgentString ?: "Mozilla/5.0 (Linux; Android 13; Mobile)"
|
||||
|
||||
kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO).launch {
|
||||
if (finished) return@launch
|
||||
|
||||
val result = VkTokenScraper.scrape(cookieString, userAgent)
|
||||
|
||||
mainHandler.post {
|
||||
if (finished) return@post
|
||||
|
||||
result.fold(
|
||||
onSuccess = { payload ->
|
||||
finished = true
|
||||
mainHandler.removeCallbacksAndMessages(null)
|
||||
runCatching { CookieManager.getInstance().flush() }
|
||||
onToken(payload)
|
||||
},
|
||||
onFailure = {
|
||||
repeatAuthorization()
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun isVkLoggedIn(): Boolean {
|
||||
val manager = CookieManager.getInstance()
|
||||
val domains = listOf(
|
||||
"https://vk.com/", "https://vk.ru/", "https://id.vk.ru/", "https://id.vk.com/",
|
||||
"https://login.vk.com/", "https://login.vk.ru/", "https://m.vk.com/", "https://m.vk.ru/"
|
||||
)
|
||||
return domains.any { domain ->
|
||||
runCatching { manager.getCookie(domain) }.getOrNull()?.contains("remixsid") == true
|
||||
}
|
||||
}
|
||||
|
||||
private val monitorTick = object : Runnable {
|
||||
override fun run() {
|
||||
if (finished || paused) return
|
||||
val view = webView
|
||||
if (view == null) {
|
||||
stop()
|
||||
return
|
||||
}
|
||||
if (System.currentTimeMillis() - startedAt > CsqttConstants.VkAutoHash.AUTH_TIMEOUT_MS) {
|
||||
finishWithError("Тайм-аут ожидания access_token")
|
||||
return
|
||||
}
|
||||
|
||||
when (phase) {
|
||||
VkAuthPhase.LOGIN -> {
|
||||
if (isVkLoggedIn()) {
|
||||
switchToTokenPhase(view)
|
||||
} else {
|
||||
val currentUrl = view.url.orEmpty()
|
||||
val path = runCatching { currentUrl.toUri().path }.getOrNull() ?: ""
|
||||
if (path.startsWith("/feed")) {
|
||||
switchToTokenPhase(view)
|
||||
} else {
|
||||
view.evaluateJavascript(
|
||||
"(function() { return document.body && (document.body.innerText.includes('Мессенджер') || document.body.innerText.includes('Лента')); })();"
|
||||
) { result ->
|
||||
if (result == "true" && phase == VkAuthPhase.LOGIN) {
|
||||
switchToTokenPhase(view)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
VkAuthPhase.TOKEN -> {
|
||||
val url = view.url.orEmpty()
|
||||
if (url != lastUrl && url.isNotBlank()) {
|
||||
lastUrl = url
|
||||
handleUrl(url)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
scheduleMonitor()
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleUrl(url: String) {
|
||||
val uri = runCatching { url.toUri() }.getOrNull() ?: return
|
||||
val fragment = uri.fragment ?: return
|
||||
when {
|
||||
fragment.contains("access_token=") -> handleAccessToken(fragment)
|
||||
fragment.startsWith("payload=") -> {
|
||||
val host = uri.host.orEmpty()
|
||||
if (host == "oauth.vk.com" || host == "oauth.vk.ru" || host == "vkhost.github.io") {
|
||||
handleSilentPayload(fragment)
|
||||
}
|
||||
}
|
||||
fragment.contains("error=") -> handleOAuthError(fragment)
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleAccessToken(fragment: String) {
|
||||
val params = parseFragmentParams(fragment)
|
||||
val token = params["access_token"]
|
||||
if (token.isNullOrBlank()) {
|
||||
finishWithError("Не удалось извлечь access_token из URL")
|
||||
return
|
||||
}
|
||||
val expiresIn = params["expires_in"]?.toLongOrNull() ?: 0L
|
||||
if (expiresIn == 0L) {
|
||||
finished = true
|
||||
mainHandler.removeCallbacksAndMessages(null)
|
||||
runCatching { CookieManager.getInstance().flush() }
|
||||
onToken(VkAuthPayload(token = token, userId = params["user_id"].orEmpty(), expiresIn = 0L))
|
||||
} else if (!nonPermanentRetried) {
|
||||
nonPermanentRetried = true
|
||||
repeatAuthorization()
|
||||
} else {
|
||||
finishWithError("VK выдал токен с ограниченным сроком действия. Попробуйте еще раз.")
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleSilentPayload(fragment: String) {
|
||||
if (silentRetried) return
|
||||
val payload = runCatching {
|
||||
JSONObject(URLDecoder.decode(fragment.removePrefix("payload="), "UTF-8"))
|
||||
}.getOrNull() ?: return
|
||||
if (payload.optString("type") != "silent_token") return
|
||||
if (payload.optString("token").isBlank()) return
|
||||
|
||||
silentRetried = true
|
||||
mainHandler.postDelayed({
|
||||
if (!finished) repeatAuthorization()
|
||||
}, CsqttConstants.VkAutoHash.AUTH_SILENT_RETRY_DELAY_MS)
|
||||
}
|
||||
|
||||
private fun handleOAuthError(fragment: String) {
|
||||
val params = parseFragmentParams(fragment)
|
||||
val message = params["error_description"] ?: params["error"] ?: "Ошибка VK"
|
||||
finishWithError(message)
|
||||
}
|
||||
|
||||
private fun repeatAuthorization() {
|
||||
if (paused) {
|
||||
pendingAuthorizationRetry = true
|
||||
return
|
||||
}
|
||||
val view = webView ?: return
|
||||
lastUrl = null
|
||||
view.loadUrl(CsqttConstants.VkAutoHash.VK_OAUTH_AUTH_URL)
|
||||
}
|
||||
|
||||
private fun finishWithError(message: String) {
|
||||
if (finished) return
|
||||
finished = true
|
||||
mainHandler.removeCallbacksAndMessages(null)
|
||||
onError(message)
|
||||
}
|
||||
|
||||
private fun parseFragmentParams(fragment: String): Map<String, String> {
|
||||
val result = HashMap<String, String>()
|
||||
fragment.split('&').forEach { part ->
|
||||
val eq = part.indexOf('=')
|
||||
if (eq <= 0) return@forEach
|
||||
val key = part.substring(0, eq)
|
||||
val value = runCatching { URLDecoder.decode(part.substring(eq + 1), "UTF-8") }.getOrDefault("")
|
||||
result[key] = value
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TV_FOCUS_FIRST_ELEMENT_JS = """
|
||||
(function() {
|
||||
if (window.__csqttTvInput) {
|
||||
window.__csqttTvInput('ensure-focus');
|
||||
return;
|
||||
}
|
||||
var selector = 'a[href],button,input:not([type=hidden]),select,textarea,[role=button],[tabindex]:not([tabindex="-1"])';
|
||||
function elements() {
|
||||
return Array.prototype.filter.call(document.querySelectorAll(selector), function(node) {
|
||||
var style = window.getComputedStyle(node);
|
||||
return !node.disabled && style.display !== 'none' && style.visibility !== 'hidden' && node.getClientRects().length > 0;
|
||||
});
|
||||
}
|
||||
function focus(node) {
|
||||
if (!node) return false;
|
||||
node.focus({preventScroll: true});
|
||||
node.scrollIntoView({block: 'center', inline: 'nearest'});
|
||||
return true;
|
||||
}
|
||||
window.__csqttTvInput = function(command) {
|
||||
var items = elements();
|
||||
var active = document.activeElement;
|
||||
var index = items.indexOf(active);
|
||||
if (command === 'ensure-focus') {
|
||||
return index >= 0 || focus(items[0]);
|
||||
}
|
||||
if (command === 'next' || command === 'previous') {
|
||||
if (!items.length) return false;
|
||||
var direction = command === 'next' ? 1 : -1;
|
||||
var next = index < 0 ? (direction > 0 ? 0 : items.length - 1) : (index + direction + items.length) % items.length;
|
||||
return focus(items[next]);
|
||||
}
|
||||
if (command === 'activate') {
|
||||
if (index < 0 && !focus(items[0])) return false;
|
||||
active = document.activeElement;
|
||||
if (!active) return false;
|
||||
active.click();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
window.__csqttTvInput('ensure-focus');
|
||||
})();
|
||||
"""
|
||||
|
||||
private val TOKEN_WAITING_HTML = """
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<style>
|
||||
html, body {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
background: #f2f3f5;
|
||||
font-family: Arial, sans-serif;
|
||||
}
|
||||
body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 18px;
|
||||
}
|
||||
.title {
|
||||
color: #2787f5;
|
||||
font-size: 20px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.dots span {
|
||||
display: inline-block;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
margin: 0 4px;
|
||||
border-radius: 50%;
|
||||
background: #2787f5;
|
||||
animation: csqtt-blink 1.2s infinite ease-in-out;
|
||||
}
|
||||
.dots span:nth-child(2) { animation-delay: .2s; }
|
||||
.dots span:nth-child(3) { animation-delay: .4s; }
|
||||
@keyframes csqtt-blink {
|
||||
0%, 80%, 100% { opacity: .25; transform: scale(.85); }
|
||||
40% { opacity: 1; transform: scale(1); }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="title">Секунду…</div>
|
||||
<div class="dots"><span></span><span></span><span></span></div>
|
||||
</body>
|
||||
</html>
|
||||
""".trimIndent()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.content.Context
|
||||
import android.os.SystemClock
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import java.security.MessageDigest
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
|
||||
object VkAutoCallsManager {
|
||||
data class StartResult(
|
||||
val hashes: String,
|
||||
val requestedCalls: Int,
|
||||
val createdCalls: Int,
|
||||
) {
|
||||
val needsWorkerRedistribution: Boolean
|
||||
get() = createdCalls < requestedCalls
|
||||
}
|
||||
|
||||
private data class ActiveCall(val callId: String, val hashKey: String)
|
||||
private data class PendingLog(val key: String, val message: String, val priority: Int, val isError: Boolean)
|
||||
|
||||
private val activeCalls = CopyOnWriteArrayList<ActiveCall>()
|
||||
private val pendingLogs = ArrayList<PendingLog>()
|
||||
private val pendingLogsLock = Any()
|
||||
|
||||
@Volatile
|
||||
private var activeToken: String? = null
|
||||
|
||||
fun hasActiveCalls(): Boolean = activeCalls.isNotEmpty()
|
||||
|
||||
fun callCountForWorkers(workers: Int): Int {
|
||||
return (1..CsqttConstants.Tunnel.MAX_VK_HASHES).firstOrNull {
|
||||
workers <= WorkerCountPolicy.maximumForHashes(it)
|
||||
} ?: CsqttConstants.Tunnel.MAX_VK_HASHES
|
||||
}
|
||||
|
||||
internal fun requestDelayForCallCount(callCount: Int): Long =
|
||||
if (callCount <= 4) {
|
||||
CsqttConstants.VkAutoHash.AUTO_CALL_SMALL_DELAY_MS
|
||||
} else {
|
||||
CsqttConstants.VkAutoHash.AUTO_CALL_LARGE_DELAY_MS
|
||||
}
|
||||
|
||||
suspend fun startAutoCalls(context: Context, token: String, workers: Int): StartResult? {
|
||||
if (token.isBlank()) return null
|
||||
|
||||
synchronized(pendingLogsLock) { pendingLogs.clear() }
|
||||
activeCalls.clear()
|
||||
|
||||
val count = callCountForWorkers(workers)
|
||||
val hashes = ArrayList<String>(count)
|
||||
|
||||
val requestDelayMs = requestDelayForCallCount(count)
|
||||
val requestPacer = VkRequestPacer(
|
||||
requestDelayMs,
|
||||
SystemClock::elapsedRealtime,
|
||||
{ waitMs -> delay(waitMs) },
|
||||
)
|
||||
var completedSlots = 0
|
||||
while (completedSlots < count) {
|
||||
val result = runVkCallAttempts {
|
||||
requestPacer.awaitRequestSlot()
|
||||
withContext(Dispatchers.IO) { VkApi.startCall(token) }
|
||||
}
|
||||
completedSlots++
|
||||
when (result) {
|
||||
is VkApiResult.Ok<*> -> {
|
||||
activeToken = token
|
||||
val call = result.value as VkApi.StartedCall
|
||||
activeCalls.add(ActiveCall(callId = call.callId, hashKey = sha256Hex(call.hash)))
|
||||
hashes.add(call.hash)
|
||||
log(
|
||||
"vk_call_created_progress",
|
||||
"[OK] Звонок VK создан ✓",
|
||||
16,
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
is VkApiResult.ApiError -> {
|
||||
log(
|
||||
"vk_auto_call_error",
|
||||
"[ERR] Звонок VK не создан · код=${result.code} ${result.message}",
|
||||
90,
|
||||
true,
|
||||
)
|
||||
if (VkApi.isTokenInvalid(result)) {
|
||||
runCatching { SettingsStore(context).clearVkAccessToken() }
|
||||
log(
|
||||
"vk_token_invalidated",
|
||||
"[ERR] Токен VK недействителен · войдите снова",
|
||||
95,
|
||||
true,
|
||||
)
|
||||
finishCalls(ArrayList(activeCalls).also { activeCalls.clear() }, token, logResults = false)
|
||||
activeToken = null
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
is VkApiResult.Failed -> {
|
||||
log(
|
||||
"vk_auto_call_error",
|
||||
"[ERR] Звонок VK не создан · ${result.reason}",
|
||||
90,
|
||||
true,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (hashes.isNotEmpty() && hashes.size < count) {
|
||||
log(
|
||||
"vk_auto_call_partial",
|
||||
"[OK] Звонки VK ${hashes.size}/$count · потоки распределены",
|
||||
45,
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
return if (hashes.isEmpty()) {
|
||||
null
|
||||
} else {
|
||||
StartResult(
|
||||
hashes = hashes.joinToString(","),
|
||||
requestedCalls = count,
|
||||
createdCalls = hashes.size,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun replayPendingLogs() {
|
||||
val copy = synchronized(pendingLogsLock) {
|
||||
val snapshot = ArrayList(pendingLogs)
|
||||
pendingLogs.clear()
|
||||
snapshot
|
||||
}
|
||||
copy.forEach { entry ->
|
||||
TunnelManager.updateLog(entry.key, entry.message, entry.priority, entry.isError)
|
||||
}
|
||||
}
|
||||
|
||||
fun finishActiveCalls() {
|
||||
if (activeCalls.isEmpty()) return
|
||||
val token = activeToken
|
||||
val calls = ArrayList(activeCalls)
|
||||
activeCalls.clear()
|
||||
activeToken = null
|
||||
if (token.isNullOrBlank()) return
|
||||
|
||||
TunnelManager.scope.launch(Dispatchers.IO + NonCancellable) {
|
||||
withTimeoutOrNull(CsqttConstants.VkAutoHash.FINISH_CALLS_TIMEOUT_MS) {
|
||||
finishCalls(calls, token, logResults = true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun finishCalls(calls: List<ActiveCall>, token: String, logResults: Boolean) {
|
||||
val results = coroutineScope {
|
||||
val deferredResults = calls.mapIndexed { index, call ->
|
||||
async(Dispatchers.IO) {
|
||||
index to VkApi.forceFinishCall(token, call.callId)
|
||||
}
|
||||
}
|
||||
deferredResults.awaitAll()
|
||||
}
|
||||
|
||||
if (logResults) {
|
||||
for ((_, result) in results) {
|
||||
when (result) {
|
||||
is VkApiResult.Ok<*> -> TunnelManager.updateLog(
|
||||
"vk_auto_call_finished",
|
||||
"[OK] Звонок VK завершён",
|
||||
40,
|
||||
false,
|
||||
)
|
||||
|
||||
is VkApiResult.ApiError -> TunnelManager.updateLog(
|
||||
"vk_auto_call_finish_error",
|
||||
"[ERR] Звонок VK не завершён · код=${result.code}",
|
||||
60,
|
||||
false,
|
||||
)
|
||||
|
||||
is VkApiResult.Failed -> TunnelManager.updateLog(
|
||||
"vk_auto_call_finish_error",
|
||||
"[ERR] Звонок VK не завершён · ${result.reason}",
|
||||
60,
|
||||
false,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun log(key: String, message: String, priority: Int, isError: Boolean) {
|
||||
if (!TunnelManager.isLoggingEnabled) return
|
||||
TunnelManager.updateLog(key, message, priority, isError)
|
||||
synchronized(pendingLogsLock) {
|
||||
pendingLogs.add(PendingLog(key, message, priority, isError))
|
||||
}
|
||||
}
|
||||
|
||||
private fun sha256Hex(value: String): String = MessageDigest.getInstance("SHA-256")
|
||||
.digest(value.toByteArray(Charsets.UTF_8))
|
||||
.joinToString("") { byte -> "%02x".format(byte) }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
internal class VkRequestPacer(
|
||||
private val intervalMs: Long,
|
||||
private val nowMs: () -> Long,
|
||||
private val sleepMs: suspend (Long) -> Unit,
|
||||
) {
|
||||
private var nextRequestAtMs = 0L
|
||||
|
||||
suspend fun awaitRequestSlot() {
|
||||
val waitMs = nextRequestAtMs - nowMs()
|
||||
if (waitMs > 0) sleepMs(waitMs)
|
||||
nextRequestAtMs = nowMs() + intervalMs
|
||||
}
|
||||
}
|
||||
|
||||
internal suspend fun <T> runVkCallAttempts(
|
||||
request: suspend () -> VkApiResult<T>,
|
||||
): VkApiResult<T> {
|
||||
var result: VkApiResult<T> = VkApiResult.Failed("not attempted")
|
||||
var attempts = 0
|
||||
while (attempts < CsqttConstants.VkAutoHash.AUTO_CALL_MAX_ATTEMPTS) {
|
||||
attempts++
|
||||
result = request()
|
||||
if (result is VkApiResult.Ok<*>) break
|
||||
if (result is VkApiResult.ApiError && VkApi.isTokenInvalid(result)) break
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.content.Context
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
enum class VkHashValidationStatus(val wireValue: String) {
|
||||
Valid("valid"),
|
||||
Invalid("invalid");
|
||||
|
||||
companion object {
|
||||
fun fromWire(value: String): VkHashValidationStatus? = entries.firstOrNull {
|
||||
it.wireValue == value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
object VkHashValidationCodec {
|
||||
fun decode(value: String): Map<String, VkHashValidationStatus> = runCatching {
|
||||
val json = JSONObject(value)
|
||||
buildMap {
|
||||
val keys = json.keys()
|
||||
while (keys.hasNext()) {
|
||||
val hash = keys.next()
|
||||
VkHashValidationStatus.fromWire(json.optString(hash))?.let { put(hash, it) }
|
||||
}
|
||||
}
|
||||
}.getOrDefault(emptyMap())
|
||||
|
||||
fun encode(results: Map<String, VkHashValidationStatus>): String {
|
||||
val json = JSONObject()
|
||||
results.toSortedMap().forEach { (hash, status) -> json.put(hash, status.wireValue) }
|
||||
return json.toString()
|
||||
}
|
||||
|
||||
fun pending(
|
||||
hashes: List<String>,
|
||||
results: Map<String, VkHashValidationStatus>,
|
||||
): List<String> = hashes
|
||||
.filter { it.length >= 16 }
|
||||
.distinct()
|
||||
.filterNot(results::containsKey)
|
||||
|
||||
fun active(
|
||||
hashes: List<String>,
|
||||
results: Map<String, VkHashValidationStatus>,
|
||||
): List<String> = hashes
|
||||
.map(String::trim)
|
||||
.filter { it.length >= 16 }
|
||||
.distinct()
|
||||
.filter { results[it] != VkHashValidationStatus.Invalid }
|
||||
|
||||
fun invalidate(
|
||||
results: Map<String, VkHashValidationStatus>,
|
||||
previousHash: String,
|
||||
): Map<String, VkHashValidationStatus> = results - previousHash
|
||||
}
|
||||
|
||||
object VkHashValidator {
|
||||
private const val OUTPUT_PREFIX = "HASH_CHECK:"
|
||||
|
||||
suspend fun check(
|
||||
context: Context,
|
||||
hashes: List<String>,
|
||||
fingerprint: String,
|
||||
clientIds: String,
|
||||
): Map<String, VkHashValidationStatus> = withContext(Dispatchers.IO) {
|
||||
if (hashes.isEmpty()) return@withContext emptyMap()
|
||||
val binary = File(
|
||||
context.applicationInfo.nativeLibraryDir,
|
||||
CsqttConstants.Tunnel.BINARY_NAME,
|
||||
)
|
||||
if (!binary.isFile) return@withContext emptyMap()
|
||||
val command = buildCommand(binary.absolutePath, hashes, fingerprint, clientIds)
|
||||
val process = runCatching {
|
||||
ProcessBuilder(command)
|
||||
.directory(context.filesDir)
|
||||
.redirectErrorStream(true)
|
||||
.apply {
|
||||
environment()["LD_LIBRARY_PATH"] = context.applicationInfo.nativeLibraryDir
|
||||
}
|
||||
.start()
|
||||
}.getOrNull() ?: return@withContext emptyMap()
|
||||
val completed = runCatching { process.waitFor(75, TimeUnit.SECONDS) }.getOrDefault(false)
|
||||
if (!completed) {
|
||||
process.destroyForcibly()
|
||||
runCatching { process.waitFor(2, TimeUnit.SECONDS) }
|
||||
return@withContext emptyMap()
|
||||
}
|
||||
val requested = hashes.toSet()
|
||||
runCatching {
|
||||
process.inputStream.bufferedReader(Charsets.UTF_8).useLines { lines ->
|
||||
lines.mapNotNull(::parseOutputLine)
|
||||
.filter { it.first in requested }
|
||||
.toMap()
|
||||
}
|
||||
}.getOrDefault(emptyMap())
|
||||
}
|
||||
|
||||
internal fun buildCommand(
|
||||
binary: String,
|
||||
hashes: List<String>,
|
||||
fingerprint: String,
|
||||
clientIds: String,
|
||||
): List<String> = buildList {
|
||||
add(binary)
|
||||
add("--validate-vk-hashes")
|
||||
add("--vk")
|
||||
add(hashes.joinToString(","))
|
||||
add("--fingerprint")
|
||||
add(fingerprint)
|
||||
add("--client-ids")
|
||||
add(clientIds)
|
||||
}
|
||||
|
||||
internal fun parseOutputLine(line: String): Pair<String, VkHashValidationStatus>? {
|
||||
if (!line.startsWith(OUTPUT_PREFIX)) return null
|
||||
return runCatching {
|
||||
val json = JSONObject(line.removePrefix(OUTPUT_PREFIX))
|
||||
val hash = json.getString("hash")
|
||||
val status = VkHashValidationStatus.fromWire(json.getString("status")) ?: return null
|
||||
hash to status
|
||||
}.getOrNull()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
internal data class VkModeSelection(
|
||||
val authMode: String,
|
||||
val hashMode: String,
|
||||
)
|
||||
|
||||
internal fun normalizeVkModeSelection(
|
||||
requestedAuthMode: String?,
|
||||
requestedHashMode: String?,
|
||||
hasVkToken: Boolean,
|
||||
): VkModeSelection {
|
||||
val authMode = when (requestedAuthMode) {
|
||||
CsqttConstants.VkAuth.MODE_CAPTCHA -> CsqttConstants.VkAuth.MODE_CAPTCHA
|
||||
CsqttConstants.VkAuth.MODE_AUTO_JS -> CsqttConstants.VkAuth.MODE_AUTO_JS
|
||||
else -> CsqttConstants.VkAuth.MODE_CALLS
|
||||
}
|
||||
val hashMode = when (requestedHashMode) {
|
||||
"auto", CsqttConstants.VkAutoHash.MODE_AUTO_API -> CsqttConstants.VkAutoHash.MODE_AUTO_API
|
||||
CsqttConstants.VkAutoHash.MODE_AUTO_JS -> CsqttConstants.VkAutoHash.MODE_AUTO_JS
|
||||
else -> CsqttConstants.VkAutoHash.MODE_MANUAL
|
||||
}
|
||||
return when {
|
||||
authMode == CsqttConstants.VkAuth.MODE_AUTO_JS ||
|
||||
hashMode == CsqttConstants.VkAutoHash.MODE_AUTO_JS ->
|
||||
VkModeSelection(
|
||||
authMode = CsqttConstants.VkAuth.MODE_AUTO_JS,
|
||||
hashMode = CsqttConstants.VkAutoHash.MODE_AUTO_JS,
|
||||
)
|
||||
else -> VkModeSelection(authMode = authMode, hashMode = hashMode)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun vkHashModeForAuthMode(
|
||||
requestedAuthMode: String,
|
||||
currentHashMode: String?,
|
||||
hasVkToken: Boolean,
|
||||
): String = when (requestedAuthMode) {
|
||||
CsqttConstants.VkAuth.MODE_AUTO_JS -> CsqttConstants.VkAutoHash.MODE_AUTO_JS
|
||||
CsqttConstants.VkAuth.MODE_CALLS -> if (currentHashMode == CsqttConstants.VkAutoHash.MODE_AUTO_JS) {
|
||||
if (hasVkToken) CsqttConstants.VkAutoHash.MODE_AUTO_API else CsqttConstants.VkAutoHash.MODE_MANUAL
|
||||
} else {
|
||||
normalizeVkModeSelection(requestedAuthMode, currentHashMode, hasVkToken).hashMode
|
||||
}
|
||||
else -> normalizeVkModeSelection(requestedAuthMode, currentHashMode, hasVkToken).hashMode
|
||||
}
|
||||
|
||||
internal fun vkAuthModeForHashMode(requestedHashMode: String, currentAuthMode: String?): String =
|
||||
when (requestedHashMode) {
|
||||
CsqttConstants.VkAutoHash.MODE_AUTO_JS -> CsqttConstants.VkAuth.MODE_AUTO_JS
|
||||
CsqttConstants.VkAutoHash.MODE_AUTO_API -> CsqttConstants.VkAuth.MODE_CALLS
|
||||
else -> if (currentAuthMode == CsqttConstants.VkAuth.MODE_AUTO_JS) {
|
||||
CsqttConstants.VkAuth.MODE_CALLS
|
||||
} else {
|
||||
normalizeVkModeSelection(currentAuthMode, requestedHashMode, false).authMode
|
||||
}
|
||||
}
|
||||
|
||||
internal fun shouldReplaceUnavailableVkHash(hashMode: String): Boolean =
|
||||
hashMode != CsqttConstants.VkAutoHash.MODE_MANUAL
|
||||
|
||||
internal fun shouldConfirmAutoJsMode(
|
||||
currentMode: String,
|
||||
requestedMode: String,
|
||||
warningAcknowledged: Boolean,
|
||||
): Boolean =
|
||||
!warningAcknowledged &&
|
||||
currentMode != CsqttConstants.VkAuth.MODE_AUTO_JS &&
|
||||
requestedMode == CsqttConstants.VkAuth.MODE_AUTO_JS
|
||||
@@ -0,0 +1,15 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
internal fun vkProbeRetryDelayMs(failures: Int): Long = when (failures.coerceAtLeast(1)) {
|
||||
in 1..15 -> 1_000L
|
||||
16 -> 2_000L
|
||||
17 -> 3_000L
|
||||
18 -> 5_000L
|
||||
19 -> 8_000L
|
||||
else -> 15_000L
|
||||
}
|
||||
|
||||
internal fun isVkProbeHttpResponse(code: Int): Boolean = code in 100..599
|
||||
@@ -0,0 +1,96 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import androidx.core.net.toUri
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
internal object VkTokenScraper {
|
||||
suspend fun scrape(cookies: String, userAgent: String): Result<VkAuthPayload> = withContext(Dispatchers.IO) {
|
||||
var endpoint = "https://oauth.vk.com/authorize?client_id=7793118&display=mobile&redirect_uri=https%3A%2F%2Foauth.vk.ru%2Fblank.html&response_type=token&scope=1073737727&v=5.199&revoke=1"
|
||||
|
||||
val jsLocationRegex = Regex("location\\.href\\s*=\\s*[\"']([^\"']+)[\"']")
|
||||
val oauthGrantRegex = Regex("(https://login\\.vk\\.(?:com|ru)/\\?act=grant_access[^\"'\\s<]+)")
|
||||
|
||||
var hopsRemaining = CsqttConstants.VkAutoHash.MAX_OAUTH_HOPS
|
||||
|
||||
try {
|
||||
while (hopsRemaining-- > 0) {
|
||||
val connection = (URL(endpoint).openConnection() as HttpURLConnection).apply {
|
||||
instanceFollowRedirects = false
|
||||
requestMethod = "GET"
|
||||
setRequestProperty("Cookie", cookies)
|
||||
setRequestProperty("User-Agent", userAgent)
|
||||
setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
|
||||
connectTimeout = 15000
|
||||
readTimeout = 15000
|
||||
}
|
||||
|
||||
val code = connection.responseCode
|
||||
|
||||
if (code == HttpURLConnection.HTTP_MOVED_TEMP || code == HttpURLConnection.HTTP_MOVED_PERM || code == HttpURLConnection.HTTP_SEE_OTHER) {
|
||||
val nextLocation = connection.getHeaderField("Location") ?: break
|
||||
val payload = parseFragment(nextLocation)
|
||||
if (payload != null) return@withContext Result.success(payload)
|
||||
endpoint = nextLocation
|
||||
continue
|
||||
}
|
||||
|
||||
if (code == HttpURLConnection.HTTP_OK) {
|
||||
val htmlContent = connection.inputStream.bufferedReader().use { it.readText() }
|
||||
|
||||
val matchJs = jsLocationRegex.find(htmlContent)
|
||||
if (matchJs != null) {
|
||||
val scriptTarget = matchJs.groupValues[1]
|
||||
val payload = parseFragment(scriptTarget)
|
||||
if (payload != null) return@withContext Result.success(payload)
|
||||
endpoint = scriptTarget
|
||||
continue
|
||||
}
|
||||
|
||||
val matchGrant = oauthGrantRegex.find(htmlContent)
|
||||
if (matchGrant != null) {
|
||||
endpoint = matchGrant.groupValues[1].replace("&", "&")
|
||||
continue
|
||||
}
|
||||
|
||||
return@withContext Result.failure(IllegalStateException("No redirection found in HTML output"))
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
Result.failure(IllegalStateException("Too many redirects: max hops exceeded"))
|
||||
} catch (t: Throwable) {
|
||||
Result.failure(t)
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseFragment(urlStr: String): VkAuthPayload? {
|
||||
if (!urlStr.contains("access_token=")) return null
|
||||
|
||||
val fragmentPart = try {
|
||||
urlStr.toUri().encodedFragment ?: urlStr.substringAfter("#", "").ifEmpty { urlStr.substringAfter("?", "") }
|
||||
} catch (e: Exception) {
|
||||
urlStr.substringAfter("#", "").ifEmpty { urlStr.substringAfter("?", "") }
|
||||
}
|
||||
|
||||
val params = fragmentPart.split("&").associate {
|
||||
val parts = it.split("=", limit = 2)
|
||||
parts[0] to parts.getOrElse(1) { "" }
|
||||
}
|
||||
|
||||
val tokenVal = params["access_token"]
|
||||
if (!tokenVal.isNullOrBlank()) {
|
||||
return VkAuthPayload(
|
||||
token = tokenVal,
|
||||
userId = params["user_id"].orEmpty(),
|
||||
expiresIn = params["expires_in"]?.toLongOrNull() ?: 0L
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.appwidget.AppWidgetManager
|
||||
import android.appwidget.AppWidgetProvider
|
||||
import android.content.ComponentName
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.VpnService
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import android.widget.RemoteViews
|
||||
import android.widget.Toast
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
class VpnWidgetProvider : AppWidgetProvider() {
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||||
|
||||
companion object {
|
||||
const val ACTION_WIDGET_TOGGLE = CsqttConstants.Widget.ACTION_TOGGLE
|
||||
|
||||
fun updateAllWidgets(context: Context) {
|
||||
runCatching {
|
||||
val appWidgetManager = AppWidgetManager.getInstance(context)
|
||||
val thisWidget = ComponentName(context, VpnWidgetProvider::class.java)
|
||||
val appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget)
|
||||
if (appWidgetIds.isNotEmpty()) {
|
||||
val intent = Intent(context, VpnWidgetProvider::class.java).apply {
|
||||
action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
|
||||
putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds)
|
||||
}
|
||||
context.sendBroadcast(intent)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
|
||||
val running = TunnelManager.running.value
|
||||
for (appWidgetId in appWidgetIds) {
|
||||
updateWidgetState(context, appWidgetManager, appWidgetId, running)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
super.onReceive(context, intent)
|
||||
if (intent.action == ACTION_WIDGET_TOGGLE) {
|
||||
runCatching {
|
||||
if (TunnelManager.running.value) {
|
||||
val stopIntent = Intent(context, TunnelService::class.java).apply { action = "STOP" }
|
||||
context.startService(stopIntent)
|
||||
updateAllWidgets(context)
|
||||
return
|
||||
}
|
||||
|
||||
if (VpnService.prepare(context) != null) {
|
||||
context.showRaisedToast("Откройте CSQTT и выдайте VPN-разрешение", Toast.LENGTH_LONG)
|
||||
openMainActivity(context)
|
||||
return
|
||||
}
|
||||
|
||||
scope.launch {
|
||||
try {
|
||||
val startIntent = buildStartIntent(context)
|
||||
if (startIntent == null) {
|
||||
context.showRaisedToast("Заполните настройки подключения в CSQTT", Toast.LENGTH_LONG)
|
||||
openMainActivity(context)
|
||||
return@launch
|
||||
}
|
||||
|
||||
context.startForegroundService(startIntent)
|
||||
} catch (e: Exception) {
|
||||
Log.e("VpnWidget", "Failed to start tunnel from widget", e)
|
||||
context.showRaisedToast("Ошибка запуска: ${e.localizedMessage}", Toast.LENGTH_SHORT)
|
||||
}
|
||||
}
|
||||
}.onFailure { e ->
|
||||
Log.e("VpnWidget", "Error handling widget click", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun updateWidgetState(
|
||||
context: Context,
|
||||
appWidgetManager: AppWidgetManager,
|
||||
appWidgetId: Int,
|
||||
running: Boolean
|
||||
) {
|
||||
val views = RemoteViews(context.packageName, R.layout.vpn_widget)
|
||||
|
||||
if (running) {
|
||||
views.setTextViewText(R.id.widget_status, "Подключено")
|
||||
views.setTextColor(R.id.widget_status, 0xFF00E5FF.toInt())
|
||||
views.setInt(R.id.widget_toggle_btn, "setBackgroundResource", R.drawable.bg_widget_button_active)
|
||||
} else {
|
||||
views.setTextViewText(R.id.widget_status, "Отключено")
|
||||
views.setTextColor(R.id.widget_status, 0xFF888888.toInt())
|
||||
views.setInt(R.id.widget_toggle_btn, "setBackgroundResource", R.drawable.bg_widget_button_inactive)
|
||||
}
|
||||
|
||||
val openIntent = Intent(context, MainActivity::class.java).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
}
|
||||
val openPendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
appWidgetId,
|
||||
openIntent,
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
|
||||
)
|
||||
views.setOnClickPendingIntent(R.id.widget_container, openPendingIntent)
|
||||
|
||||
val toggleIntent = Intent(context, VpnWidgetProvider::class.java).apply {
|
||||
action = ACTION_WIDGET_TOGGLE
|
||||
}
|
||||
val togglePendingIntent = PendingIntent.getBroadcast(
|
||||
context,
|
||||
appWidgetId + 1000,
|
||||
toggleIntent,
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
|
||||
)
|
||||
views.setOnClickPendingIntent(R.id.widget_toggle_btn, togglePendingIntent)
|
||||
|
||||
appWidgetManager.updateAppWidget(appWidgetId, views)
|
||||
}
|
||||
|
||||
private suspend fun buildStartIntent(context: Context): Intent? {
|
||||
val store = SettingsStore(context.applicationContext)
|
||||
val source = resolveConnectionSource(store) ?: return null
|
||||
|
||||
return Intent(context, TunnelService::class.java).apply {
|
||||
action = "START"
|
||||
putExtra("peer", source.peer)
|
||||
putExtra("vk_hashes", source.hashes)
|
||||
putExtra("vk_hashes_from_link", source.hashesFromLink)
|
||||
putExtra("secondary_vk_hash", store.secondaryVkHash.first())
|
||||
putExtra("workers_per_hash", store.workersPerHash.first())
|
||||
putExtra("port", 0)
|
||||
putExtra("sni", store.sni.first())
|
||||
putExtra("connection_password", source.password)
|
||||
putExtra("protocol", store.protocol.first())
|
||||
putExtra("vk_auth_mode", store.vkAuthMode.first())
|
||||
putExtra("captcha_mode", store.captchaMode.first())
|
||||
putExtra("captcha_solve_method", store.captchaSolveMethod.first())
|
||||
putExtra("fingerprint", store.selectedFingerprint.first())
|
||||
putExtra("client_ids", store.activeClientIds.first())
|
||||
putExtra("obfs_mode", store.obfsMode.first())
|
||||
putExtra("turn_transport", store.turnTransport.first())
|
||||
}
|
||||
}
|
||||
|
||||
private fun openMainActivity(context: Context) {
|
||||
val intent = Intent(context, MainActivity::class.java).apply {
|
||||
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
}
|
||||
runCatching {
|
||||
val pendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
200,
|
||||
intent,
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
|
||||
)
|
||||
pendingIntent.send()
|
||||
}.onFailure {
|
||||
context.startActivity(intent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
internal enum class WifiAutoPauseAction {
|
||||
NONE,
|
||||
PAUSE,
|
||||
RESUME,
|
||||
}
|
||||
|
||||
internal fun wifiAutoPauseAction(
|
||||
enabled: Boolean,
|
||||
wifiConnected: Boolean,
|
||||
desiredRunning: Boolean,
|
||||
paused: Boolean,
|
||||
): WifiAutoPauseAction = when {
|
||||
paused && (!enabled || !wifiConnected) -> WifiAutoPauseAction.RESUME
|
||||
enabled && wifiConnected && desiredRunning && !paused -> WifiAutoPauseAction.PAUSE
|
||||
else -> WifiAutoPauseAction.NONE
|
||||
}
|
||||
|
||||
internal fun effectiveWifiAutoPauseConnection(
|
||||
paused: Boolean,
|
||||
callbackWifiConnected: Boolean,
|
||||
defaultPhysicalWifiConnected: Boolean?,
|
||||
): Boolean = if (paused) {
|
||||
defaultPhysicalWifiConnected ?: callbackWifiConnected
|
||||
} else {
|
||||
callbackWifiConnected
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
internal object WorkerCountPolicy {
|
||||
fun normalize(
|
||||
requested: Int,
|
||||
maximum: Int = CsqttConstants.Tunnel.MAX_WORKERS,
|
||||
): Int {
|
||||
val group = CsqttConstants.Tunnel.WORKERS_PER_GROUP
|
||||
val normalizedMaximum = (maximum.coerceAtLeast(group) / group) * group
|
||||
return (requested.coerceIn(group, normalizedMaximum) / group) * group
|
||||
}
|
||||
|
||||
fun maximumForHashes(hashCount: Int): Int {
|
||||
val requested = hashCount.coerceIn(1, CsqttConstants.Tunnel.MAX_VK_HASHES) *
|
||||
CsqttConstants.Tunnel.GROUPS_PER_VK_HASH * CsqttConstants.Tunnel.WORKERS_PER_GROUP
|
||||
return normalize(requested)
|
||||
}
|
||||
|
||||
fun maximumForSources(
|
||||
linkMode: Boolean,
|
||||
linkHashCount: Int,
|
||||
autoHashMode: Boolean,
|
||||
manualHashCount: Int,
|
||||
): Int = when {
|
||||
linkMode && linkHashCount > 0 -> maximumForHashes(linkHashCount)
|
||||
autoHashMode -> CsqttConstants.Tunnel.MAX_WORKERS
|
||||
else -> maximumForHashes(manualHashCount)
|
||||
}
|
||||
|
||||
fun defaultMaximum(extraWorkers: Boolean): Int =
|
||||
if (extraWorkers) CsqttConstants.Tunnel.MAX_WORKERS else CsqttConstants.Tunnel.DEFAULT_MAX_WORKERS
|
||||
|
||||
fun normalizeForHashes(requested: Int, hashCount: Int): Int =
|
||||
normalize(requested, maximumForHashes(hashCount))
|
||||
|
||||
fun normalizeForHashValues(
|
||||
requested: Int,
|
||||
hashes: Iterable<String>,
|
||||
allowRedistribution: Boolean = false,
|
||||
): Int {
|
||||
if (allowRedistribution) return normalize(requested)
|
||||
val hashCount = hashes
|
||||
.map { it.trim() }
|
||||
.filter { it.isNotEmpty() }
|
||||
.distinct()
|
||||
.take(CsqttConstants.Tunnel.MAX_VK_HASHES)
|
||||
.count()
|
||||
return normalizeForHashes(requested, hashCount)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
internal class WorkerRecoveryPolicy(
|
||||
private val minimumPeak: Int = CsqttConstants.Tunnel.WORKERS_PER_GROUP,
|
||||
) {
|
||||
private var peak = 0
|
||||
private var armedTarget = 0
|
||||
|
||||
@Synchronized
|
||||
fun observe(active: Int): Boolean {
|
||||
val bounded = active.coerceAtLeast(0)
|
||||
peak = maxOf(peak, bounded)
|
||||
if (armedTarget != 0 && bounded >= armedTarget) {
|
||||
armedTarget = 0
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun armAtZero(): Int? {
|
||||
if (armedTarget != 0) return armedTarget
|
||||
if (peak < minimumPeak) return null
|
||||
armedTarget = peak
|
||||
return armedTarget
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun shouldRecover(active: Int, target: Int): Boolean =
|
||||
armedTarget == target && active.coerceAtLeast(0) < target
|
||||
|
||||
@Synchronized
|
||||
fun reset() {
|
||||
peak = 0
|
||||
armedTarget = 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.lerp
|
||||
import androidx.compose.ui.graphics.luminance
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.design.CsqttSpacing
|
||||
|
||||
@Composable
|
||||
private fun appSectionCardColor(): Color {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val isDark = colors.background.luminance() < 0.22f
|
||||
return if (isDark) {
|
||||
lerp(colors.background, colors.surface, 0.82f)
|
||||
} else {
|
||||
lerp(colors.surface, colors.surfaceVariant, 0.28f)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun appSectionCardBorderColor(): Color {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val isDark = colors.background.luminance() < 0.22f
|
||||
return if (isDark) {
|
||||
colors.outlineVariant.copy(alpha = 0.32f)
|
||||
} else {
|
||||
colors.outlineVariant.copy(alpha = 0.24f)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun AppSectionCard(
|
||||
modifier: Modifier = Modifier,
|
||||
contentPadding: PaddingValues = PaddingValues(CsqttSpacing.Md),
|
||||
verticalArrangement: Arrangement.Vertical = Arrangement.spacedBy(CsqttSpacing.Md),
|
||||
content: @Composable ColumnScope.() -> Unit
|
||||
) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Card,
|
||||
color = appSectionCardColor(),
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
border = BorderStroke(1.dp, appSectionCardBorderColor()),
|
||||
shadowElevation = if (MaterialTheme.colorScheme.background.luminance() < 0.22f) 4.dp else 10.dp,
|
||||
tonalElevation = if (MaterialTheme.colorScheme.background.luminance() < 0.22f) 0.dp else 2.dp,
|
||||
modifier = modifier.fillMaxWidth()
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(contentPadding),
|
||||
verticalArrangement = verticalArrangement,
|
||||
content = content
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Update
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.csqtt.client.AppReleaseInfo
|
||||
import com.csqtt.client.RemoteVersionSource
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
|
||||
@Composable
|
||||
fun AppUpdateDialog(
|
||||
release: AppReleaseInfo,
|
||||
onPostpone: () -> Unit,
|
||||
onUpdate: () -> Unit
|
||||
) {
|
||||
val isTagOnly = release.source == RemoteVersionSource.Tag
|
||||
val title = if (isTagOnly) "Найден новый tag" else "Доступно обновление"
|
||||
val description = if (isTagOnly) {
|
||||
"На GitHub обнаружен более новый tag ${release.versionTag}. Похоже, опубликованный release ещё не догнал его."
|
||||
} else {
|
||||
"Вышла новая версия приложения ${release.versionTag}. Можно открыть страницу релиза и обновиться вручную."
|
||||
}
|
||||
|
||||
Dialog(
|
||||
onDismissRequest = {},
|
||||
properties = DialogProperties(
|
||||
usePlatformDefaultWidth = false,
|
||||
dismissOnBackPress = false,
|
||||
dismissOnClickOutside = false
|
||||
)
|
||||
) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Dialog,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
tonalElevation = 8.dp,
|
||||
modifier = Modifier.fillMaxWidth(0.92f)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(horizontal = 22.dp, vertical = 20.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(14.dp)
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Update,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(20.dp)
|
||||
)
|
||||
Spacer(Modifier.width(10.dp))
|
||||
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
Text(
|
||||
text = release.versionTag,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Text(
|
||||
text = description,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 20.sp
|
||||
)
|
||||
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.35f))
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
OutlinedButton(
|
||||
onClick = onPostpone,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.height(50.dp),
|
||||
shape = CsqttShapes.Pill
|
||||
) {
|
||||
Text("Позже", fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = onUpdate,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.height(50.dp),
|
||||
shape = CsqttShapes.Pill
|
||||
) {
|
||||
Text("Обновить", fontWeight = FontWeight.Bold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.Hyphens
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import kotlinx.coroutines.delay
|
||||
|
||||
@Composable
|
||||
internal fun AutoVkRiskDialog(
|
||||
requireAcknowledgement: Boolean,
|
||||
onAcknowledge: () -> Unit,
|
||||
onDoNotRemind: (() -> Unit)? = null,
|
||||
) {
|
||||
TimedWarningDialog(
|
||||
title = "Внимание!",
|
||||
paragraphs = listOf(
|
||||
"«Авто ВК» использует неофициальные браузерные методы VK API для создания звонка и получения TURN credentials без анонимных звонков. Сетевой стек PRIMP маскирует HTTP/TLS-профиль под обычный браузер.",
|
||||
"Разработчик не может исключить блокировку VK-аккаунта и честно оценить её вероятность. Используйте режим на свой риск; если важен основной аккаунт, выбирайте второстепенный. Рекомендуется включать «Авто ВК», когда «Авто» и «Авто API» не работают.",
|
||||
),
|
||||
requireAcknowledgement = requireAcknowledgement,
|
||||
onAcknowledge = onAcknowledge,
|
||||
onDoNotRemind = onDoNotRemind,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun TcpTransportRiskDialog(
|
||||
onAcknowledge: () -> Unit,
|
||||
onDoNotRemind: () -> Unit,
|
||||
) {
|
||||
TimedWarningDialog(
|
||||
title = "Внимание!",
|
||||
paragraphs = listOf(
|
||||
"TCP — экспериментальный режим для сетей, в которых провайдер ограничивает UDP-трафик. TCP используется только между вашим устройством и серверами VK TURN; между VK TURN и вашим VPS трафик всегда идёт по UDP.",
|
||||
"Если UDP работает без ограничений, используйте его: UDP стабильнее, быстрее и по своей природе ближе к настоящим звонкам.",
|
||||
),
|
||||
requireAcknowledgement = true,
|
||||
onAcknowledge = onAcknowledge,
|
||||
onDoNotRemind = onDoNotRemind,
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TimedWarningDialog(
|
||||
title: String,
|
||||
paragraphs: List<String>,
|
||||
requireAcknowledgement: Boolean,
|
||||
onAcknowledge: () -> Unit,
|
||||
onDoNotRemind: (() -> Unit)?,
|
||||
) {
|
||||
var secondsLeft by rememberSaveable(requireAcknowledgement) {
|
||||
mutableIntStateOf(if (requireAcknowledgement) 8 else 0)
|
||||
}
|
||||
if (requireAcknowledgement) {
|
||||
LaunchedEffect(Unit) {
|
||||
while (secondsLeft > 0) {
|
||||
delay(1_000)
|
||||
secondsLeft -= 1
|
||||
}
|
||||
}
|
||||
}
|
||||
val actionsEnabled = secondsLeft == 0
|
||||
|
||||
AlertDialog(
|
||||
onDismissRequest = {},
|
||||
properties = DialogProperties(
|
||||
dismissOnBackPress = false,
|
||||
dismissOnClickOutside = false,
|
||||
),
|
||||
title = {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
},
|
||||
text = {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
paragraphs.forEach { paragraph ->
|
||||
Text(
|
||||
text = paragraph,
|
||||
style = MaterialTheme.typography.bodyMedium.copy(hyphens = Hyphens.Auto),
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
textAlign = TextAlign.Start,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
if (onDoNotRemind != null) {
|
||||
OutlinedButton(
|
||||
onClick = onDoNotRemind,
|
||||
enabled = actionsEnabled,
|
||||
modifier = Modifier.fillMaxWidth().height(48.dp),
|
||||
) {
|
||||
Text("Не напоминать")
|
||||
}
|
||||
}
|
||||
Button(
|
||||
onClick = onAcknowledge,
|
||||
enabled = actionsEnabled,
|
||||
modifier = Modifier.fillMaxWidth().height(48.dp),
|
||||
) {
|
||||
Text("Понятно")
|
||||
}
|
||||
if (!actionsEnabled) {
|
||||
Text(
|
||||
text = secondsLeft.toString(),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
textAlign = TextAlign.Center,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import android.content.Intent
|
||||
import android.net.VpnService
|
||||
import android.widget.Toast
|
||||
import androidx.activity.compose.rememberLauncherForActivityResult
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.IntrinsicSize
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.scale
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.ColorFilter
|
||||
import androidx.compose.ui.graphics.ColorMatrix
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.csqtt.client.ConnectionSource
|
||||
import com.csqtt.client.ConnectionStartBlocker
|
||||
import com.csqtt.client.ConnectionStartPolicy
|
||||
import com.csqtt.client.CsqttConstants
|
||||
import com.csqtt.client.R
|
||||
import com.csqtt.client.SettingsStore
|
||||
import com.csqtt.client.StoredSecretState
|
||||
import com.csqtt.client.TunnelAuthSnapshot
|
||||
import com.csqtt.client.TunnelManager
|
||||
import com.csqtt.client.TunnelService
|
||||
import com.csqtt.client.VkHashValidationCodec
|
||||
import com.csqtt.client.newTunnelSessionId
|
||||
import com.csqtt.client.resolveConnectionSource
|
||||
import com.csqtt.client.showRaisedToast
|
||||
import com.csqtt.client.ui.components.CsqttScreen
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.utils.parseCsqttLink
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import java.util.Locale
|
||||
|
||||
@Composable
|
||||
internal fun ConnectionTab(
|
||||
settingsStore: SettingsStore,
|
||||
tunnelAuthSettings: TunnelAuthSnapshot,
|
||||
onInvalidConfiguration: () -> Unit,
|
||||
) {
|
||||
val context = androidx.compose.ui.platform.LocalContext.current.applicationContext
|
||||
val scope = rememberCoroutineScope()
|
||||
val connectionPassword = tunnelAuthSettings.connectionPassword
|
||||
val tunnelRunning by TunnelManager.running.collectAsStateWithLifecycle()
|
||||
val tunnelStarting by TunnelManager.starting.collectAsStateWithLifecycle()
|
||||
val tunnelStopping by TunnelManager.stopping.collectAsStateWithLifecycle()
|
||||
val autoPausedForWifi by TunnelManager.autoPausedForWifi.collectAsStateWithLifecycle()
|
||||
val cooldownActive by TunnelManager.cooldownActive.collectAsStateWithLifecycle()
|
||||
|
||||
val csqttLinkMode by settingsStore.csqttLinkMode.collectAsStateWithLifecycle(initialValue = false)
|
||||
val csqttLink by settingsStore.csqttLink.collectAsStateWithLifecycle(initialValue = "")
|
||||
val peer by settingsStore.peer.collectAsStateWithLifecycle(initialValue = "")
|
||||
val vkHashes by settingsStore.vkHashes.collectAsStateWithLifecycle(initialValue = "")
|
||||
val vkHashCheckResultsJson by settingsStore.vkHashCheckResults.collectAsStateWithLifecycle(initialValue = "{}")
|
||||
val workersPerHash by settingsStore.workersPerHash.collectAsStateWithLifecycle(initialValue = 18)
|
||||
val sni by settingsStore.sni.collectAsStateWithLifecycle(initialValue = "")
|
||||
val obfsMode by settingsStore.obfsMode.collectAsStateWithLifecycle(initialValue = CsqttConstants.Tunnel.DEFAULT_OBFS_MODE)
|
||||
val turnTransport by settingsStore.turnTransport.collectAsStateWithLifecycle(initialValue = CsqttConstants.Tunnel.DEFAULT_TURN_TRANSPORT)
|
||||
val manualPortsEnabled by settingsStore.manualPortsEnabled.collectAsStateWithLifecycle(initialValue = false)
|
||||
val serverPeerPort by settingsStore.serverPeerPort.collectAsStateWithLifecycle(
|
||||
initialValue = CsqttConstants.Network.DEFAULT_SERVER_PEER_PORT,
|
||||
)
|
||||
val vkAuthMode by settingsStore.vkAuthMode.collectAsStateWithLifecycle(initialValue = CsqttConstants.VkAuth.MODE_CALLS)
|
||||
val captchaMode by settingsStore.captchaMode.collectAsStateWithLifecycle(initialValue = "auto")
|
||||
val captchaSolveMethod by settingsStore.captchaSolveMethod.collectAsStateWithLifecycle(initialValue = "auto")
|
||||
val activeFingerprint by settingsStore.selectedFingerprint.collectAsStateWithLifecycle(initialValue = CsqttConstants.Tunnel.DEFAULT_FINGERPRINT)
|
||||
val activeClientIds by settingsStore.activeClientIds.collectAsStateWithLifecycle(initialValue = CsqttConstants.Tunnel.DEFAULT_CLIENT_IDS)
|
||||
val savedHashMode by settingsStore.vkHashMode.collectAsStateWithLifecycle(initialValue = SettingsStore.cachedVkHashMode)
|
||||
val savedVkAccessToken by settingsStore.vkAccessToken.collectAsStateWithLifecycle(initialValue = SettingsStore.cachedVkAccessToken)
|
||||
|
||||
var pendingStartAfterVpnPermission by remember { mutableStateOf(false) }
|
||||
|
||||
val parsedLink = remember(csqttLink) { parseCsqttLink(csqttLink) }
|
||||
val linkHashes = parsedLink?.hashes.orEmpty()
|
||||
val manualHashes = remember(vkHashes, vkHashCheckResultsJson) {
|
||||
VkHashValidationCodec.active(
|
||||
vkHashes.split(Regex("[,\\s\\n]+")),
|
||||
VkHashValidationCodec.decode(vkHashCheckResultsJson),
|
||||
)
|
||||
}
|
||||
val accountAutoJsMode = vkAuthMode == CsqttConstants.VkAuth.MODE_AUTO_JS
|
||||
val hashSettingsLoaded = savedHashMode != null && savedVkAccessToken != null
|
||||
val autoHashMode = accountAutoJsMode || (
|
||||
savedHashMode != null && savedHashMode != CsqttConstants.VkAutoHash.MODE_MANUAL
|
||||
)
|
||||
val vkTokenActive = savedVkAccessToken?.isNotBlank() == true
|
||||
val hashesReady = hashSettingsLoaded && when {
|
||||
csqttLinkMode && linkHashes.isNotEmpty() -> true
|
||||
autoHashMode -> vkTokenActive
|
||||
else -> manualHashes.isNotEmpty()
|
||||
}
|
||||
val peerPortValid = !manualPortsEnabled || serverPeerPort in 1..65535
|
||||
val startBlocker = ConnectionStartPolicy.blocker(
|
||||
linkMode = csqttLinkMode,
|
||||
linkValid = parsedLink != null,
|
||||
peerValid = peer.isNotBlank() && !peer.contains(":"),
|
||||
peerPortValid = peerPortValid,
|
||||
connectionPasswordSet = connectionPassword.isNotBlank(),
|
||||
connectionPasswordReadable = tunnelAuthSettings.connectionPasswordState != StoredSecretState.Unreadable,
|
||||
hashesReady = hashesReady,
|
||||
)
|
||||
val isValid = startBlocker == null
|
||||
val hashStatus = when {
|
||||
csqttLinkMode && linkHashes.isNotEmpty() -> "${linkHashes.size}/${CsqttConstants.Tunnel.MAX_VK_HASHES}"
|
||||
autoHashMode && vkTokenActive -> "Авто"
|
||||
autoHashMode -> "Токен"
|
||||
else -> "${manualHashes.size}/${CsqttConstants.Tunnel.MAX_VK_HASHES}"
|
||||
}
|
||||
|
||||
fun startIntent(source: ConnectionSource, generationId: Long, salt: String): Intent =
|
||||
Intent(context, TunnelService::class.java).apply {
|
||||
action = "START"
|
||||
putExtra("peer", source.peer)
|
||||
putExtra("vk_hashes", source.hashes)
|
||||
putExtra("vk_hashes_from_link", source.hashesFromLink)
|
||||
putExtra("secondary_vk_hash", "")
|
||||
putExtra("workers_per_hash", workersPerHash)
|
||||
putExtra("port", 0)
|
||||
putExtra("sni", sni)
|
||||
putExtra("connection_password", source.password)
|
||||
putExtra("vk_auth_mode", vkAuthMode)
|
||||
putExtra("captcha_mode", captchaMode)
|
||||
putExtra("captcha_solve_method", captchaSolveMethod)
|
||||
putExtra("fingerprint", activeFingerprint)
|
||||
putExtra("client_ids", activeClientIds)
|
||||
putExtra("obfs_mode", obfsMode)
|
||||
putExtra("turn_transport", turnTransport)
|
||||
putExtra("generation_id", generationId)
|
||||
putExtra("session_salt", salt)
|
||||
}
|
||||
|
||||
fun startTunnelService() {
|
||||
scope.launch {
|
||||
val source = resolveConnectionSource(settingsStore) ?: run {
|
||||
context.showRaisedToast("Заполните настройки подключения", Toast.LENGTH_SHORT)
|
||||
return@launch
|
||||
}
|
||||
TunnelManager.isLoggingEnabled = settingsStore.loggingEnabled.first()
|
||||
val nextGen = System.currentTimeMillis() / 1000L
|
||||
val salt = newTunnelSessionId()
|
||||
val intent = startIntent(source, nextGen, salt)
|
||||
runCatching { context.startForegroundService(intent) }
|
||||
.onFailure { error ->
|
||||
TunnelManager.updateLog(
|
||||
"foreground_request_error",
|
||||
"Android заблокировал запуск VPN: ${error.message ?: error.javaClass.simpleName}",
|
||||
99,
|
||||
true,
|
||||
)
|
||||
Toast.makeText(
|
||||
context,
|
||||
"Android заблокировал запуск VPN. Проверьте ограничения батареи приложения.",
|
||||
Toast.LENGTH_LONG,
|
||||
).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val vpnPermissionLauncher = rememberLauncherForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult()
|
||||
) {
|
||||
if (pendingStartAfterVpnPermission) {
|
||||
pendingStartAfterVpnPermission = false
|
||||
if (VpnService.prepare(context) == null) {
|
||||
startTunnelService()
|
||||
} else {
|
||||
context.showRaisedToast("VPN-разрешение не выдано", Toast.LENGTH_SHORT)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun toggleTunnel() {
|
||||
if (tunnelRunning || tunnelStarting || autoPausedForWifi) {
|
||||
context.startService(Intent(context, TunnelService::class.java).apply { action = "STOP" })
|
||||
return
|
||||
}
|
||||
if (!isValid) {
|
||||
val blocker = requireNotNull(startBlocker)
|
||||
TunnelManager.updateLog(
|
||||
"connection_configuration_${blocker.name}",
|
||||
"[ПОДКЛЮЧЕНИЕ] Запуск не начат: ${blocker.message}",
|
||||
99,
|
||||
true,
|
||||
)
|
||||
if (blocker == ConnectionStartBlocker.StoredSecret) {
|
||||
scope.launch {
|
||||
val reset = settingsStore.resetUnreadableConnectionPassword()
|
||||
if (reset) {
|
||||
context.showRaisedToast(
|
||||
"Сохранённый пароль сброшен. Введите его заново в разделе «Авторизация».",
|
||||
Toast.LENGTH_LONG,
|
||||
)
|
||||
}
|
||||
onInvalidConfiguration()
|
||||
}
|
||||
return
|
||||
}
|
||||
onInvalidConfiguration()
|
||||
return
|
||||
}
|
||||
val vpnIntent = VpnService.prepare(context)
|
||||
if (vpnIntent != null) {
|
||||
pendingStartAfterVpnPermission = true
|
||||
vpnPermissionLauncher.launch(vpnIntent)
|
||||
} else {
|
||||
startTunnelService()
|
||||
}
|
||||
}
|
||||
|
||||
CsqttScreen {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f)
|
||||
.padding(bottom = 16.dp)
|
||||
.offset(y = 10.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
TunnelConnectionPanel(
|
||||
tunnelRunning = tunnelRunning,
|
||||
tunnelStarting = tunnelStarting,
|
||||
tunnelStopping = tunnelStopping,
|
||||
autoPausedForWifi = autoPausedForWifi,
|
||||
cooldownActive = cooldownActive,
|
||||
configurationValid = isValid,
|
||||
obfsMode = obfsMode,
|
||||
hashStatus = hashStatus,
|
||||
workMode = workModeDisplayName(vkAuthMode),
|
||||
onToggleTunnel = { toggleTunnel() },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TunnelConnectionPanel(
|
||||
tunnelRunning: Boolean,
|
||||
tunnelStarting: Boolean,
|
||||
tunnelStopping: Boolean,
|
||||
autoPausedForWifi: Boolean,
|
||||
cooldownActive: Boolean,
|
||||
configurationValid: Boolean,
|
||||
obfsMode: String,
|
||||
hashStatus: String,
|
||||
workMode: String,
|
||||
onToggleTunnel: () -> Unit,
|
||||
) {
|
||||
val isStarting = tunnelStarting && !tunnelRunning && !tunnelStopping
|
||||
val canToggle = !tunnelStopping && (tunnelRunning || isStarting || autoPausedForWifi || !cooldownActive || !configurationValid)
|
||||
val activeVisual = tunnelRunning || isStarting || autoPausedForWifi || tunnelStopping
|
||||
val logoScale = if (activeVisual) 1.06f else 0.96f
|
||||
val statusColor = when {
|
||||
autoPausedForWifi -> MaterialTheme.colorScheme.tertiary
|
||||
tunnelStopping -> MaterialTheme.colorScheme.tertiary
|
||||
tunnelRunning -> MaterialTheme.colorScheme.primary
|
||||
isStarting -> MaterialTheme.colorScheme.primary
|
||||
cooldownActive -> MaterialTheme.colorScheme.tertiary
|
||||
else -> MaterialTheme.colorScheme.onSurfaceVariant
|
||||
}
|
||||
val statusText = when {
|
||||
autoPausedForWifi -> "Ожидание. Автопауза при Wi-Fi"
|
||||
tunnelStopping -> "Ожидание"
|
||||
tunnelRunning -> "Подключено"
|
||||
isStarting -> "Подключение"
|
||||
cooldownActive -> "Ожидание"
|
||||
else -> "Отключено"
|
||||
}
|
||||
|
||||
AppSectionCard(
|
||||
contentPadding = PaddingValues(horizontal = 20.dp, vertical = 20.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
Image(
|
||||
painter = painterResource(id = R.drawable.ic_c_logo),
|
||||
contentDescription = when {
|
||||
tunnelStopping -> "Ожидание отключения VPN"
|
||||
tunnelRunning || autoPausedForWifi -> "Остановить VPN"
|
||||
else -> "Включить VPN"
|
||||
},
|
||||
modifier = Modifier
|
||||
.size(172.dp)
|
||||
.clip(CsqttShapes.Pill)
|
||||
.clickable(
|
||||
enabled = canToggle,
|
||||
onClick = onToggleTunnel,
|
||||
)
|
||||
.scale(logoScale),
|
||||
colorFilter = if (activeVisual) {
|
||||
null
|
||||
} else {
|
||||
ColorFilter.colorMatrix(ColorMatrix().apply { setToSaturation(0f) })
|
||||
},
|
||||
alpha = when {
|
||||
activeVisual -> 1f
|
||||
canToggle -> 0.66f
|
||||
else -> 0.34f
|
||||
},
|
||||
)
|
||||
|
||||
Text(
|
||||
text = statusText,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = statusColor,
|
||||
textAlign = TextAlign.Center,
|
||||
)
|
||||
|
||||
TunnelUptimeText(tunnelRunning = tunnelRunning || autoPausedForWifi || tunnelStopping)
|
||||
|
||||
TunnelConnectionStatusPanel(
|
||||
obfs = obfsDisplayName(obfsMode),
|
||||
hashStatus = hashStatus,
|
||||
workMode = workMode,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TunnelUptimeText(tunnelRunning: Boolean) {
|
||||
val uptimeSeconds by TunnelManager.uptimeSeconds.collectAsStateWithLifecycle()
|
||||
Text(
|
||||
text = formatTunnelUptime(uptimeSeconds),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = if (tunnelRunning) {
|
||||
MaterialTheme.colorScheme.primary
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.70f)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TunnelConnectionStatusPanel(
|
||||
obfs: String,
|
||||
hashStatus: String,
|
||||
workMode: String,
|
||||
) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Control,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline.copy(alpha = 0.28f)),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(IntrinsicSize.Min)
|
||||
.padding(horizontal = 4.dp, vertical = 2.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
ConnectionStatusItem(
|
||||
title = "Маскировка",
|
||||
value = obfs,
|
||||
modifier = Modifier.weight(1f).padding(horizontal = 5.dp, vertical = 8.dp),
|
||||
)
|
||||
ConnectionStatusDivider()
|
||||
ConnectionStatusItem(
|
||||
title = "Хеши",
|
||||
value = hashStatus,
|
||||
modifier = Modifier.weight(1f).padding(horizontal = 5.dp, vertical = 8.dp),
|
||||
)
|
||||
ConnectionStatusDivider()
|
||||
ConnectionStatusItem(
|
||||
title = "Режим кредов",
|
||||
value = workMode,
|
||||
modifier = Modifier.weight(1f).padding(horizontal = 5.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ConnectionStatusItem(
|
||||
title: String,
|
||||
value: String,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier,
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = TextAlign.Center,
|
||||
maxLines = 1,
|
||||
softWrap = false,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
Text(
|
||||
text = value,
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.80f),
|
||||
textAlign = TextAlign.Center,
|
||||
maxLines = 1,
|
||||
softWrap = false,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ConnectionStatusDivider() {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxHeight()
|
||||
.width(1.dp)
|
||||
.background(MaterialTheme.colorScheme.onSurface.copy(alpha = 0.12f)),
|
||||
)
|
||||
}
|
||||
|
||||
private fun obfsDisplayName(mode: String): String = when (mode) {
|
||||
"audio" -> "Простая"
|
||||
"video" -> "Средняя"
|
||||
else -> mode.ifBlank { "Средняя" }
|
||||
}
|
||||
|
||||
private fun workModeDisplayName(mode: String): String = when (mode) {
|
||||
CsqttConstants.VkAuth.MODE_CAPTCHA -> "Капча"
|
||||
CsqttConstants.VkAuth.MODE_AUTO_JS -> "Авто ВК"
|
||||
else -> "Авто"
|
||||
}
|
||||
|
||||
private fun formatTunnelUptime(seconds: Long?): String {
|
||||
val totalSeconds = seconds?.coerceAtLeast(0L) ?: 0L
|
||||
val hours = totalSeconds / 3600
|
||||
val minutes = (totalSeconds % 3600) / 60
|
||||
val sec = totalSeconds % 60
|
||||
return String.format(Locale.US, "%02d:%02d:%02d", hours, minutes, sec)
|
||||
}
|
||||
|
||||
private fun formatMillis(value: Double): String = when {
|
||||
value < 0.05 -> "wall 0 мс"
|
||||
value < 10.0 -> String.format(Locale.US, "wall %.1f мс", value)
|
||||
else -> String.format(Locale.US, "wall %.0f мс", value)
|
||||
}
|
||||
|
||||
private fun formatRate(value: Double): String = when {
|
||||
value < 0.05 -> "0/с"
|
||||
value < 10.0 -> String.format(Locale.US, "%.1f/с", value)
|
||||
else -> String.format(Locale.US, "%.0f/с", value)
|
||||
}
|
||||
@@ -0,0 +1,753 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import android.content.Context
|
||||
import com.csqtt.client.CsqttConstants
|
||||
import com.csqtt.client.DeployManager
|
||||
import com.csqtt.client.TunnelManager
|
||||
import net.schmizz.sshj.SSHClient as SshjClient
|
||||
import net.schmizz.sshj.xfer.FileSystemFile
|
||||
import net.schmizz.sshj.transport.verification.PromiscuousVerifier
|
||||
import net.schmizz.sshj.userauth.UserAuthException
|
||||
import net.schmizz.sshj.userauth.method.AuthKeyboardInteractive
|
||||
import net.schmizz.sshj.userauth.method.PasswordResponseProvider
|
||||
import net.schmizz.sshj.userauth.password.PasswordUtils
|
||||
import org.bouncycastle.jce.provider.BouncyCastleProvider
|
||||
import java.io.File
|
||||
import java.io.FileOutputStream
|
||||
import java.io.IOException
|
||||
import java.security.Security
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.json.JSONObject
|
||||
|
||||
private const val CMD_TIMEOUT = CsqttConstants.Timeouts.DEPLOY_CMD_TIMEOUT_MS
|
||||
private const val SFTP_UPLOAD_ATTEMPTS = 2
|
||||
private const val UPLOAD_RECONNECT_ATTEMPTS = 1
|
||||
|
||||
/**
|
||||
* SSH passwords are protocol data, not shell text. Spaces and punctuation are
|
||||
* valid and must arrive at SSHJ unchanged; only pasted line breaks are removed
|
||||
* because neither password SSH nor sudo can represent them as one prompt.
|
||||
*/
|
||||
internal fun sanitizeSshPassword(value: String): String =
|
||||
value.replace("\r", "").replace("\n", "")
|
||||
|
||||
internal fun isSuccessfulDeployResult(exitStatus: Int, output: String): Boolean =
|
||||
exitStatus == 0 && output.lineSequence().any { it.trim() == "CSQTT_DEPLOY_OK" }
|
||||
|
||||
private fun deployFailureDetail(output: String): String? =
|
||||
output.lineSequence()
|
||||
.map(String::trim)
|
||||
.lastOrNull { it.startsWith("CSQTT_DEPLOY_ERROR|") }
|
||||
?.split("|", limit = 3)
|
||||
?.getOrNull(2)
|
||||
?.trim()
|
||||
?.takeIf(String::isNotEmpty)
|
||||
?.take(360)
|
||||
|
||||
internal fun deployFailureMessage(exitStatus: Int, output: String): String {
|
||||
val detail = deployFailureDetail(output)
|
||||
fun withDetail(message: String): String =
|
||||
if (detail == null) message else "$message Причина: $detail"
|
||||
|
||||
return when {
|
||||
output.lineSequence().any { it.trim() == "CSQTT_DEPLOY_ROLLED_BACK" } || exitStatus == 30 ->
|
||||
withDetail("Новый релиз не прошёл проверку; предыдущая установка восстановлена")
|
||||
output.lineSequence().any { it.trim() == "CSQTT_DEPLOY_ROLLBACK_FAILED" } || exitStatus == 31 ->
|
||||
withDetail("Новый релиз не запустился, а автоматический rollback завершился с ошибкой — требуется проверка VPS")
|
||||
exitStatus == 20 ->
|
||||
withDetail("Кандидат не прошёл предзапусковую проверку; работающий сервер не останавливался")
|
||||
exitStatus == 2 ->
|
||||
withDetail("Установщик отклонил параметры развёртывания")
|
||||
else ->
|
||||
detail ?: "Установщик завершился с кодом $exitStatus; подробности сохранены в errors.log"
|
||||
}
|
||||
}
|
||||
|
||||
internal fun friendlyDeployError(message: String?): String {
|
||||
val text = message.orEmpty()
|
||||
return when {
|
||||
text.contains("Auth fail (public key)", ignoreCase = true) ||
|
||||
text.contains("Auth fail (key parse)", ignoreCase = true) ->
|
||||
"SSH: Auth fail — ключ не принят сервером. Проверьте: 1) приватный ключ вставлен целиком (-----BEGIN...-----END), 2) публичный ключ добавлен в authorized_keys на VPS, 3) логин верный"
|
||||
text.contains("Auth fail", ignoreCase = true) ->
|
||||
"SSH-аутентификация отклонена: проверьте логин, пароль и разрешение PasswordAuthentication на VPS"
|
||||
text.contains("authentication", ignoreCase = true) ->
|
||||
"SSH-аутентификация отклонена: проверьте логин, пароль и разрешение PasswordAuthentication на VPS"
|
||||
text.contains("SFTP/SCP upload failed", ignoreCase = true) ->
|
||||
"Загрузка на VPS оборвалась даже после автоматического переподключения SSH; проверьте стабильность Wi-Fi и подробную причину в errors.log"
|
||||
text.contains("reject HostKey", ignoreCase = true) ||
|
||||
text.contains("HostKey", ignoreCase = true) ||
|
||||
text.contains("host key", ignoreCase = true) ->
|
||||
"SSH-ключ сервера изменился или не принят"
|
||||
text.contains("timeout", ignoreCase = true) ->
|
||||
"Истекло время ожидания SSH/SFTP"
|
||||
text.contains("UnknownHost", ignoreCase = true) ||
|
||||
text.contains("No route to host", ignoreCase = true) ->
|
||||
"VPS недоступен по указанному адресу"
|
||||
text.contains("session is down", ignoreCase = true) ||
|
||||
text.contains("connection is closed", ignoreCase = true) ->
|
||||
"SSH-соединение было разорвано"
|
||||
text.contains("Connection refused", ignoreCase = true) ->
|
||||
"SSH: соединение отклонено — проверьте порт и доступность VPS"
|
||||
text.isBlank() -> "Неизвестная ошибка установки"
|
||||
else -> text.take(240)
|
||||
}
|
||||
}
|
||||
|
||||
internal enum class DeployOutputLevel { LOG, OK, ERR }
|
||||
|
||||
internal data class DeployOutputLine(
|
||||
val message: String,
|
||||
val level: DeployOutputLevel,
|
||||
)
|
||||
|
||||
private val ANSI_ESCAPE = Regex("\u001B\\[[;\\d]*m")
|
||||
private val DEPLOY_SYMBOLS = Regex("[\\p{So}\\p{Sk}\\uFE0F\\u200D]")
|
||||
private val DEPLOY_STATUS_PREFIX = Regex("^\\[(?:OK|ERR|LOG|WARN|✓|!|✗|►)]\\s*", RegexOption.IGNORE_CASE)
|
||||
|
||||
internal fun parseDeployOutputLine(rawLine: String): DeployOutputLine? {
|
||||
val raw = rawLine.replace(ANSI_ESCAPE, "").trim()
|
||||
if (
|
||||
raw.isEmpty() ||
|
||||
raw.startsWith("CSQTT_PROGRESS|") ||
|
||||
raw.startsWith("CSQTT_DEPLOY_ERROR|") ||
|
||||
raw == "CSQTT_DEPLOY_OK" ||
|
||||
raw == "CSQTT_DEPLOY_ROLLED_BACK" ||
|
||||
raw == "CSQTT_DEPLOY_ROLLBACK_FAILED"
|
||||
) return null
|
||||
|
||||
val warning = raw.startsWith("[WARN]", ignoreCase = true) || raw.startsWith("[!]") || raw.startsWith("⚠")
|
||||
val explicitError = raw.startsWith("[ERR]", ignoreCase = true) || raw.startsWith("[✗]") || raw.startsWith("✗")
|
||||
val success = raw.startsWith("[OK]", ignoreCase = true) || raw.startsWith("[✓]") || raw.startsWith("✓")
|
||||
val lower = raw.lowercase()
|
||||
val looksLikeError = explicitError || (!warning && (
|
||||
lower.contains("error:") ||
|
||||
lower.contains("failed") ||
|
||||
lower.contains("fatal") ||
|
||||
lower.contains("не запуст") ||
|
||||
lower.contains("ошибка")
|
||||
))
|
||||
|
||||
var clean = raw
|
||||
.replace(DEPLOY_STATUS_PREFIX, "")
|
||||
.replace(DEPLOY_SYMBOLS, "")
|
||||
.trim { it.isWhitespace() || it in "═║╔╗╚╝─━" }
|
||||
.replace(Regex("\\s+"), " ")
|
||||
.trim()
|
||||
if (clean.isEmpty() || clean.all { it == '=' || it == '-' || it == '_' }) return null
|
||||
if (warning && !clean.startsWith("Предупреждение:", ignoreCase = true)) {
|
||||
clean = "Предупреждение: $clean"
|
||||
}
|
||||
|
||||
val level = when {
|
||||
looksLikeError -> DeployOutputLevel.ERR
|
||||
success -> DeployOutputLevel.OK
|
||||
else -> DeployOutputLevel.LOG
|
||||
}
|
||||
return DeployOutputLine(clean.take(500), level)
|
||||
}
|
||||
|
||||
private fun publishDeployOutput(rawLine: String) {
|
||||
val line = parseDeployOutputLine(rawLine) ?: return
|
||||
when (line.level) {
|
||||
DeployOutputLevel.LOG -> TunnelManager.addDeployInfoLog(line.message)
|
||||
DeployOutputLevel.OK -> TunnelManager.addDeploySuccessLog(line.message)
|
||||
DeployOutputLevel.ERR -> TunnelManager.addDeployErrorLog(line.message)
|
||||
}
|
||||
}
|
||||
|
||||
internal enum class ServerArchitecture(
|
||||
val assetName: String,
|
||||
val displayName: String,
|
||||
) {
|
||||
AMD64("csqtt-linux-amd64", "amd64"),
|
||||
ARM64("csqtt-linux-arm64", "ARM64"),
|
||||
ARMV7("csqtt-linux-armv7", "ARM32"),
|
||||
}
|
||||
|
||||
internal fun serverArchitectureForMachine(output: String): ServerArchitecture {
|
||||
val machine = output.lineSequence().map(String::trim).firstOrNull { it.isNotEmpty() }
|
||||
?.lowercase(Locale.ROOT)
|
||||
?: throw IOException("VPS не вернул архитектуру через uname -m")
|
||||
return when (machine) {
|
||||
"x86_64", "amd64" -> ServerArchitecture.AMD64
|
||||
"aarch64", "arm64" -> ServerArchitecture.ARM64
|
||||
"armv7l", "armv7", "armhf" -> ServerArchitecture.ARMV7
|
||||
else -> throw IOException(
|
||||
"Архитектура VPS $machine пока не поддерживается. Поддерживаются: x86_64, aarch64, armv7l",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun deployAssetLabel(fileName: String): String = when (fileName) {
|
||||
"deploy.sh" -> "скрипт установки"
|
||||
"csqtt-linux-amd64" -> "сервер CSQTT (amd64)"
|
||||
"csqtt-linux-arm64" -> "сервер CSQTT (ARM64)"
|
||||
"csqtt-linux-armv7" -> "сервер CSQTT (ARM32)"
|
||||
"csqtt.env" -> "настройки веб-панели"
|
||||
"csqtt-deploy.json" -> "настройки доступа"
|
||||
"hev-socks5-tunnel" -> "C-движок туннеля"
|
||||
else -> fileName
|
||||
}
|
||||
|
||||
private fun readableFileSize(bytes: Long): String = when {
|
||||
bytes >= 1024L * 1024L -> String.format(java.util.Locale.US, "%.1f МБ", bytes / (1024.0 * 1024.0))
|
||||
bytes >= 1024L -> String.format(java.util.Locale.US, "%.1f КБ", bytes / 1024.0)
|
||||
else -> "$bytes Б"
|
||||
}
|
||||
|
||||
private data class SSHExecResult(val output: String, val exitStatus: Int)
|
||||
|
||||
private class DeploySSHClient(
|
||||
private var ssh: SshjClient,
|
||||
private val sudoPass: String,
|
||||
private val reconnect: ((String) -> SshjClient)? = null,
|
||||
) {
|
||||
|
||||
private fun reconnectFor(stage: String): Boolean {
|
||||
val factory = reconnect ?: return false
|
||||
return try {
|
||||
runCatching { ssh.disconnect() }
|
||||
TunnelManager.addDeployInfoLog("SSH-соединение восстановление: $stage")
|
||||
ssh = factory(stage)
|
||||
DeployManager.activeSession = ssh
|
||||
TunnelManager.addDeploySuccessLog("SSH-соединение восстановлено")
|
||||
true
|
||||
} catch (error: Exception) {
|
||||
DeployManager.writeError(
|
||||
"SSH reconnect failed during $stage (${error.javaClass.simpleName}): ${error.message}",
|
||||
)
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun ensureConnected(stage: String): Boolean =
|
||||
ssh.isConnected || reconnectFor(stage)
|
||||
|
||||
fun exec(command: String, timeout: Long = CMD_TIMEOUT): String =
|
||||
execResult(command, timeout).output
|
||||
|
||||
fun execResult(command: String, timeout: Long = CMD_TIMEOUT): SSHExecResult {
|
||||
if (!ensureConnected("команда")) {
|
||||
DeployManager.writeError("SSH exec: клиент отключён перед командой: ${command.take(80)}")
|
||||
return SSHExecResult("error: session is down", -1)
|
||||
}
|
||||
|
||||
val result = StringBuilder()
|
||||
val progressRegex = Regex("^CSQTT_PROGRESS\\|(\\d+\\.?\\d*)\\|(.+)$")
|
||||
val cmdAdjusted = if (command.contains("sudo") && !command.contains("sudo -S")) {
|
||||
command.replace("sudo ", "sudo -S ")
|
||||
} else command
|
||||
|
||||
val sshSession = ssh.startSession()
|
||||
return try {
|
||||
val remoteCmd = sshSession.exec(cmdAdjusted)
|
||||
|
||||
if (cmdAdjusted.contains("sudo -S")) {
|
||||
runCatching {
|
||||
remoteCmd.outputStream.write("$sudoPass\n".toByteArray())
|
||||
remoteCmd.outputStream.flush()
|
||||
}
|
||||
}
|
||||
|
||||
val stdoutDone = CountDownLatch(1)
|
||||
val stderrDone = CountDownLatch(1)
|
||||
|
||||
val stdoutThread = Thread({
|
||||
try {
|
||||
remoteCmd.inputStream.bufferedReader().forEachLine { line ->
|
||||
val clean = line.replace(ANSI_ESCAPE, "")
|
||||
val match = progressRegex.find(clean.trim())
|
||||
when {
|
||||
match != null -> {
|
||||
val p = match.groupValues[1].toFloatOrNull() ?: 0f
|
||||
val step = match.groupValues[2].trim()
|
||||
DeployManager.updateProgress(p, step)
|
||||
TunnelManager.addDeployInfoLog("Этап: $step")
|
||||
}
|
||||
!clean.contains("CSQTT_PROGRESS") -> {
|
||||
synchronized(result) { result.appendLine(clean) }
|
||||
publishDeployOutput(clean)
|
||||
val parsed = parseDeployOutputLine(clean)
|
||||
if (parsed?.level == DeployOutputLevel.ERR) {
|
||||
DeployManager.writeError("REMOTE: $clean")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) {}
|
||||
stdoutDone.countDown()
|
||||
}, "deploy-stdout")
|
||||
stdoutThread.isDaemon = true
|
||||
stdoutThread.start()
|
||||
|
||||
val stderrThread = Thread({
|
||||
try {
|
||||
remoteCmd.errorStream.bufferedReader().forEachLine { line ->
|
||||
if (!line.contains("password for")) {
|
||||
val clean = line.replace(ANSI_ESCAPE, "")
|
||||
if (clean.isNotBlank() && !isBenignStderr(clean)) {
|
||||
synchronized(result) { result.appendLine(clean) }
|
||||
DeployManager.writeError("STDERR: $clean")
|
||||
val display = parseDeployOutputLine(clean)?.message ?: clean.trim().take(500)
|
||||
TunnelManager.addDeployErrorLog("Сервер: $display")
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_: Exception) {}
|
||||
stderrDone.countDown()
|
||||
}, "deploy-stderr")
|
||||
stderrThread.isDaemon = true
|
||||
stderrThread.start()
|
||||
|
||||
val finished = stdoutDone.await(timeout, TimeUnit.MILLISECONDS)
|
||||
stderrDone.await(2, TimeUnit.SECONDS)
|
||||
|
||||
if (!finished) {
|
||||
DeployManager.writeError("SSH timeout (${timeout / 1000}s): ${command.take(80)}")
|
||||
return SSHExecResult("error: timeout", -1)
|
||||
}
|
||||
|
||||
remoteCmd.join(3, TimeUnit.SECONDS)
|
||||
SSHExecResult(result.toString(), remoteCmd.exitStatus ?: -1)
|
||||
} catch (e: Exception) {
|
||||
DeployManager.writeError("SSH exec error: ${e.message} | cmd: ${command.take(80)}")
|
||||
TunnelManager.addDeployErrorLog("SSH exec error: ${e.message}")
|
||||
SSHExecResult("error: ${e.message}", -1)
|
||||
} finally {
|
||||
runCatching { sshSession.close() }
|
||||
}
|
||||
}
|
||||
|
||||
fun upload(localFile: File, remotePath: String) {
|
||||
uploadInternal(localFile, remotePath, UPLOAD_RECONNECT_ATTEMPTS)
|
||||
}
|
||||
|
||||
private fun uploadInternal(localFile: File, remotePath: String, reconnectsLeft: Int) {
|
||||
if (!localFile.isFile || !localFile.canRead()) {
|
||||
throw IOException("Local deploy file is unavailable: ${localFile.name}")
|
||||
}
|
||||
if (!ensureConnected("загрузка ${deployAssetLabel(localFile.name)}")) {
|
||||
throw IOException("SSH client disconnected before upload: ${localFile.name}")
|
||||
}
|
||||
|
||||
val label = deployAssetLabel(localFile.name)
|
||||
TunnelManager.addDeployInfoLog("Загрузка: $label (${readableFileSize(localFile.length())})")
|
||||
var sftpSuccess = false
|
||||
var lastError = "SFTP channel did not accept the file"
|
||||
repeat(SFTP_UPLOAD_ATTEMPTS) { attempt ->
|
||||
try {
|
||||
ssh.newSFTPClient().use { sftp ->
|
||||
sftp.put(FileSystemFile(localFile), remotePath)
|
||||
val remoteSize = sftp.lstat(remotePath).size
|
||||
if (remoteSize == localFile.length()) {
|
||||
TunnelManager.addDeploySuccessLog("Загружено: $label")
|
||||
sftpSuccess = true
|
||||
return
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
lastError = "SFTP: ${e.message ?: e.javaClass.simpleName}"
|
||||
DeployManager.writeError(
|
||||
"SFTP upload attempt ${attempt + 1}/$SFTP_UPLOAD_ATTEMPTS failed: " +
|
||||
"${e.message} | file: ${localFile.name}"
|
||||
)
|
||||
if (attempt + 1 < SFTP_UPLOAD_ATTEMPTS && ssh.isConnected) {
|
||||
Thread.sleep(500)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!sftpSuccess && ssh.isConnected) {
|
||||
try {
|
||||
DeployManager.writeError("Falling back to SCP for ${localFile.name}...")
|
||||
ssh.newSCPFileTransfer().upload(FileSystemFile(localFile), remotePath)
|
||||
TunnelManager.addDeploySuccessLog("Загружено (SCP): $label")
|
||||
return
|
||||
} catch (e: Exception) {
|
||||
lastError = "SCP: ${e.message ?: e.javaClass.simpleName}"
|
||||
DeployManager.writeError("SCP upload failed: ${e.message} | file: ${localFile.name}")
|
||||
}
|
||||
}
|
||||
|
||||
if (ssh.isConnected) {
|
||||
try {
|
||||
DeployManager.writeError("Falling back to chunked stream upload for ${localFile.name}...")
|
||||
val tempRemote = "$remotePath.tmp"
|
||||
execResult(rootCommand("rm -f '$tempRemote'"), 30000L)
|
||||
localFile.inputStream().buffered(64 * 1024).use { inputStream ->
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
var bytesRead: Int
|
||||
var totalUploaded = 0L
|
||||
val totalLength = localFile.length()
|
||||
while (inputStream.read(buffer).also { bytesRead = it } != -1) {
|
||||
val chunk = if (bytesRead == buffer.size) buffer else buffer.copyOf(bytesRead)
|
||||
val base64 = android.util.Base64.encodeToString(chunk, android.util.Base64.NO_WRAP)
|
||||
val cmd = "printf '%s' '$base64' | base64 -d >> '$tempRemote'"
|
||||
val res = execResult(rootCommand(cmd), 60000L)
|
||||
if (res.exitStatus != 0) {
|
||||
throw IOException("Chunk upload failed at offset $totalUploaded")
|
||||
}
|
||||
totalUploaded += bytesRead
|
||||
val percent = (totalUploaded.toFloat() / totalLength.toFloat().coerceAtLeast(1f)).coerceIn(0f, 1f)
|
||||
DeployManager.updateProgress(percent * 0.5f, "Загрузка: $label (${(percent * 100).toInt()}%)")
|
||||
}
|
||||
}
|
||||
val moveRes = execResult(rootCommand("mv -f '$tempRemote' '$remotePath' && chmod 0755 '$remotePath'"), 30000L)
|
||||
if (moveRes.exitStatus == 0) {
|
||||
TunnelManager.addDeploySuccessLog("Загружено (Stream): $label")
|
||||
return
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
lastError = "stream: ${e.message ?: e.javaClass.simpleName}"
|
||||
DeployManager.writeError("Stream upload failed: ${e.message} | file: ${localFile.name}")
|
||||
}
|
||||
}
|
||||
|
||||
if (reconnectsLeft > 0 && reconnectFor("повторная загрузка $label")) {
|
||||
uploadInternal(localFile, remotePath, reconnectsLeft - 1)
|
||||
return
|
||||
}
|
||||
|
||||
val message = "SFTP/SCP upload failed for ${localFile.name}: $lastError"
|
||||
TunnelManager.addDeployErrorLog("Не удалось загрузить $label: $lastError")
|
||||
throw IOException(message)
|
||||
}
|
||||
}
|
||||
|
||||
private val bcInitialized = AtomicBoolean(false)
|
||||
|
||||
private fun ensureBouncyCastle() {
|
||||
if (bcInitialized.compareAndSet(false, true)) {
|
||||
Security.removeProvider("BC")
|
||||
Security.insertProviderAt(BouncyCastleProvider(), 1)
|
||||
}
|
||||
}
|
||||
|
||||
private fun createSSHClient(
|
||||
host: String,
|
||||
user: String,
|
||||
pass: String,
|
||||
port: Int = 22,
|
||||
privateKey: String = "",
|
||||
keyPassphrase: String = "",
|
||||
): SshjClient {
|
||||
require(host.isNotBlank()) { "SSH host is empty" }
|
||||
require(user.isNotBlank()) { "SSH login is empty" }
|
||||
val keysMode = privateKey.isNotBlank()
|
||||
require(keysMode || pass.isNotEmpty()) { "SSH password is empty" }
|
||||
require(port in 1..65535) { "Invalid SSH port: $port" }
|
||||
|
||||
ensureBouncyCastle()
|
||||
val ssh = SshjClient()
|
||||
ssh.connectTimeout = 30000
|
||||
ssh.timeout = 300000
|
||||
ssh.addHostKeyVerifier(PromiscuousVerifier())
|
||||
|
||||
try {
|
||||
ssh.connect(host, port)
|
||||
runCatching { ssh.connection.keepAlive.keepAliveInterval = 10 }
|
||||
} catch (e: Exception) {
|
||||
DeployManager.writeError("SSH connect failed (${e.javaClass.simpleName}): ${e.message}")
|
||||
throw e
|
||||
}
|
||||
|
||||
if (keysMode) {
|
||||
try {
|
||||
DeployManager.writeError("SSH key mode: key=${privateKey.length}b, passphrase=${keyPassphrase.isNotBlank()}")
|
||||
val passwordFinder = if (keyPassphrase.isNotBlank()) {
|
||||
PasswordUtils.createOneOff(keyPassphrase.toCharArray())
|
||||
} else {
|
||||
null
|
||||
}
|
||||
val keyProvider = ssh.loadKeys(privateKey, null, passwordFinder)
|
||||
ssh.authPublickey(user, keyProvider)
|
||||
} catch (e: UserAuthException) {
|
||||
DeployManager.writeError("SSH pubkey auth failed: ${e.message}")
|
||||
throw IOException("Auth fail (public key): ${e.message}", e)
|
||||
} catch (e: IOException) {
|
||||
DeployManager.writeError("SSH key parse error: ${e.message}")
|
||||
throw IOException("Auth fail (key parse): ${e.message}", e)
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
// `authPassword` carries the exact Kotlin String to SSHJ, which
|
||||
// is important for passwords containing spaces or punctuation.
|
||||
ssh.authPassword(user, pass)
|
||||
} catch (passwordError: UserAuthException) {
|
||||
try {
|
||||
// Some hosting panels expose password auth only through the
|
||||
// keyboard-interactive method. Use a fresh character array;
|
||||
// a one-off provider may consume its input while answering.
|
||||
ssh.auth(
|
||||
user,
|
||||
listOf(
|
||||
AuthKeyboardInteractive(
|
||||
PasswordResponseProvider(
|
||||
PasswordUtils.createOneOff(pass.toCharArray()),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
} catch (keyboardError: UserAuthException) {
|
||||
DeployManager.writeError(
|
||||
"SSH password auth failed: password=${passwordError.message}; " +
|
||||
"keyboard-interactive=${keyboardError.message}",
|
||||
)
|
||||
throw IOException("Auth fail (password): ${keyboardError.message}", keyboardError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ssh
|
||||
}
|
||||
|
||||
private fun shellQuote(value: String): String {
|
||||
return "'" + value.replace("'", "'\"'\"'") + "'"
|
||||
}
|
||||
|
||||
private fun systemdEnvironmentValue(value: String): String = buildString {
|
||||
append('"')
|
||||
value.forEach { ch ->
|
||||
when (ch) {
|
||||
'\\' -> append("\\\\")
|
||||
'"' -> append("\\\"")
|
||||
'\n', '\r' -> append(' ')
|
||||
else -> append(ch)
|
||||
}
|
||||
}
|
||||
append('"')
|
||||
}
|
||||
|
||||
private fun dockerEnvironmentValue(value: String): String =
|
||||
value.replace('\n', ' ').replace('\r', ' ')
|
||||
|
||||
internal fun deployEnvironmentValue(value: String, installInDocker: Boolean): String =
|
||||
if (installInDocker) dockerEnvironmentValue(value) else systemdEnvironmentValue(value)
|
||||
|
||||
internal fun deployMode(installInDocker: Boolean): String =
|
||||
if (installInDocker) "docker" else "systemd"
|
||||
|
||||
private fun rootCommand(command: String): String {
|
||||
val quoted = shellQuote(command)
|
||||
return "if [ \"\$(id -u)\" = \"0\" ]; then bash -c $quoted; " +
|
||||
"elif command -v sudo >/dev/null 2>&1; then sudo bash -c $quoted; " +
|
||||
"else echo 'error: root privileges required and sudo not found'; exit 1; fi"
|
||||
}
|
||||
|
||||
private val BENIGN_STDERR = Regex(
|
||||
"debconf|dpkg-preconfigure|TERM is not set|falling back to frontend|" +
|
||||
"unable to re-open stdin|controlling tty|unable to initialize frontend|" +
|
||||
"^Warning:|frontend:\\s*(Readline|Teletype|Dialog)",
|
||||
RegexOption.IGNORE_CASE
|
||||
)
|
||||
|
||||
private fun isBenignStderr(line: String): Boolean = BENIGN_STDERR.containsMatchIn(line)
|
||||
|
||||
internal suspend fun performDeploy(
|
||||
context: Context,
|
||||
host: String, user: String, pass: String, port: Int,
|
||||
mainPass: String, webLogin: String, webPass: String,
|
||||
peerPort: Int, webPort: Int,
|
||||
onProgress: (Float, String) -> Unit,
|
||||
privateKey: String = "",
|
||||
keyPassphrase: String = "",
|
||||
certificate: String = "",
|
||||
installInDocker: Boolean = false,
|
||||
): Boolean = withContext(Dispatchers.IO) {
|
||||
var ssh: SshjClient? = null
|
||||
var tempDir: File? = null
|
||||
try {
|
||||
TunnelManager.beginDeployLog("Начало установки на $host:$port")
|
||||
onProgress(0.02f, "Подключение...")
|
||||
|
||||
TunnelManager.addDeployInfoLog("SSH/SFTP используют текущий системный маршрут")
|
||||
TunnelManager.addDeployInfoLog("Подключение к VPS по SSH")
|
||||
val initialSsh = createSSHClient(host, user, pass, port, privateKey, keyPassphrase)
|
||||
ssh = initialSsh
|
||||
DeployManager.activeSession = initialSsh
|
||||
val sshClient = DeploySSHClient(initialSsh, pass) { stage ->
|
||||
TunnelManager.addDeployInfoLog("Повторное SSH-подключение: $stage")
|
||||
createSSHClient(host, user, pass, port, privateKey, keyPassphrase).also {
|
||||
ssh = it
|
||||
}
|
||||
}
|
||||
TunnelManager.addDeploySuccessLog("SSH-соединение установлено")
|
||||
|
||||
val architectureResult = sshClient.execResult("uname -m", timeout = 10000L)
|
||||
if (architectureResult.exitStatus != 0) {
|
||||
throw IOException("Не удалось определить архитектуру VPS: ${architectureResult.output.trim().take(160)}")
|
||||
}
|
||||
val serverArchitecture = serverArchitectureForMachine(architectureResult.output)
|
||||
TunnelManager.addDeployInfoLog("Архитектура VPS: ${serverArchitecture.displayName}")
|
||||
|
||||
onProgress(0.05f, "Подготовка файлов...")
|
||||
TunnelManager.addDeployInfoLog("Подготовка файлов установки")
|
||||
val deviceId = TunnelManager.readDeviceId(context)
|
||||
|
||||
val workingDir = File(context.cacheDir, "deploy-${System.nanoTime()}")
|
||||
tempDir = workingDir
|
||||
if (!workingDir.mkdirs() && !workingDir.isDirectory) {
|
||||
throw IOException("Не удалось создать временный каталог установки")
|
||||
}
|
||||
fun extractAsset(assetName: String): File {
|
||||
val target = File(workingDir, assetName)
|
||||
context.assets.open(assetName).use { input ->
|
||||
FileOutputStream(target).use { output -> input.copyTo(output) }
|
||||
}
|
||||
if (!target.isFile || target.length() == 0L) {
|
||||
throw IOException("Файл $assetName отсутствует или пуст в assets")
|
||||
}
|
||||
return target
|
||||
}
|
||||
|
||||
val scriptFile = extractAsset("deploy.sh")
|
||||
val serverFile = extractAsset(serverArchitecture.assetName)
|
||||
val environmentFile = File(workingDir, "csqtt.env").apply {
|
||||
writeText(
|
||||
buildString {
|
||||
appendLine("CSQTT_WEB_USER=${deployEnvironmentValue(webLogin, installInDocker)}")
|
||||
appendLine("CSQTT_WEB_PASS=${deployEnvironmentValue(webPass, installInDocker)}")
|
||||
}
|
||||
)
|
||||
}
|
||||
val overridesFile = File(workingDir, "csqtt-deploy.json").apply {
|
||||
writeText(
|
||||
JSONObject()
|
||||
.put("main_password", mainPass)
|
||||
.put("device_id", deviceId)
|
||||
.toString()
|
||||
)
|
||||
}
|
||||
TunnelManager.addDeploySuccessLog("Файлы установки подготовлены")
|
||||
|
||||
onProgress(0.06f, "Подготовка сервера...")
|
||||
sshClient.upload(scriptFile, "/tmp/deploy.sh")
|
||||
|
||||
val deployEnvironment =
|
||||
"env CSQTT_PEER_PORT=$peerPort CSQTT_SSH_PORT=$port CSQTT_WEB_PORT=$webPort " +
|
||||
"CSQTT_DEPLOY_MODE=${deployMode(installInDocker)}"
|
||||
onProgress(0.10f, "Загрузка нового сервера...")
|
||||
sshClient.upload(serverFile, "/tmp/.csqtt-upload-server")
|
||||
sshClient.upload(environmentFile, "/tmp/.csqtt-upload-web.env")
|
||||
sshClient.upload(overridesFile, "/tmp/.csqtt-upload-overrides.json")
|
||||
|
||||
onProgress(0.18f, "Установка нового сервера...")
|
||||
TunnelManager.addDeployInfoLog("Запуск установщика на VPS")
|
||||
val deployResult = sshClient.execResult(
|
||||
rootCommand("$deployEnvironment bash /tmp/deploy.sh install"),
|
||||
timeout = CMD_TIMEOUT
|
||||
)
|
||||
val output = deployResult.output
|
||||
|
||||
if (isSuccessfulDeployResult(deployResult.exitStatus, output)) {
|
||||
TunnelManager.addDeploySuccessLog(
|
||||
if (installInDocker) {
|
||||
"Установка завершена · Docker-контейнер CSQTT активен"
|
||||
} else {
|
||||
"Установка завершена · служба CSQTT активна"
|
||||
}
|
||||
)
|
||||
DeployManager.stopDeploy("success")
|
||||
return@withContext true
|
||||
} else {
|
||||
DeployManager.writeError(
|
||||
"Deploy failed: exit=${deployResult.exitStatus}, success marker=${output.contains("CSQTT_DEPLOY_OK")}" +
|
||||
"\n${output.takeLast(1200)}"
|
||||
)
|
||||
val failureMessage = deployFailureMessage(deployResult.exitStatus, output)
|
||||
TunnelManager.addDeployErrorLog(failureMessage)
|
||||
DeployManager.stopDeploy(failureMessage)
|
||||
return@withContext false
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
DeployManager.writeError("Deploy cancelled")
|
||||
TunnelManager.addDeployWarningLog("установка отменена пользователем")
|
||||
DeployManager.stopDeploy("Установка отменена")
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
val friendly = friendlyDeployError(e.message)
|
||||
DeployManager.writeError(
|
||||
"Deploy error (${e.javaClass.simpleName}): ${e.message}\n" +
|
||||
e.stackTraceToString().take(1200)
|
||||
)
|
||||
TunnelManager.addDeployErrorLog(friendly)
|
||||
DeployManager.stopDeploy(friendly)
|
||||
return@withContext false
|
||||
} finally {
|
||||
try { ssh?.disconnect() } catch (_: Exception) {}
|
||||
DeployManager.activeSession = null
|
||||
runCatching { tempDir?.deleteRecursively() }
|
||||
}
|
||||
}
|
||||
|
||||
internal suspend fun performUninstall(
|
||||
context: Context,
|
||||
host: String, user: String, pass: String, port: Int,
|
||||
peerPort: Int,
|
||||
onProgress: (Float, String) -> Unit,
|
||||
privateKey: String = "",
|
||||
keyPassphrase: String = "",
|
||||
certificate: String = "",
|
||||
): Boolean = withContext(Dispatchers.IO) {
|
||||
var ssh: SshjClient? = null
|
||||
var uninstallScript: File? = null
|
||||
try {
|
||||
TunnelManager.beginDeployLog("Начало удаления с $host:$port")
|
||||
onProgress(0.05f, "Подключение...")
|
||||
TunnelManager.addDeployInfoLog("SSH/SFTP используют текущий системный маршрут")
|
||||
TunnelManager.addDeployInfoLog("Подключение к VPS по SSH")
|
||||
ssh = createSSHClient(host, user, pass, port, privateKey, keyPassphrase)
|
||||
DeployManager.activeSession = ssh
|
||||
val sshClient = DeploySSHClient(ssh, pass)
|
||||
TunnelManager.addDeploySuccessLog("SSH-соединение установлено")
|
||||
|
||||
onProgress(0.15f, "Подготовка штатного удаления...")
|
||||
TunnelManager.addDeployInfoLog("Загрузка штатного установщика CSQTT")
|
||||
uninstallScript = File(context.cacheDir, "csqtt-uninstall-${System.nanoTime()}.sh")
|
||||
context.assets.open("deploy.sh").use { input ->
|
||||
FileOutputStream(uninstallScript).use { output -> input.copyTo(output) }
|
||||
}
|
||||
if (!uninstallScript.isFile || uninstallScript.length() == 0L) {
|
||||
throw IOException("Не удалось подготовить штатный установщик CSQTT")
|
||||
}
|
||||
sshClient.upload(uninstallScript, "/tmp/deploy.sh")
|
||||
|
||||
onProgress(0.30f, "Удаление через deploy.sh...")
|
||||
TunnelManager.addDeployInfoLog("Запуск серверного удаления")
|
||||
sshClient.exec(
|
||||
rootCommand("env CSQTT_PEER_PORT=$peerPort CSQTT_SSH_PORT=$port bash /tmp/deploy.sh uninstall"),
|
||||
timeout = 30000L,
|
||||
)
|
||||
|
||||
onProgress(1.0f, "Готово!")
|
||||
TunnelManager.addDeploySuccessLog("Удаление CSQTT завершено")
|
||||
DeployManager.stopDeploy("success")
|
||||
return@withContext true
|
||||
|
||||
} catch (e: CancellationException) {
|
||||
DeployManager.writeError("Uninstall cancelled")
|
||||
TunnelManager.addDeployWarningLog("удаление отменено пользователем")
|
||||
DeployManager.stopDeploy("Удаление отменено")
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
val friendly = friendlyDeployError(e.message)
|
||||
DeployManager.writeError("Uninstall error (${e.javaClass.simpleName}): ${e.message}")
|
||||
TunnelManager.addDeployErrorLog(friendly)
|
||||
DeployManager.stopDeploy(friendly)
|
||||
return@withContext false
|
||||
} finally {
|
||||
try { ssh?.disconnect() } catch (_: Exception) {}
|
||||
DeployManager.activeSession = null
|
||||
uninstallScript?.delete()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import android.content.res.Configuration
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.expandVertically
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.shrinkVertically
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.snap
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Key
|
||||
import androidx.compose.material.icons.outlined.Visibility
|
||||
import androidx.compose.material.icons.outlined.VisibilityOff
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.tooling.preview.Preview
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.csqtt.client.CSQTTTheme
|
||||
import com.csqtt.client.CsqttConstants
|
||||
import com.csqtt.client.R
|
||||
import com.csqtt.client.ui.components.CsqttScreen
|
||||
import com.csqtt.client.ui.components.CsqttSettingRow
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.design.CsqttSizes
|
||||
import com.csqtt.client.ui.design.CsqttSpacing
|
||||
import com.csqtt.client.ui.design.CsqttTheme
|
||||
|
||||
@Composable
|
||||
internal fun DeployScreen(
|
||||
state: DeployUiState,
|
||||
onAction: (DeployAction) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
snackbarHostState: SnackbarHostState = remember { SnackbarHostState() },
|
||||
) {
|
||||
var passwordVisible by rememberSaveable { mutableStateOf(false) }
|
||||
val scrollState = rememberScrollState()
|
||||
|
||||
CsqttScreen(
|
||||
modifier = modifier,
|
||||
) {
|
||||
Box(modifier = Modifier.fillMaxWidth().weight(1f)) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.verticalScroll(scrollState),
|
||||
verticalArrangement = Arrangement.spacedBy(CsqttSpacing.Md),
|
||||
) {
|
||||
AppSectionCard {
|
||||
Text("Деплой и SSH", style = MaterialTheme.typography.titleMedium, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold)
|
||||
if (state.sshKeysMode) {
|
||||
AdaptiveFieldPair(
|
||||
first = {
|
||||
DeployTextField(
|
||||
value = state.host,
|
||||
onValueChange = { onAction(DeployAction.HostChanged(it)) },
|
||||
label = "IP сервера или домен",
|
||||
placeholder = "1.2.3.4",
|
||||
enabled = !state.isDeploying,
|
||||
isError = state.host.isBlank(),
|
||||
keyboardType = KeyboardType.Uri,
|
||||
)
|
||||
},
|
||||
second = {
|
||||
DeployTextField(
|
||||
value = state.sshLogin,
|
||||
onValueChange = { onAction(DeployAction.LoginChanged(it)) },
|
||||
label = "Логин SSH",
|
||||
enabled = !state.isDeploying,
|
||||
isError = state.sshLogin.isBlank(),
|
||||
imeAction = ImeAction.Next,
|
||||
)
|
||||
},
|
||||
)
|
||||
AnimatedVisibility(
|
||||
visible = state.manualPorts,
|
||||
enter = fadeIn() + expandVertically(expandFrom = Alignment.Top),
|
||||
exit = fadeOut() + shrinkVertically(shrinkTowards = Alignment.Top),
|
||||
) {
|
||||
ManualPortFields(state = state, onAction = onAction)
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = { onAction(DeployAction.EditSshKeys) },
|
||||
enabled = !state.isDeploying,
|
||||
modifier = Modifier.fillMaxWidth().height(52.dp),
|
||||
shape = CsqttShapes.Pill,
|
||||
colors = ButtonDefaults.outlinedButtonColors(
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f),
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
border = BorderStroke(
|
||||
1.dp,
|
||||
if (state.sshKeysFilled < 1) MaterialTheme.colorScheme.error
|
||||
else MaterialTheme.colorScheme.outline.copy(alpha = 0.5f),
|
||||
),
|
||||
) {
|
||||
Icon(Icons.Default.Key, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("Ключи SSH ${state.sshKeysFilled}/1", fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold, maxLines = 1)
|
||||
}
|
||||
} else {
|
||||
DeployTextField(
|
||||
value = state.host,
|
||||
onValueChange = { onAction(DeployAction.HostChanged(it)) },
|
||||
label = "IP сервера или домен",
|
||||
placeholder = "1.2.3.4",
|
||||
enabled = !state.isDeploying,
|
||||
isError = state.host.isBlank(),
|
||||
keyboardType = KeyboardType.Uri,
|
||||
)
|
||||
AnimatedVisibility(
|
||||
visible = state.manualPorts,
|
||||
enter = fadeIn() + expandVertically(expandFrom = Alignment.Top),
|
||||
exit = fadeOut() + shrinkVertically(shrinkTowards = Alignment.Top),
|
||||
) {
|
||||
ManualPortFields(state = state, onAction = onAction)
|
||||
}
|
||||
AdaptiveFieldPair(
|
||||
first = {
|
||||
DeployTextField(
|
||||
value = state.sshLogin,
|
||||
onValueChange = { onAction(DeployAction.LoginChanged(it)) },
|
||||
label = "Логин SSH",
|
||||
enabled = !state.isDeploying,
|
||||
isError = state.sshLogin.isBlank(),
|
||||
imeAction = ImeAction.Next,
|
||||
)
|
||||
},
|
||||
second = {
|
||||
DeployTextField(
|
||||
value = state.sshPassword,
|
||||
onValueChange = { onAction(DeployAction.PasswordChanged(it)) },
|
||||
label = "Пароль SSH",
|
||||
enabled = !state.isDeploying,
|
||||
isError = state.sshPassword.isBlank(),
|
||||
keyboardType = KeyboardType.Password,
|
||||
visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
|
||||
trailingContent = {
|
||||
IconButton(onClick = { passwordVisible = !passwordVisible }) {
|
||||
Icon(
|
||||
imageVector = if (passwordVisible) Icons.Outlined.VisibilityOff else Icons.Outlined.Visibility,
|
||||
contentDescription = if (passwordVisible) "Скрыть пароль" else "Показать пароль",
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
Column {
|
||||
CsqttSettingRow(
|
||||
title = "Ключи SSH",
|
||||
checked = state.sshKeysMode,
|
||||
enabled = !state.isDeploying,
|
||||
onCheckedChange = { onAction(DeployAction.SshKeysModeChanged(it)) },
|
||||
)
|
||||
CsqttSettingRow(
|
||||
title = "Ручные порты",
|
||||
checked = state.manualPorts,
|
||||
enabled = !state.isDeploying,
|
||||
onCheckedChange = { onAction(DeployAction.ManualPortsChanged(it)) },
|
||||
)
|
||||
CsqttSettingRow(
|
||||
title = "Установить в Docker",
|
||||
checked = state.dockerInstall,
|
||||
enabled = !state.isDeploying,
|
||||
onCheckedChange = { onAction(DeployAction.DockerInstallChanged(it)) },
|
||||
onInfoClick = { onAction(DeployAction.DockerInfo) },
|
||||
infoContentDescription = "О Docker-установке",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (state.isDeploying) {
|
||||
DeployProgressCard(
|
||||
progress = state.progress,
|
||||
currentStep = state.currentStep,
|
||||
)
|
||||
}
|
||||
|
||||
ServerActionBar(
|
||||
state = state,
|
||||
onAction = onAction,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
|
||||
SnackbarHost(
|
||||
hostState = snackbarHostState,
|
||||
modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 72.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun ManualPortFields(
|
||||
state: DeployUiState,
|
||||
onAction: (DeployAction) -> Unit,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(CsqttSpacing.Sm),
|
||||
) {
|
||||
DeployTextField(
|
||||
value = state.sshPort,
|
||||
onValueChange = { onAction(DeployAction.SshPortChanged(it)) },
|
||||
label = "SSH-порт",
|
||||
placeholder = "22",
|
||||
enabled = !state.isDeploying,
|
||||
isError = state.showValidation && !isValidPort(state.sshPort),
|
||||
keyboardType = KeyboardType.Number,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
DeployTextField(
|
||||
value = state.peerPort,
|
||||
onValueChange = { onAction(DeployAction.PeerPortChanged(it)) },
|
||||
label = "Порт туннеля",
|
||||
placeholder = "46000",
|
||||
enabled = !state.isDeploying,
|
||||
isError = state.showValidation && !isValidPort(state.peerPort),
|
||||
keyboardType = KeyboardType.Number,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
DeployTextField(
|
||||
value = state.webPort,
|
||||
onValueChange = { onAction(DeployAction.WebPortChanged(it)) },
|
||||
label = "Порт WEB-панели",
|
||||
placeholder = "46002",
|
||||
enabled = !state.isDeploying,
|
||||
isError = state.showValidation && !isValidPort(state.webPort),
|
||||
keyboardType = KeyboardType.Number,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun DeployProgressCard(
|
||||
progress: Float,
|
||||
currentStep: String,
|
||||
) {
|
||||
val animatedProgress by animateFloatAsState(
|
||||
targetValue = progress,
|
||||
animationSpec = if (progress <= 0.01f) snap() else tween(durationMillis = 320, easing = FastOutSlowInEasing),
|
||||
label = "deploy_progress",
|
||||
)
|
||||
|
||||
AppSectionCard(verticalArrangement = Arrangement.spacedBy(CsqttSpacing.Xs)) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(CsqttSpacing.Md),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Text(
|
||||
text = currentStep.ifBlank { "Подготовка…" },
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
modifier = Modifier.weight(1f),
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
text = "${(animatedProgress * 100).toInt()}%",
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.primary,
|
||||
)
|
||||
}
|
||||
LinearProgressIndicator(
|
||||
progress = { animatedProgress },
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Preview(name = "Deploy compact", widthDp = 360, heightDp = 800, showBackground = true)
|
||||
@Preview(name = "Deploy dark", widthDp = 720, heightDp = 900, uiMode = Configuration.UI_MODE_NIGHT_YES)
|
||||
@Composable
|
||||
private fun DeployScreenPreview() {
|
||||
com.csqtt.client.CSQTTTheme(themeMode = CsqttConstants.Theme.MODE_DARK) {
|
||||
DeployScreen(
|
||||
state = DeployUiState(
|
||||
host = "vpn.example.com",
|
||||
sshLogin = "root",
|
||||
sshPassword = "password",
|
||||
mainPasswordConfigured = true,
|
||||
webPanelConfigured = true,
|
||||
),
|
||||
onAction = {},
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import com.csqtt.client.showRaisedToast
|
||||
import android.content.Intent
|
||||
import android.content.res.Configuration
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.widget.Toast
|
||||
import androidx.core.net.toUri
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.animation.core.snap
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.outlined.Visibility
|
||||
import androidx.compose.material.icons.outlined.VisibilityOff
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import com.csqtt.client.TunnelService
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.tooling.preview.Preview
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.csqtt.client.DeployManager
|
||||
import com.csqtt.client.DeploySettingsSnapshot
|
||||
import com.csqtt.client.SettingsStore
|
||||
import com.csqtt.client.TunnelManager
|
||||
import com.csqtt.client.CsqttConstants
|
||||
import com.csqtt.client.R
|
||||
import com.csqtt.client.ui.dialogs.DeploySecretsDialog
|
||||
import com.csqtt.client.ui.dialogs.SshKeysDialog
|
||||
import com.csqtt.client.ui.dialogs.UninstallConfirmDialog
|
||||
import com.csqtt.client.ui.components.CsqttBanner
|
||||
import com.csqtt.client.ui.components.CsqttScreen
|
||||
import com.csqtt.client.ui.components.CsqttSettingRow
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.design.CsqttSizes
|
||||
import com.csqtt.client.ui.design.CsqttSpacing
|
||||
import com.csqtt.client.ui.design.CsqttTheme
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@Immutable
|
||||
internal data class DeployUiState(
|
||||
val host: String = "",
|
||||
val sshLogin: String = "",
|
||||
val sshPassword: String = "",
|
||||
val manualPorts: Boolean = false,
|
||||
val sshPort: String = CsqttConstants.Network.DEFAULT_SSH_PORT.toString(),
|
||||
val peerPort: String = CsqttConstants.Network.DEFAULT_SERVER_PEER_PORT.toString(),
|
||||
val webPort: String = CsqttConstants.Network.DEFAULT_SERVER_WEB_PORT.toString(),
|
||||
val mainPasswordConfigured: Boolean = false,
|
||||
val webPanelConfigured: Boolean = false,
|
||||
val sshKeysMode: Boolean = false,
|
||||
val dockerInstall: Boolean = false,
|
||||
val sshKeysFilled: Int = 0,
|
||||
val isDeploying: Boolean = false,
|
||||
val progress: Float = 0f,
|
||||
val currentStep: String = "",
|
||||
val showValidation: Boolean = false,
|
||||
) {
|
||||
val portsValid: Boolean
|
||||
get() = !manualPorts || listOf(sshPort, peerPort, webPort).all(::isValidPort)
|
||||
|
||||
val authorizationConfigured: Boolean
|
||||
get() = mainPasswordConfigured && webPanelConfigured
|
||||
|
||||
val sshAuthReady: Boolean
|
||||
get() = sshLogin.isNotBlank() && if (sshKeysMode) sshKeysFilled == 1 else sshPassword.isNotBlank()
|
||||
|
||||
val canInstall: Boolean
|
||||
get() = host.isNotBlank() && sshAuthReady && authorizationConfigured && portsValid
|
||||
|
||||
val canUninstall: Boolean
|
||||
get() = host.isNotBlank() && sshAuthReady && portsValid
|
||||
}
|
||||
|
||||
internal sealed interface DeployAction {
|
||||
data class HostChanged(val value: String) : DeployAction
|
||||
data class LoginChanged(val value: String) : DeployAction
|
||||
data class PasswordChanged(val value: String) : DeployAction
|
||||
data class ManualPortsChanged(val enabled: Boolean) : DeployAction
|
||||
data class SshKeysModeChanged(val enabled: Boolean) : DeployAction
|
||||
data class DockerInstallChanged(val enabled: Boolean) : DeployAction
|
||||
data object EditSshKeys : DeployAction
|
||||
data object DockerInfo : DeployAction
|
||||
data class SshPortChanged(val value: String) : DeployAction
|
||||
data class PeerPortChanged(val value: String) : DeployAction
|
||||
data class WebPortChanged(val value: String) : DeployAction
|
||||
data object EditAuthorization : DeployAction
|
||||
data object Install : DeployAction
|
||||
data object Uninstall : DeployAction
|
||||
data object OpenControlPanel : DeployAction
|
||||
data object PanelInfo : DeployAction
|
||||
}
|
||||
|
||||
internal fun passwordToSynchronizeAfterDeploy(deploySucceeded: Boolean, mainPassword: String): String? =
|
||||
mainPassword.takeIf { deploySucceeded && it.isNotBlank() }
|
||||
|
||||
internal fun isValidPort(value: String): Boolean = value.toIntOrNull() in 1..65535
|
||||
|
||||
@Immutable
|
||||
internal data class EffectiveServerPorts(
|
||||
val ssh: Int,
|
||||
val peer: Int,
|
||||
val web: Int,
|
||||
)
|
||||
|
||||
internal fun resolveServerPorts(
|
||||
manualPorts: Boolean,
|
||||
sshPort: String,
|
||||
peerPort: String,
|
||||
webPort: String,
|
||||
): EffectiveServerPorts {
|
||||
if (!manualPorts) {
|
||||
return EffectiveServerPorts(
|
||||
ssh = CsqttConstants.Network.DEFAULT_SSH_PORT,
|
||||
peer = CsqttConstants.Network.DEFAULT_SERVER_PEER_PORT,
|
||||
web = CsqttConstants.Network.DEFAULT_SERVER_WEB_PORT,
|
||||
)
|
||||
}
|
||||
return EffectiveServerPorts(
|
||||
ssh = sshPort.toIntOrNull()?.takeIf { it in 1..65535 }
|
||||
?: CsqttConstants.Network.DEFAULT_SSH_PORT,
|
||||
peer = peerPort.toIntOrNull()?.takeIf { it in 1..65535 }
|
||||
?: CsqttConstants.Network.DEFAULT_SERVER_PEER_PORT,
|
||||
web = webPort.toIntOrNull()?.takeIf { it in 1..65535 }
|
||||
?: CsqttConstants.Network.DEFAULT_SERVER_WEB_PORT,
|
||||
)
|
||||
}
|
||||
|
||||
internal fun hasWebPanelCredentials(login: String, password: String): Boolean =
|
||||
login.isNotBlank() && password.isNotBlank()
|
||||
|
||||
private fun showDeployToast(context: android.content.Context, message: String) {
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
context.showRaisedToast(message, Toast.LENGTH_LONG)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun DeployTab(
|
||||
settingsStore: SettingsStore,
|
||||
savedSettings: DeploySettingsSnapshot,
|
||||
) {
|
||||
val context = LocalContext.current.applicationContext
|
||||
val scope = rememberCoroutineScope()
|
||||
val snackbarHostState = remember { SnackbarHostState() }
|
||||
|
||||
LaunchedEffect(Unit) { DeployManager.init(context) }
|
||||
|
||||
if (!savedSettings.isLoaded) return
|
||||
|
||||
val savedIp = savedSettings.ip
|
||||
val savedLogin = savedSettings.sshLogin
|
||||
val savedPassword = savedSettings.sshPassword
|
||||
val savedWebLogin = savedSettings.webLogin
|
||||
val savedWebPassword = savedSettings.webPassword
|
||||
val savedMainPass = savedSettings.mainPassword
|
||||
val savedSshPort = savedSettings.sshPort
|
||||
val savedManualPorts = savedSettings.manualPortsEnabled
|
||||
val savedSshKeysMode = savedSettings.sshKeysMode
|
||||
val savedDockerInstall = savedSettings.dockerInstall
|
||||
val savedSshPrivateKey = savedSettings.sshPrivateKey
|
||||
val savedSshKeyPassphrase = savedSettings.sshKeyPassphrase
|
||||
val savedSshCertificate = savedSettings.sshCertificate
|
||||
val savedServerPeerPort = savedSettings.serverPeerPort
|
||||
val savedServerWebPort = savedSettings.serverWebPort
|
||||
val isDeploying by DeployManager.isDeploying.collectAsStateWithLifecycle()
|
||||
val deployProgress by DeployManager.deployProgress.collectAsStateWithLifecycle()
|
||||
val currentStep by DeployManager.currentStep.collectAsStateWithLifecycle()
|
||||
|
||||
var host by rememberSaveable(savedSettings.profile) { mutableStateOf(savedIp) }
|
||||
var sshLogin by rememberSaveable(savedSettings.profile) { mutableStateOf(savedLogin) }
|
||||
var sshPassword by rememberSaveable(savedSettings.profile) { mutableStateOf(savedPassword) }
|
||||
var sshPort by rememberSaveable(savedSettings.profile) {
|
||||
mutableStateOf(savedSshPort.ifBlank { CsqttConstants.Network.DEFAULT_SSH_PORT.toString() })
|
||||
}
|
||||
var peerPort by rememberSaveable(savedSettings.profile) { mutableStateOf(savedServerPeerPort.toString()) }
|
||||
var webPort by rememberSaveable(savedSettings.profile) { mutableStateOf(savedServerWebPort.toString()) }
|
||||
var dockerInstall by rememberSaveable(savedSettings.profile) { mutableStateOf(savedDockerInstall) }
|
||||
var generalEdited by rememberSaveable(savedSettings.profile) { mutableStateOf(false) }
|
||||
var credentialsEdited by rememberSaveable(savedSettings.profile) { mutableStateOf(false) }
|
||||
var portsEdited by rememberSaveable(savedSettings.profile) { mutableStateOf(false) }
|
||||
var showValidation by rememberSaveable(savedSettings.profile) { mutableStateOf(false) }
|
||||
var showSecretsDialog by rememberSaveable(savedSettings.profile) { mutableStateOf(false) }
|
||||
var showUninstallDialog by rememberSaveable(savedSettings.profile) { mutableStateOf(false) }
|
||||
var showPanelInfoDialog by rememberSaveable(savedSettings.profile) { mutableStateOf(false) }
|
||||
var showSshKeysDialog by rememberSaveable(savedSettings.profile) { mutableStateOf(false) }
|
||||
var showDockerInfoDialog by rememberSaveable(savedSettings.profile) { mutableStateOf(false) }
|
||||
|
||||
LaunchedEffect(savedSettings.profile, savedIp) {
|
||||
if (!generalEdited) {
|
||||
host = savedIp
|
||||
}
|
||||
}
|
||||
LaunchedEffect(savedSettings.profile, savedLogin, savedPassword) {
|
||||
if (!credentialsEdited) {
|
||||
sshLogin = savedLogin
|
||||
sshPassword = savedPassword
|
||||
}
|
||||
}
|
||||
LaunchedEffect(savedSettings.profile, savedSshPort, savedServerPeerPort, savedServerWebPort) {
|
||||
if (!portsEdited) {
|
||||
sshPort = savedSshPort.ifBlank { CsqttConstants.Network.DEFAULT_SSH_PORT.toString() }
|
||||
peerPort = savedServerPeerPort.toString()
|
||||
webPort = savedServerWebPort.toString()
|
||||
}
|
||||
}
|
||||
LaunchedEffect(savedSettings.profile, savedDockerInstall) {
|
||||
dockerInstall = savedDockerInstall
|
||||
}
|
||||
|
||||
LaunchedEffect(savedSettings.profile, host, generalEdited) {
|
||||
if (!generalEdited) return@LaunchedEffect
|
||||
kotlinx.coroutines.delay(450)
|
||||
settingsStore.saveDeploy(host)
|
||||
}
|
||||
LaunchedEffect(savedSettings.profile, sshLogin, sshPassword, credentialsEdited, savedMainPass, savedWebLogin, savedWebPassword) {
|
||||
if (!credentialsEdited) return@LaunchedEffect
|
||||
kotlinx.coroutines.delay(450)
|
||||
settingsStore.saveDeploySecrets(savedMainPass, sshLogin, sshPassword, savedWebLogin, savedWebPassword)
|
||||
}
|
||||
LaunchedEffect(savedSettings.profile, sshPort, peerPort, webPort, portsEdited) {
|
||||
if (!portsEdited) return@LaunchedEffect
|
||||
kotlinx.coroutines.delay(450)
|
||||
val ssh = sshPort.toIntOrNull()
|
||||
val peer = peerPort.toIntOrNull()
|
||||
val web = webPort.toIntOrNull()
|
||||
if (ssh in 1..65535 && peer in 1..65535 && web in 1..65535) {
|
||||
settingsStore.savePorts(peer!!, web!!, ssh.toString())
|
||||
}
|
||||
}
|
||||
|
||||
val state = DeployUiState(
|
||||
host = host,
|
||||
sshLogin = sshLogin,
|
||||
sshPassword = sshPassword,
|
||||
manualPorts = savedManualPorts,
|
||||
sshPort = sshPort,
|
||||
peerPort = peerPort,
|
||||
webPort = webPort,
|
||||
mainPasswordConfigured = savedMainPass.isNotBlank(),
|
||||
webPanelConfigured = hasWebPanelCredentials(savedWebLogin, savedWebPassword),
|
||||
sshKeysMode = savedSshKeysMode,
|
||||
dockerInstall = dockerInstall,
|
||||
sshKeysFilled = if (savedSshPrivateKey.isNotBlank()) 1 else 0,
|
||||
isDeploying = isDeploying,
|
||||
progress = deployProgress,
|
||||
currentStep = currentStep,
|
||||
showValidation = showValidation,
|
||||
)
|
||||
|
||||
fun startDeploy() {
|
||||
if (DeployManager.isDeploying.value) return
|
||||
val ports = resolveServerPorts(savedManualPorts, sshPort, peerPort, webPort)
|
||||
val effectiveSshPort = ports.ssh
|
||||
val effectivePeerPort = ports.peer
|
||||
val effectiveWebPort = ports.web
|
||||
val deployPrivateKey = if (savedSshKeysMode) savedSshPrivateKey else ""
|
||||
val deployKeyPassphrase = if (savedSshKeysMode) savedSshKeyPassphrase else ""
|
||||
val deployCertificate = if (savedSshKeysMode) savedSshCertificate else ""
|
||||
val deployPassword = if (savedSshKeysMode) "" else sshPassword
|
||||
scope.launch {
|
||||
settingsStore.saveDeploy(host)
|
||||
settingsStore.saveDeploySecrets(savedMainPass, sshLogin, sshPassword, savedWebLogin, savedWebPassword)
|
||||
settingsStore.savePorts(effectivePeerPort, effectiveWebPort, effectiveSshPort.toString())
|
||||
}
|
||||
DeployManager.startDeploy()
|
||||
DeployManager.scope.launch {
|
||||
try {
|
||||
context.startForegroundService(Intent(context, TunnelService::class.java).apply { action = "DEPLOY_START" })
|
||||
val success = performDeploy(
|
||||
context = context,
|
||||
host = host,
|
||||
user = sshLogin,
|
||||
pass = deployPassword,
|
||||
port = effectiveSshPort,
|
||||
mainPass = savedMainPass,
|
||||
webLogin = savedWebLogin,
|
||||
webPass = savedWebPassword,
|
||||
peerPort = effectivePeerPort,
|
||||
webPort = effectiveWebPort,
|
||||
onProgress = DeployManager::updateProgress,
|
||||
privateKey = deployPrivateKey,
|
||||
keyPassphrase = deployKeyPassphrase,
|
||||
certificate = deployCertificate,
|
||||
installInDocker = dockerInstall,
|
||||
)
|
||||
if (success) {
|
||||
passwordToSynchronizeAfterDeploy(success, savedMainPass)?.let { mainPassword ->
|
||||
settingsStore.saveConnectionPassword(mainPassword)
|
||||
TunnelManager.addDeployInfoLog("Пароль подключения синхронизирован с паролем сервера")
|
||||
}
|
||||
showDeployToast(context, "Установка успешно завершена")
|
||||
} else {
|
||||
val message = DeployManager.lastResult.value.ifBlank { "Ошибка установки" }
|
||||
scope.launch { snackbarHostState.showSnackbar(message) }
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
DeployManager.stopDeploy("Установка отменена")
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
val message = friendlyDeployError(e.message)
|
||||
DeployManager.writeError(
|
||||
"Deploy UI error (${e.javaClass.simpleName}): ${e.message}\n" +
|
||||
e.stackTraceToString().take(1200)
|
||||
)
|
||||
TunnelManager.addDeployErrorLog(message)
|
||||
DeployManager.stopDeploy(message)
|
||||
scope.launch { snackbarHostState.showSnackbar(message) }
|
||||
} finally {
|
||||
runCatching {
|
||||
context.startService(Intent(context, TunnelService::class.java).apply { action = "DEPLOY_STOP" })
|
||||
}.onFailure { DeployManager.writeError("Не удалось остановить foreground-режим деплоя: ${it.message}") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun startUninstall() {
|
||||
if (DeployManager.isDeploying.value) return
|
||||
val ports = resolveServerPorts(savedManualPorts, sshPort, peerPort, webPort)
|
||||
val effectiveSshPort = ports.ssh
|
||||
val effectivePeerPort = ports.peer
|
||||
val uninstallPrivateKey = if (savedSshKeysMode) savedSshPrivateKey else ""
|
||||
val uninstallKeyPassphrase = if (savedSshKeysMode) savedSshKeyPassphrase else ""
|
||||
val uninstallCertificate = if (savedSshKeysMode) savedSshCertificate else ""
|
||||
val uninstallPassword = if (savedSshKeysMode) "" else sshPassword
|
||||
DeployManager.startDeploy()
|
||||
DeployManager.scope.launch {
|
||||
try {
|
||||
context.startForegroundService(Intent(context, TunnelService::class.java).apply { action = "DEPLOY_START" })
|
||||
val success = performUninstall(
|
||||
context = context,
|
||||
host = host,
|
||||
user = sshLogin,
|
||||
pass = uninstallPassword,
|
||||
port = effectiveSshPort,
|
||||
peerPort = effectivePeerPort,
|
||||
onProgress = DeployManager::updateProgress,
|
||||
privateKey = uninstallPrivateKey,
|
||||
keyPassphrase = uninstallKeyPassphrase,
|
||||
certificate = uninstallCertificate,
|
||||
)
|
||||
if (success) {
|
||||
showDeployToast(context, "Удаление успешно завершено")
|
||||
} else {
|
||||
val message = DeployManager.lastResult.value.ifBlank { "Ошибка удаления" }
|
||||
scope.launch { snackbarHostState.showSnackbar(message) }
|
||||
}
|
||||
} catch (e: CancellationException) {
|
||||
DeployManager.stopDeploy("Удаление отменено")
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
val message = friendlyDeployError(e.message)
|
||||
DeployManager.writeError(
|
||||
"Uninstall UI error (${e.javaClass.simpleName}): ${e.message}\n" +
|
||||
e.stackTraceToString().take(1200)
|
||||
)
|
||||
TunnelManager.addDeployErrorLog(message)
|
||||
DeployManager.stopDeploy(message)
|
||||
scope.launch { snackbarHostState.showSnackbar(message) }
|
||||
} finally {
|
||||
runCatching {
|
||||
context.startService(Intent(context, TunnelService::class.java).apply { action = "DEPLOY_STOP" })
|
||||
}.onFailure { DeployManager.writeError("Не удалось остановить foreground-режим удаления: ${it.message}") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DeployScreen(
|
||||
state = state,
|
||||
snackbarHostState = snackbarHostState,
|
||||
onAction = { action ->
|
||||
when (action) {
|
||||
is DeployAction.HostChanged -> {
|
||||
host = action.value.filterNot(Char::isWhitespace)
|
||||
generalEdited = true
|
||||
}
|
||||
is DeployAction.LoginChanged -> {
|
||||
sshLogin = action.value.filterNot(Char::isWhitespace)
|
||||
credentialsEdited = true
|
||||
}
|
||||
is DeployAction.PasswordChanged -> {
|
||||
sshPassword = sanitizeSshPassword(action.value)
|
||||
credentialsEdited = true
|
||||
}
|
||||
is DeployAction.ManualPortsChanged -> {
|
||||
if (!action.enabled) {
|
||||
sshPort = CsqttConstants.Network.DEFAULT_SSH_PORT.toString()
|
||||
peerPort = CsqttConstants.Network.DEFAULT_SERVER_PEER_PORT.toString()
|
||||
webPort = CsqttConstants.Network.DEFAULT_SERVER_WEB_PORT.toString()
|
||||
portsEdited = false
|
||||
}
|
||||
scope.launch { settingsStore.saveManualPortsEnabled(action.enabled) }
|
||||
}
|
||||
is DeployAction.SshKeysModeChanged -> scope.launch {
|
||||
settingsStore.saveSshKeysMode(action.enabled)
|
||||
}
|
||||
is DeployAction.DockerInstallChanged -> {
|
||||
dockerInstall = action.enabled
|
||||
scope.launch { settingsStore.saveDockerInstall(action.enabled) }
|
||||
}
|
||||
DeployAction.EditSshKeys -> showSshKeysDialog = true
|
||||
DeployAction.DockerInfo -> showDockerInfoDialog = true
|
||||
is DeployAction.SshPortChanged -> {
|
||||
sshPort = action.value.filter(Char::isDigit).take(5)
|
||||
portsEdited = true
|
||||
}
|
||||
is DeployAction.PeerPortChanged -> {
|
||||
peerPort = action.value.filter(Char::isDigit).take(5)
|
||||
portsEdited = true
|
||||
}
|
||||
is DeployAction.WebPortChanged -> {
|
||||
webPort = action.value.filter(Char::isDigit).take(5)
|
||||
portsEdited = true
|
||||
}
|
||||
DeployAction.EditAuthorization -> showSecretsDialog = true
|
||||
DeployAction.Install -> {
|
||||
showValidation = true
|
||||
if (state.canInstall) startDeploy()
|
||||
}
|
||||
DeployAction.Uninstall -> if (state.canUninstall) showUninstallDialog = true
|
||||
DeployAction.PanelInfo -> showPanelInfoDialog = true
|
||||
DeployAction.OpenControlPanel -> {
|
||||
if (host.isBlank()) {
|
||||
scope.launch { snackbarHostState.showSnackbar("Сначала укажите IP сервера") }
|
||||
} else {
|
||||
val effectiveWebPort = resolveServerPorts(
|
||||
savedManualPorts,
|
||||
sshPort,
|
||||
peerPort,
|
||||
webPort,
|
||||
).web
|
||||
runCatching {
|
||||
context.startActivity(
|
||||
Intent(Intent.ACTION_VIEW, "https://$host:$effectiveWebPort".toUri()).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
)
|
||||
}.onFailure {
|
||||
scope.launch { snackbarHostState.showSnackbar("Не удалось открыть панель управления") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
if (showSecretsDialog) {
|
||||
DeploySecretsDialog(
|
||||
settingsStore = settingsStore,
|
||||
initialMainPass = savedMainPass,
|
||||
initialSshLogin = sshLogin,
|
||||
initialSshPass = sshPassword,
|
||||
initialWebLogin = savedWebLogin,
|
||||
initialWebPass = savedWebPassword,
|
||||
onSaved = {},
|
||||
onDismiss = { showSecretsDialog = false },
|
||||
)
|
||||
}
|
||||
|
||||
if (showUninstallDialog) {
|
||||
UninstallConfirmDialog(
|
||||
onDismiss = { showUninstallDialog = false },
|
||||
onConfirm = {
|
||||
showUninstallDialog = false
|
||||
startUninstall()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if (showPanelInfoDialog) {
|
||||
WebPanelInfoDialog(onDismiss = { showPanelInfoDialog = false })
|
||||
}
|
||||
|
||||
if (showSshKeysDialog) {
|
||||
SshKeysDialog(
|
||||
initialPrivateKey = savedSshPrivateKey,
|
||||
initialPassphrase = savedSshKeyPassphrase,
|
||||
initialCertificate = savedSshCertificate,
|
||||
onSave = { privateKey, keyPassphrase, certificate ->
|
||||
showSshKeysDialog = false
|
||||
scope.launch { settingsStore.saveSshKeys(privateKey, keyPassphrase, certificate) }
|
||||
},
|
||||
onDismiss = { showSshKeysDialog = false },
|
||||
)
|
||||
}
|
||||
|
||||
if (showDockerInfoDialog) {
|
||||
DockerInstallInfoDialog(onDismiss = { showDockerInfoDialog = false })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import android.content.pm.PackageManager
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.foundation.selection.toggleable
|
||||
import androidx.compose.foundation.text.KeyboardActions
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Apps
|
||||
import androidx.compose.material.icons.outlined.Search
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.graphics.asImageBitmap
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.core.graphics.drawable.toBitmap
|
||||
import com.csqtt.client.R
|
||||
import com.csqtt.client.SettingsStore
|
||||
import com.csqtt.client.TunnelManager
|
||||
import com.csqtt.client.ui.components.CsqttEmptyState
|
||||
import com.csqtt.client.ui.components.CsqttLoadingState
|
||||
import com.csqtt.client.ui.components.CsqttScreen
|
||||
import com.csqtt.client.ui.components.CsqttSegmentedControl
|
||||
import com.csqtt.client.ui.components.CsqttSettingRow
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.design.CsqttSizes
|
||||
import com.csqtt.client.ui.design.CsqttSpacing
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
|
||||
private object AppCache {
|
||||
@Volatile
|
||||
var cachedList: List<AppItem>? = null
|
||||
}
|
||||
|
||||
private enum class RoutingMode { ExcludeSelected, IncludeSelected }
|
||||
|
||||
@Composable
|
||||
fun ExceptionsTab(
|
||||
settingsStore: SettingsStore,
|
||||
savedExcluded: String,
|
||||
showSystemApps: Boolean,
|
||||
isWhitelist: Boolean,
|
||||
) {
|
||||
val context = LocalContext.current.applicationContext
|
||||
val focusManager = LocalFocusManager.current
|
||||
val scope = rememberCoroutineScope()
|
||||
// Taps edit a local draft; the DataStore write (and VPN reload) is
|
||||
// debounced so a burst of toggles costs one persist instead of one per tap.
|
||||
val persistedSelection = remember(savedExcluded) {
|
||||
savedExcluded.split(',').filter(String::isNotBlank).toSet()
|
||||
}
|
||||
var selectedPackages by remember { mutableStateOf(persistedSelection) }
|
||||
var lastSavedSelection by remember { mutableStateOf(persistedSelection) }
|
||||
var saveJob by remember { mutableStateOf<Job?>(null) }
|
||||
|
||||
// Adopt persisted changes only when they came from outside (profile switch,
|
||||
// another screen): our own writes set lastSavedSelection first, so the
|
||||
// echo of our save never resets a draft that already moved past it.
|
||||
LaunchedEffect(persistedSelection) {
|
||||
if (persistedSelection != lastSavedSelection) {
|
||||
selectedPackages = persistedSelection
|
||||
}
|
||||
lastSavedSelection = persistedSelection
|
||||
}
|
||||
var appsList by remember { mutableStateOf(AppCache.cachedList.orEmpty()) }
|
||||
var isLoading by remember { mutableStateOf(AppCache.cachedList == null) }
|
||||
var isMigrationReady by rememberSaveable { mutableStateOf(false) }
|
||||
var searchQuery by rememberSaveable { mutableStateOf("") }
|
||||
|
||||
LaunchedEffect(Unit) {
|
||||
withContext(Dispatchers.IO) { settingsStore.migrateLegacyWhitelistMode() }
|
||||
isMigrationReady = true
|
||||
|
||||
AppCache.cachedList?.let {
|
||||
appsList = it
|
||||
isLoading = false
|
||||
return@LaunchedEffect
|
||||
}
|
||||
|
||||
isLoading = true
|
||||
val loadedApps = withContext(Dispatchers.IO) {
|
||||
val packageManager = context.packageManager
|
||||
packageManager
|
||||
.getInstalledApplications(PackageManager.GET_META_DATA)
|
||||
.asSequence()
|
||||
.filter { app ->
|
||||
app.packageName != context.packageName &&
|
||||
!app.packageName.contains("vkontakte") &&
|
||||
!app.packageName.contains("vk.calls")
|
||||
}
|
||||
.map { app ->
|
||||
AppItem(
|
||||
name = app.loadLabel(packageManager).toString(),
|
||||
packageName = app.packageName,
|
||||
icon = runCatching { app.loadIcon(packageManager).toBitmap().asImageBitmap() }.getOrNull(),
|
||||
isSystem = (app.flags and android.content.pm.ApplicationInfo.FLAG_SYSTEM) != 0,
|
||||
)
|
||||
}
|
||||
.sortedBy { it.name.lowercase() }
|
||||
.toList()
|
||||
}
|
||||
AppCache.cachedList = loadedApps
|
||||
appsList = loadedApps
|
||||
isLoading = false
|
||||
}
|
||||
|
||||
val filteredApps = remember(appsList, showSystemApps, searchQuery) {
|
||||
val visibleApps = if (showSystemApps) {
|
||||
appsList
|
||||
} else {
|
||||
appsList.filter {
|
||||
!it.isSystem || it.packageName == "com.google.android.youtube" || it.packageName == "com.android.vending"
|
||||
}
|
||||
}
|
||||
if (searchQuery.isBlank()) {
|
||||
visibleApps
|
||||
} else {
|
||||
visibleApps.filter {
|
||||
it.name.contains(searchQuery, ignoreCase = true) ||
|
||||
it.packageName.contains(searchQuery, ignoreCase = true)
|
||||
}
|
||||
}
|
||||
}
|
||||
val listState = rememberLazyListState()
|
||||
val routingMode = if (isWhitelist) RoutingMode.IncludeSelected else RoutingMode.ExcludeSelected
|
||||
|
||||
fun persistSelection(selection: Set<String>) {
|
||||
lastSavedSelection = selection
|
||||
saveJob?.cancel()
|
||||
saveJob = scope.launch {
|
||||
delay(250)
|
||||
settingsStore.saveExcludedApps(selection.sorted().joinToString(","))
|
||||
TunnelManager.reloadVpn()
|
||||
}
|
||||
}
|
||||
|
||||
DisposableEffect(Unit) {
|
||||
onDispose {
|
||||
// A burst still inside the debounce window must not be lost when
|
||||
// the tab closes right after the last tap.
|
||||
saveJob?.cancel()
|
||||
val pending = selectedPackages
|
||||
if (pending != persistedSelection) {
|
||||
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
|
||||
settingsStore.saveExcludedApps(pending.sorted().joinToString(","))
|
||||
TunnelManager.reloadVpn()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CsqttScreen {
|
||||
OutlinedTextField(
|
||||
value = searchQuery,
|
||||
onValueChange = { searchQuery = it },
|
||||
label = {
|
||||
Text(
|
||||
stringResource(R.string.exceptions_search_label),
|
||||
maxLines = 1,
|
||||
softWrap = false,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
},
|
||||
placeholder = {
|
||||
Text(
|
||||
stringResource(R.string.exceptions_search_placeholder),
|
||||
maxLines = 1,
|
||||
softWrap = false,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
},
|
||||
leadingIcon = { Icon(Icons.Outlined.Search, contentDescription = null) },
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
|
||||
keyboardActions = KeyboardActions(onSearch = { focusManager.clearFocus() }),
|
||||
shape = CsqttShapes.Control,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
|
||||
AppSectionCard(
|
||||
contentPadding = PaddingValues(horizontal = CsqttSpacing.Md, vertical = CsqttSpacing.Sm),
|
||||
verticalArrangement = Arrangement.spacedBy(CsqttSpacing.Sm),
|
||||
) {
|
||||
CsqttSegmentedControl(
|
||||
options = listOf(
|
||||
RoutingMode.ExcludeSelected to stringResource(R.string.exceptions_mode_exclude),
|
||||
RoutingMode.IncludeSelected to stringResource(R.string.exceptions_mode_include),
|
||||
),
|
||||
selected = routingMode,
|
||||
enabled = isMigrationReady,
|
||||
onSelected = { mode ->
|
||||
if (mode == routingMode) return@CsqttSegmentedControl
|
||||
scope.launch {
|
||||
settingsStore.saveExceptionsMode(
|
||||
selectedPackages.sorted().joinToString(","),
|
||||
mode == RoutingMode.IncludeSelected,
|
||||
)
|
||||
delay(300)
|
||||
TunnelManager.reloadVpn()
|
||||
}
|
||||
},
|
||||
)
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f))
|
||||
CsqttSettingRow(
|
||||
title = stringResource(R.string.exceptions_system_apps),
|
||||
checked = showSystemApps,
|
||||
onCheckedChange = { enabled ->
|
||||
scope.launch { settingsStore.saveShowSystemApps(enabled) }
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
Text(
|
||||
text = stringResource(R.string.exceptions_selected_count, selectedPackages.size),
|
||||
style = MaterialTheme.typography.labelLarge,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
when {
|
||||
!isMigrationReady || isLoading -> {
|
||||
Box(modifier = Modifier.fillMaxWidth().weight(1f), contentAlignment = Alignment.Center) {
|
||||
CsqttLoadingState(label = stringResource(R.string.exceptions_loading))
|
||||
}
|
||||
}
|
||||
|
||||
filteredApps.isEmpty() -> {
|
||||
Box(modifier = Modifier.fillMaxWidth().weight(1f), contentAlignment = Alignment.Center) {
|
||||
CsqttEmptyState(
|
||||
title = stringResource(R.string.exceptions_empty_title),
|
||||
description = stringResource(R.string.exceptions_empty_description),
|
||||
icon = Icons.Outlined.Apps,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
else -> {
|
||||
LazyColumn(
|
||||
state = listState,
|
||||
modifier = Modifier.fillMaxWidth().weight(1f),
|
||||
contentPadding = PaddingValues(bottom = CsqttSizes.ScreenBottomPadding),
|
||||
verticalArrangement = Arrangement.spacedBy(CsqttSpacing.Xs),
|
||||
) {
|
||||
items(
|
||||
items = filteredApps,
|
||||
key = { it.packageName },
|
||||
contentType = { "application" },
|
||||
) { app ->
|
||||
val isSelected = app.packageName in selectedPackages
|
||||
AppRow(
|
||||
app = app,
|
||||
isSelected = isSelected,
|
||||
onClick = {
|
||||
val newSelection = if (isSelected) {
|
||||
selectedPackages - app.packageName
|
||||
} else {
|
||||
selectedPackages + app.packageName
|
||||
}
|
||||
selectedPackages = newSelection
|
||||
persistSelection(newSelection)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import kotlinx.coroutines.launch
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import com.csqtt.client.SettingsStore
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.csqtt.client.R
|
||||
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import com.csqtt.client.CsqttConstants
|
||||
import com.csqtt.client.TunnelManager
|
||||
import com.csqtt.client.ui.components.CsqttSegmentedControl
|
||||
import com.csqtt.client.ui.components.CsqttSettingRow
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.design.CsqttSizes
|
||||
import com.csqtt.client.ui.tunnel.ExtraWorkersInfoDialog
|
||||
|
||||
private enum class UsageRole { Owner, Participant }
|
||||
|
||||
@Composable
|
||||
fun FloatingToolbar(
|
||||
settingsStore: SettingsStore,
|
||||
csqttLinkMode: Boolean,
|
||||
activeProfile: Int,
|
||||
onActiveProfileChange: (Int) -> Unit,
|
||||
currentTheme: String,
|
||||
onThemeChange: (String) -> Unit,
|
||||
activeFingerprint: String,
|
||||
onFingerprintChange: (String) -> Unit,
|
||||
autoPauseOnWifi: Boolean,
|
||||
onAutoPauseOnWifiChange: (Boolean) -> Unit,
|
||||
modifier: Modifier = Modifier
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
val selectedRole = if (csqttLinkMode) UsageRole.Participant else UsageRole.Owner
|
||||
val extraWorkersEnabled by settingsStore.extraWorkers.collectAsStateWithLifecycle(
|
||||
initialValue = SettingsStore.cachedExtraWorkers,
|
||||
)
|
||||
val vkAuthMode by settingsStore.vkAuthMode.collectAsStateWithLifecycle(
|
||||
initialValue = CsqttConstants.VkAuth.MODE_CALLS,
|
||||
)
|
||||
val tunnelRunning by TunnelManager.running.collectAsStateWithLifecycle()
|
||||
var isExpanded by rememberSaveable { mutableStateOf(false) }
|
||||
var showAutoPauseInfo by rememberSaveable { mutableStateOf(false) }
|
||||
var showExtraWorkersInfo by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
IconButton(
|
||||
onClick = { isExpanded = true },
|
||||
modifier = modifier.size(40.dp),
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(id = R.drawable.ic_more_smooth),
|
||||
contentDescription = stringResource(R.string.quick_settings),
|
||||
modifier = Modifier.size(30.dp),
|
||||
tint = Color.Unspecified,
|
||||
)
|
||||
}
|
||||
|
||||
if (isExpanded) {
|
||||
Dialog(
|
||||
onDismissRequest = { isExpanded = false },
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||
) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Dialog,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
shadowElevation = 8.dp,
|
||||
tonalElevation = 4.dp,
|
||||
modifier = Modifier.fillMaxWidth(0.9f)
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.padding(16.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
"Настройки",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onSurface
|
||||
)
|
||||
IconButton(
|
||||
onClick = { isExpanded = false },
|
||||
modifier = Modifier.size(48.dp)
|
||||
) {
|
||||
Icon(
|
||||
Icons.Filled.Close,
|
||||
contentDescription = stringResource(R.string.action_close),
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Text(
|
||||
"Ваша роль использования",
|
||||
style = MaterialTheme.typography.labelMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
modifier = Modifier.padding(start = 4.dp, bottom = 4.dp)
|
||||
)
|
||||
|
||||
CsqttSegmentedControl(
|
||||
options = listOf(
|
||||
UsageRole.Owner to "Владелец",
|
||||
UsageRole.Participant to "Участник",
|
||||
),
|
||||
selected = selectedRole,
|
||||
onSelected = { role ->
|
||||
val participant = role == UsageRole.Participant
|
||||
if (participant != csqttLinkMode) {
|
||||
scope.launch { settingsStore.saveCsqttLinkMode(participant) }
|
||||
}
|
||||
},
|
||||
modifier = Modifier
|
||||
.padding(horizontal = 4.dp)
|
||||
.height(CsqttSizes.CompactControlHeight),
|
||||
)
|
||||
|
||||
HorizontalDivider(
|
||||
modifier = Modifier.padding(vertical = 4.dp),
|
||||
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f)
|
||||
)
|
||||
|
||||
CompactDropdownSetting(
|
||||
title = "Профиль конфигурации",
|
||||
selectedKey = activeProfile.toString(),
|
||||
options = (CsqttConstants.Profiles.MIN_INDEX..CsqttConstants.Profiles.MAX_INDEX)
|
||||
.map { profile -> profile.toString() to "Профиль $profile" },
|
||||
enabled = true,
|
||||
onSelected = { profile ->
|
||||
profile.toIntOrNull()?.let(onActiveProfileChange)
|
||||
},
|
||||
)
|
||||
|
||||
CompactDropdownSetting(
|
||||
title = "Отпечаток",
|
||||
selectedKey = activeFingerprint,
|
||||
options = listOf(
|
||||
"chrome" to "Chrome",
|
||||
"safari" to "Safari",
|
||||
"firefox" to "Firefox",
|
||||
"edge" to "Edge",
|
||||
"opera" to "Opera",
|
||||
),
|
||||
enabled = true,
|
||||
onSelected = onFingerprintChange,
|
||||
)
|
||||
|
||||
CompactDropdownSetting(
|
||||
title = "Оформление",
|
||||
selectedKey = currentTheme,
|
||||
options = listOf(
|
||||
CsqttConstants.Theme.MODE_SYSTEM to "Система",
|
||||
CsqttConstants.Theme.MODE_LIGHT to "Светлая",
|
||||
CsqttConstants.Theme.MODE_DARK to "Тёмная",
|
||||
),
|
||||
enabled = true,
|
||||
onSelected = onThemeChange,
|
||||
)
|
||||
|
||||
HorizontalDivider(
|
||||
modifier = Modifier.padding(vertical = 4.dp),
|
||||
color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f),
|
||||
)
|
||||
|
||||
CsqttSettingRow(
|
||||
title = "Автопауза при Wi-Fi",
|
||||
checked = autoPauseOnWifi,
|
||||
onCheckedChange = onAutoPauseOnWifiChange,
|
||||
onInfoClick = { showAutoPauseInfo = true },
|
||||
infoContentDescription = "Как работает автопауза при Wi-Fi",
|
||||
)
|
||||
|
||||
if (vkAuthMode != CsqttConstants.VkAuth.MODE_AUTO_JS) {
|
||||
CsqttSettingRow(
|
||||
title = "Экстра потоки",
|
||||
checked = extraWorkersEnabled == true,
|
||||
enabled = !tunnelRunning,
|
||||
onCheckedChange = { enabled ->
|
||||
scope.launch { settingsStore.saveExtraWorkers(enabled) }
|
||||
},
|
||||
onInfoClick = { showExtraWorkersInfo = true },
|
||||
infoContentDescription = "Информация об экстра потоках",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (showAutoPauseInfo) {
|
||||
WifiAutoPauseInfoDialog(onDismiss = { showAutoPauseInfo = false })
|
||||
}
|
||||
if (showExtraWorkersInfo) {
|
||||
ExtraWorkersInfoDialog(onDismiss = { showExtraWorkersInfo = false })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import com.csqtt.client.showRaisedToast
|
||||
import com.csqtt.client.CsqttConstants
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.util.Log
|
||||
import android.widget.Toast
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.expandVertically
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.shrinkVertically
|
||||
import androidx.core.net.toUri
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.defaultMinSize
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowForward
|
||||
import androidx.compose.material.icons.automirrored.filled.HelpOutline
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Code
|
||||
import androidx.compose.material.icons.filled.ContentCopy
|
||||
import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||
import androidx.compose.material.icons.filled.Person
|
||||
import androidx.compose.material.icons.filled.Update
|
||||
import androidx.compose.material.icons.outlined.Code
|
||||
import androidx.compose.material.icons.outlined.ContentCopy
|
||||
import androidx.compose.material.icons.outlined.Info
|
||||
import androidx.compose.material.icons.outlined.Person
|
||||
import androidx.compose.material.icons.outlined.Update
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.FilledTonalIconButton
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.rotate
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.semantics.heading
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.csqtt.client.BuildConfig
|
||||
import com.csqtt.client.R
|
||||
import com.csqtt.client.SettingsStore
|
||||
import com.csqtt.client.UPDATE_DIALOG_ACTION_POSTPONED
|
||||
import com.csqtt.client.UPDATE_DIALOG_ACTION_UPDATE
|
||||
import com.csqtt.client.CSQTTColors
|
||||
import com.csqtt.client.fetchLatestReleaseInfo
|
||||
import com.csqtt.client.isNewerVersion
|
||||
import kotlinx.coroutines.launch
|
||||
import com.csqtt.client.ui.components.CsqttScreen
|
||||
import com.csqtt.client.ui.design.CsqttSpacing
|
||||
import com.csqtt.client.ui.dialogs.CryptoDonateDialog
|
||||
|
||||
private const val ReleasesUrl = CsqttConstants.Links.RELEASES
|
||||
private const val IssuesUrl = CsqttConstants.Links.ISSUES
|
||||
private const val DeveloperProfileUrl = CsqttConstants.Links.DEVELOPER_PROFILE
|
||||
private const val RepositoryUrl = CsqttConstants.Links.REPOSITORY
|
||||
private const val DonateUrl = CsqttConstants.Links.DONATE
|
||||
|
||||
private val browserPackages = listOf(
|
||||
"com.android.chrome",
|
||||
"com.google.android.googlequicksearchbox",
|
||||
"org.mozilla.firefox",
|
||||
"com.yandex.browser",
|
||||
"ru.yandex.searchplugin",
|
||||
"com.yandex.browser.lite",
|
||||
"com.opera.browser",
|
||||
"com.opera.mini.native",
|
||||
"com.microsoft.emmx",
|
||||
"com.brave.browser",
|
||||
"com.duckduckgo.mobile.android",
|
||||
"com.sec.android.app.sbrowser",
|
||||
"com.vivaldi.browser",
|
||||
"com.kiwibrowser.browser",
|
||||
)
|
||||
|
||||
private fun openUrlInBrowser(context: Context, url: String) {
|
||||
try {
|
||||
val pm = context.packageManager
|
||||
val uri = url.toUri()
|
||||
for (pkg in browserPackages) {
|
||||
val intent = Intent(Intent.ACTION_VIEW, uri).apply {
|
||||
addCategory(Intent.CATEGORY_BROWSABLE)
|
||||
setPackage(pkg)
|
||||
}
|
||||
if (intent.resolveActivity(pm) != null) {
|
||||
context.startActivity(intent)
|
||||
return
|
||||
}
|
||||
}
|
||||
val intent = Intent(Intent.ACTION_VIEW, uri).apply { addCategory(Intent.CATEGORY_BROWSABLE) }
|
||||
if (intent.resolveActivity(pm) != null) context.startActivity(intent)
|
||||
} catch (error: Exception) {
|
||||
Log.w("CSQTT", "Не удалось открыть ссылку: $url", error)
|
||||
context.showRaisedToast("Не удалось открыть ссылку", Toast.LENGTH_SHORT)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun InfoTab(
|
||||
settingsStore: SettingsStore,
|
||||
actionsExpanded: Boolean,
|
||||
projectExpanded: Boolean,
|
||||
onActionsToggle: () -> Unit,
|
||||
onProjectToggle: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val currentVersion = remember { "v${BuildConfig.VERSION_NAME.removePrefix("v")}" }
|
||||
var isCheckingUpdates by remember { mutableStateOf(false) }
|
||||
var pendingManualRelease by remember { mutableStateOf<com.csqtt.client.AppReleaseInfo?>(null) }
|
||||
var showCryptoDialog by remember { mutableStateOf(false) }
|
||||
val updateLatestVersion by settingsStore.updateLatestVersion.collectAsStateWithLifecycle(initialValue = "")
|
||||
val updateLastError by settingsStore.updateLastError.collectAsStateWithLifecycle(initialValue = "")
|
||||
val updateStatus = remember(isCheckingUpdates, updateLatestVersion, updateLastError, currentVersion) {
|
||||
when {
|
||||
isCheckingUpdates -> "Проверяем GitHub releases..."
|
||||
updateLatestVersion.isNotBlank() && isNewerVersion(currentVersion, updateLatestVersion) ->
|
||||
"На GitHub доступна версия $updateLatestVersion"
|
||||
updateLatestVersion.isNotBlank() -> "Последняя версия: $updateLatestVersion"
|
||||
updateLastError.isNotBlank() -> "Последняя проверка завершилась ошибкой"
|
||||
else -> "Проверить GitHub вручную"
|
||||
}
|
||||
}
|
||||
|
||||
CsqttScreen {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.fillMaxWidth()
|
||||
.padding(bottom = 32.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
InfoHeroCard(
|
||||
currentVersion = currentVersion,
|
||||
onSupportClick = { openUrlInBrowser(context, DonateUrl) },
|
||||
onCryptoClick = { showCryptoDialog = true },
|
||||
)
|
||||
|
||||
ExpandableSectionCard(
|
||||
title = "Действия",
|
||||
expanded = actionsExpanded,
|
||||
onToggle = onActionsToggle,
|
||||
icon = {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Info,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
}
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
WideActionTile(
|
||||
title = "Поднять вопрос",
|
||||
subtitle = "Открыть GitHub issue",
|
||||
onClick = { openUrlInBrowser(context, IssuesUrl) },
|
||||
icon = {
|
||||
Icon(
|
||||
painter = painterResource(id = R.drawable.ic_github),
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(20.dp),
|
||||
tint = MaterialTheme.colorScheme.onPrimaryContainer
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
WideActionTile(
|
||||
title = "Собрать отчёт",
|
||||
subtitle = "Android, ABI, версия, устройство",
|
||||
onClick = {
|
||||
val clipboard = context.getSystemService(ClipboardManager::class.java)
|
||||
clipboard?.setPrimaryClip(ClipData.newPlainText("CSQTT Report", buildSupportReport()))
|
||||
context.showRaisedToast("Отчёт сформирован и скопирован", Toast.LENGTH_SHORT)
|
||||
},
|
||||
icon = {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.ContentCopy,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(20.dp),
|
||||
tint = MaterialTheme.colorScheme.onPrimaryContainer
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
WideActionTile(
|
||||
title = "Проверить обновления",
|
||||
subtitle = updateStatus,
|
||||
onClick = {
|
||||
if (isCheckingUpdates) return@WideActionTile
|
||||
isCheckingUpdates = true
|
||||
scope.launch {
|
||||
val checkedAt = System.currentTimeMillis()
|
||||
val release = fetchLatestReleaseInfo(currentVersion)
|
||||
val latest = release?.versionTag
|
||||
settingsStore.saveUpdateState(
|
||||
lastCheckAt = checkedAt,
|
||||
latestVersion = latest ?: "",
|
||||
error = if (release == null) "Не удалось проверить" else ""
|
||||
)
|
||||
isCheckingUpdates = false
|
||||
|
||||
if (release == null) {
|
||||
val message = if (updateLatestVersion.isNotBlank()) {
|
||||
"Не удалось проверить. Последняя известная версия: $updateLatestVersion"
|
||||
} else {
|
||||
"Не удалось проверить обновления"
|
||||
}
|
||||
context.showRaisedToast(message, Toast.LENGTH_SHORT)
|
||||
return@launch
|
||||
}
|
||||
|
||||
if (isNewerVersion(currentVersion, release.versionTag)) {
|
||||
settingsStore.saveUpdateDialogShown(release.versionTag, checkedAt)
|
||||
pendingManualRelease = release
|
||||
} else {
|
||||
Toast.makeText(
|
||||
context,
|
||||
"У вас уже последняя версия: ${release.versionTag}",
|
||||
Toast.LENGTH_SHORT
|
||||
).show()
|
||||
}
|
||||
}
|
||||
},
|
||||
icon = {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Update,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(20.dp),
|
||||
tint = MaterialTheme.colorScheme.onPrimaryContainer
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
pendingManualRelease?.let { release ->
|
||||
AppUpdateDialog(
|
||||
release = release,
|
||||
onPostpone = {
|
||||
pendingManualRelease = null
|
||||
context.showRaisedToast("Обновление отложено на 24 часа.", Toast.LENGTH_SHORT)
|
||||
scope.launch {
|
||||
val now = System.currentTimeMillis()
|
||||
settingsStore.saveUpdatePostpone(
|
||||
version = release.versionTag,
|
||||
until = now + 24L * 60L * 60L * 1000L
|
||||
)
|
||||
settingsStore.saveUpdateDialogAction(
|
||||
version = release.versionTag,
|
||||
action = UPDATE_DIALOG_ACTION_POSTPONED,
|
||||
actedAt = now
|
||||
)
|
||||
}
|
||||
},
|
||||
onUpdate = {
|
||||
pendingManualRelease = null
|
||||
scope.launch {
|
||||
settingsStore.saveUpdateDialogAction(
|
||||
version = release.versionTag,
|
||||
action = UPDATE_DIALOG_ACTION_UPDATE,
|
||||
actedAt = System.currentTimeMillis()
|
||||
)
|
||||
openUrlInBrowser(context, release.releaseUrl)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
if (showCryptoDialog) {
|
||||
CryptoDonateDialog(onDismiss = { showCryptoDialog = false })
|
||||
}
|
||||
|
||||
ExpandableSectionCard(
|
||||
title = "О проекте",
|
||||
expanded = projectExpanded,
|
||||
onToggle = onProjectToggle,
|
||||
icon = {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Code,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
}
|
||||
) {
|
||||
ProjectLinkRow(
|
||||
title = "Автор Android-версии",
|
||||
subtitle = "GitHub профиль amurcanov",
|
||||
onClick = { openUrlInBrowser(context, DeveloperProfileUrl) },
|
||||
icon = {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Person,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
ProjectLinkRow(
|
||||
title = "Репозиторий CSQTT",
|
||||
subtitle = "Исходники и релизы приложения",
|
||||
onClick = { openUrlInBrowser(context, RepositoryUrl) },
|
||||
icon = {
|
||||
Icon(
|
||||
painter = painterResource(id = R.drawable.ic_github),
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
ProjectLinkRow(
|
||||
title = "Актуальные релизы",
|
||||
subtitle = "Страница загрузки APK",
|
||||
onClick = { openUrlInBrowser(context, ReleasesUrl) },
|
||||
icon = {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Update,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(18.dp)
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(20.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import com.csqtt.client.showRaisedToast
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.widget.Toast
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.defaultMinSize
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.lazy.LazyColumn
|
||||
import androidx.compose.foundation.lazy.items
|
||||
import androidx.compose.foundation.lazy.rememberLazyListState
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.ContentCopy
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material.icons.outlined.Terminal
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||
import com.csqtt.client.DeployManager
|
||||
import com.csqtt.client.LogEntry
|
||||
import com.csqtt.client.R
|
||||
import com.csqtt.client.SettingsStore
|
||||
import com.csqtt.client.TunnelManager
|
||||
import com.csqtt.client.ui.components.CsqttEmptyState
|
||||
import com.csqtt.client.ui.components.CsqttScreen
|
||||
import com.csqtt.client.ui.components.CsqttSettingRow
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.design.CsqttSpacing
|
||||
import com.csqtt.client.ui.design.CsqttTheme
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
|
||||
@Composable
|
||||
fun LogsTab(settingsStore: SettingsStore) {
|
||||
val loggingEnabled by settingsStore.loggingEnabled.collectAsStateWithLifecycle(initialValue = true)
|
||||
val scope = rememberCoroutineScope()
|
||||
|
||||
CsqttScreen {
|
||||
AppSectionCard(
|
||||
contentPadding = PaddingValues(horizontal = CsqttSpacing.Md, vertical = CsqttSpacing.Xs),
|
||||
verticalArrangement = Arrangement.spacedBy(CsqttSpacing.None),
|
||||
) {
|
||||
CsqttSettingRow(
|
||||
title = stringResource(R.string.logs_enabled),
|
||||
checked = loggingEnabled,
|
||||
onCheckedChange = { enabled ->
|
||||
TunnelManager.isLoggingEnabled = enabled
|
||||
scope.launch {
|
||||
settingsStore.saveLoggingEnabled(enabled)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// The terminal panel is the only place reading TunnelManager.logs, so a
|
||||
// log flush (~120ms under traffic) recomposes this panel alone instead
|
||||
// of the whole tab.
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.weight(1f),
|
||||
shape = CsqttShapes.Card,
|
||||
color = CsqttTheme.extendedColors.terminalBackground,
|
||||
contentColor = CsqttTheme.extendedColors.terminalText,
|
||||
) {
|
||||
LogsTerminal()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun LogsTerminal() {
|
||||
val context = LocalContext.current
|
||||
val currentLogs = TunnelManager.logs
|
||||
val listState = rememberLazyListState()
|
||||
val copiedMessage = stringResource(R.string.logs_copied)
|
||||
val isDeploying by DeployManager.isDeploying.collectAsStateWithLifecycle()
|
||||
|
||||
LaunchedEffect(currentLogs.size, isDeploying) {
|
||||
if (isDeploying) {
|
||||
val latestDeployIndex = currentLogs.indexOfLast { it.key.startsWith("deploy_") }
|
||||
if (latestDeployIndex >= 0) listState.animateScrollToItem(latestDeployIndex)
|
||||
}
|
||||
}
|
||||
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
if (currentLogs.isEmpty()) {
|
||||
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
|
||||
CsqttEmptyState(
|
||||
title = stringResource(R.string.logs_empty_title),
|
||||
icon = Icons.Outlined.Terminal,
|
||||
modifier = Modifier.padding(CsqttSpacing.Md),
|
||||
contentColor = CsqttTheme.extendedColors.terminalText,
|
||||
secondaryContentColor = CsqttTheme.extendedColors.terminalMuted,
|
||||
)
|
||||
}
|
||||
} else {
|
||||
LazyColumn(
|
||||
state = listState,
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
contentPadding = PaddingValues(start = CsqttSpacing.Md, top = CsqttSpacing.Md, end = CsqttSpacing.Md, bottom = 64.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(CsqttSpacing.Xs),
|
||||
) {
|
||||
items(
|
||||
items = currentLogs,
|
||||
key = { it.key },
|
||||
contentType = { "log_line" },
|
||||
) { entry ->
|
||||
LogLine(entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.align(Alignment.BottomEnd)
|
||||
.padding(16.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
IconButton(
|
||||
onClick = {
|
||||
val text = currentLogs.joinToString("\n") { "${it.message} (x${it.count})" }
|
||||
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
|
||||
clipboard.setPrimaryClip(ClipData.newPlainText("CSQTT Logs", text))
|
||||
context.showRaisedToast(copiedMessage, Toast.LENGTH_SHORT)
|
||||
},
|
||||
enabled = currentLogs.isNotEmpty(),
|
||||
modifier = Modifier.size(40.dp)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.ContentCopy,
|
||||
contentDescription = stringResource(R.string.action_copy),
|
||||
tint = if (currentLogs.isNotEmpty()) Color.White else Color.White.copy(alpha = 0.4f),
|
||||
modifier = Modifier.size(22.dp)
|
||||
)
|
||||
}
|
||||
|
||||
IconButton(
|
||||
onClick = TunnelManager::clearLogs,
|
||||
modifier = Modifier.size(40.dp)
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.Delete,
|
||||
contentDescription = stringResource(R.string.action_clear),
|
||||
tint = Color.White,
|
||||
modifier = Modifier.size(22.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,66 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
|
||||
@Composable
|
||||
internal fun WifiAutoPauseInfoDialog(onDismiss: () -> Unit) {
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Dialog,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
tonalElevation = 6.dp,
|
||||
modifier = Modifier.fillMaxWidth(0.9f),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Text(
|
||||
"Автопауза при Wi-Fi",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
Text(
|
||||
"Когда функция включена и устройство подключается к Wi-Fi, CSQTT переходит в ожидание и отключает свой VPN-сервис. После отключения Wi-Fi CSQTT автоматически возвращается к обычному подключению, если до паузы он был включён.\n\nПо умолчанию функция выключена.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 20.sp,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Button(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.fillMaxWidth().height(48.dp),
|
||||
shape = CsqttShapes.Pill,
|
||||
colors = ButtonDefaults.buttonColors(contentColor = MaterialTheme.colorScheme.onPrimary),
|
||||
) {
|
||||
Text("Понятно", fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import androidx.compose.foundation.Image
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.selection.toggleable
|
||||
import androidx.compose.material3.Checkbox
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.ImageBitmap
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.semantics.clearAndSetSemantics
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.design.CsqttSpacing
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.ui.graphics.luminance
|
||||
|
||||
@Immutable
|
||||
internal data class AppItem(
|
||||
val name: String,
|
||||
val packageName: String,
|
||||
val icon: ImageBitmap?,
|
||||
val isSystem: Boolean,
|
||||
)
|
||||
|
||||
@Composable
|
||||
internal fun AppRow(
|
||||
app: AppItem,
|
||||
isSelected: Boolean,
|
||||
onClick: () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val isDark = colors.background.luminance() < 0.22f
|
||||
|
||||
val surfaceColor = if (isSelected) {
|
||||
colors.primaryContainer.copy(alpha = if (isDark) 0.65f else 0.85f)
|
||||
} else {
|
||||
colors.surface.copy(alpha = if (isDark) 0.50f else 0.65f)
|
||||
}
|
||||
|
||||
val borderColor = if (isSelected) {
|
||||
colors.primary.copy(alpha = 0.50f)
|
||||
} else {
|
||||
colors.outlineVariant.copy(alpha = if (isDark) 0.28f else 0.35f)
|
||||
}
|
||||
|
||||
Surface(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.heightIn(min = 68.dp)
|
||||
.toggleable(
|
||||
value = isSelected,
|
||||
role = Role.Checkbox,
|
||||
onValueChange = { onClick() },
|
||||
),
|
||||
shape = CsqttShapes.Card,
|
||||
color = surfaceColor,
|
||||
contentColor = if (isSelected) colors.onPrimaryContainer else colors.onSurface,
|
||||
border = BorderStroke(1.dp, borderColor),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = CsqttSpacing.Md, vertical = 12.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(CsqttSpacing.Md),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (app.icon != null) {
|
||||
Image(
|
||||
bitmap = app.icon,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(42.dp).clip(CsqttShapes.Small),
|
||||
)
|
||||
} else {
|
||||
Box(modifier = Modifier.size(42.dp).background(colors.surfaceVariant, CsqttShapes.Small))
|
||||
}
|
||||
|
||||
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(
|
||||
text = app.name,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
fontWeight = if (isSelected) androidx.compose.ui.text.font.FontWeight.SemiBold else androidx.compose.ui.text.font.FontWeight.Normal,
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
Text(
|
||||
text = app.packageName,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = colors.onSurfaceVariant.copy(alpha = 0.8f),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
|
||||
Checkbox(
|
||||
checked = isSelected,
|
||||
onCheckedChange = null,
|
||||
modifier = Modifier.clearAndSetSemantics { },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
import androidx.compose.ui.graphics.lerp
|
||||
import androidx.compose.ui.graphics.luminance
|
||||
|
||||
@Composable
|
||||
internal fun AppBackdrop(
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val isDark = colors.background.luminance() < 0.22f
|
||||
val baseBrush = remember(colors.background, colors.surface, colors.surfaceVariant, isDark) {
|
||||
Brush.verticalGradient(
|
||||
colors = if (isDark) {
|
||||
listOf(
|
||||
lerp(colors.background, colors.surface, 0.18f),
|
||||
colors.background,
|
||||
lerp(colors.surfaceVariant, colors.background, 0.72f),
|
||||
)
|
||||
} else {
|
||||
listOf(
|
||||
lerp(colors.background, colors.surface, 0.78f),
|
||||
colors.background,
|
||||
lerp(colors.surfaceVariant, colors.background, 0.30f),
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
.background(baseBrush),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui.components
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.RowScope
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.semantics.heading
|
||||
import androidx.compose.ui.semantics.semantics
|
||||
import com.csqtt.client.ui.design.CsqttSizes
|
||||
import com.csqtt.client.ui.design.CsqttSpacing
|
||||
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.csqtt.client.R
|
||||
|
||||
internal val LocalCsqttHeaderActions = staticCompositionLocalOf<(@Composable RowScope.() -> Unit)?> { null }
|
||||
|
||||
@Composable
|
||||
fun CsqttScreen(
|
||||
modifier: Modifier = Modifier,
|
||||
title: String? = null,
|
||||
subtitle: String? = null,
|
||||
actions: (@Composable RowScope.() -> Unit)? = null,
|
||||
content: @Composable ColumnScope.() -> Unit,
|
||||
) {
|
||||
val headerActions = LocalCsqttHeaderActions.current
|
||||
|
||||
Column(
|
||||
modifier = modifier
|
||||
.fillMaxSize()
|
||||
.padding(horizontal = CsqttSizes.ScreenHorizontalPadding)
|
||||
.padding(top = CsqttSizes.ScreenTopPadding),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.widthIn(max = CsqttSizes.ContentMaxWidth),
|
||||
verticalArrangement = Arrangement.spacedBy(CsqttSpacing.Md),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(bottom = 2.dp),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(id = R.drawable.ic_csqtt_logo),
|
||||
contentDescription = "CSQTT",
|
||||
tint = Color.Unspecified,
|
||||
modifier = Modifier.height(26.dp)
|
||||
)
|
||||
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(id = R.drawable.ic_v219_by_amurcanov),
|
||||
contentDescription = "v2.1.9 by amurcanov",
|
||||
tint = Color.Unspecified,
|
||||
modifier = Modifier.height(19.dp)
|
||||
)
|
||||
headerActions?.let { Row(content = it) }
|
||||
}
|
||||
}
|
||||
if (!title.isNullOrBlank() || actions != null) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(CsqttSpacing.Md),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.weight(1f),
|
||||
verticalArrangement = Arrangement.spacedBy(CsqttSpacing.Xxs),
|
||||
) {
|
||||
if (!title.isNullOrBlank()) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.headlineSmall,
|
||||
color = MaterialTheme.colorScheme.onBackground,
|
||||
modifier = Modifier.semantics { heading() },
|
||||
)
|
||||
}
|
||||
subtitle?.let {
|
||||
Text(
|
||||
text = it,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
actions?.let { Row(content = it) }
|
||||
}
|
||||
}
|
||||
content()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui.components
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.defaultMinSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.selection.selectable
|
||||
import androidx.compose.foundation.selection.selectableGroup
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.rounded.Check
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.design.CsqttSizes
|
||||
import com.csqtt.client.ui.design.CsqttSpacing
|
||||
|
||||
@Composable
|
||||
fun <T> CsqttSegmentedControl(
|
||||
options: List<Pair<T, String>>,
|
||||
selected: T,
|
||||
onSelected: (T) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
enabled: Boolean = true,
|
||||
) {
|
||||
Row(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.selectableGroup(),
|
||||
horizontalArrangement = Arrangement.spacedBy(CsqttSpacing.Xs),
|
||||
) {
|
||||
options.forEach { (value, label) ->
|
||||
val isSelected = value == selected
|
||||
Surface(
|
||||
shape = CsqttShapes.Control,
|
||||
color = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceVariant,
|
||||
contentColor = if (isSelected) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier
|
||||
.weight(1f)
|
||||
.defaultMinSize(minHeight = CsqttSizes.MinimumTouchTarget)
|
||||
.selectable(
|
||||
selected = isSelected,
|
||||
enabled = enabled,
|
||||
role = Role.RadioButton,
|
||||
onClick = { onSelected(value) },
|
||||
),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(horizontal = CsqttSpacing.Xs, vertical = 13.dp),
|
||||
horizontalArrangement = Arrangement.Center,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
if (isSelected) {
|
||||
Icon(
|
||||
imageVector = Icons.Rounded.Check,
|
||||
contentDescription = null,
|
||||
modifier = Modifier.size(CsqttSizes.IconSmall),
|
||||
)
|
||||
androidx.compose.foundation.layout.Spacer(Modifier.width(CsqttSpacing.Xxs))
|
||||
}
|
||||
Text(text = label, style = MaterialTheme.typography.labelMedium, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui.components
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.selection.toggleable
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.HelpOutline
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Switch
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.csqtt.client.ui.design.CsqttSizes
|
||||
import com.csqtt.client.ui.design.CsqttSpacing
|
||||
|
||||
@Composable
|
||||
fun CsqttSettingRow(
|
||||
title: String,
|
||||
checked: Boolean,
|
||||
onCheckedChange: ((Boolean) -> Unit)?,
|
||||
modifier: Modifier = Modifier,
|
||||
description: String? = null,
|
||||
enabled: Boolean = true,
|
||||
onInfoClick: (() -> Unit)? = null,
|
||||
infoContentDescription: String = "Подробнее",
|
||||
) {
|
||||
val interactionModifier = if (onCheckedChange == null) {
|
||||
Modifier
|
||||
} else {
|
||||
Modifier.toggleable(
|
||||
value = checked,
|
||||
enabled = enabled,
|
||||
role = Role.Switch,
|
||||
onValueChange = onCheckedChange,
|
||||
)
|
||||
}
|
||||
|
||||
Row(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.then(interactionModifier)
|
||||
.padding(vertical = CsqttSpacing.Xs),
|
||||
horizontalArrangement = Arrangement.spacedBy(CsqttSpacing.Md),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.weight(1f),
|
||||
verticalArrangement = Arrangement.spacedBy(CsqttSpacing.Xxs),
|
||||
) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.bodyLarge,
|
||||
color = if (enabled) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.55f),
|
||||
)
|
||||
description?.let {
|
||||
Text(
|
||||
text = it,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (onInfoClick != null) {
|
||||
IconButton(
|
||||
onClick = onInfoClick,
|
||||
enabled = enabled,
|
||||
modifier = Modifier.size(34.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.HelpOutline,
|
||||
contentDescription = infoContentDescription,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(CsqttSizes.IconMedium),
|
||||
)
|
||||
}
|
||||
}
|
||||
Switch(
|
||||
checked = checked,
|
||||
onCheckedChange = null,
|
||||
enabled = enabled,
|
||||
modifier = Modifier.padding(start = CsqttSpacing.Xs),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui.components
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.outlined.Info
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.design.CsqttSpacing
|
||||
|
||||
@Composable
|
||||
fun CsqttLoadingState(
|
||||
label: String,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier.fillMaxWidth().padding(CsqttSpacing.Xl),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(CsqttSpacing.Md),
|
||||
) {
|
||||
CircularProgressIndicator()
|
||||
Text(text = label, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun CsqttEmptyState(
|
||||
title: String,
|
||||
modifier: Modifier = Modifier,
|
||||
description: String? = null,
|
||||
icon: ImageVector = Icons.Outlined.Info,
|
||||
contentColor: Color = MaterialTheme.colorScheme.onSurface,
|
||||
secondaryContentColor: Color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier.fillMaxWidth().padding(CsqttSpacing.Xl),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(CsqttSpacing.Xs),
|
||||
) {
|
||||
Icon(imageVector = icon, contentDescription = null, tint = secondaryContentColor)
|
||||
Text(text = title, style = MaterialTheme.typography.titleMedium, color = contentColor)
|
||||
description?.let {
|
||||
Text(text = it, style = MaterialTheme.typography.bodyMedium, color = secondaryContentColor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun CsqttBanner(
|
||||
text: String,
|
||||
containerColor: Color,
|
||||
contentColor: Color,
|
||||
modifier: Modifier = Modifier,
|
||||
icon: ImageVector = Icons.Outlined.Info,
|
||||
) {
|
||||
Surface(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
shape = CsqttShapes.Control,
|
||||
color = containerColor,
|
||||
contentColor = contentColor,
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.padding(CsqttSpacing.Md),
|
||||
horizontalArrangement = Arrangement.spacedBy(CsqttSpacing.Sm),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Icon(imageVector = icon, contentDescription = null, modifier = Modifier.size(20.dp))
|
||||
Text(text = text, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import androidx.compose.foundation.interaction.MutableInteractionSource
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.text.BasicTextField
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.material3.ExperimentalMaterial3Api
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextFieldDefaults
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.design.CsqttSpacing
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
internal fun DeployTextField(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
label: String,
|
||||
modifier: Modifier = Modifier,
|
||||
placeholder: String? = null,
|
||||
enabled: Boolean = true,
|
||||
isError: Boolean = false,
|
||||
keyboardType: KeyboardType = KeyboardType.Text,
|
||||
imeAction: ImeAction = ImeAction.Next,
|
||||
visualTransformation: VisualTransformation = VisualTransformation.None,
|
||||
trailingContent: (@Composable () -> Unit)? = null,
|
||||
) {
|
||||
val interactionSource = remember { MutableInteractionSource() }
|
||||
val colors = OutlinedTextFieldDefaults.colors()
|
||||
BasicTextField(
|
||||
value = value,
|
||||
onValueChange = onValueChange,
|
||||
enabled = enabled,
|
||||
singleLine = true,
|
||||
keyboardOptions = KeyboardOptions(keyboardType = keyboardType, imeAction = imeAction),
|
||||
visualTransformation = visualTransformation,
|
||||
interactionSource = interactionSource,
|
||||
textStyle = MaterialTheme.typography.bodyLarge.copy(color = MaterialTheme.colorScheme.onSurface),
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
decorationBox = { innerTextField ->
|
||||
OutlinedTextFieldDefaults.DecorationBox(
|
||||
value = value,
|
||||
innerTextField = innerTextField,
|
||||
enabled = enabled,
|
||||
singleLine = true,
|
||||
visualTransformation = visualTransformation,
|
||||
interactionSource = interactionSource,
|
||||
isError = isError,
|
||||
label = { Text(label, maxLines = 1, softWrap = false, overflow = TextOverflow.Ellipsis) },
|
||||
placeholder = placeholder?.let {
|
||||
{ Text(it, maxLines = 1, softWrap = false, overflow = TextOverflow.Ellipsis) }
|
||||
},
|
||||
trailingIcon = trailingContent,
|
||||
colors = colors,
|
||||
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 14.dp),
|
||||
container = {
|
||||
OutlinedTextFieldDefaults.Container(
|
||||
enabled = enabled,
|
||||
isError = isError,
|
||||
interactionSource = interactionSource,
|
||||
colors = colors,
|
||||
shape = CsqttShapes.Control,
|
||||
)
|
||||
},
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun AdaptiveFieldPair(
|
||||
first: @Composable () -> Unit,
|
||||
second: @Composable () -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Row(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(CsqttSpacing.Sm),
|
||||
) {
|
||||
Box(modifier = Modifier.weight(1f)) { first() }
|
||||
Box(modifier = Modifier.weight(1f)) { second() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
|
||||
@Composable
|
||||
internal fun DockerInstallInfoDialog(onDismiss: () -> Unit) {
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Dialog,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
tonalElevation = 6.dp,
|
||||
modifier = Modifier.fillMaxWidth(0.9f),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Text(
|
||||
"Установка в Docker",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
)
|
||||
Text(
|
||||
text = "Если включено, CSQTT устанавливается и запускается в отдельном Docker-контейнере вместо службы csqtt.service. Если Docker отсутствует, установщик загрузит актуальную стабильную версию и запустит Docker автоматически.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 20.sp,
|
||||
)
|
||||
Text(
|
||||
text = "Для максимальной совместимости контейнер запускается в privileged-режиме, использует сеть VPS и /dev/net/tun. Это открывает контейнеру доступ к возможностям ядра и устройствам VPS, включая io_uring и netfilter, но заметно ослабляет изоляцию Docker.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 20.sp,
|
||||
)
|
||||
Text(
|
||||
text = "Конфигурация и база клиентов остаются на VPS в /etc/csqtt и используются одинаково в Docker и systemd. Контейнер автоматически запускается после перезагрузки. Включайте этот режим только на доверенном VPS, где вы принимаете риск расширенных прав контейнера.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 20.sp,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Button(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.fillMaxWidth().height(48.dp),
|
||||
shape = CsqttShapes.Pill,
|
||||
colors = ButtonDefaults.buttonColors(contentColor = MaterialTheme.colorScheme.onPrimary),
|
||||
) {
|
||||
Text("Понятно", fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.HelpOutline
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Key
|
||||
import androidx.compose.material.icons.filled.Language
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
|
||||
import androidx.compose.material.icons.filled.Download
|
||||
|
||||
@Composable
|
||||
internal fun ServerActionBar(
|
||||
state: DeployUiState,
|
||||
onAction: (DeployAction) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
Column(
|
||||
modifier = modifier.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
OutlinedButton(
|
||||
onClick = { onAction(DeployAction.EditAuthorization) },
|
||||
modifier = Modifier.weight(1f).height(52.dp),
|
||||
shape = CsqttShapes.Pill,
|
||||
colors = ButtonDefaults.outlinedButtonColors(
|
||||
containerColor = Color.Transparent,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
border = BorderStroke(
|
||||
1.dp,
|
||||
if (state.authorizationConfigured) MaterialTheme.colorScheme.outline.copy(alpha = 0.4f) else MaterialTheme.colorScheme.error,
|
||||
),
|
||||
contentPadding = PaddingValues(horizontal = 8.dp),
|
||||
) {
|
||||
Icon(Icons.Default.Key, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("Авторизация", fontWeight = FontWeight.Bold, maxLines = 1)
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = { onAction(DeployAction.Install) },
|
||||
enabled = !state.isDeploying,
|
||||
modifier = Modifier.weight(1f).height(52.dp),
|
||||
shape = CsqttShapes.Pill,
|
||||
contentPadding = PaddingValues(horizontal = 8.dp),
|
||||
elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp, pressedElevation = 0.dp)
|
||||
) {
|
||||
if (state.isDeploying) {
|
||||
CircularProgressIndicator(
|
||||
modifier = Modifier.size(16.dp),
|
||||
color = MaterialTheme.colorScheme.onPrimary,
|
||||
strokeWidth = 2.dp,
|
||||
)
|
||||
Spacer(Modifier.width(6.dp))
|
||||
} else {
|
||||
Icon(Icons.Default.Download, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
}
|
||||
Text(
|
||||
if (state.isDeploying) "Установка…" else "Установить",
|
||||
fontWeight = FontWeight.Bold,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
OutlinedButton(
|
||||
onClick = { onAction(DeployAction.OpenControlPanel) },
|
||||
modifier = Modifier.weight(1f).height(52.dp),
|
||||
shape = CsqttShapes.Pill,
|
||||
colors = ButtonDefaults.outlinedButtonColors(
|
||||
containerColor = Color.Transparent,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
),
|
||||
contentPadding = PaddingValues(horizontal = 4.dp),
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline.copy(alpha = 0.4f))
|
||||
) {
|
||||
Icon(Icons.Default.Language, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text(
|
||||
"Панель",
|
||||
fontWeight = FontWeight.Bold,
|
||||
maxLines = 1,
|
||||
)
|
||||
IconButton(
|
||||
onClick = { onAction(DeployAction.PanelInfo) },
|
||||
modifier = Modifier.size(34.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.HelpOutline,
|
||||
contentDescription = "Информация о панели",
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(20.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = { onAction(DeployAction.Uninstall) },
|
||||
enabled = !state.isDeploying && state.canUninstall,
|
||||
modifier = Modifier.weight(1f).height(52.dp),
|
||||
shape = CsqttShapes.Pill,
|
||||
contentPadding = PaddingValues(horizontal = 8.dp),
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.error,
|
||||
contentColor = MaterialTheme.colorScheme.onError,
|
||||
),
|
||||
elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp, pressedElevation = 0.dp)
|
||||
) {
|
||||
Icon(Icons.Default.Delete, contentDescription = null, modifier = Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("Удалить", fontWeight = FontWeight.Bold, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
|
||||
@Composable
|
||||
internal fun WebPanelInfoDialog(onDismiss: () -> Unit) {
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Dialog,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
tonalElevation = 6.dp,
|
||||
modifier = Modifier.fillMaxWidth(0.9f),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Text("Веб-панель управления", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
text = "У CSQTT есть собственная веб-панель управления сервером. По умолчанию она расположена на порту 46002; если включить режим ручных портов, порт можно изменить на свой.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 20.sp,
|
||||
)
|
||||
Text(
|
||||
text = "Кнопка «Панель» открывает панель в браузере по адресу вашего сервера. Чтобы панель заработала, укажите IP сервера, придумайте логин и пароль в окне «Авторизация» и установите CSQTT на сервер.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 20.sp,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Button(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.fillMaxWidth().height(48.dp),
|
||||
shape = CsqttShapes.Pill,
|
||||
colors = ButtonDefaults.buttonColors(contentColor = MaterialTheme.colorScheme.onPrimary),
|
||||
) {
|
||||
Text("Понятно", fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui.design
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.compose.runtime.ReadOnlyComposable
|
||||
import androidx.compose.runtime.staticCompositionLocalOf
|
||||
import androidx.compose.ui.graphics.Color
|
||||
|
||||
@Immutable
|
||||
data class CsqttExtendedColors(
|
||||
val success: Color,
|
||||
val onSuccess: Color,
|
||||
val successContainer: Color,
|
||||
val onSuccessContainer: Color,
|
||||
val warning: Color,
|
||||
val onWarning: Color,
|
||||
val warningContainer: Color,
|
||||
val onWarningContainer: Color,
|
||||
val info: Color,
|
||||
val onInfo: Color,
|
||||
val infoContainer: Color,
|
||||
val onInfoContainer: Color,
|
||||
val terminalBackground: Color,
|
||||
val terminalText: Color,
|
||||
val terminalMuted: Color,
|
||||
val terminalError: Color,
|
||||
val terminalSuccess: Color,
|
||||
)
|
||||
|
||||
internal val CsqttLightExtendedColors = CsqttExtendedColors(
|
||||
success = Color(0xFF356A4C),
|
||||
onSuccess = Color.White,
|
||||
successContainer = Color(0xFFB8F2CE),
|
||||
onSuccessContainer = Color(0xFF082014),
|
||||
warning = Color(0xFF7B5800),
|
||||
onWarning = Color.White,
|
||||
warningContainer = Color(0xFFFFDEA2),
|
||||
onWarningContainer = Color(0xFF271900),
|
||||
info = Color(0xFF475D92),
|
||||
onInfo = Color.White,
|
||||
infoContainer = Color(0xFFD9E2FF),
|
||||
onInfoContainer = Color(0xFF001A43),
|
||||
terminalBackground = Color(0xFF15171B),
|
||||
terminalText = Color(0xFFDDE1E8),
|
||||
terminalMuted = Color(0xFF9DA3AE),
|
||||
terminalError = Color(0xFFFFB4AB),
|
||||
terminalSuccess = Color(0xFF9BD4AF),
|
||||
)
|
||||
|
||||
internal val CsqttDarkExtendedColors = CsqttExtendedColors(
|
||||
success = Color(0xFF9BD4AF),
|
||||
onSuccess = Color(0xFF06391E),
|
||||
successContainer = Color(0xFF1D5134),
|
||||
onSuccessContainer = Color(0xFFB7F1CD),
|
||||
warning = Color(0xFFF2C25B),
|
||||
onWarning = Color(0xFF402D00),
|
||||
warningContainer = Color(0xFF5C4200),
|
||||
onWarningContainer = Color(0xFFFFDEA2),
|
||||
info = Color(0xFFB2C5FF),
|
||||
onInfo = Color(0xFF172E60),
|
||||
infoContainer = Color(0xFF304577),
|
||||
onInfoContainer = Color(0xFFD9E2FF),
|
||||
terminalBackground = Color(0xFF101216),
|
||||
terminalText = Color(0xFFDDE1E8),
|
||||
terminalMuted = Color(0xFF9DA3AE),
|
||||
terminalError = Color(0xFFFFB4AB),
|
||||
terminalSuccess = Color(0xFF9BD4AF),
|
||||
)
|
||||
|
||||
internal val LocalCsqttExtendedColors = staticCompositionLocalOf { CsqttDarkExtendedColors }
|
||||
|
||||
object CsqttTheme {
|
||||
val extendedColors: CsqttExtendedColors
|
||||
@Composable
|
||||
@ReadOnlyComposable
|
||||
get() = LocalCsqttExtendedColors.current
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui.design
|
||||
|
||||
import androidx.compose.animation.core.FastOutLinearInEasing
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
import androidx.compose.animation.core.LinearOutSlowInEasing
|
||||
import androidx.compose.animation.core.spring
|
||||
import androidx.compose.animation.core.tween
|
||||
import androidx.compose.runtime.Immutable
|
||||
|
||||
@Immutable
|
||||
object CsqttMotion {
|
||||
const val Instant = 90
|
||||
const val Fast = 140
|
||||
const val Normal = 220
|
||||
const val Slow = 320
|
||||
const val Backdrop = 520
|
||||
|
||||
val StandardEasing = FastOutSlowInEasing
|
||||
val DecelerateEasing = LinearOutSlowInEasing
|
||||
val AccelerateEasing = FastOutLinearInEasing
|
||||
|
||||
fun <T> fastTween() = tween<T>(durationMillis = Fast, easing = StandardEasing)
|
||||
|
||||
fun <T> standardTween() = tween<T>(durationMillis = Normal, easing = StandardEasing)
|
||||
|
||||
fun <T> slowTween() = tween<T>(durationMillis = Slow, easing = StandardEasing)
|
||||
|
||||
fun <T> backdropTween() = tween<T>(durationMillis = Backdrop, easing = StandardEasing)
|
||||
|
||||
fun <T> softSpring() = spring<T>(dampingRatio = 0.88f, stiffness = 500f)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui.design
|
||||
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.Shapes
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@Immutable
|
||||
object CsqttShapes {
|
||||
val Small = RoundedCornerShape(22.dp)
|
||||
val Control = RoundedCornerShape(percent = 50)
|
||||
val Card = RoundedCornerShape(34.dp)
|
||||
val LargeCard = RoundedCornerShape(42.dp)
|
||||
val Dialog = RoundedCornerShape(40.dp)
|
||||
val Pill = RoundedCornerShape(percent = 50)
|
||||
}
|
||||
|
||||
val CsqttMaterialShapes = Shapes(
|
||||
extraSmall = CsqttShapes.Small,
|
||||
small = CsqttShapes.Small,
|
||||
medium = CsqttShapes.Control,
|
||||
large = CsqttShapes.Card,
|
||||
extraLarge = CsqttShapes.Dialog,
|
||||
)
|
||||
@@ -0,0 +1,25 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui.design
|
||||
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@Immutable
|
||||
object CsqttSizes {
|
||||
val ScreenHorizontalPadding = 20.dp
|
||||
val ScreenTopPadding = 12.dp
|
||||
val ScreenBottomPadding = 32.dp
|
||||
|
||||
val ControlHeight = 52.dp
|
||||
val CompactControlHeight = 44.dp
|
||||
val MinimumTouchTarget = 48.dp
|
||||
|
||||
val IconSmall = 18.dp
|
||||
val IconMedium = 20.dp
|
||||
val IconLarge = 24.dp
|
||||
|
||||
val ContentMaxWidth = 720.dp
|
||||
val Divider = 1.dp
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui.design
|
||||
|
||||
import androidx.compose.runtime.Immutable
|
||||
import androidx.compose.ui.unit.dp
|
||||
|
||||
@Immutable
|
||||
object CsqttSpacing {
|
||||
val None = 0.dp
|
||||
val Xxs = 4.dp
|
||||
val Xs = 8.dp
|
||||
val Sm = 12.dp
|
||||
val Md = 16.dp
|
||||
val Lg = 20.dp
|
||||
val Xl = 24.dp
|
||||
val Xxl = 32.dp
|
||||
val Xxxl = 40.dp
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui.dialogs
|
||||
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import android.content.Context
|
||||
import android.widget.Toast
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.selection.SelectionContainer
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.outlined.ContentCopy
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.graphics.luminance
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.csqtt.client.R
|
||||
import com.csqtt.client.showRaisedToast
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
|
||||
private const val GRAM_TON_WALLET = "UQCsHSj_Bev5AG3vCz-84TQC7BSWjNdNdOjP9M2gWUEmbyD7"
|
||||
private const val USDT_TON_WALLET = "UQCsHSj_Bev5AG3vCz-84TQC7BSWjNdNdOjP9M2gWUEmbyD7"
|
||||
private const val USDT_TRC20_WALLET = "TD1oiQiHmjqsRDPxfUjUbSWxEmcr4k7Lob"
|
||||
|
||||
private fun copyAddressToClipboard(context: Context, label: String, address: String) {
|
||||
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
|
||||
clipboard?.setPrimaryClip(ClipData.newPlainText(label, address))
|
||||
context.showRaisedToast("Адрес скопирован", Toast.LENGTH_SHORT)
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun CryptoDonateDialog(onDismiss: () -> Unit) {
|
||||
val context = LocalContext.current
|
||||
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false)
|
||||
) {
|
||||
Surface(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth(0.92f)
|
||||
.padding(12.dp),
|
||||
shape = CsqttShapes.Dialog,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
tonalElevation = 8.dp
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(22.dp)
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text(
|
||||
text = "Поддержать криптовалютой",
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.Bold
|
||||
)
|
||||
IconButton(onClick = onDismiss) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
|
||||
CryptoAddressField(
|
||||
title = "GRAM",
|
||||
instruction = "Перевод Gram в сети TON на криптокошелек:",
|
||||
address = GRAM_TON_WALLET,
|
||||
onCopy = { copyAddressToClipboard(context, "Gram Address", GRAM_TON_WALLET) }
|
||||
)
|
||||
|
||||
CryptoAddressField(
|
||||
title = "USDT TON",
|
||||
instruction = "Перевод USDT в сети TON на криптокошелек:",
|
||||
address = USDT_TON_WALLET,
|
||||
onCopy = { copyAddressToClipboard(context, "USDT TON Address", USDT_TON_WALLET) }
|
||||
)
|
||||
|
||||
CryptoAddressField(
|
||||
title = "USDT TRC20",
|
||||
instruction = "Перевод USDT в сети TRC20 на криптокошелек:",
|
||||
address = USDT_TRC20_WALLET,
|
||||
onCopy = { copyAddressToClipboard(context, "USDT TRC20 Address", USDT_TRC20_WALLET) }
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(4.dp))
|
||||
|
||||
Button(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(48.dp),
|
||||
shape = CsqttShapes.Pill,
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.primary,
|
||||
contentColor = MaterialTheme.colorScheme.onPrimary
|
||||
)
|
||||
) {
|
||||
Text(
|
||||
text = "Хорошо",
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
fontSize = 15.sp
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CryptoAddressField(
|
||||
title: String,
|
||||
instruction: String,
|
||||
address: String,
|
||||
onCopy: () -> Unit
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val isDark = colors.background.luminance() < 0.22f
|
||||
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(6.dp)
|
||||
) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.primary
|
||||
)
|
||||
Text(
|
||||
text = instruction,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = colors.onSurfaceVariant,
|
||||
lineHeight = 18.sp
|
||||
)
|
||||
|
||||
Surface(
|
||||
shape = CsqttShapes.Control,
|
||||
color = if (isDark) Color(0xFF13171F) else Color(0xFFF1F3F7),
|
||||
border = BorderStroke(1.dp, colors.outlineVariant.copy(alpha = if (isDark) 0.35f else 0.5f)),
|
||||
modifier = Modifier.fillMaxWidth()
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.padding(start = 14.dp, end = 8.dp, top = 8.dp, bottom = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
SelectionContainer(
|
||||
modifier = Modifier.weight(1f)
|
||||
) {
|
||||
Text(
|
||||
text = address,
|
||||
style = MaterialTheme.typography.bodySmall.copy(
|
||||
fontSize = 12.5.sp,
|
||||
lineHeight = 17.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
),
|
||||
fontFamily = FontFamily.Monospace,
|
||||
color = colors.onSurface,
|
||||
maxLines = 2,
|
||||
overflow = TextOverflow.Ellipsis
|
||||
)
|
||||
}
|
||||
|
||||
Surface(
|
||||
shape = CsqttShapes.Pill,
|
||||
color = Color(0xFF121418),
|
||||
contentColor = Color.White,
|
||||
modifier = Modifier
|
||||
.size(42.dp)
|
||||
.clip(CsqttShapes.Pill)
|
||||
.clickable(onClick = onCopy)
|
||||
) {
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.fillMaxSize()
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Outlined.ContentCopy,
|
||||
contentDescription = "Скопировать",
|
||||
tint = Color.White,
|
||||
modifier = Modifier.size(20.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui.dialogs
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import com.csqtt.client.SettingsStore
|
||||
import kotlinx.coroutines.launch
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.design.CsqttSizes
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun DeploySecretsDialog(
|
||||
settingsStore: SettingsStore,
|
||||
initialMainPass: String,
|
||||
initialSshLogin: String,
|
||||
initialSshPass: String,
|
||||
initialWebLogin: String,
|
||||
initialWebPass: String,
|
||||
onSaved: () -> Unit,
|
||||
onDismiss: () -> Unit
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
var passInput by rememberSaveable { mutableStateOf(initialMainPass) }
|
||||
var webLoginInput by rememberSaveable { mutableStateOf(initialWebLogin) }
|
||||
var webPassInput by rememberSaveable { mutableStateOf(initialWebPass) }
|
||||
var passwordsVisible by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
Dialog(onDismissRequest = onDismiss) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Dialog,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
tonalElevation = 8.dp
|
||||
) {
|
||||
Column(modifier = Modifier.padding(24.dp).fillMaxWidth().verticalScroll(rememberScrollState())) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Text("Авторизация", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
|
||||
IconButton(onClick = onDismiss) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
Text(
|
||||
text = "Придумайте свои данные — латиница и цифры. Они будут созданы на сервере при установке, искать ничего не нужно.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Spacer(Modifier.height(16.dp))
|
||||
|
||||
val allowedChars = Regex("^[a-zA-Z0-9]+$")
|
||||
val invalidHint: @Composable () -> Unit = {
|
||||
Text("Разрешена «Латиница» и «Цифры»", color = MaterialTheme.colorScheme.error)
|
||||
}
|
||||
val isPasswordValid = passInput.isNotEmpty() && passInput.matches(allowedChars)
|
||||
val isWebLoginValid = webLoginInput.isNotEmpty() && webLoginInput.matches(allowedChars)
|
||||
val isWebPassValid = webPassInput.isNotEmpty() && webPassInput.matches(allowedChars)
|
||||
|
||||
Text("Подключение", color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.SemiBold)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
OutlinedTextField(
|
||||
value = passInput,
|
||||
onValueChange = {
|
||||
passInput = it.filter { c -> !c.isWhitespace() }
|
||||
},
|
||||
label = { Text("Пароль туннеля (придумайте)", maxLines = 1, softWrap = false, overflow = TextOverflow.Ellipsis) },
|
||||
placeholder = { Text("придумайте пароль", maxLines = 1, softWrap = false, overflow = TextOverflow.Ellipsis) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = CsqttShapes.Control,
|
||||
isError = !isPasswordValid,
|
||||
supportingText = if (passInput.isNotEmpty() && !isPasswordValid) invalidHint else null,
|
||||
visualTransformation = if (passwordsVisible) VisualTransformation.None else PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
|
||||
trailingIcon = {
|
||||
TextButton(onClick = { passwordsVisible = !passwordsVisible }) {
|
||||
Text(if (passwordsVisible) "Скрыть" else "Показать")
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(16.dp))
|
||||
HorizontalDivider()
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Text("Данные доступа к web панели", color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.SemiBold)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = webLoginInput,
|
||||
onValueChange = {
|
||||
webLoginInput = it.filter { c -> !c.isWhitespace() }
|
||||
},
|
||||
label = { Text("Логин WEB (придумайте)", maxLines = 1, softWrap = false, overflow = TextOverflow.Ellipsis) },
|
||||
placeholder = { Text("придумайте логин", maxLines = 1, softWrap = false, overflow = TextOverflow.Ellipsis) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = CsqttShapes.Control,
|
||||
isError = !isWebLoginValid,
|
||||
supportingText = if (webLoginInput.isNotEmpty() && !isWebLoginValid) invalidHint else null
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(8.dp))
|
||||
|
||||
OutlinedTextField(
|
||||
value = webPassInput,
|
||||
onValueChange = {
|
||||
webPassInput = it.filter { c -> !c.isWhitespace() }
|
||||
},
|
||||
label = { Text("Пароль WEB (придумайте)", maxLines = 1, softWrap = false, overflow = TextOverflow.Ellipsis) },
|
||||
placeholder = { Text("придумайте пароль", maxLines = 1, softWrap = false, overflow = TextOverflow.Ellipsis) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = CsqttShapes.Control,
|
||||
isError = !isWebPassValid,
|
||||
supportingText = if (webPassInput.isNotEmpty() && !isWebPassValid) invalidHint else null,
|
||||
visualTransformation = if (passwordsVisible) VisualTransformation.None else PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
|
||||
)
|
||||
|
||||
Spacer(Modifier.height(20.dp))
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
scope.launch {
|
||||
settingsStore.saveDeploySecrets(passInput, initialSshLogin, initialSshPass, webLoginInput, webPassInput)
|
||||
onSaved()
|
||||
onDismiss()
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = CsqttSizes.ControlHeight),
|
||||
shape = CsqttShapes.Control,
|
||||
enabled = isPasswordValid && isWebLoginValid && isWebPassValid,
|
||||
colors = ButtonDefaults.buttonColors(contentColor = MaterialTheme.colorScheme.onPrimary)
|
||||
) {
|
||||
Text("Сохранить", fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui.dialogs
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.isSystemInDarkTheme
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material.icons.filled.Tag
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import com.csqtt.client.VkHashValidationCodec
|
||||
import com.csqtt.client.VkHashValidationStatus
|
||||
import com.csqtt.client.ui.utils.stripVkUrlStatic
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.design.CsqttSizes
|
||||
import kotlinx.coroutines.launch
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun HashesDialog(
|
||||
hash1: String,
|
||||
hash2: String,
|
||||
hash3: String,
|
||||
hash4: String,
|
||||
hash5: String,
|
||||
hash6: String,
|
||||
validationResults: Map<String, VkHashValidationStatus>,
|
||||
onValidationResultsChange: (Map<String, VkHashValidationStatus>) -> Unit,
|
||||
onCheck: suspend (List<String>) -> Map<String, VkHashValidationStatus>,
|
||||
onSave: (String, String, String, String, String, String) -> Unit,
|
||||
onDismiss: () -> Unit
|
||||
) {
|
||||
var h1 by remember { mutableStateOf(hash1) }
|
||||
var h2 by remember { mutableStateOf(hash2) }
|
||||
var h3 by remember { mutableStateOf(hash3) }
|
||||
var h4 by remember { mutableStateOf(hash4) }
|
||||
var h5 by remember { mutableStateOf(hash5) }
|
||||
var h6 by remember { mutableStateOf(hash6) }
|
||||
var results by remember(validationResults) { mutableStateOf(validationResults) }
|
||||
var isChecking by remember { mutableStateOf(false) }
|
||||
var unavailableCount by remember { mutableIntStateOf(0) }
|
||||
val scope = rememberCoroutineScope()
|
||||
val hashes = listOf(h1, h2, h3, h4, h5, h6)
|
||||
val validBorder = if (isSystemInDarkTheme()) Color(0xFF66BB6A) else Color(0xFF2E7D32)
|
||||
|
||||
fun updateHash(index: Int, raw: String) {
|
||||
val cleaned = stripVkUrlStatic(raw.filter { it != ' ' && it != '\n' && it != '\r' })
|
||||
val previous = hashes[index]
|
||||
if (cleaned == previous) return
|
||||
if (results.containsKey(previous)) {
|
||||
val updatedResults = VkHashValidationCodec.invalidate(results, previous)
|
||||
results = updatedResults
|
||||
onValidationResultsChange(updatedResults)
|
||||
}
|
||||
unavailableCount = 0
|
||||
when (index) {
|
||||
0 -> h1 = cleaned
|
||||
1 -> h2 = cleaned
|
||||
2 -> h3 = cleaned
|
||||
3 -> h4 = cleaned
|
||||
4 -> h5 = cleaned
|
||||
5 -> h6 = cleaned
|
||||
}
|
||||
}
|
||||
|
||||
Dialog(onDismissRequest = onDismiss) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Dialog,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
tonalElevation = 8.dp
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(24.dp).fillMaxWidth().verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp)
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(Icons.Default.Tag, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(24.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("VK Хеши", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
IconButton(onClick = onDismiss) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
|
||||
Text(
|
||||
text = "Больше хешей — выше лимит потоков и лучшее распределение нагрузки.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(bottom = 4.dp)
|
||||
)
|
||||
|
||||
hashes.forEachIndexed { idx, value ->
|
||||
val label = if (idx == 0) "VK Хеш 1 *" else "VK Хеш ${idx + 1}"
|
||||
val isShort = value.isNotBlank() && value.length < 16
|
||||
val status = results[value]
|
||||
val isInvalid = status == VkHashValidationStatus.Invalid
|
||||
val fieldColors = if (status == VkHashValidationStatus.Valid) {
|
||||
OutlinedTextFieldDefaults.colors(
|
||||
focusedBorderColor = validBorder,
|
||||
unfocusedBorderColor = validBorder,
|
||||
)
|
||||
} else {
|
||||
OutlinedTextFieldDefaults.colors()
|
||||
}
|
||||
OutlinedTextField(
|
||||
value = value,
|
||||
onValueChange = { updateHash(idx, it) },
|
||||
label = { Text(label, maxLines = 1, softWrap = false, overflow = TextOverflow.Ellipsis) },
|
||||
placeholder = {
|
||||
Text(
|
||||
"Ссылка звонка или хеш",
|
||||
maxLines = 1,
|
||||
softWrap = false,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
},
|
||||
singleLine = true,
|
||||
enabled = !isChecking,
|
||||
isError = isShort || isInvalid,
|
||||
supportingText = if (isShort) {
|
||||
{ Text("Хеш ${idx + 1} — короткий (мин. 16)", color = MaterialTheme.colorScheme.error) }
|
||||
} else null,
|
||||
trailingIcon = {
|
||||
IconButton(
|
||||
onClick = { updateHash(idx, "") },
|
||||
enabled = value.isNotEmpty(),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Delete,
|
||||
contentDescription = "Удалить хеш ${idx + 1}",
|
||||
tint = MaterialTheme.colorScheme.error.copy(
|
||||
alpha = if (value.isNotEmpty()) 1f else 0.38f,
|
||||
),
|
||||
)
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = CsqttShapes.Control,
|
||||
colors = fieldColors,
|
||||
)
|
||||
}
|
||||
|
||||
val pendingHashes = VkHashValidationCodec.pending(hashes, results)
|
||||
OutlinedButton(
|
||||
onClick = {
|
||||
isChecking = true
|
||||
unavailableCount = 0
|
||||
scope.launch {
|
||||
val checked = onCheck(pendingHashes)
|
||||
val updatedResults = results + checked
|
||||
results = updatedResults
|
||||
onValidationResultsChange(updatedResults)
|
||||
unavailableCount = pendingHashes.size - checked.size
|
||||
isChecking = false
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = CsqttSizes.ControlHeight),
|
||||
enabled = !isChecking && pendingHashes.isNotEmpty(),
|
||||
shape = CsqttShapes.Control,
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary),
|
||||
colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.primary),
|
||||
) {
|
||||
Text(
|
||||
if (isChecking) "Проверяем..." else "Проверить актив",
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
)
|
||||
}
|
||||
|
||||
if (unavailableCount > 0) {
|
||||
Text(
|
||||
"Не удалось проверить: $unavailableCount. Поля оставлены без статуса.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
onSave(h1, h2, h3, h4, h5, h6)
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = CsqttSizes.ControlHeight),
|
||||
shape = CsqttShapes.Control,
|
||||
colors = ButtonDefaults.buttonColors(contentColor = MaterialTheme.colorScheme.onPrimary)
|
||||
) {
|
||||
Text("Сохранить", fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui.dialogs
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Key
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import com.csqtt.client.SettingsStore
|
||||
import kotlinx.coroutines.launch
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.design.CsqttSizes
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun SecretsDialog(
|
||||
settingsStore: SettingsStore,
|
||||
initialPassword: String,
|
||||
onSaved: () -> Unit,
|
||||
onDismiss: () -> Unit
|
||||
) {
|
||||
val scope = rememberCoroutineScope()
|
||||
var passwordInput by rememberSaveable { mutableStateOf(initialPassword) }
|
||||
var passwordVisible by rememberSaveable { mutableStateOf(false) }
|
||||
|
||||
Dialog(onDismissRequest = onDismiss) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Dialog,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
tonalElevation = 8.dp
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(24.dp).fillMaxWidth().verticalScroll(rememberScrollState())
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
imageVector = Icons.Default.Key,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(24.dp)
|
||||
)
|
||||
Spacer(modifier = Modifier.width(8.dp))
|
||||
Text("Подключение", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
IconButton(onClick = onDismiss) {
|
||||
Icon(imageVector = Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
|
||||
Spacer(modifier = Modifier.height(16.dp))
|
||||
|
||||
val isPasswordValid = passwordInput.isNotEmpty() && passwordInput.matches(Regex("^[a-zA-Z0-9_.!?:#/-]+$"))
|
||||
|
||||
OutlinedTextField(
|
||||
value = passwordInput,
|
||||
onValueChange = { passwordInput = it.filter { c -> !c.isWhitespace() } },
|
||||
label = { Text("Пароль туннеля", maxLines = 1, softWrap = false, overflow = TextOverflow.Ellipsis) },
|
||||
placeholder = { Text("укажите пароль", maxLines = 1, softWrap = false, overflow = TextOverflow.Ellipsis) },
|
||||
singleLine = true,
|
||||
isError = !isPasswordValid,
|
||||
supportingText = if (passwordInput.isNotEmpty() && !isPasswordValid) {
|
||||
{ Text("Разрешены только буквы, цифры и знаки . ! ? : # - _ /", color = MaterialTheme.colorScheme.error) }
|
||||
} else null,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = CsqttShapes.Control,
|
||||
visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
|
||||
trailingIcon = {
|
||||
TextButton(onClick = { passwordVisible = !passwordVisible }) {
|
||||
Text(if (passwordVisible) "Скрыть" else "Показать")
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
Spacer(modifier = Modifier.height(20.dp))
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
scope.launch {
|
||||
settingsStore.saveConnectionPassword(passwordInput)
|
||||
onSaved()
|
||||
onDismiss()
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = CsqttSizes.ControlHeight),
|
||||
shape = CsqttShapes.Control,
|
||||
colors = ButtonDefaults.buttonColors(contentColor = MaterialTheme.colorScheme.onPrimary)
|
||||
) {
|
||||
Text("Сохранить", fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui.dialogs
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.text.KeyboardOptions
|
||||
import androidx.compose.foundation.verticalScroll
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Key
|
||||
import androidx.compose.material.icons.outlined.Visibility
|
||||
import androidx.compose.material.icons.outlined.VisibilityOff
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedTextField
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.PasswordVisualTransformation
|
||||
import androidx.compose.ui.text.input.VisualTransformation
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.design.CsqttSizes
|
||||
|
||||
private const val PRIVATE_KEY_PLACEHOLDER =
|
||||
"-----BEGIN OPENSSH PRIVATE KEY-----\n...\n-----END OPENSSH PRIVATE KEY-----"
|
||||
|
||||
private const val CERTIFICATE_PLACEHOLDER =
|
||||
"ssh-ed25519-cert-v01@openssh.com AAAAIHNzaC1lZDI1NTE5...\nuser-cert"
|
||||
|
||||
private val SshKeyFieldShape = RoundedCornerShape(8.dp)
|
||||
|
||||
private val PRIVATE_KEY_HEADERS = listOf(
|
||||
"BEGIN OPENSSH PRIVATE KEY",
|
||||
"BEGIN RSA PRIVATE KEY",
|
||||
"BEGIN EC PRIVATE KEY",
|
||||
"BEGIN DSA PRIVATE KEY",
|
||||
"BEGIN PRIVATE KEY",
|
||||
)
|
||||
|
||||
internal fun validateSshPrivateKey(value: String, passphrase: String): String? {
|
||||
val trimmed = value.trim()
|
||||
if (trimmed.isEmpty()) return "Не удалось распознать приватный SSH-ключ"
|
||||
if ("BEGIN CERTIFICATE" in trimmed && PRIVATE_KEY_HEADERS.none { it in trimmed }) {
|
||||
return "Это X.509/TLS-сертификат. Для SSH требуется приватный SSH-ключ или сертификат OpenSSH вида ssh-*-cert-v01@openssh.com."
|
||||
}
|
||||
if (trimmed.startsWith("ssh-") && !trimmed.contains("-----BEGIN")) {
|
||||
return "Вставлен публичный ключ, но требуется приватный"
|
||||
}
|
||||
if (PRIVATE_KEY_HEADERS.none { it in trimmed }) {
|
||||
return "Не удалось распознать приватный SSH-ключ"
|
||||
}
|
||||
val looksEncrypted = "ENCRYPTED" in trimmed || "aes256-ctr" in trimmed || "bcrypt" in trimmed
|
||||
if (looksEncrypted && passphrase.isBlank()) {
|
||||
return "Ключ зашифрован. Укажите пароль ключа."
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
internal fun validateSshCertificate(value: String): String? {
|
||||
val trimmed = value.trim()
|
||||
if (trimmed.isEmpty()) return null
|
||||
if ("BEGIN CERTIFICATE" in trimmed) {
|
||||
return "Это X.509/TLS-сертификат. Для SSH требуется сертификат OpenSSH вида ssh-*-cert-v01@openssh.com."
|
||||
}
|
||||
if (!trimmed.contains("-cert-") || !trimmed.contains("@openssh.com")) {
|
||||
return "Сертификат должен быть вида ssh-*-cert-v01@openssh.com"
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SshKeysDialog(
|
||||
initialPrivateKey: String,
|
||||
initialPassphrase: String,
|
||||
initialCertificate: String,
|
||||
onSave: (String, String, String) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
var privateKey by rememberSaveable { mutableStateOf(initialPrivateKey) }
|
||||
var passphrase by rememberSaveable { mutableStateOf(initialPassphrase) }
|
||||
var certificate by rememberSaveable { mutableStateOf(initialCertificate) }
|
||||
var passphraseVisible by rememberSaveable { mutableStateOf(false) }
|
||||
var privateKeyError by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
var certificateError by rememberSaveable { mutableStateOf<String?>(null) }
|
||||
|
||||
Dialog(onDismissRequest = onDismiss) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Dialog,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
tonalElevation = 8.dp,
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.padding(24.dp)
|
||||
.fillMaxWidth()
|
||||
.verticalScroll(rememberScrollState()),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Default.Key,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(24.dp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("Ключи SSH", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)
|
||||
}
|
||||
IconButton(onClick = onDismiss) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
|
||||
Text(
|
||||
text = "Для входа достаточно одного приватного ключа — приложение само определит его формат. Пароль и сертификат нужны только если ключ зашифрован или используется сертификат OpenSSH.",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
|
||||
OutlinedTextField(
|
||||
value = privateKey,
|
||||
onValueChange = {
|
||||
privateKey = it
|
||||
privateKeyError = null
|
||||
},
|
||||
label = { Text("Приватный SSH-ключ *", maxLines = 1, softWrap = false, overflow = TextOverflow.Ellipsis) },
|
||||
placeholder = { Text(PRIVATE_KEY_PLACEHOLDER, fontFamily = FontFamily.Monospace, fontSize = 12.sp) },
|
||||
supportingText = {
|
||||
Text(
|
||||
text = privateKeyError ?: "Поддерживаются OpenSSH, RSA PEM, EC и PKCS#8",
|
||||
color = if (privateKeyError != null) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
},
|
||||
isError = privateKeyError != null,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 140.dp),
|
||||
shape = SshKeyFieldShape,
|
||||
textStyle = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Default),
|
||||
)
|
||||
|
||||
OutlinedTextField(
|
||||
value = passphrase,
|
||||
onValueChange = { passphrase = it.filter { c -> !c.isWhitespace() } },
|
||||
label = { Text("Пароль ключа (необязательно)", maxLines = 1, softWrap = false, overflow = TextOverflow.Ellipsis) },
|
||||
placeholder = { Text("если приватный ключ зашифрован", maxLines = 1, softWrap = false, overflow = TextOverflow.Ellipsis) },
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = SshKeyFieldShape,
|
||||
visualTransformation = if (passphraseVisible) VisualTransformation.None else PasswordVisualTransformation(),
|
||||
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
|
||||
trailingIcon = {
|
||||
IconButton(onClick = { passphraseVisible = !passphraseVisible }) {
|
||||
Icon(
|
||||
imageVector = if (passphraseVisible) Icons.Outlined.VisibilityOff else Icons.Outlined.Visibility,
|
||||
contentDescription = if (passphraseVisible) "Скрыть пароль" else "Показать пароль",
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
OutlinedTextField(
|
||||
value = certificate,
|
||||
onValueChange = {
|
||||
certificate = it
|
||||
certificateError = null
|
||||
},
|
||||
label = { Text("SSH-сертификат OpenSSH (необязательно)", maxLines = 1, softWrap = false, overflow = TextOverflow.Ellipsis) },
|
||||
placeholder = { Text(CERTIFICATE_PLACEHOLDER, fontFamily = FontFamily.Monospace, fontSize = 12.sp) },
|
||||
supportingText = if (certificateError != null) {
|
||||
{ Text(certificateError!!, color = MaterialTheme.colorScheme.error) }
|
||||
} else null,
|
||||
isError = certificateError != null,
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = 90.dp),
|
||||
shape = SshKeyFieldShape,
|
||||
textStyle = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
|
||||
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Default),
|
||||
)
|
||||
|
||||
Button(
|
||||
onClick = {
|
||||
val keyError = validateSshPrivateKey(privateKey, passphrase)
|
||||
val certError = validateSshCertificate(certificate)
|
||||
privateKeyError = keyError
|
||||
certificateError = certError
|
||||
if (keyError == null && certError == null) {
|
||||
onSave(privateKey.trim(), passphrase.trim(), certificate.trim())
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxWidth().heightIn(min = CsqttSizes.ControlHeight),
|
||||
shape = CsqttShapes.Control,
|
||||
colors = ButtonDefaults.buttonColors(contentColor = MaterialTheme.colorScheme.onPrimary),
|
||||
) {
|
||||
Text("Сохранить", fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui.dialogs
|
||||
|
||||
import androidx.compose.foundation.layout.*
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material3.*
|
||||
import androidx.compose.runtime.*
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.design.CsqttSizes
|
||||
|
||||
@OptIn(ExperimentalMaterial3Api::class)
|
||||
@Composable
|
||||
fun UninstallConfirmDialog(onDismiss: () -> Unit, onConfirm: () -> Unit) {
|
||||
var confirmText by remember { mutableStateOf("") }
|
||||
val isConfirmed = confirmText.trim().lowercase() == "да"
|
||||
|
||||
Dialog(onDismissRequest = onDismiss) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Dialog,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
tonalElevation = 8.dp
|
||||
) {
|
||||
Column(modifier = Modifier.padding(24.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
|
||||
Text(
|
||||
"Удаление CSQTT с сервера",
|
||||
style = MaterialTheme.typography.titleLarge,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.error
|
||||
)
|
||||
Text(
|
||||
"Будут удалены: бинарник, systemd-сервис, бот, конфигурация CSQTT и только помеченные правила firewall/NAT для CSQTT.\n\nЭто действие необратимо.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant
|
||||
)
|
||||
OutlinedTextField(
|
||||
value = confirmText,
|
||||
onValueChange = { confirmText = it },
|
||||
label = {
|
||||
Text(
|
||||
"Введите «да» для подтверждения",
|
||||
maxLines = 1,
|
||||
softWrap = false,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
},
|
||||
singleLine = true,
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
shape = CsqttShapes.Control,
|
||||
colors = OutlinedTextFieldDefaults.colors(
|
||||
focusedBorderColor = MaterialTheme.colorScheme.error,
|
||||
unfocusedBorderColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f)
|
||||
)
|
||||
)
|
||||
Column(modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
OutlinedButton(
|
||||
onClick = onDismiss, modifier = Modifier.fillMaxWidth().heightIn(min = CsqttSizes.ControlHeight),
|
||||
shape = CsqttShapes.Control,
|
||||
colors = ButtonDefaults.outlinedButtonColors(contentColor = MaterialTheme.colorScheme.onSurface)
|
||||
) { Text("Отмена") }
|
||||
Button(
|
||||
onClick = onConfirm, modifier = Modifier.fillMaxWidth().heightIn(min = CsqttSizes.ControlHeight),
|
||||
shape = CsqttShapes.Control, enabled = isConfirmed,
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.error,
|
||||
contentColor = MaterialTheme.colorScheme.onError
|
||||
)
|
||||
) {
|
||||
Icon(Icons.Default.Delete, null, Modifier.size(18.dp))
|
||||
Spacer(Modifier.width(6.dp))
|
||||
Text("Удалить", fontWeight = FontWeight.Bold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui.dialogs
|
||||
|
||||
import android.graphics.Outline
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.view.ViewOutlineProvider
|
||||
import android.widget.FrameLayout
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.material.icons.filled.Key
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.alpha
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import androidx.lifecycle.compose.LocalLifecycleOwner
|
||||
import com.csqtt.client.VkAuthPayload
|
||||
import com.csqtt.client.VkAuthPhase
|
||||
import com.csqtt.client.VkAuthSession
|
||||
import com.csqtt.client.VkAuthWebViewManager
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
|
||||
@Composable
|
||||
internal fun VkAuthDialog(
|
||||
onToken: (VkAuthPayload) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val lifecycleOwner = LocalLifecycleOwner.current
|
||||
var uiReady by remember { mutableStateOf(false) }
|
||||
var errorMessage by remember { mutableStateOf<String?>(null) }
|
||||
var phase by remember { mutableStateOf(VkAuthPhase.LOGIN) }
|
||||
|
||||
val webView = remember { VkAuthWebViewManager.acquire(context) }
|
||||
val session = remember {
|
||||
VkAuthSession(
|
||||
onUiReady = { uiReady = true },
|
||||
onToken = onToken,
|
||||
onError = { errorMessage = it },
|
||||
onPhaseChange = { phase = it },
|
||||
)
|
||||
}
|
||||
|
||||
DisposableEffect(session, webView, lifecycleOwner) {
|
||||
session.attach(webView)
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
when (event) {
|
||||
Lifecycle.Event.ON_STOP -> session.pause()
|
||||
Lifecycle.Event.ON_START -> session.resume()
|
||||
else -> Unit
|
||||
}
|
||||
}
|
||||
lifecycleOwner.lifecycle.addObserver(observer)
|
||||
onDispose {
|
||||
lifecycleOwner.lifecycle.removeObserver(observer)
|
||||
session.stop()
|
||||
VkAuthWebViewManager.release(webView)
|
||||
}
|
||||
}
|
||||
|
||||
val webAlpha by animateFloatAsState(
|
||||
targetValue = if (uiReady && errorMessage == null) 1f else 0f,
|
||||
label = "vk_auth_web_alpha",
|
||||
)
|
||||
|
||||
val title = when (phase) {
|
||||
VkAuthPhase.LOGIN -> "Войдите в аккаунт ВК"
|
||||
VkAuthPhase.TOKEN -> "Получение токена"
|
||||
}
|
||||
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Dialog,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
tonalElevation = 8.dp,
|
||||
modifier = Modifier.fillMaxWidth(0.95f),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(16.dp).fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.SpaceBetween,
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Default.Key,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.primary,
|
||||
modifier = Modifier.size(24.dp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
IconButton(onClick = onDismiss) {
|
||||
Icon(Icons.Default.Close, contentDescription = "Закрыть")
|
||||
}
|
||||
}
|
||||
|
||||
if (phase == VkAuthPhase.LOGIN) {
|
||||
Text(
|
||||
"Войдите любым способом, затем токен будет получен автоматически",
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
|
||||
Box(
|
||||
modifier = Modifier.fillMaxWidth().height(440.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
AndroidView(
|
||||
factory = { ctx ->
|
||||
FrameLayout(ctx).apply {
|
||||
isFocusable = false
|
||||
isFocusableInTouchMode = false
|
||||
descendantFocusability = ViewGroup.FOCUS_AFTER_DESCENDANTS
|
||||
val radius = 32f * ctx.resources.displayMetrics.density
|
||||
outlineProvider = object : ViewOutlineProvider() {
|
||||
override fun getOutline(view: View, outline: Outline) {
|
||||
outline.setRoundRect(0, 0, view.width, view.height, radius)
|
||||
}
|
||||
}
|
||||
clipToOutline = true
|
||||
addView(
|
||||
webView,
|
||||
FrameLayout.LayoutParams(
|
||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||
),
|
||||
)
|
||||
post { webView.requestFocus() }
|
||||
}
|
||||
},
|
||||
modifier = Modifier.fillMaxSize().alpha(webAlpha),
|
||||
)
|
||||
|
||||
if (!uiReady && errorMessage == null) {
|
||||
CircularProgressIndicator(color = MaterialTheme.colorScheme.primary)
|
||||
}
|
||||
|
||||
errorMessage?.let { message ->
|
||||
Column(
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
modifier = Modifier.padding(16.dp),
|
||||
) {
|
||||
Text(
|
||||
text = message,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.error,
|
||||
)
|
||||
Button(
|
||||
onClick = onDismiss,
|
||||
shape = CsqttShapes.Pill,
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
contentColor = MaterialTheme.colorScheme.onPrimary,
|
||||
),
|
||||
) {
|
||||
Text("Закрыть", fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui.dialogs
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Delete
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
|
||||
@Composable
|
||||
internal fun VkTokenRevokeDialog(
|
||||
onCancel: () -> Unit,
|
||||
onRevokeToken: () -> Unit,
|
||||
) {
|
||||
Dialog(
|
||||
onDismissRequest = onCancel,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Dialog,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
tonalElevation = 8.dp,
|
||||
modifier = Modifier.fillMaxWidth(0.9f),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(24.dp).fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Icon(
|
||||
Icons.Default.Delete,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.error,
|
||||
modifier = Modifier.size(24.dp),
|
||||
)
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text(
|
||||
"Отзыв VK-авторизации",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
|
||||
Text(
|
||||
text = "При удалении токена сессия VK сохраняется настолько, насколько это возможно: токен можно будет быстро получить заново, либо вы сможете сменить аккаунт самостоятельно.",
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 20.sp,
|
||||
)
|
||||
|
||||
Button(
|
||||
onClick = onCancel,
|
||||
modifier = Modifier.fillMaxWidth().height(48.dp),
|
||||
shape = CsqttShapes.Pill,
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = MaterialTheme.colorScheme.primary,
|
||||
contentColor = MaterialTheme.colorScheme.onPrimary,
|
||||
),
|
||||
elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp, pressedElevation = 0.dp),
|
||||
) {
|
||||
Text("Отмена", fontWeight = FontWeight.Bold, maxLines = 1)
|
||||
}
|
||||
|
||||
OutlinedButton(
|
||||
onClick = onRevokeToken,
|
||||
modifier = Modifier.fillMaxWidth().height(48.dp),
|
||||
shape = CsqttShapes.Pill,
|
||||
colors = ButtonDefaults.outlinedButtonColors(
|
||||
containerColor = Color.Transparent,
|
||||
contentColor = MaterialTheme.colorScheme.error,
|
||||
),
|
||||
border = BorderStroke(1.dp, MaterialTheme.colorScheme.error),
|
||||
) {
|
||||
Text("Удалить токен", fontWeight = FontWeight.SemiBold, maxLines = 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import androidx.compose.animation.AnimatedVisibility
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.animation.expandVertically
|
||||
import androidx.compose.animation.fadeIn
|
||||
import androidx.compose.animation.fadeOut
|
||||
import androidx.compose.animation.shrinkVertically
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.text.TextAutoSize
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.ColumnScope
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.defaultMinSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.heightIn
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.ArrowForward
|
||||
import androidx.compose.material.icons.filled.KeyboardArrowDown
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.HorizontalDivider
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.draw.rotate
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.res.painterResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.csqtt.client.CSQTTColors
|
||||
import com.csqtt.client.R
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.design.CsqttSpacing
|
||||
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.ui.graphics.Brush
|
||||
|
||||
import androidx.compose.material.icons.filled.Favorite
|
||||
|
||||
@Composable
|
||||
internal fun InfoHeroCard(
|
||||
currentVersion: String,
|
||||
onSupportClick: () -> Unit,
|
||||
onCryptoClick: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
|
||||
AppSectionCard(
|
||||
contentPadding = PaddingValues(20.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
horizontalAlignment = Alignment.CenterHorizontally,
|
||||
) {
|
||||
Text(
|
||||
text = "Поддержать разработчика Amurcanov",
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = colors.onSurface,
|
||||
textAlign = androidx.compose.ui.text.style.TextAlign.Center,
|
||||
maxLines = 1,
|
||||
softWrap = false,
|
||||
overflow = TextOverflow.Clip,
|
||||
autoSize = TextAutoSize.StepBased(
|
||||
minFontSize = 12.sp,
|
||||
maxFontSize = MaterialTheme.typography.titleMedium.fontSize,
|
||||
stepSize = 0.5.sp,
|
||||
),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
)
|
||||
|
||||
Button(
|
||||
onClick = onSupportClick,
|
||||
modifier = Modifier.fillMaxWidth().height(52.dp),
|
||||
shape = CsqttShapes.Pill,
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = CSQTTColors.donate,
|
||||
contentColor = Color.White,
|
||||
),
|
||||
contentPadding = PaddingValues(horizontal = 16.dp)
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(R.drawable.ic_yoomoney),
|
||||
contentDescription = "ЮMoney",
|
||||
tint = Color.Unspecified,
|
||||
modifier = Modifier.height(26.dp)
|
||||
)
|
||||
}
|
||||
|
||||
Button(
|
||||
onClick = onCryptoClick,
|
||||
modifier = Modifier.fillMaxWidth().height(52.dp),
|
||||
shape = CsqttShapes.Pill,
|
||||
colors = ButtonDefaults.buttonColors(
|
||||
containerColor = Color(0xFF1E293B),
|
||||
contentColor = Color.White,
|
||||
),
|
||||
contentPadding = PaddingValues(horizontal = 16.dp)
|
||||
) {
|
||||
Icon(
|
||||
painter = painterResource(R.drawable.ic_crypto_logo),
|
||||
contentDescription = "CRYPTO",
|
||||
tint = Color.White,
|
||||
modifier = Modifier.height(28.dp)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ExpandableSectionCard(
|
||||
title: String,
|
||||
expanded: Boolean,
|
||||
onToggle: () -> Unit,
|
||||
icon: @Composable () -> Unit,
|
||||
content: @Composable ColumnScope.() -> Unit,
|
||||
) {
|
||||
val arrowRotation by animateFloatAsState(
|
||||
targetValue = if (expanded) 180f else 0f,
|
||||
label = "section_arrow_rotation",
|
||||
)
|
||||
|
||||
AppSectionCard(
|
||||
contentPadding = PaddingValues(horizontal = 18.dp, vertical = 18.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(12.dp),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.clip(CsqttShapes.Control)
|
||||
.clickable(onClick = onToggle)
|
||||
.padding(vertical = 2.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Surface(shape = CsqttShapes.Pill, color = MaterialTheme.colorScheme.primaryContainer) {
|
||||
Box(modifier = Modifier.size(40.dp), contentAlignment = Alignment.Center) { icon() }
|
||||
}
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.titleMedium,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = MaterialTheme.colorScheme.onSurface,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
Icon(
|
||||
imageVector = Icons.Default.KeyboardArrowDown,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(24.dp).rotate(arrowRotation),
|
||||
)
|
||||
}
|
||||
|
||||
AnimatedVisibility(
|
||||
visible = expanded,
|
||||
enter = expandVertically() + fadeIn(),
|
||||
exit = shrinkVertically() + fadeOut(),
|
||||
) {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
|
||||
HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.30f))
|
||||
content()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun WideActionTile(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
onClick: () -> Unit,
|
||||
icon: @Composable () -> Unit,
|
||||
) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Card,
|
||||
color = MaterialTheme.colorScheme.surface.copy(alpha = 0.70f),
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
modifier = Modifier.fillMaxWidth().clip(CsqttShapes.Card).clickable(onClick = onClick),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 15.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Surface(shape = CsqttShapes.Pill, color = MaterialTheme.colorScheme.primaryContainer) {
|
||||
Box(modifier = Modifier.size(40.dp), contentAlignment = Alignment.Center) { icon() }
|
||||
}
|
||||
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) {
|
||||
Text(title, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
text = subtitle,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 18.sp,
|
||||
)
|
||||
}
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.ArrowForward,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun ProjectLinkRow(
|
||||
title: String,
|
||||
subtitle: String,
|
||||
onClick: () -> Unit,
|
||||
icon: @Composable () -> Unit,
|
||||
) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Card,
|
||||
color = MaterialTheme.colorScheme.surface.copy(alpha = 0.64f),
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
modifier = Modifier.fillMaxWidth().clip(CsqttShapes.Card).clickable(onClick = onClick),
|
||||
) {
|
||||
Row(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 14.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(12.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Surface(shape = CsqttShapes.Pill, color = MaterialTheme.colorScheme.primaryContainer) {
|
||||
Box(
|
||||
modifier = Modifier.defaultMinSize(minWidth = 40.dp, minHeight = 40.dp),
|
||||
contentAlignment = Alignment.Center,
|
||||
) {
|
||||
icon()
|
||||
}
|
||||
}
|
||||
Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
Text(title, style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
text = subtitle,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 18.sp,
|
||||
)
|
||||
}
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.ArrowForward,
|
||||
contentDescription = null,
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import android.os.Build
|
||||
import com.csqtt.client.BuildConfig
|
||||
|
||||
internal fun buildSupportReport(): String {
|
||||
val androidVersion = Build.VERSION.RELEASE ?: "?"
|
||||
val sdkInt = Build.VERSION.SDK_INT
|
||||
val primaryAbi = Build.SUPPORTED_ABIS.firstOrNull().orEmpty().ifBlank { "unknown" }
|
||||
val supportedAbis = Build.SUPPORTED_ABIS.joinToString().ifBlank { "unknown" }
|
||||
val manufacturer = Build.MANUFACTURER.orEmpty().ifBlank { "unknown" }
|
||||
val brand = Build.BRAND.orEmpty().ifBlank { "unknown" }
|
||||
val model = Build.MODEL.orEmpty().ifBlank { "unknown" }
|
||||
val device = Build.DEVICE.orEmpty().ifBlank { "unknown" }
|
||||
val product = Build.PRODUCT.orEmpty().ifBlank { "unknown" }
|
||||
val hardware = Build.HARDWARE.orEmpty().ifBlank { "unknown" }
|
||||
val board = Build.BOARD.orEmpty().ifBlank { "unknown" }
|
||||
val romDisplay = Build.DISPLAY.orEmpty().ifBlank { "unknown" }
|
||||
val buildId = Build.ID.orEmpty().ifBlank { "unknown" }
|
||||
val buildFingerprint = Build.FINGERPRINT.orEmpty().ifBlank { "unknown" }
|
||||
val buildType = Build.TYPE.orEmpty().ifBlank { "unknown" }
|
||||
val socManufacturer = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
Build.SOC_MANUFACTURER.orEmpty().ifBlank { "unknown" }
|
||||
} else {
|
||||
"n/a"
|
||||
}
|
||||
val socModel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
Build.SOC_MODEL.orEmpty().ifBlank { "unknown" }
|
||||
} else {
|
||||
"n/a"
|
||||
}
|
||||
|
||||
return buildString {
|
||||
appendLine("Версия приложения: ${BuildConfig.VERSION_NAME}")
|
||||
appendLine("Андроид: $androidVersion (SDK $sdkInt)")
|
||||
appendLine("Устройство: $manufacturer / $brand / $model")
|
||||
appendLine("Код устройства: $device")
|
||||
appendLine("Продукт: $product")
|
||||
appendLine("ABI: $primaryAbi")
|
||||
appendLine("Все ABI: $supportedAbis")
|
||||
appendLine("SoC: $socManufacturer / $socModel")
|
||||
appendLine("Hardware: $hardware")
|
||||
appendLine("Board: $board")
|
||||
appendLine("ROM: $romDisplay")
|
||||
appendLine("Build ID: $buildId")
|
||||
appendLine("Build type: $buildType")
|
||||
appendLine("Fingerprint: $buildFingerprint")
|
||||
}.trim()
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import androidx.compose.foundation.BorderStroke
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.defaultMinSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.csqtt.client.LogEntry
|
||||
import com.csqtt.client.LogLevel
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
import com.csqtt.client.ui.design.CsqttSpacing
|
||||
import com.csqtt.client.ui.design.CsqttTheme
|
||||
|
||||
private data class TagColors(
|
||||
val background: Color,
|
||||
val text: Color,
|
||||
val border: Color = Color.Transparent,
|
||||
)
|
||||
|
||||
private fun isErrorLog(tag: String, level: LogLevel, isError: Boolean): Boolean {
|
||||
return isError || level == LogLevel.ERR ||
|
||||
tag.contains("ОШИБКА", ignoreCase = true) ||
|
||||
tag.contains("ФАТАЛ", ignoreCase = true) ||
|
||||
tag.contains("ERR", ignoreCase = true)
|
||||
}
|
||||
|
||||
private fun isGreenLog(tag: String, level: LogLevel, isError: Boolean): Boolean {
|
||||
if (isErrorLog(tag, level, isError)) return false
|
||||
return level == LogLevel.OK ||
|
||||
level == LogLevel.NET ||
|
||||
tag.contains("OK", ignoreCase = true) ||
|
||||
tag.contains("NET", ignoreCase = true) ||
|
||||
tag.contains("СЕТЬ", ignoreCase = true) ||
|
||||
tag.contains("WRAP", ignoreCase = true) ||
|
||||
tag.contains("ВОРКЕР", ignoreCase = true) ||
|
||||
(tag.contains("ДЕПЛОЙ", ignoreCase = true) && (level == LogLevel.OK || level == LogLevel.NET))
|
||||
}
|
||||
|
||||
private fun resolveTagColors(isGreen: Boolean, isError: Boolean): TagColors {
|
||||
if (isError) {
|
||||
return TagColors(
|
||||
background = Color(0xFF3E1218),
|
||||
text = Color(0xFFFF897D),
|
||||
border = Color(0xFF681D26),
|
||||
)
|
||||
}
|
||||
if (isGreen) {
|
||||
return TagColors(
|
||||
background = Color(0xFF052E16),
|
||||
text = Color(0xFF4ADE80),
|
||||
border = Color(0xFF14532D),
|
||||
)
|
||||
}
|
||||
return TagColors(
|
||||
background = Color(0xFF0A223D),
|
||||
text = Color(0xFF3DBFFD),
|
||||
border = Color(0xFF1475FD),
|
||||
)
|
||||
}
|
||||
|
||||
private fun parseMessageTag(rawMessage: String, level: LogLevel): Pair<String, String> {
|
||||
val trimmed = rawMessage.trim()
|
||||
if (trimmed.startsWith("[")) {
|
||||
val closeIndex = trimmed.indexOf(']')
|
||||
if (closeIndex in 1..24) {
|
||||
val tag = trimmed.substring(1, closeIndex).trim()
|
||||
val body = trimmed.substring(closeIndex + 1).trim()
|
||||
if (tag.isNotEmpty() && body.isNotEmpty()) {
|
||||
return tag to body
|
||||
}
|
||||
}
|
||||
}
|
||||
return level.name to trimmed
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun LogLine(
|
||||
entry: LogEntry,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val terminalColors = CsqttTheme.extendedColors
|
||||
val level = entry.level ?: when {
|
||||
entry.isError -> LogLevel.ERR
|
||||
entry.priority <= 2 -> LogLevel.OK
|
||||
entry.priority <= 4 -> LogLevel.DBG
|
||||
entry.priority <= 6 -> LogLevel.NET
|
||||
else -> LogLevel.LOG
|
||||
}
|
||||
|
||||
val (rawTag, body) = parseMessageTag(entry.message, level)
|
||||
val isError = isErrorLog(rawTag, level, entry.isError)
|
||||
val isGreen = isGreenLog(rawTag, level, isError)
|
||||
|
||||
val displayTag = if (isGreen) "OK" else rawTag
|
||||
val tagColors = resolveTagColors(isGreen = isGreen, isError = isError)
|
||||
|
||||
val bodyColor = when {
|
||||
isError -> terminalColors.terminalError
|
||||
isGreen -> terminalColors.terminalSuccess
|
||||
else -> terminalColors.terminalText
|
||||
}
|
||||
|
||||
Row(
|
||||
modifier = modifier
|
||||
.fillMaxWidth()
|
||||
.padding(vertical = 2.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(CsqttSpacing.Sm),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Pill,
|
||||
color = tagColors.background,
|
||||
contentColor = tagColors.text,
|
||||
border = BorderStroke(1.dp, tagColors.border),
|
||||
modifier = Modifier.defaultMinSize(minHeight = 22.dp),
|
||||
) {
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.padding(horizontal = 7.dp, vertical = 2.dp),
|
||||
) {
|
||||
Text(
|
||||
text = displayTag,
|
||||
style = MaterialTheme.typography.labelSmall.copy(
|
||||
fontSize = 10.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
letterSpacing = 0.5.sp,
|
||||
),
|
||||
fontFamily = FontFamily.Monospace,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Text(
|
||||
text = body,
|
||||
color = bodyColor,
|
||||
style = MaterialTheme.typography.bodySmall.copy(
|
||||
fontSize = 12.sp,
|
||||
lineHeight = 16.sp,
|
||||
),
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontWeight = if (entry.isError || level == LogLevel.ERR) FontWeight.SemiBold else FontWeight.Normal,
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
|
||||
if (entry.count > 1) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Pill,
|
||||
color = Color(0xFF142438),
|
||||
contentColor = Color(0xFF3DBFFD),
|
||||
border = BorderStroke(1.dp, Color(0xFF1E4976)),
|
||||
modifier = Modifier.defaultMinSize(minHeight = 18.dp),
|
||||
) {
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.padding(horizontal = 6.dp, vertical = 1.dp),
|
||||
) {
|
||||
Text(
|
||||
text = "x${entry.count}",
|
||||
style = MaterialTheme.typography.labelSmall.copy(
|
||||
fontSize = 10.sp,
|
||||
fontWeight = FontWeight.Medium,
|
||||
),
|
||||
fontFamily = FontFamily.Monospace,
|
||||
maxLines = 1,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.csqtt.client.CsqttConstants
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
|
||||
@Composable
|
||||
internal fun HashModeInfoDialog(mode: String? = null, onDismiss: () -> Unit) {
|
||||
val (title, text) = when (mode) {
|
||||
CsqttConstants.VkAutoHash.MODE_MANUAL -> "Режим «Ручной»" to """
|
||||
• Вы сами создаёте звонки или группы с вечными звонками в VK, копируете ссылку и вставляете её в окно «VK Хеши».
|
||||
• Можно использовать до 6 разных хешей для распределения нагрузки.
|
||||
• Полный ручной контроль над источниками пула звонков без необходимости входа в VK ID.
|
||||
""".trimIndent()
|
||||
CsqttConstants.VkAutoHash.MODE_AUTO_API -> "Режим «Авто API»" to """
|
||||
• Приложение создаёт необходимые звонки через официальный метод VK API calls.start.
|
||||
• Количество хешей выбирается автоматически — от 1 до 6 по числу потоков.
|
||||
• При остановке туннеля звонки корректно завершаются через calls.forceFinish.
|
||||
• VK access token хранится в защищённом Android Keystore.
|
||||
""".trimIndent()
|
||||
CsqttConstants.VkAutoHash.MODE_AUTO_JS -> "Режим «Авто ВК»" to """
|
||||
• Rust повторяет браузерную цепочку VK Calls: получает call-token через messages.getCallToken, открывает сессию OK Calls и создаёт один звонок через vchat.startConversation.
|
||||
• session_key и идентификаторы звонков остаются внутри Rust-процесса и не выводятся в журнал.
|
||||
• Источник TURN-кредов задаётся отдельно режимом работы: «Капча», «Авто» или account-сессии «Авто ВК».
|
||||
• В режимах работы «Капча» и «Авто» создатель выходит после готовности TURN-наборов; в режиме «Авто ВК» удерживает звонок до отключения.
|
||||
• WSS и WebTransport не запускаются, поскольку для получения join_link и TURN-хешей они не требуются.
|
||||
""".trimIndent()
|
||||
else -> "Режимы ВК Хешей" to """
|
||||
• Ручной — несмотря на жёлтый индикатор, является стабильным и проверенно рабочим, но с последними событиями создавать вечные хеши получается сложным или невозможным.
|
||||
|
||||
• Авто API — использует вечный VK токен для создания звонков через официальный API calls.start (пока вечно живущих, что будет потом — не ясно), работает стабильно и хорошо. Создаёт звонки и использует их; после того как вы отключаетесь от CSQTT, звонки завершаются, ничего не утекает, поведение выглядит штатным.
|
||||
|
||||
• Авто ВК — использует браузерную цепочку API (другие, но официальные API методы calls.getConversationParams), также требует ваш VK токен. Стабильный метод на случай возникновения проблем с первыми двумя. Временное ограничение данного режима — создание только 1 звонка. Когда вы отключаетесь от CSQTT, звонок завершается. Поведение выглядит штатным.
|
||||
""".trimIndent()
|
||||
}
|
||||
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Dialog,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
tonalElevation = 6.dp,
|
||||
modifier = Modifier.fillMaxWidth(0.9f),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
text = text,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 20.sp,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Button(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.fillMaxWidth().height(48.dp),
|
||||
shape = CsqttShapes.Pill,
|
||||
colors = ButtonDefaults.buttonColors(contentColor = MaterialTheme.colorScheme.onPrimary),
|
||||
) {
|
||||
Text("Понятно", fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import androidx.compose.animation.core.animateFloatAsState
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.RowScope
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.automirrored.filled.HelpOutline
|
||||
import androidx.compose.material.icons.filled.ArrowDropDown
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material3.DropdownMenu
|
||||
import androidx.compose.material3.DropdownMenuItem
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.IconButton
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.OutlinedButton
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
|
||||
data class ModeIndicator(
|
||||
val progress: Float,
|
||||
val color: Color,
|
||||
)
|
||||
|
||||
@Composable
|
||||
internal fun ModeProgressBar(
|
||||
progress: Float,
|
||||
color: Color,
|
||||
modifier: Modifier = Modifier,
|
||||
) {
|
||||
val animatedProgress by animateFloatAsState(
|
||||
targetValue = progress.coerceIn(0.05f, 1f),
|
||||
label = "mode_progress",
|
||||
)
|
||||
Box(
|
||||
modifier = modifier
|
||||
.height(4.dp)
|
||||
.clip(RoundedCornerShape(2.dp))
|
||||
.background(MaterialTheme.colorScheme.onSurface.copy(alpha = 0.12f))
|
||||
) {
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxHeight()
|
||||
.fillMaxWidth(animatedProgress)
|
||||
.background(color, RoundedCornerShape(2.dp))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun CompactDropdownSetting(
|
||||
title: String,
|
||||
selectedKey: String,
|
||||
options: List<Pair<String, String>>,
|
||||
enabled: Boolean,
|
||||
onSelected: (String) -> Unit,
|
||||
modifier: Modifier = Modifier,
|
||||
onTitleInfo: (() -> Unit)? = null,
|
||||
onInfo: ((String) -> Unit)? = null,
|
||||
leadingContent: (@Composable RowScope.() -> Unit)? = null,
|
||||
indicatorProvider: ((String) -> ModeIndicator?)? = null,
|
||||
) {
|
||||
var expanded by rememberSaveable { mutableStateOf(false) }
|
||||
val selectedLabel = options.firstOrNull { it.first == selectedKey }?.second.orEmpty()
|
||||
val currentIndicator = indicatorProvider?.invoke(selectedKey)
|
||||
|
||||
Row(
|
||||
modifier = modifier.fillMaxWidth().padding(vertical = 6.dp),
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||
modifier = Modifier.weight(1f),
|
||||
) {
|
||||
Text(
|
||||
text = title,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
fontWeight = FontWeight.Medium,
|
||||
maxLines = 1,
|
||||
softWrap = false,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (onTitleInfo != null) {
|
||||
IconButton(
|
||||
onClick = onTitleInfo,
|
||||
modifier = Modifier.size(24.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.HelpOutline,
|
||||
contentDescription = "Информация: $title",
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(16.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
leadingContent?.invoke(this)
|
||||
Box(modifier = Modifier.widthIn(min = 90.dp, max = 135.dp)) {
|
||||
OutlinedButton(
|
||||
onClick = { expanded = true },
|
||||
enabled = enabled,
|
||||
modifier = Modifier.fillMaxWidth().height(44.dp),
|
||||
shape = CsqttShapes.Pill,
|
||||
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp),
|
||||
colors = ButtonDefaults.outlinedButtonColors(
|
||||
containerColor = Color.Transparent,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
disabledContainerColor = Color.Transparent,
|
||||
disabledContentColor = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.45f),
|
||||
),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.weight(1f).padding(start = 5.dp),
|
||||
verticalArrangement = Arrangement.Center,
|
||||
) {
|
||||
Text(
|
||||
text = selectedLabel,
|
||||
maxLines = 1,
|
||||
softWrap = false,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (currentIndicator != null) {
|
||||
Spacer(Modifier.height(2.dp))
|
||||
ModeProgressBar(
|
||||
progress = currentIndicator.progress,
|
||||
color = currentIndicator.color,
|
||||
modifier = Modifier.fillMaxWidth(0.9f),
|
||||
)
|
||||
}
|
||||
}
|
||||
Icon(Icons.Default.ArrowDropDown, contentDescription = null, modifier = Modifier.size(20.dp))
|
||||
}
|
||||
DropdownMenu(
|
||||
expanded = expanded,
|
||||
onDismissRequest = { expanded = false },
|
||||
modifier = Modifier.widthIn(min = 160.dp, max = 220.dp),
|
||||
) {
|
||||
options.forEach { (key, label) ->
|
||||
val itemIndicator = indicatorProvider?.invoke(key)
|
||||
DropdownMenuItem(
|
||||
text = {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(start = 5.dp, top = 2.dp, bottom = 2.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(3.dp),
|
||||
) {
|
||||
Text(
|
||||
text = label,
|
||||
maxLines = 1,
|
||||
softWrap = false,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
if (itemIndicator != null) {
|
||||
ModeProgressBar(
|
||||
progress = itemIndicator.progress,
|
||||
color = itemIndicator.color,
|
||||
modifier = Modifier.fillMaxWidth(0.85f),
|
||||
)
|
||||
}
|
||||
}
|
||||
},
|
||||
trailingIcon = if (onInfo != null) {
|
||||
{
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
IconButton(
|
||||
onClick = {
|
||||
expanded = false
|
||||
onInfo(key)
|
||||
},
|
||||
modifier = Modifier.size(32.dp),
|
||||
) {
|
||||
Icon(
|
||||
imageVector = Icons.AutoMirrored.Filled.HelpOutline,
|
||||
contentDescription = "Информация: $label",
|
||||
tint = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.size(18.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
null
|
||||
},
|
||||
onClick = {
|
||||
expanded = false
|
||||
onSelected(key)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.material3.Button
|
||||
import androidx.compose.material3.ButtonDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Surface
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.compose.ui.window.Dialog
|
||||
import androidx.compose.ui.window.DialogProperties
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
|
||||
@Composable
|
||||
internal fun ObfsInfoDialog(mode: String? = null, onDismiss: () -> Unit) {
|
||||
val (title, text) = when (mode) {
|
||||
"audio" -> "Режим «Простая» (audio)" to """
|
||||
• RTP-пакеты с версией 2, тип полезной нагрузки 111 (обычно Opus аудио).
|
||||
• Заголовок содержит расширения с полями abs-send-time и transport sequence.
|
||||
• Полезная нагрузка шифруется алгоритмом ChaCha20-Poly1305 со встроенным тегом аутентификации Poly1305.
|
||||
• Дополняется случайным паддингом до 24 байт.
|
||||
|
||||
На проводе виден стандартный RTP-пакет, но шифрование и отсутствие HMAC отличают его от стандартного SRTP.
|
||||
""".trimIndent()
|
||||
"video" -> "Режим «Средняя» (video)" to """
|
||||
• RTP-пакеты с версией 2, тип полезной нагрузки 96 (обычно VP8/H.264 видео).
|
||||
• Заголовок с расширениями аналогичен режиму audio.
|
||||
• Шифрование полезной нагрузки — AES-128-CTR, отдельный ключ.
|
||||
• В конце пакета добавляется аутентификационный тег HMAC-SHA1 длиной 10 байт, что полностью соответствует спецификации SRTP.
|
||||
• Дополняется случайным паддингом до 60 байт.
|
||||
|
||||
На проводе полезная нагрузка имеет формат, близкий к защищённому видеопотоку SRTP. Этот режим не подменяет TLS SNI или сертификаты TURN.
|
||||
""".trimIndent()
|
||||
else -> "Маскировка трафика" to """
|
||||
• По умолчанию используется «Средняя» маскировка.
|
||||
• Разница в потреблении ресурсов у «Простой» маскировки очень маленькая, но «Средняя» на проводе выглядит более реалистично как медиа-поток SRTP (защищённый видеозвонок WebRTC).
|
||||
• Разницы в скорости или задержках вы в целом можете не увидеть.
|
||||
""".trimIndent()
|
||||
}
|
||||
|
||||
Dialog(
|
||||
onDismissRequest = onDismiss,
|
||||
properties = DialogProperties(usePlatformDefaultWidth = false),
|
||||
) {
|
||||
Surface(
|
||||
shape = CsqttShapes.Dialog,
|
||||
color = MaterialTheme.colorScheme.surface,
|
||||
contentColor = MaterialTheme.colorScheme.onSurface,
|
||||
tonalElevation = 6.dp,
|
||||
modifier = Modifier.fillMaxWidth(0.9f),
|
||||
) {
|
||||
Column(
|
||||
modifier = Modifier.padding(24.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(16.dp),
|
||||
) {
|
||||
Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
|
||||
Text(
|
||||
text = text,
|
||||
style = MaterialTheme.typography.bodyMedium,
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
lineHeight = 20.sp,
|
||||
)
|
||||
Spacer(Modifier.height(8.dp))
|
||||
Button(
|
||||
onClick = onDismiss,
|
||||
modifier = Modifier.fillMaxWidth().height(48.dp),
|
||||
shape = CsqttShapes.Pill,
|
||||
colors = ButtonDefaults.buttonColors(contentColor = MaterialTheme.colorScheme.onPrimary),
|
||||
) {
|
||||
Text("Понятно", fontWeight = FontWeight.SemiBold)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// SPDX-FileCopyrightText: 2026 amurcanov
|
||||
// SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0
|
||||
|
||||
package com.csqtt.client.ui
|
||||
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.material3.FilterChip
|
||||
import androidx.compose.material3.FilterChipDefaults
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextAlign
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.csqtt.client.ui.design.CsqttShapes
|
||||
|
||||
@Composable
|
||||
internal fun ProtocolChip(
|
||||
label: String,
|
||||
selected: Boolean,
|
||||
modifier: Modifier = Modifier,
|
||||
enabled: Boolean = true,
|
||||
isError: Boolean = false,
|
||||
centerText: Boolean = false,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
FilterChip(
|
||||
modifier = modifier,
|
||||
selected = selected,
|
||||
onClick = onClick,
|
||||
enabled = enabled,
|
||||
label = {
|
||||
Text(
|
||||
text = label,
|
||||
fontWeight = if (selected) FontWeight.Bold else FontWeight.Medium,
|
||||
textAlign = if (centerText) TextAlign.Center else null,
|
||||
modifier = if (centerText) Modifier.fillMaxWidth() else Modifier,
|
||||
)
|
||||
},
|
||||
shape = CsqttShapes.Pill,
|
||||
colors = FilterChipDefaults.filterChipColors(
|
||||
selectedContainerColor = MaterialTheme.colorScheme.primary,
|
||||
selectedLabelColor = MaterialTheme.colorScheme.onPrimary,
|
||||
containerColor = MaterialTheme.colorScheme.surfaceVariant,
|
||||
labelColor = MaterialTheme.colorScheme.onSurface,
|
||||
disabledContainerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.38f),
|
||||
disabledSelectedContainerColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.38f),
|
||||
disabledLabelColor = if (isError) {
|
||||
MaterialTheme.colorScheme.error
|
||||
} else {
|
||||
MaterialTheme.colorScheme.onSurface.copy(alpha = 0.55f)
|
||||
},
|
||||
),
|
||||
border = FilterChipDefaults.filterChipBorder(
|
||||
enabled = enabled,
|
||||
selected = selected,
|
||||
borderColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.4f),
|
||||
selectedBorderColor = MaterialTheme.colorScheme.primary,
|
||||
disabledBorderColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.2f),
|
||||
disabledSelectedBorderColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.38f),
|
||||
),
|
||||
)
|
||||
}
|
||||
Loaded 100 of 263 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user