From 4083609b12caeda52eaab73ee68e0ba2737282ae Mon Sep 17 00:00:00 2001 From: wenil Date: Fri, 19 Jun 2026 11:43:24 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20ClaudeMeter=20=E2=80=94=20Wear=20OS=20r?= =?UTF-8?q?ate-limit=20tracker=20for=20Claude=20Code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - wear: Compose for Wear UI, polls api.anthropic.com, shows 5h/7d utilization - mobile: companion app — token input + Data Layer API + WiFi ADB install - ADB pairing via libadb-android (SPAKE2 + TLS), pm install on watch - Build: AGP 8.7.3, Gradle 8.13, Kotlin 1.9.22, compileSdk 35 --- .gitignore | 20 ++ README.md | 77 +++++ build.gradle.kts | 5 + gradle.properties | 4 + gradle/wrapper/gradle-wrapper.properties | 7 + gradlew | 251 +++++++++++++++ gradlew.bat | 94 ++++++ mobile/build.gradle.kts | 68 ++++ mobile/src/main/AndroidManifest.xml | 22 ++ .../eps/claudemeter/AdbConnectionManager.kt | 112 +++++++ .../src/main/java/com/eps/claudemeter/App.kt | 26 ++ .../java/com/eps/claudemeter/MainActivity.kt | 292 ++++++++++++++++++ settings.gradle.kts | 18 ++ wear/build.gradle.kts | 44 +++ wear/src/main/AndroidManifest.xml | 40 +++ .../java/com/eps/claudemeter/ApiPoller.kt | 61 ++++ .../java/com/eps/claudemeter/MainActivity.kt | 117 +++++++ .../eps/claudemeter/TokenReceiverService.kt | 19 ++ .../java/com/eps/claudemeter/TokenStore.kt | 24 ++ 19 files changed, 1301 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 build.gradle.kts create mode 100644 gradle.properties create mode 100644 gradle/wrapper/gradle-wrapper.properties create mode 100644 gradlew create mode 100644 gradlew.bat create mode 100644 mobile/build.gradle.kts create mode 100644 mobile/src/main/AndroidManifest.xml create mode 100644 mobile/src/main/java/com/eps/claudemeter/AdbConnectionManager.kt create mode 100644 mobile/src/main/java/com/eps/claudemeter/App.kt create mode 100644 mobile/src/main/java/com/eps/claudemeter/MainActivity.kt create mode 100644 settings.gradle.kts create mode 100644 wear/build.gradle.kts create mode 100644 wear/src/main/AndroidManifest.xml create mode 100644 wear/src/main/java/com/eps/claudemeter/ApiPoller.kt create mode 100644 wear/src/main/java/com/eps/claudemeter/MainActivity.kt create mode 100644 wear/src/main/java/com/eps/claudemeter/TokenReceiverService.kt create mode 100644 wear/src/main/java/com/eps/claudemeter/TokenStore.kt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2601211 --- /dev/null +++ b/.gitignore @@ -0,0 +1,20 @@ +# Build +build/ +.gradle/ +*.apk +*.aab + +# IDE +.idea/ +*.iml +local.properties + +# Gradle wrapper (keep gradlew + wrapper jar + properties) +gradle/wrapper/gradle-wrapper.jar + +# OS +.DS_Store +Thumbs.db + +# Assets (generated by build) +mobile/src/main/assets/wear.apk diff --git a/README.md b/README.md new file mode 100644 index 0000000..eebd352 --- /dev/null +++ b/README.md @@ -0,0 +1,77 @@ +# Claude Meter — лимит Claude Code на часах + +Минимальное Wear OS приложение для Galaxy Watch 6 Classic (и любых Wear OS 3+). +Опрашивает `api.anthropic.com` так же, как [Clawdmeter](https://github.com/HermannBjorgvin/Clawdmeter), +но без ESP32/демона/BLE — часы ходят на API сами по WiFi. + +Показывает: +- **5h** — загрузка 5-часового окна (%) и минуты до сброса +- **7d** — загрузка недельного окна (%) и минуты до сброса +- **status** — `normal` / `banned` / `unknown` + +Цвет: зелёный <70%, янтарь 70–90%, красный ≥90%. + +## Архитектура (минимум) + +- **mobile** (телефон) — одно приложение, две функции: + 1. Поле ввода OAuth-токена + кнопка «Отправить токен» (через Wearable Data Layer). + 2. Установка wear APK на часы по WiFi ADB — без компьютера, прямо с телефона. + Использует [dadb](https://github.com/mobile-dev-inc/dadb) — pure-Kotlin ADB-клиент. + Wear APK встроен в mobile APK (assets), копируется при установке. +- **wear** (часы): + - `TokenReceiverService` — `WearableListenerService`, ловит `/token` даже когда app закрыто. + - `TokenStore` — `EncryptedSharedPreferences` (токен шифруется на устройстве). + - `ApiPoller` — один `HttpURLConnection` POST к `api.anthropic.com/v1/messages` + (`max_tokens=1`, haiku — самый дешёвый запрос ради rate-limit заголовков). + - `MainActivity` — Compose for Wear, авто-опрос при запуске + кнопка «Обновить». + +## APK + +После `./gradlew assembleDebug`: +- `mobile/build/outputs/apk/debug/mobile-debug.apk` — для телефона (27 МБ, включает wear APK) +- `wear/build/outputs/apk/debug/wear-debug.apk` — для часов (22 МБ, можно ставить и вручную) + +## Установка + +### Шаг 1: поставить mobile APK на телефон +``` +adb install -r mobile/build/outputs/apk/debug/mobile-debug.apk +``` +Или скопировать APK на телефон и открыть. + +### Шаг 2: включить отладку по WiFi на часах +1. На часах: Settings → About watch → тапнуть 7 раз по «Build number» → Developer mode. +2. Settings → Developer options → **Debug over WiFi** → включить. +3. Запомнить IP-адрес (показан в Developer options под «Debug over WiFi»). + +### Шаг 3: установить wear APK с телефона +1. Открыть **Claude Meter Setup** на телефоне. +2. В секции «2. Установка приложения на часы» ввести IP часов и порт (5555). +3. Нажать «Установить на часы». +4. При первом подключении — подтвердить RSA-ключ на часах (появится диалог). +5. Готово — приложение Claude Meter появилось на часах. + +> ADB-ключ генерируется один раз, хранится в `filesDir` приложения на телефоне. +> При следующих установках подтверждение на часах не нужно. + +### Шаг 4: отправить токен +1. Скопировать `accessToken` из `~/.claude/.credentials.json` на ПК. +2. В секции «1. Токен Claude Code» вставить токен → «Отправить токен». +3. На часах открыть **Claude Meter** — увидит токен → покажет проценты. + +Токен протухает (OAuth) — перепастить на телефоне, «Отправить» снова. +`// ponytail: token on-device, re-paste on OAuth expiry.` + +## Где взять токен + +Claude Code хранит OAuth-токен в `~/.claude/.credentials.json`: +```json +{"claudeAiOauth": {"accessToken": "***..."}} +``` + +## Что добавлять потом (не сейчас) + +- **Фоновое обновление** — `WorkManager` periodic (~15 мин). Сейчас по тапу + при запуске. +- **Complication на циферблате** — always-on виджет с %. Больше бойлерплейта, делаем когда v0 зайдёт. +- **График истории** — Room + простая диаграмма. YAGNI пока. +- **Авто-рефреш токена** — если Claude Code добавит refresh-token flow. Сейчас ручная перепоставка. diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..d061a14 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,5 @@ +// Top-level — общие плагины для подмодулей +plugins { + id("com.android.application") version "8.7.3" apply false + id("org.jetbrains.kotlin.android") version "1.9.22" apply false +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..f712009 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,4 @@ +org.gradle.jvmargs=-Xmx2048m +android.useAndroidX=true +kotlin.code.style=official +android.nonTransitiveRClass=true diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..37f853b --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..ef07e01 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/mobile/build.gradle.kts b/mobile/build.gradle.kts new file mode 100644 index 0000000..5a94d46 --- /dev/null +++ b/mobile/build.gradle.kts @@ -0,0 +1,68 @@ +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") +} + +android { + namespace = "com.eps.claudemeter" + compileSdk = 35 + + defaultConfig { + applicationId = "com.eps.claudemeter" + minSdk = 26 + targetSdk = 35 + versionCode = 1 + versionName = "0.1" + } + + buildFeatures { compose = true } + composeOptions { kotlinCompilerExtensionVersion = "1.5.8" } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + kotlinOptions { jvmTarget = "17" } + + packaging { + resources { + excludes += setOf( + "META-INF/DEPENDENCIES", "META-INF/LICENSE", "META-INF/LICENSE.txt", + "META-INF/NOTICE", "META-INF/NOTICE.txt", + "META-INF/*.SF", "META-INF/*.DSA", "META-INF/*.RSA", + ) + } + } +} + +dependencies { + implementation("androidx.core:core-ktx:1.12.0") + implementation("androidx.activity:activity-compose:1.8.2") + implementation(platform("androidx.compose:compose-bom:2024.02.00")) + implementation("androidx.compose.ui:ui") + implementation("androidx.compose.material3:material3") + implementation("androidx.compose.material:material-icons-extended") + + // Coroutines + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3") + + // Wearable Data Layer — передача токена на часы + implementation("com.google.android.gms:play-services-wearable:18.1.0") + + // libadb-android — full ADB protocol: SPAKE2 pairing + TLS connection + streams + implementation("com.github.MuntashirAkon:libadb-android:3.1.1") + // sun-security-android — exposes android.sun.security.x509.* at compile time + implementation("com.github.MuntashirAkon:sun-security-android:1.1") + // hiddenapibypass — access hidden Android APIs at runtime + implementation("org.lsposed.hiddenapibypass:hiddenapibypass:6.1") + // Conscrypt — TLS 1.3 provider, required for ADB pairing + implementation("org.conscrypt:conscrypt-android:2.5.2") +} + +// ponytail: копируем wear APK в assets mobile перед сборкой +tasks.register("copyWearApk") { + from(project(":wear").layout.buildDirectory.file("outputs/apk/debug/wear-debug.apk")) + into(layout.projectDirectory.dir("src/main/assets")) + rename { "wear.apk" } + dependsOn(":wear:assembleDebug") +} +tasks.named("preBuild") { dependsOn("copyWearApk") } diff --git a/mobile/src/main/AndroidManifest.xml b/mobile/src/main/AndroidManifest.xml new file mode 100644 index 0000000..3ee39a4 --- /dev/null +++ b/mobile/src/main/AndroidManifest.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + diff --git a/mobile/src/main/java/com/eps/claudemeter/AdbConnectionManager.kt b/mobile/src/main/java/com/eps/claudemeter/AdbConnectionManager.kt new file mode 100644 index 0000000..2531404 --- /dev/null +++ b/mobile/src/main/java/com/eps/claudemeter/AdbConnectionManager.kt @@ -0,0 +1,112 @@ +package com.eps.claudemeter + +import android.content.Context +import android.os.Build +import android.sun.misc.BASE64Encoder +import android.sun.security.provider.X509Factory +import android.sun.security.x509.* +import io.github.muntashirakon.adb.AbsAdbConnectionManager +import java.io.* +import java.nio.charset.StandardCharsets +import java.security.* +import java.security.cert.Certificate +import java.security.cert.CertificateException +import java.security.cert.CertificateFactory +import java.security.spec.PKCS8EncodedKeySpec +import java.util.* + +// ponytail: один менеджер, ключи генерируются один раз и хранятся в filesDir. +// X.509 сертификат через android.sun.security.x509 — так делает официальный пример libadb-android. +class AdbConnectionManager private constructor(context: Context) : AbsAdbConnectionManager() { + + private val mPrivateKey: PrivateKey + private val mCertificate: Certificate + + init { + setApi(Build.VERSION.SDK_INT) + + val priv = readPrivateKey(context) + val cert = readCertificate(context) + + if (priv != null && cert != null) { + mPrivateKey = priv + mCertificate = cert + } else { + // генерация новой пары ключей + val kpg = KeyPairGenerator.getInstance("RSA") + kpg.initialize(2048, SecureRandom.getInstance("SHA1PRNG")) + val keyPair = kpg.generateKeyPair() + mPrivateKey = keyPair.private + + val subject = "CN=ClaudeMeter" + val algo = "SHA512withRSA" + val notAfter = Date(System.currentTimeMillis() + 86400000L) + + val extensions = CertificateExtensions() + extensions.set("SubjectKeyIdentifier", + SubjectKeyIdentifierExtension(KeyIdentifier(keyPair.public).identifier)) + extensions.set("PrivateKeyUsage", PrivateKeyUsageExtension(Date(), notAfter)) + + val x500 = X500Name(subject) + val info = X509CertInfo() + info.set("version", CertificateVersion(2)) + info.set("serialNumber", CertificateSerialNumber(Random().nextInt() and Int.MAX_VALUE)) + info.set("algorithmID", CertificateAlgorithmId(AlgorithmId.get(algo))) + info.set("subject", CertificateSubjectName(x500)) + info.set("key", CertificateX509Key(keyPair.public)) + info.set("validity", CertificateValidity(Date(), notAfter)) + info.set("issuer", CertificateIssuerName(x500)) + info.set("extensions", extensions) + + val certImpl = X509CertImpl(info) + certImpl.sign(mPrivateKey, algo) + mCertificate = certImpl + + writePrivateKey(context, mPrivateKey) + writeCertificate(context, mCertificate) + } + } + + override fun getPrivateKey(): PrivateKey = mPrivateKey + override fun getCertificate(): Certificate = mCertificate + override fun getDeviceName(): String = "ClaudeMeter" + + companion object { + @Volatile private var instance: AdbConnectionManager? = null + + fun get(context: Context): AdbConnectionManager = + instance ?: synchronized(this) { + instance ?: AdbConnectionManager(context.applicationContext).also { instance = it } + } + + private fun readPrivateKey(ctx: Context): PrivateKey? { + val f = File(ctx.filesDir, "private.key") + if (!f.exists()) return null + val bytes = f.readBytes() + return KeyFactory.getInstance("RSA").generatePrivate(PKCS8EncodedKeySpec(bytes)) + } + + private fun writePrivateKey(ctx: Context, key: PrivateKey) { + File(ctx.filesDir, "private.key").writeBytes(key.encoded) + } + + private fun readCertificate(ctx: Context): Certificate? { + val f = File(ctx.filesDir, "cert.pem") + if (!f.exists()) return null + FileInputStream(f).use { inp -> + return CertificateFactory.getInstance("X.509").generateCertificate(inp) + } + } + + private fun writeCertificate(ctx: Context, cert: Certificate) { + val f = File(ctx.filesDir, "cert.pem") + FileOutputStream(f).use { out -> + out.write(X509Factory.BEGIN_CERT.toByteArray(StandardCharsets.UTF_8)) + out.write('\n'.code) + BASE64Encoder().encode(cert.encoded, out) + out.write('\n'.code) + out.write(X509Factory.END_CERT.toByteArray(StandardCharsets.UTF_8)) + } + } + } +} diff --git a/mobile/src/main/java/com/eps/claudemeter/App.kt b/mobile/src/main/java/com/eps/claudemeter/App.kt new file mode 100644 index 0000000..f220516 --- /dev/null +++ b/mobile/src/main/java/com/eps/claudemeter/App.kt @@ -0,0 +1,26 @@ +package com.eps.claudemeter + +import android.app.Application +import android.content.Context +import android.os.Build +import org.conscrypt.Conscrypt +import org.lsposed.hiddenapibypass.HiddenApiBypass +import java.security.Security +import io.github.muntashirakon.adb.PRNGFixes + +// ponytail: HiddenApiBypass в attachBaseContext (первое что выполняется), +// Conscrypt + PRNGFixes в onCreate. Без этого pairing не работает. +class App : Application() { + override fun onCreate() { + super.onCreate() + PRNGFixes.apply() + Security.insertProviderAt(Conscrypt.newProvider(), 1) + } + + override fun attachBaseContext(base: Context) { + super.attachBaseContext(base) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + HiddenApiBypass.addHiddenApiExemptions("L") + } + } +} diff --git a/mobile/src/main/java/com/eps/claudemeter/MainActivity.kt b/mobile/src/main/java/com/eps/claudemeter/MainActivity.kt new file mode 100644 index 0000000..b4f62a9 --- /dev/null +++ b/mobile/src/main/java/com/eps/claudemeter/MainActivity.kt @@ -0,0 +1,292 @@ +package com.eps.claudemeter + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +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.automirrored.filled.Send +import androidx.compose.material.icons.filled.Bluetooth +import androidx.compose.material.icons.filled.Download +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.ui.unit.dp +import com.google.android.gms.wearable.PutDataMapRequest +import com.google.android.gms.wearable.Wearable +import io.github.muntashirakon.adb.AdbStream +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File + +// ponytail: один экран, три секции: токен → спаривание → установка APK. +class MainActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContent { + MaterialTheme { + Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + SetupScreen() + } + } + } + } +} + +@Composable +private fun SetupScreen() { + val ctx = LocalContext.current + val scope = rememberCoroutineScope() + + // --- токен --- + var token by remember { mutableStateOf("") } + var tokenStatus by remember { mutableStateOf(null) } + var sendingToken by remember { mutableStateOf(false) } + + // --- спаривание --- + var watchIp by remember { mutableStateOf("") } + var pairPort by remember { mutableStateOf("") } + var pairCode by remember { mutableStateOf("") } + var pairStatus by remember { mutableStateOf(null) } + var pairing by remember { mutableStateOf(false) } + + // --- установка --- + var sessionPort by remember { mutableStateOf("") } + var installStatus by remember { mutableStateOf(null) } + var installing by remember { mutableStateOf(false) } + + Column( + Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(24.dp), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + Text("Claude Meter", style = MaterialTheme.typography.headlineMedium) + + // === секция 1: токен === + HorizontalDivider() + Text("1. Токен Claude Code", style = MaterialTheme.typography.titleMedium) + Text( + "Вставь accessToken из ~/.claude/.credentials.json", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + OutlinedTextField( + value = token, + onValueChange = { token = it }, + label = { Text("OAuth токен") }, + modifier = Modifier.fillMaxWidth(), + minLines = 2 + ) + Button( + onClick = { + sendingToken = true; tokenStatus = null + val req = PutDataMapRequest.create("/token").apply { + dataMap.putString("token", token.trim()) + dataMap.putLong("ts", System.currentTimeMillis()) + }.asPutDataRequest().setUrgent() + Wearable.getDataClient(ctx) + .putDataItem(req) + .addOnSuccessListener { tokenStatus = "Отправлено на часы"; sendingToken = false } + .addOnFailureListener { e -> tokenStatus = "Ошибка: ${e.message}"; sendingToken = false } + }, + enabled = token.isNotBlank() && !sendingToken, + modifier = Modifier.fillMaxWidth() + ) { + Icon(Icons.AutoMirrored.Filled.Send, contentDescription = null) + Spacer(Modifier.width(8.dp)) + Text("Отправить токен") + } + tokenStatus?.let { Text(it, color = MaterialTheme.colorScheme.primary) } + + // === секция 2: спаривание === + Spacer(Modifier.height(8.dp)) + HorizontalDivider() + Text("2. Спаривание с часами", style = MaterialTheme.typography.titleMedium) + Text( + "На часах: Settings → Developer options → Wireless debugging →\n" + + "«Pair device with pairing code». Введи порт и код с экрана часов.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + OutlinedTextField( + value = watchIp, + onValueChange = { watchIp = it }, + label = { Text("IP часов") }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + keyboardOptions = KeyboardOptions( + keyboardType = KeyboardType.Number, + imeAction = ImeAction.Next + ) + ) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + OutlinedTextField( + value = pairPort, + onValueChange = { pairPort = it.filter { c -> c.isDigit() } }, + label = { Text("Pairing порт") }, + modifier = Modifier.weight(1f), + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number) + ) + OutlinedTextField( + value = pairCode, + onValueChange = { pairCode = it.filter { c -> c.isDigit() }.take(6) }, + label = { Text("Код (6 цифр)") }, + modifier = Modifier.weight(1f), + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number) + ) + } + Button( + onClick = { + scope.launch { + pairing = true; pairStatus = null + try { + withContext(Dispatchers.IO) { + val mgr = AdbConnectionManager.get(ctx) + mgr.setHostAddress(watchIp.trim()) + val ok = mgr.pair(watchIp.trim(), pairPort.trim().toInt(), pairCode.trim()) + if (!ok) throw Exception("Pairing failed") + } + pairStatus = "✅ Спарено! Теперь введи session порт (Шаг 3)" + } catch (e: Exception) { + pairStatus = "❌ ${e.message ?: e.javaClass.simpleName}" + } + pairing = false + } + }, + enabled = watchIp.isNotBlank() && pairPort.isNotBlank() && pairCode.length == 6 && !pairing, + modifier = Modifier.fillMaxWidth() + ) { + Icon(Icons.Default.Bluetooth, contentDescription = null) + Spacer(Modifier.width(8.dp)) + Text(if (pairing) "Спаривание..." else "Спарить") + } + pairStatus?.let { + Text( + it, + style = MaterialTheme.typography.bodyMedium, + color = if (it.startsWith("✅")) MaterialTheme.colorScheme.primary + else if (it.startsWith("❌")) MaterialTheme.colorScheme.error + else MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + // === секция 3: установка APK === + Spacer(Modifier.height(8.dp)) + HorizontalDivider() + Text("3. Установка приложения на часы", style = MaterialTheme.typography.titleMedium) + Text( + "Session порт показан на главном экране Wireless debugging (не pairing порт!).", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + OutlinedTextField( + value = sessionPort, + onValueChange = { sessionPort = it.filter { c -> c.isDigit() } }, + label = { Text("Session порт") }, + modifier = Modifier.fillMaxWidth(), + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number) + ) + Button( + onClick = { + scope.launch { + installing = true; installStatus = null + try { + installStatus = "Копирую APK из assets..." + val apkFile = File(ctx.cacheDir, "wear.apk") + withContext(Dispatchers.IO) { + ctx.assets.open("wear.apk").use { inp -> + apkFile.outputStream().use { inp.copyTo(it) } + } + } + installStatus = "Подключаюсь к ${watchIp}:${sessionPort}..." + withContext(Dispatchers.IO) { + val mgr = AdbConnectionManager.get(ctx) + mgr.setHostAddress(watchIp.trim()) + val connected = mgr.connect(watchIp.trim(), sessionPort.trim().toInt()) + if (!connected) throw Exception("Не удалось подключиться. Спарены?") + + // 1. push APK через shell:cat + installStatus = "Загружаю APK на часы..." + pushFile(mgr, apkFile, "/data/local/tmp/wear.apk") + + // 2. pm install + installStatus = "Устанавливаю..." + val output = execShell(mgr, "pm install -r /data/local/tmp/wear.apk 2>&1; echo END") + if (!output.contains("Success")) { + throw Exception("Install failed: $output") + } + + mgr.disconnect() + } + installStatus = "✅ Установлено на часы!" + } catch (e: Exception) { + installStatus = "❌ ${e.message ?: e.javaClass.simpleName}" + try { AdbConnectionManager.get(ctx).disconnect() } catch (_: Exception) {} + } + installing = false + } + }, + enabled = watchIp.isNotBlank() && sessionPort.isNotBlank() && !installing, + modifier = Modifier.fillMaxWidth() + ) { + Icon(Icons.Default.Download, contentDescription = null) + Spacer(Modifier.width(8.dp)) + Text(if (installing) "Установка..." else "Установить на часы") + } + installStatus?.let { + Text( + it, + style = MaterialTheme.typography.bodyMedium, + color = if (it.startsWith("✅")) MaterialTheme.colorScheme.primary + else if (it.startsWith("❌")) MaterialTheme.colorScheme.error + else MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } +} + +// ponytail: push файла через shell:cat > path, потом закрытие потока = EOF для cat. +private fun pushFile(mgr: AdbConnectionManager, file: File, remotePath: String) { + val stream: AdbStream = mgr.openStream("shell:cat > $remotePath") + val out = stream.openOutputStream() + file.inputStream().use { inp -> + val buf = ByteArray(65536) + while (true) { + val n = inp.read(buf) + if (n < 0) break + out.write(buf, 0, n) + } + } + out.flush() + out.close() + stream.close() +} + +// ponytail: shell команда с sentinel, чтобы получить полный вывод. +private fun execShell(mgr: AdbConnectionManager, command: String): String { + val stream: AdbStream = mgr.openStream("shell:$command") + val sb = StringBuilder() + val inp = stream.openInputStream() + val buf = ByteArray(4096) + while (true) { + val n = inp.read(buf) + if (n < 0) break + sb.append(String(buf, 0, n, Charsets.UTF_8)) + if (sb.contains("END")) break + } + stream.close() + return sb.toString().replace("END", "").trim() +} diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..ac9ab35 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,18 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + maven { url = uri("https://jitpack.io") } + } +} + +rootProject.name = "ClaudeMeter" +include(":mobile", ":wear") diff --git a/wear/build.gradle.kts b/wear/build.gradle.kts new file mode 100644 index 0000000..c462609 --- /dev/null +++ b/wear/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") +} + +android { + namespace = "com.eps.claudemeter" + compileSdk = 35 + + defaultConfig { + applicationId = "com.eps.claudemeter" + minSdk = 30 // Wear OS 3+; Galaxy Watch 6 Classic = API 33 + targetSdk = 35 + versionCode = 1 + versionName = "0.1" + } + + buildFeatures { compose = true } + composeOptions { kotlinCompilerExtensionVersion = "1.5.8" } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + kotlinOptions { jvmTarget = "17" } +} + +dependencies { + implementation("androidx.core:core-ktx:1.12.0") + implementation("androidx.activity:activity-compose:1.8.2") + implementation("androidx.lifecycle:lifecycle-runtime-compose:2.7.0") + + // Wear Compose + implementation("androidx.wear.compose:compose-material:1.3.0") + implementation("androidx.wear.compose:compose-foundation:1.3.0") + + // Wearable Data Layer — приём токена с телефона + implementation("com.google.android.gms:play-services-wearable:18.1.0") + + // Шифр.хранилище для токена (security — не упрощаем) + implementation("androidx.security:security-crypto:1.1.0-alpha06") + + // Coroutines + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3") +} diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml new file mode 100644 index 0000000..46af538 --- /dev/null +++ b/wear/src/main/AndroidManifest.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/wear/src/main/java/com/eps/claudemeter/ApiPoller.kt b/wear/src/main/java/com/eps/claudemeter/ApiPoller.kt new file mode 100644 index 0000000..bb78c5a --- /dev/null +++ b/wear/src/main/java/com/eps/claudemeter/ApiPoller.kt @@ -0,0 +1,61 @@ +package com.eps.claudemeter + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.net.HttpURLConnection +import java.net.URL +import kotlin.math.roundToInt + +// ponytail: тот же запрос, что у Clawdmeter — POST с max_tokens=1 ради rate-limit заголовков. +// HttpURLConnection (stdlib), без OkHttp. Один запрос = один Usage. +object ApiPoller { + private const val URL_STR = "https://api.anthropic.com/v1/messages" + // ponytail: haiku — самый дешёвый, нужен только заголовок + private const val BODY = + """{"model":"claude-haiku-4-5-20251001","max_tokens":1,"messages":[{"role":"user","content":"hi"}]}""" + + suspend fun poll(token: String): Usage = withContext(Dispatchers.IO) { + val conn = (URL(URL_STR).openConnection() as HttpURLConnection).apply { + requestMethod = "POST" + setRequestProperty("Authorization", "Bearer $token") + setRequestProperty("anthropic-version", "2023-06-01") + setRequestProperty("Content-Type", "application/json") + setRequestProperty("User-Agent", "claude-code/2.1.5") + doOutput = true + connectTimeout = 20000 + readTimeout = 20000 + } + try { + conn.outputStream.use { it.write(BODY.toByteArray()) } + val code = conn.responseCode + if (code >= 400) throw Exception("HTTP $code: ${conn.errorStream?.bufferedReader()?.use { it.readText() }?.take(200)}") + val h: (String) -> String? = { name -> conn.getHeaderField(name) } + Usage( + short = pct(h("anthropic-ratelimit-unified-5h-utilization")), + shortReset = resetMin(h("anthropic-ratelimit-unified-5h-reset")), + weekly = pct(h("anthropic-ratelimit-unified-7d-utilization")), + weeklyReset = resetMin(h("anthropic-ratelimit-unified-7d-reset")), + status = h("anthropic-ratelimit-unified-5h-status") ?: "unknown", + ) + } finally { + conn.disconnect() + } + } + + private fun pct(s: String?): Int = + s?.toFloatOrNull()?.let { (it * 100).roundToInt() } ?: 0 + + private fun resetMin(s: String?): Int { + val ts = s?.toFloatOrNull()?.toLong() ?: return 0 + val mins = (ts - System.currentTimeMillis() / 1000) / 60 + return if (mins > 0) mins.toInt() else 0 + } +} + +data class Usage( + val short: Int, // % загрузки 5-часового окна + val shortReset: Int, // минуты до сброса + val weekly: Int, // % недельного окна + val weeklyReset: Int, // минуты до сброса + val status: String, // normal / banned / unknown +) diff --git a/wear/src/main/java/com/eps/claudemeter/MainActivity.kt b/wear/src/main/java/com/eps/claudemeter/MainActivity.kt new file mode 100644 index 0000000..90634f0 --- /dev/null +++ b/wear/src/main/java/com/eps/claudemeter/MainActivity.kt @@ -0,0 +1,117 @@ +package com.eps.claudemeter + +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +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.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.wear.compose.foundation.lazy.ScalingLazyColumn +import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState +import androidx.wear.compose.material.* +import kotlinx.coroutines.launch + +// ponytail: один экран, авто-опрос при запуске + кнопка Refresh. Никакой архитектуры. +// Фоновый WorkManager добавим когда v0 зайдёт — YAGNI сейчас. +class MainActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContent { + MaterialTheme { Screen() } + } + } +} + +@Composable +private fun Screen() { + val ctx = androidx.compose.ui.platform.LocalContext.current + val scope = rememberCoroutineScope() + var usage by remember { mutableStateOf(null) } + var error by remember { mutableStateOf(null) } + var loading by remember { mutableStateOf(false) } + + fun refresh() { + scope.launch { + loading = true; error = null + try { + val token = TokenStore.get(ctx) ?: throw Exception("Нет токена. Отправь с телефона.") + usage = ApiPoller.poll(token) + } catch (e: Exception) { + error = e.message + } + loading = false + } + } + + // авто-обновление при запуске + LaunchedEffect(Unit) { refresh() } + + val listState = rememberScalingLazyListState() + ScalingLazyColumn( + state = listState, + modifier = Modifier.fillMaxSize(), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + item { Text("Claude Meter", style = MaterialTheme.typography.title3) } + + if (loading) item { Text("…", style = MaterialTheme.typography.body1) } + + val u = usage + if (u != null) { + // ponytail: 5h — короткий слот, 7d — длинный. % и минуты до сброса. + item { Metric("5h", u.short, u.shortReset) } + item { Metric("7d", u.weekly, u.weeklyReset) } + item { + Text( + "status: ${u.status}", + style = MaterialTheme.typography.body2, + color = if (u.status == "normal") Color(0xFF4CAF50) else MaterialTheme.colors.secondary, + textAlign = TextAlign.Center, + modifier = Modifier.fillMaxWidth(), + ) + } + } + + val err = error + if (err != null) { + item { + Text( + err, + style = MaterialTheme.typography.body2, + color = Color(0xFFE53935), + ) + } + } + + item { + Button(onClick = { refresh() }) { + Text("Обновить") + } + } + } +} + +@Composable +private fun Metric(label: String, pct: Int, resetMin: Int) { + val color = when { + pct >= 90 -> Color(0xFFE53935) + pct >= 70 -> Color(0xFFFFA000) + else -> Color(0xFF4CAF50) + } + Card(onClick = {}) { + Column( + modifier = Modifier.fillMaxWidth(), + horizontalAlignment = Alignment.CenterHorizontally, + ) { + Text("$label $pct%", style = MaterialTheme.typography.title1, color = color) + Text("сброс ${resetMin} мин", style = MaterialTheme.typography.body2) + } + } +} diff --git a/wear/src/main/java/com/eps/claudemeter/TokenReceiverService.kt b/wear/src/main/java/com/eps/claudemeter/TokenReceiverService.kt new file mode 100644 index 0000000..c23b4ab --- /dev/null +++ b/wear/src/main/java/com/eps/claudemeter/TokenReceiverService.kt @@ -0,0 +1,19 @@ +package com.eps.claudemeter + +import com.google.android.gms.wearable.DataEvent +import com.google.android.gms.wearable.DataEventBuffer +import com.google.android.gms.wearable.DataMapItem +import com.google.android.gms.wearable.WearableListenerService + +// ponytail: ловит "/token" с телефона, сохраняет. Запускается системой, не Activity. +class TokenReceiverService : WearableListenerService() { + override fun onDataChanged(events: DataEventBuffer) { + for (event in events) { + if (event.type != DataEvent.TYPE_CHANGED) continue + if (event.dataItem.uri.path != "/token") continue + val token = DataMapItem.fromDataItem(event.dataItem).dataMap.getString("token") + ?: continue + TokenStore.save(this, token) + } + } +} diff --git a/wear/src/main/java/com/eps/claudemeter/TokenStore.kt b/wear/src/main/java/com/eps/claudemeter/TokenStore.kt new file mode 100644 index 0000000..1840eb1 --- /dev/null +++ b/wear/src/main/java/com/eps/claudemeter/TokenStore.kt @@ -0,0 +1,24 @@ +package com.eps.claudemeter + +import android.content.Context +import androidx.security.crypto.EncryptedSharedPreferences +import androidx.security.crypto.MasterKey + +// ponytail: один ключ, одно хранилище. Токен шифруется на устройстве. +object TokenStore { + private const val FILE = "secret_prefs" + private const val KEY = "token" + + private fun prefs(ctx: Context) = EncryptedSharedPreferences.create( + ctx, + FILE, + MasterKey.Builder(ctx).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build(), + EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, + EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM, + ) + + fun save(ctx: Context, token: String) = + prefs(ctx).edit().putString(KEY, token).apply() + + fun get(ctx: Context): String? = prefs(ctx).getString(KEY, null) +}