Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/android.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ jobs:
- uses: gradle/actions/setup-gradle@v4
with:
gradle-version: '8.9'
- name: Build APK
run: gradle --no-daemon :app:assembleDebug
- name: Test and build APK
run: gradle --no-daemon :app:testDebugUnitTest :app:assembleDebug
- uses: actions/upload-artifact@v4
with:
name: LikeFolder-debug-apk
Expand Down
5 changes: 3 additions & 2 deletions app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ android {
applicationId = "com.likefolder.app"
minSdk = 29
targetSdk = 35
versionCode = 1
versionName = "0.1.0"
versionCode = 3
versionName = "0.1.2"
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
Expand All @@ -18,4 +18,5 @@ android {

dependencies {
implementation("androidx.work:work-runtime:2.10.0")
testImplementation("junit:junit:4.13.2")
}
75 changes: 75 additions & 0 deletions app/src/main/java/com/likefolder/app/DeviceCodePoller.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package com.likefolder.app;

import java.io.IOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** Polls one device code until authorization, cancellation, or expiry. */
final class DeviceCodePoller {
private static final long MIN_INTERVAL_MS = 5000;
private static final long MAX_NETWORK_DELAY_MS = 60000;
private static final Pattern OAUTH_ERROR = Pattern.compile(
"\"error\"\\s*:\\s*\"(authorization_pending|slow_down)\"");

interface Request<T> { T request() throws IOException; }
interface Clock { long now(); }
interface Sleeper { void sleep(long millis) throws InterruptedException; }
interface Listener { void onWaiting(boolean networkRetry); }

static final class ExpiredException extends IOException {
ExpiredException(IOException networkFailure) {
super(networkFailure == null
? "Время действия кода истекло. Получи новый код."
: "Время действия кода истекло: нет связи с Яндексом. Проверь интернет, VPN и Частный DNS, затем получи новый код.",
networkFailure);
}
}

static <T> T await(Request<T> request, long intervalMs, long expiresAtMs,
Clock clock, Sleeper sleeper, Listener listener) throws IOException, InterruptedException {
long serverInterval = Math.max(MIN_INTERVAL_MS, intervalMs);
long delay = serverInterval;
IOException lastNetworkFailure = null;
while (true) {
checkInterrupted();
long remaining = expiresAtMs - clock.now();
if (remaining <= 0) throw new ExpiredException(lastNetworkFailure);
sleeper.sleep(Math.min(delay, remaining));
checkInterrupted();
// The code can expire while sleeping, particularly after a network backoff.
if (clock.now() >= expiresAtMs) throw new ExpiredException(lastNetworkFailure);
try {
T result = request.request();
checkInterrupted();
return result;
} catch (IOException ex) {
checkInterrupted();
if (ex instanceof Net.ApiError) {
Matcher error = OAUTH_ERROR.matcher(String.valueOf(ex.getMessage()));
if (!error.find()) throw ex;
lastNetworkFailure = null;
if ("slow_down".equals(error.group(1))) serverInterval += MIN_INTERVAL_MS;
delay = serverInterval;
listener.onWaiting(false);
} else if (ex instanceof UnknownHostException || ex instanceof SocketTimeoutException
|| ex instanceof SocketException) {
lastNetworkFailure = ex;
delay = Math.max(serverInterval, Math.min(MAX_NETWORK_DELAY_MS, delay * 2));
listener.onWaiting(true);
} else {
// Malformed responses, TLS errors, and other terminal failures must surface.
throw ex;
}
}
}
}

private static void checkInterrupted() throws InterruptedException {
if (Thread.currentThread().isInterrupted()) throw new InterruptedException("Авторизация отменена");
}

private DeviceCodePoller() { }
}
112 changes: 75 additions & 37 deletions app/src/main/java/com/likefolder/app/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.text.InputType;
import android.view.Gravity;
import android.view.View;
Expand All @@ -27,9 +28,13 @@
import android.widget.Switch;
import android.widget.TextView;
import org.json.JSONObject;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/** Lightweight native Android UI, no overlays or hooks into the official Yandex app. */
public final class MainActivity extends Activity {
Expand All @@ -42,12 +47,14 @@ public final class MainActivity extends Activity {
private Store store;
private LinearLayout loginCard, controls;
private TextView statusText, countText, folderLabel, codeLabel, codeHint;
private Button codeButton, copyButton;
private Button loginButton, codeButton, copyButton;
private EditText folderEdit;
private Switch quickSwitch;
private CheckBox wifiOnly;
private boolean changingSwitch = false;
private volatile boolean authorizing = false;
private boolean authorizing = false;
private int loginAttempt = 0;
private Future<?> loginTask;
private volatile String verificationUrl = "", userCode = "";
private final Runnable ticker = new Runnable() {
@Override public void run() { refresh(); handler.postDelayed(this, 2000); }
Expand All @@ -67,7 +74,9 @@ public final class MainActivity extends Activity {
super.onResume(); handler.removeCallbacks(ticker); ticker.run();
}
@Override protected void onPause() { handler.removeCallbacks(ticker); super.onPause(); }
@Override protected void onDestroy() { executor.shutdownNow(); super.onDestroy(); }
@Override protected void onDestroy() {
cancelLogin(); executor.shutdownNow(); super.onDestroy();
}

private void buildUI() {
ScrollView scroll = new ScrollView(this);
Expand Down Expand Up @@ -98,9 +107,9 @@ private void buildUI() {
loginCard.addView(loginTitle);
TextView loginDesc = text("Вход по коду на странице Яндекса. Пароль не вводится в LikeFolder.", 14, MUTED, false);
marginTop(loginDesc, 8); loginCard.addView(loginDesc);
Button loginBtn = button("Получить код входа", true);
marginTop(loginBtn, 16); loginCard.addView(loginBtn);
loginBtn.setOnClickListener(v -> startLogin(loginBtn));
loginButton = button("Получить код входа", true);
marginTop(loginButton, 16); loginCard.addView(loginButton);
loginButton.setOnClickListener(v -> startLogin());
codeLabel = text("", 26, ACCENT, true);
codeLabel.setTextIsSelectable(true);
marginTop(codeLabel, 14);
Expand Down Expand Up @@ -201,52 +210,82 @@ private void buildUI() {
.setPositiveButton("Отключить", (d, w) -> logout()).show());
marginTop(account, 14); controls.addView(account);
}
private void startLogin(Button loginButton) {
private void startLogin() {
if (authorizing) return;
final int attempt = ++loginAttempt;
clearLoginCode();
authorizing = true; loginButton.setEnabled(false);
codeHint.setText("Получаю код авторизации…");
executor.execute(() -> {
loginTask = executor.submit(() -> {
try {
JSONObject code = YandexApi.requestCode(UUID.randomUUID().toString().replace("-", "").substring(0, 16));
if (Thread.currentThread().isInterrupted()) throw new InterruptedException();
String device = code.getString("device_code");
String user = code.getString("user_code");
String link = code.optString("verification_url", "https://ya.ru/device");
int waitSeconds = Math.max(5, code.optInt("interval", 5));
long until = System.currentTimeMillis() + 1000L * code.optInt("expires_in", 300);
verificationUrl = link; userCode = user;
runOnUiThread(() -> {
String link = code.optString("verification_url", "https://oauth.yandex.ru/device");
long interval = 1000L * Math.max(5, code.optInt("interval", 5));
long until = SystemClock.elapsedRealtime() + 1000L * Math.max(0, code.optInt("expires_in", 300));
postLoginUpdate(attempt, () -> {
verificationUrl = link; userCode = user;
codeLabel.setText(user);
codeHint.setText("Открой сайт, введи код и разреши доступ. Здесь вход продолжится автоматически.");
codeButton.setVisibility(View.VISIBLE);
copyButton.setVisibility(View.VISIBLE);
});
while (!Thread.currentThread().isInterrupted() && System.currentTimeMillis() < until) {
Thread.sleep(waitSeconds * 1000L);
JSONObject result = DeviceCodePoller.await(() -> YandexApi.pollCode(device),
interval, until, SystemClock::elapsedRealtime, Thread::sleep,
retrying -> postLoginUpdate(attempt, () -> codeHint.setText(retrying
? "Связь с Яндексом прервалась. Повторяю проверку автоматически — новый код пока не нужен. Если ожидание затянется, переключи Wi-Fi или мобильный интернет."
: "Ожидаю подтверждения на странице Яндекса. Вход продолжится автоматически.")));
String access = result.getString("access_token");
String refreshToken = result.optString("refresh_token", "");
postLoginUpdate(attempt, () -> {
try {
JSONObject result = YandexApi.pollCode(device);
String access = result.getString("access_token");
store.saveTokens(access, result.optString("refresh_token", ""));
store.saveTokens(access, refreshToken);
store.status("Аккаунт подключён. Получаю исходный список лайков…");
runOnUiThread(() -> {
loginButton.setEnabled(true); codeHint.setText("Вход выполнен");
SyncWorker.schedule(this);
startServiceAction(SyncService.ACTION_ONCE);
refresh();
});
return;
} catch (Net.ApiError ex) {
String message = ex.getMessage();
if (message.contains("authorization_pending")) continue;
if (message.contains("slow_down")) { waitSeconds += 5; continue; }
throw ex;
finishLogin("Вход выполнен");
SyncWorker.schedule(this);
startServiceAction(SyncService.ACTION_ONCE);
refresh();
} catch (Exception ex) {
finishLogin(loginError(ex));
}
}
throw new IllegalStateException("Время действия кода истекло. Получи новый код.");
});
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
postLoginUpdate(attempt, () -> finishLogin("Вход отменён. Получи новый код, чтобы повторить."));
} catch (Exception ex) {
runOnUiThread(() -> { codeHint.setText("Не удалось подключиться: " + ex.getMessage()); loginButton.setEnabled(true); });
} finally { authorizing = false; }
postLoginUpdate(attempt, () -> finishLogin(loginError(ex)));
}
});
}
private void postLoginUpdate(int attempt, Runnable update) {
runOnUiThread(() -> {
if (attempt == loginAttempt && !isDestroyed() && !isFinishing()) update.run();
});
}
private void clearLoginCode() {
verificationUrl = ""; userCode = "";
codeLabel.setText("");
codeButton.setVisibility(View.GONE); copyButton.setVisibility(View.GONE);
}
private void finishLogin(String message) {
authorizing = false; loginTask = null;
loginButton.setEnabled(true);
clearLoginCode(); codeHint.setText(message);
}
private void cancelLogin() {
++loginAttempt;
if (loginTask != null) loginTask.cancel(true);
finishLogin("");
}
private static String loginError(Exception ex) {
if (ex instanceof UnknownHostException)
return "Не удалось найти сервер Яндекса. Проверь подключение, VPN и частный DNS или переключи сеть, затем получи новый код.";
if (ex instanceof SocketTimeoutException || ex instanceof SocketException)
return "Не удалось связаться с Яндексом. Проверь интернет и получи новый код.";
return "Не удалось подключиться: " + ex.getMessage();
}
private void showTokenDialog() {
EditText input = new EditText(this);
input.setSingleLine(true);
Expand All @@ -259,6 +298,7 @@ private void showTokenDialog() {
.setPositiveButton("Подключить", (dialog, which) -> {
String token = input.getText().toString().trim();
if (token.length() < 20) { store.status("Токен выглядит слишком коротким"); return; }
cancelLogin();
store.saveTokens(token, "");
store.status("Проверяю введённый токен…");
SyncWorker.schedule(this);
Expand All @@ -267,12 +307,10 @@ private void showTokenDialog() {
}).show();
}
private void logout() {
cancelLogin();
startService(new Intent(this, SyncService.class).setAction(SyncService.ACTION_STOP));
SyncWorker.cancel(this);
store.signOut();
verificationUrl = ""; userCode = "";
codeLabel.setText(""); codeHint.setText("");
codeButton.setVisibility(View.GONE); copyButton.setVisibility(View.GONE);
refresh();
}
private void startServiceAction(String action) {
Expand Down
2 changes: 1 addition & 1 deletion app/src/main/java/com/likefolder/app/SyncEngine.java
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ String run(Mode mode) throws IOException {
lastError = ex.getMessage();
// Prevent a failing API / expired entitlement from causing hundreds of network calls.
if (ok == 0 && errors >= 5) {
String status = "MP3 недоступны, первые 5 загрузок завершились ошибкой: " + lastError;
String status = "Выгрузка остановлена: первые 5 загрузок завершились ошибкой. " + lastError;
store.status(status);
return status;
}
Expand Down
24 changes: 16 additions & 8 deletions app/src/main/java/com/likefolder/app/YandexApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -116,16 +116,24 @@ String mp3Url(String trackId) throws IOException {
String xml;
try { xml = Net.readText(conn.getInputStream()); }
finally { conn.disconnect(); }
String host = xmlTag(xml, "host");
String path = xmlTag(xml, "path");
String ts = xmlTag(xml, "ts");
String s = xmlTag(xml, "s");
if (!host.matches("[A-Za-z0-9.-]+") || !path.startsWith("/") || !ts.matches("[0-9]+"))
throw new IOException("Неподдерживаемый ответ CDN");
String md5 = md5(CDN_SALT + path.substring(1) + s);
return "https://" + host + "/get-mp3/" + md5 + "/" + ts + path;
return mp3UrlFromXml(xml);
} catch (org.json.JSONException ex) { throw new IOException("Не удалось получить ссылку на MP3", ex); }
}
static String mp3UrlFromXml(String xml) throws IOException {
String host = xmlTag(xml, "host");
String path = xmlTag(xml, "path");
String ts = xmlTag(xml, "ts");
String s = xmlTag(xml, "s");
if (!host.matches("[A-Za-z0-9.-]+"))
throw new IOException("Неподдерживаемый ответ CDN: неверное поле host");
if (!path.startsWith("/"))
throw new IOException("Неподдерживаемый ответ CDN: неверное поле path");
// CDN timestamps contain hexadecimal digits. Preserve the original URL token verbatim.
if (!ts.matches("[0-9A-Fa-f]+"))
throw new IOException("Неподдерживаемый ответ CDN: неверное поле ts");
String sign = md5(CDN_SALT + path.substring(1) + s);
return "https://" + host + "/get-mp3/" + sign + "/" + ts + path;
}
private static String xmlTag(String xml, String tag) throws IOException {
Matcher m = Pattern.compile("<" + tag + ">([^<]{1,2000})</" + tag + ">").matcher(xml);
if (!m.find()) throw new IOException("Нет поля " + tag + " в CDN-ответе");
Expand Down
Loading
Loading