diff --git a/controller/app/src/androidTest/java/org/appdevforall/k2go/analytics/AnalyticsConsentGateTest.java b/controller/app/src/androidTest/java/org/appdevforall/k2go/analytics/AnalyticsConsentGateTest.java index ae0237919..ee45efe42 100644 --- a/controller/app/src/androidTest/java/org/appdevforall/k2go/analytics/AnalyticsConsentGateTest.java +++ b/controller/app/src/androidTest/java/org/appdevforall/k2go/analytics/AnalyticsConsentGateTest.java @@ -8,8 +8,9 @@ import androidx.test.core.app.ApplicationProvider; import androidx.test.ext.junit.runners.AndroidJUnit4; -import org.appdevforall.k2go.delivery.data.AnalyticsConsent; +import org.appdevforall.k2go.delivery.data.OnlineConsent; import org.junit.After; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -29,34 +30,41 @@ private Context ctx() { return ApplicationProvider.getApplicationContext(); } + private boolean before; + + @Before + public void setUp() { + before = OnlineConsent.isEnabled(ctx()); + } + @After public void tearDown() { - AnalyticsConsent.setEnabled(ctx(), false); + OnlineConsent.setEnabled(ctx(), before); } @Test public void consentDefaultsOff() { Context ctx = ctx(); - AnalyticsConsent.setEnabled(ctx, false); - assertFalse(AnalyticsConsent.isEnabled(ctx)); + ctx.getSharedPreferences("iiab_delivery", Context.MODE_PRIVATE).edit().remove("online_choice").commit(); + assertFalse(OnlineConsent.isEnabled(ctx)); } @Test public void gatedPath_doesNotThrow_whenConsentOff() { Context ctx = ctx(); - AnalyticsConsent.setEnabled(ctx, false); + OnlineConsent.setEnabled(ctx, false); emitAll(AnalyticsClient.with(ctx)); - assertFalse(AnalyticsConsent.isEnabled(ctx)); + assertFalse(OnlineConsent.isEnabled(ctx)); } @Test public void emitPath_doesNotThrow_whenConsentOn() { Context ctx = ctx(); - AnalyticsConsent.setEnabled(ctx, true); + OnlineConsent.setEnabled(ctx, true); AnalyticsClient client = AnalyticsClient.with(ctx); client.applyConsent(); emitAll(client); - assertTrue(AnalyticsConsent.isEnabled(ctx)); + assertTrue(OnlineConsent.isEnabled(ctx)); } private void emitAll(AnalyticsClient client) { diff --git a/controller/app/src/main/AndroidManifest.xml b/controller/app/src/main/AndroidManifest.xml index d3bf401cc..bbdf805af 100644 --- a/controller/app/src/main/AndroidManifest.xml +++ b/controller/app/src/main/AndroidManifest.xml @@ -104,7 +104,6 @@ android:screenOrientation="portrait" tools:replace="screenOrientation" /> - SDK - // stays inert); manifest sets io.sentry.auto-init=false, so this is the only init path. - // Init here (before our handler) so K2GoUncaughtExceptionHandler wraps Sentry: save -> report. - try { - if (org.appdevforall.k2go.delivery.data.CrashReportConsent.isEnabled(this)) { - io.sentry.android.core.SentryAndroid.init(this); - } - } catch (Throwable t) { - Log.e("IIABApplication", "Sentry init skipped", t); - } + // K2GO-588: no outbound request before the first app call goes out with a device-revealing + // User-Agent; every HttpURLConnection without its own agent sends this neutral one. + System.setProperty("http.agent", "K2Go"); + + // K2GO-588: the one privacy choice replaces the two old opt-ins; their answers are dropped + // and the user is asked again (OnlineChoiceDialog). Crash reports start here, before our + // handler, so K2GoUncaughtExceptionHandler wraps Sentry: save -> report. + org.appdevforall.k2go.delivery.data.OnlineConsent.dropOldAnswers(this); + org.appdevforall.k2go.delivery.OnlineChoiceEffects.startCrashReports(this); // Capture uncaught exceptions into a crash report, offered on next launch. Thread.UncaughtExceptionHandler previous = Thread.getDefaultUncaughtExceptionHandler(); diff --git a/controller/app/src/main/java/org/appdevforall/k2go/InstallationPlanner.java b/controller/app/src/main/java/org/appdevforall/k2go/InstallationPlanner.java index 0dc7a399d..e8e5f31b7 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/InstallationPlanner.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/InstallationPlanner.java @@ -148,13 +148,17 @@ public static void getOrFetchCatalog(Context context, CacheListener listener) { } } + // K2GO-588: an automatic read with no user tap: only with the online choice on. + if (!org.appdevforall.k2go.networkpolicy.data.NetworkCostAdmission.allowsAutomatic(context)) { + new Handler(Looper.getMainLooper()).post(() -> listener.onError("offline")); + return; + } + try { URL url = new URL(KIWIX_URL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); - conn.setRequestProperty("User-Agent", "Mozilla/5.0"); conn.setConnectTimeout(8000); conn.setReadTimeout(8000); - BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder html = new StringBuilder(); String line; diff --git a/controller/app/src/main/java/org/appdevforall/k2go/SetupActivity.java b/controller/app/src/main/java/org/appdevforall/k2go/SetupActivity.java deleted file mode 100644 index ef15a85d7..000000000 --- a/controller/app/src/main/java/org/appdevforall/k2go/SetupActivity.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * ============================================================================ - * Name : SetupActivity.java - * Author : AppDevForAll - * Copyright : Copyright (c) 2026 AppDevForAll - * Description : Host for the setup/settings shell (WIZARD and SETTINGS modes) - * ============================================================================ - */ -package org.appdevforall.k2go; - -import android.os.Bundle; -import android.view.View; - -import androidx.annotation.NonNull; -import androidx.appcompat.app.AppCompatActivity; -import androidx.fragment.app.Fragment; - -import com.google.android.material.snackbar.Snackbar; -import org.appdevforall.k2go.util.Snackbars; - -import org.appdevforall.k2go.feedback.presentation.FeedbackFragment; -import org.appdevforall.k2go.settings.AboutFragment; - -/** - * Host for the setup/settings shell. First run (setup not complete) opens in WIZARD - * mode: only the Setup section, Back blocked. After setup it opens (from the header - * gear) in SETTINGS mode: a compact rail switches between Setup, Feedback and About. - * Thin host — section logic lives in the fragments (no god class). - */ -public class SetupActivity extends AppCompatActivity { - - /** - * ADFA-5137: true opens this screen as the first-run wizard, false as Settings. Set by whoever - * opens it, because the mode is a property of the reason for opening it and of nothing else. - * Absent means Settings, which is the safe default: a Settings screen is navigable and a wizard - * blocks Back. - */ - public static final String EXTRA_WIZARD_MODE = "org.iiab.controller.SETUP_WIZARD_MODE"; - - private boolean wizardMode; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_setup); - org.appdevforall.k2go.help.TooltipWiring.wireAll(getWindow().getDecorView()); - - // ADFA-5137: the caller says which mode this is, because only the caller knows. - // - // It used to read setup_complete, and that was the one reader asking a genuinely different - // question: not "is there a system" but "am I the first-run wizard or am I Settings". Two - // callers open this screen for those two reasons — MainActivity's first-run redirect and its - // Settings button — so the answer belongs in the Intent. Migrating this one to the presence - // rule would have produced a Settings screen that believes it is a wizard. - wizardMode = getIntent() != null && getIntent().getBooleanExtra(EXTRA_WIZARD_MODE, false); - - View rail = findViewById(R.id.setup_rail); - if (wizardMode) { - rail.setVisibility(View.GONE); - } else { - rail.setVisibility(View.VISIBLE); - findViewById(R.id.settings_topbar).setVisibility(View.VISIBLE); - findViewById(R.id.btn_settings_done).setOnClickListener(v -> finish()); - findViewById(R.id.nav_setup).setOnClickListener(v -> show(SetupSectionFragment.newInstance(false))); - findViewById(R.id.nav_feedback).setOnClickListener(v -> show(new FeedbackFragment())); - findViewById(R.id.nav_about).setOnClickListener(v -> show(new AboutFragment())); - } - - if (savedInstanceState == null) { - show(SetupSectionFragment.newInstance(wizardMode)); - } - } - - private void show(@NonNull Fragment fragment) { - getSupportFragmentManager().beginTransaction() - .replace(R.id.setup_content, fragment) - .commit(); - } - - @Override - public void onBackPressed() { - if (wizardMode) { - Snackbars.make(findViewById(android.R.id.content), - getString(R.string.setup_back_blocked_msg)).show(); - } else { - super.onBackPressed(); - } - } -} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/SetupSectionFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/SetupSectionFragment.java deleted file mode 100644 index e028bf7a4..000000000 --- a/controller/app/src/main/java/org/appdevforall/k2go/SetupSectionFragment.java +++ /dev/null @@ -1,483 +0,0 @@ -package org.appdevforall.k2go; - -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.net.Uri; -import android.os.Build; -import android.os.Bundle; -import android.os.PowerManager; -import android.provider.Settings; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.animation.Animation; -import android.view.animation.AnimationUtils; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.Spinner; -import android.widget.TextView; - -import androidx.activity.result.ActivityResultLauncher; -import androidx.activity.result.contract.ActivityResultContracts; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import org.appdevforall.k2go.ui.dialog.BrandDialog; -import androidx.appcompat.widget.SwitchCompat; -import androidx.core.app.NotificationManagerCompat; -import androidx.core.content.ContextCompat; -import androidx.fragment.app.Fragment; - -import org.appdevforall.k2go.applang.data.AppLocaleController; -import org.appdevforall.k2go.applang.domain.AppLanguage; -import org.appdevforall.k2go.applang.domain.LocaleMatcher; -import org.appdevforall.k2go.applang.domain.SupportedAppLanguages; -import org.appdevforall.k2go.delivery.data.AnalyticsConsent; - -import com.google.android.material.snackbar.Snackbar; -import org.appdevforall.k2go.util.Snackbars; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; - -/** - * Permissions + language section, shared by the first-run wizard and the settings shell. - * Gated by {@code ARG_WIZARD}: WIZARD shows a gated "Continue" (enabled only once all - * required permissions are granted; the host blocks Back); SETTINGS hides Continue, - * persists the language on selection, and allows free navigation. - */ -public class SetupSectionFragment extends Fragment { - - private static final String ARG_WIZARD = "wizard"; - private static final String DELIVERY_PREFS = "iiab_delivery"; - private static final String KEY_ENROLLMENT_SHOWN = "analytics_enrollment_shown"; - - public static SetupSectionFragment newInstance(boolean wizard) { - SetupSectionFragment f = new SetupSectionFragment(); - Bundle b = new Bundle(); - b.putBoolean(ARG_WIZARD, wizard); - f.setArguments(b); - return f; - } - - private boolean wizard; - - private SwitchCompat switchNotif, switchStorage, switchBattery, switchOverlay; - private Button btnContinue; - private Button btnManageAll; - private Spinner spinnerLanguage; - private Spinner spinnerAppLanguage; - private boolean contentSelectionInitialized = false; - - private ActivityResultLauncher requestPermissionLauncher; - private ActivityResultLauncher storageLauncher; - private ActivityResultLauncher batteryLauncher; - private ActivityResultLauncher overlayLauncher; - private ActivityResultLauncher notifLauncher; - - private static class LocaleItem { - final Locale locale; - final String displayName; - - LocaleItem(Locale locale, String displayName) { - this.locale = locale; - this.displayName = displayName.substring(0, 1).toUpperCase() + displayName.substring(1); - } - - @Override - public String toString() { - return displayName; - } - } - - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - wizard = getArguments() == null || getArguments().getBoolean(ARG_WIZARD, true); - - requestPermissionLauncher = registerForActivityResult( - new ActivityResultContracts.RequestPermission(), isGranted -> checkAllPermissions()); - notifLauncher = registerForActivityResult( - new ActivityResultContracts.StartActivityForResult(), r -> checkAllPermissions()); - storageLauncher = registerForActivityResult( - new ActivityResultContracts.StartActivityForResult(), r -> checkAllPermissions()); - batteryLauncher = registerForActivityResult( - new ActivityResultContracts.StartActivityForResult(), r -> checkAllPermissions()); - overlayLauncher = registerForActivityResult( - new ActivityResultContracts.StartActivityForResult(), r -> checkAllPermissions()); - } - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - return inflater.inflate(R.layout.fragment_setup_section, container, false); - } - - @Override - public void onViewCreated(@NonNull View v, @Nullable Bundle savedInstanceState) { - super.onViewCreated(v, savedInstanceState); - org.appdevforall.k2go.help.TooltipWiring.wireAll(v); - - TextView welcomeText = v.findViewById(R.id.setup_welcome_text); - welcomeText.setText(getString(R.string.setup_welcome, getString(R.string.app_name))); - - switchNotif = v.findViewById(R.id.switch_perm_notifications); - switchStorage = v.findViewById(R.id.switch_perm_storage); - switchBattery = v.findViewById(R.id.switch_perm_battery); - switchOverlay = v.findViewById(R.id.switch_perm_overlay); - btnContinue = v.findViewById(R.id.btn_setup_continue); - btnManageAll = v.findViewById(R.id.btn_manage_all); - spinnerLanguage = v.findViewById(R.id.spinner_language); - spinnerAppLanguage = v.findViewById(R.id.spinner_app_language); - // Don't let the spinners restore a stale numeric position across activity - // recreation: the option lists are re-sorted per UI locale, so a restored index - // would point at a different language. Our setSelection(...) is the source of - // truth on every (re)creation. See ADFA-4304. - spinnerLanguage.setSaveEnabled(false); - spinnerAppLanguage.setSaveEnabled(false); - - if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { - switchNotif.setVisibility(View.GONE); - } - - setupListeners(); - setupAppLanguageSpinner(); - setupLanguageSpinner(); - setupLanguageSectionToggle(v); - checkAllPermissions(); - - if (wizard) { - btnContinue.setOnClickListener(view -> { - persistSelectedLanguage(); - maybeShowAnalyticsEnrollment(); - }); - } else { - btnContinue.setVisibility(View.GONE); - spinnerLanguage.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - if (!contentSelectionInitialized) { - // Skip the initial programmatic selection so recreating the - // activity (e.g. after an App Language change) never rewrites - // the stored content language. Only real user picks persist. - contentSelectionInitialized = true; - return; - } - persistSelectedLanguage(); - } - - @Override - public void onNothingSelected(AdapterView parent) { - } - }); - } - } - - @Override - public void onResume() { - super.onResume(); - checkAllPermissions(); - } - - private void persistSelectedLanguage() { - LocaleItem selectedItem = (LocaleItem) spinnerLanguage.getSelectedItem(); - if (selectedItem == null) { - return; - } - Locale loc = selectedItem.locale; - SharedPreferences prefs = requireContext().getSharedPreferences( - getString(R.string.pref_file_internal), Context.MODE_PRIVATE); - prefs.edit() - .putString("selected_lang_minimal", loc.getLanguage()) - .putString("selected_lang_simple", loc.getLanguage() + "-" + loc.getCountry()) - .putString("selected_lang_full", loc.getLanguage() + "_" + loc.getCountry() + ".UTF-8") - .apply(); - } - - /** - * One-time analytics enrollment during first-run setup. Shows a clear, no-dark-pattern - * choice to share strictly anonymous, operational usage stats; either choice records - * the consent and proceeds. Shown at most once (guarded by a flag). - */ - private void maybeShowAnalyticsEnrollment() { - // ADFA-5337: no analytics compiled in (no google-services.json) → nothing to consent to; skip. - if (!BuildConfig.ANALYTICS_ENABLED) { - completeSetup(); - return; - } - SharedPreferences delivery = requireContext().getSharedPreferences( - DELIVERY_PREFS, Context.MODE_PRIVATE); - if (delivery.getBoolean(KEY_ENROLLMENT_SHOWN, false)) { - completeSetup(); - return; - } - new BrandDialog(requireContext()) - .setTitle(R.string.analytics_enroll_title) - .setMessage(getString(R.string.analytics_enroll_body, getString(R.string.app_name))) - .setCancelable(false) - .setPositive(R.string.analytics_enroll_accept, () -> { - AnalyticsConsent.setEnabled(requireContext(), true); - org.appdevforall.k2go.analytics.AnalyticsClient.with(requireContext()).applyConsent(); - finishEnrollment(delivery); - }) - .setNegative(R.string.analytics_enroll_decline, () -> { - AnalyticsConsent.setEnabled(requireContext(), false); - org.appdevforall.k2go.analytics.AnalyticsClient.with(requireContext()).applyConsent(); - finishEnrollment(delivery); - }) - .show(); - } - - private void finishEnrollment(SharedPreferences delivery) { - delivery.edit().putBoolean(KEY_ENROLLMENT_SHOWN, true).apply(); - completeSetup(); - } - - private void completeSetup() { - // ADFA-4466 Phase 2: setup funnel completion (no-op unless opted in). - org.appdevforall.k2go.analytics.AnalyticsClient.with(requireContext()).logOnboardingCompleted(); - // ADFA-5137: nothing to mark. This screen belongs to the legacy setup shell, and it wrote - // setup_complete on its way out — a fourth writer of a flag nobody cleared. LibraryActivity - // now asks the device instead, so if this path really did install a system it will be found, - // and if it did not, the wizard is where the user should land. - startActivity(new Intent(requireContext(), org.appdevforall.k2go.redesign.LibraryActivity.class)); - requireActivity().finish(); - } - - /** - * Collapsible "Language" section (ADFA-4304): collapsed by default so first-run setup - * stays short. Opening it reveals the App Language + Content Language selectors; the - * defaults already apply if the operator never opens it. - */ - private void setupLanguageSectionToggle(View root) { - View header = root.findViewById(R.id.language_header); - View options = root.findViewById(R.id.language_options); - TextView chevron = root.findViewById(R.id.language_chevron); - chevron.setText("\u25B8"); // collapsed indicator - header.setOnClickListener(x -> { - boolean expand = options.getVisibility() != View.VISIBLE; - options.setVisibility(expand ? View.VISIBLE : View.GONE); - chevron.setText(expand ? "\u25BE" : "\u25B8"); - }); - } - - /** - * App UI language selector (ADFA-4304): lets the operator show the app in any shipped - * language regardless of the phone's locale. "System default" clears the override. - * Thin — the actual locale switch lives in {@link AppLocaleController}. - */ - private void setupAppLanguageSpinner() { - List languages = - SupportedAppLanguages.all(getString(R.string.setup_app_lang_system)); - ArrayAdapter adapter = new ArrayAdapter<>( - requireContext(), android.R.layout.simple_spinner_item, languages); - adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); - spinnerAppLanguage.setAdapter(adapter); - spinnerAppLanguage.setSelection( - SupportedAppLanguages.indexOfTag(languages, AppLocaleController.currentTag()), false); - - spinnerAppLanguage.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - String tag = ((AppLanguage) parent.getItemAtPosition(position)).tag(); - // No-op on the initial/programmatic selection; only apply a real change - // (applying recreates the activity in the chosen language). - if (!tag.equals(AppLocaleController.currentTag())) { - AppLocaleController.apply(tag); - } - } - - @Override - public void onNothingSelected(AdapterView parent) { - } - }); - } - - private void setupLanguageSpinner() { - List localeItems = new ArrayList<>(); - Set addedNames = new HashSet<>(); - - for (Locale locale : Locale.getAvailableLocales()) { - if (!locale.getLanguage().isEmpty() && !locale.getCountry().isEmpty()) { - String name = locale.getDisplayName(); - if (!addedNames.contains(name)) { - localeItems.add(new LocaleItem(locale, name)); - addedNames.add(name); - } - } - } - - Collections.sort(localeItems, (a, b) -> a.displayName.compareToIgnoreCase(b.displayName)); - - ArrayAdapter adapter = new ArrayAdapter<>( - requireContext(), android.R.layout.simple_spinner_item, localeItems); - adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); - spinnerLanguage.setAdapter(adapter); - spinnerLanguage.setSelection(contentSelectionIndex(localeItems), false); - } - - /** - * Content-language selection follows the STORED preference, so it stays put when the - * app UI language changes (that override alters {@code Locale.getDefault()} on - * recreation). Only on first run (nothing stored yet) does it fall back to the phone - * locale. See ADFA-4304. - */ - private int contentSelectionIndex(List items) { - SharedPreferences prefs = requireContext().getSharedPreferences( - getString(R.string.pref_file_internal), Context.MODE_PRIVATE); - String storedSimple = prefs.getString("selected_lang_simple", null); // e.g. "es-ES" - String lang; - String country; - if (storedSimple != null && !storedSimple.isEmpty()) { - String[] parts = storedSimple.split("-", 2); - lang = parts[0]; - country = parts.length > 1 ? parts[1] : ""; - } else { - // First run: fall back to the DEVICE locale, read from the system resources - // so it is immune to the app UI language override (AppCompat changes - // Locale.getDefault(), which would otherwise drift the content selection). - Locale device = deviceLocale(); - lang = device.getLanguage(); - country = device.getCountry(); - } - List locales = new ArrayList<>(items.size()); - for (LocaleItem item : items) { - locales.add(item.locale); - } - return LocaleMatcher.pickIndex(locales, lang, country); - } - - /** The physical device locale, unaffected by the per-app UI language override. */ - private Locale deviceLocale() { - android.content.res.Configuration sys = android.content.res.Resources.getSystem().getConfiguration(); - if (sys.getLocales().isEmpty()) { - return Locale.getDefault(); - } - return sys.getLocales().get(0); - } - - private void setupListeners() { - switchNotif.setOnClickListener(v -> { - if (hasNotifPermission()) { - handleRevokeAttempt(v); - return; - } - if (switchNotif.isChecked() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - Intent intent = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS); - intent.putExtra(Settings.EXTRA_APP_PACKAGE, requireContext().getPackageName()); - notifLauncher.launch(intent); - } - switchNotif.setChecked(false); - }); - - switchStorage.setOnClickListener(v -> { - if (hasStoragePermission()) { - handleRevokeAttempt(v); - return; - } - if (switchStorage.isChecked()) { - org.appdevforall.k2go.permissions.StoragePermission.request( - requireContext(), storageLauncher, requestPermissionLauncher); - } - switchStorage.setChecked(false); - }); - - switchBattery.setOnClickListener(v -> { - if (hasBatteryPermission()) { - handleRevokeAttempt(v); - return; - } - if (switchBattery.isChecked() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS); - intent.setData(Uri.parse("package:" + requireContext().getPackageName())); - batteryLauncher.launch(intent); - } - switchBattery.setChecked(false); - }); - - switchOverlay.setOnClickListener(v -> { - if (hasOverlayPermission()) { - handleRevokeAttempt(v); - return; - } - if (switchOverlay.isChecked() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, - Uri.parse("package:" + requireContext().getPackageName())); - overlayLauncher.launch(intent); - } - switchOverlay.setChecked(false); - }); - - btnManageAll.setOnClickListener(v -> openAppSettings()); - } - - private void handleRevokeAttempt(View switchView) { - ((SwitchCompat) switchView).setChecked(true); - Animation shake = AnimationUtils.loadAnimation(requireContext(), R.anim.shake); - switchView.startAnimation(shake); - Snackbars.make(requireView(), R.string.revoke_permission_warning) - .setAction(R.string.settings_label, v -> openAppSettings()).show(); - } - - private void openAppSettings() { - Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); - intent.setData(Uri.parse("package:" + requireContext().getPackageName())); - startActivity(intent); - } - - private void checkAllPermissions() { - boolean notif = hasNotifPermission(); - boolean storage = hasStoragePermission(); - boolean battery = hasBatteryPermission(); - boolean overlay = hasOverlayPermission(); - - switchNotif.setChecked(notif); - switchStorage.setChecked(storage); - switchBattery.setChecked(battery); - switchOverlay.setChecked(overlay); - - if (!wizard) { - return; - } - - boolean allGranted = storage && battery && overlay; - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - allGranted = allGranted && notif; - } - btnContinue.setEnabled(allGranted); - btnContinue.setBackgroundTintList(ContextCompat.getColorStateList(requireContext(), - allGranted ? R.color.btn_explore_ready : R.color.btn_explore_disabled)); - } - - private boolean hasNotifPermission() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { - return NotificationManagerCompat.from(requireContext()).areNotificationsEnabled(); - } - return true; - } - - private boolean hasStoragePermission() { - return org.appdevforall.k2go.permissions.StoragePermission.isGranted(requireContext()); - } - - private boolean hasBatteryPermission() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - PowerManager pm = (PowerManager) requireContext().getSystemService(Context.POWER_SERVICE); - return pm != null && pm.isIgnoringBatteryOptimizations(requireContext().getPackageName()); - } - return true; - } - - private boolean hasOverlayPermission() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - return Settings.canDrawOverlays(requireContext()); - } - return true; - } -} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/analytics/AnalyticsClient.java b/controller/app/src/main/java/org/appdevforall/k2go/analytics/AnalyticsClient.java index fe11b03f5..8a6051992 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/analytics/AnalyticsClient.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/analytics/AnalyticsClient.java @@ -6,7 +6,7 @@ import org.appdevforall.k2go.BuildConfig; import org.appdevforall.k2go.analytics.domain.AnalyticsBuckets; -import org.appdevforall.k2go.delivery.data.AnalyticsConsent; +import org.appdevforall.k2go.delivery.data.OnlineConsent; import org.appdevforall.k2go.delivery.data.InstallId; import org.appdevforall.k2go.feedback.data.FeedbackDiagnostics; @@ -18,7 +18,7 @@ * shared store-and-forward backbone and the Cloudflare Worker are out of scope for now. * *

Consent-gated: every method is a no-op unless the operator has opted in - * ({@link AnalyticsConsent}, default OFF). Collection is also toggled at the SDK level through + * ({@link OnlineConsent}, default OFF). Collection is also toggled at the SDK level through * {@link FirebaseAnalyticsBridge} so nothing is gathered while consent is OFF. Advertising ID / * SSAID collection is disabled in the standard-flavor manifest. * @@ -50,7 +50,7 @@ public void applyConsent() { if (!BuildConfig.ANALYTICS_ENABLED) { return; // fdroid flavor, or standard without google-services.json: nothing to sync } - FirebaseAnalyticsBridge.setCollectionEnabled(app, AnalyticsConsent.isEnabled(app)); + FirebaseAnalyticsBridge.setCollectionEnabled(app, OnlineConsent.isEnabled(app)); } // -------------------------------------------------------------- app lifecycle @@ -188,7 +188,7 @@ private boolean gate() { if (!BuildConfig.ANALYTICS_ENABLED) { return false; // fdroid flavor, or standard without google-services.json: analytics off } - boolean consent = AnalyticsConsent.isEnabled(app); + boolean consent = OnlineConsent.isEnabled(app); FirebaseAnalyticsBridge.setCollectionEnabled(app, consent); return consent; } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/delivery/OnlineChoiceEffects.java b/controller/app/src/main/java/org/appdevforall/k2go/delivery/OnlineChoiceEffects.java new file mode 100644 index 000000000..d6c65c250 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/delivery/OnlineChoiceEffects.java @@ -0,0 +1,62 @@ +/* + * ============================================================================ + * Name : OnlineChoiceEffects.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-588. The one place that applies the privacy choice to the + * clients that act on it (analytics, crash reports). + * ============================================================================ + */ +package org.appdevforall.k2go.delivery; + +import android.content.Context; +import android.util.Log; + +import org.appdevforall.k2go.analytics.AnalyticsClient; +import org.appdevforall.k2go.delivery.data.OnlineConsent; + +/** + * K2GO-588: every change of the choice (onboarding, Settings) calls {@link #apply(Context)}, and the + * app start calls {@link #startCrashReports(Context)}. Gates that read the choice on each call + * (network admission, Sentry beforeSend) need nothing here. + */ +public final class OnlineChoiceEffects { + + private static final String TAG = "OnlineChoiceEffects"; + + private OnlineChoiceEffects() {} + + /** Applies the stored choice now: analytics collection, and crash reports on or off. */ + public static void apply(Context ctx) { + Context app = ctx.getApplicationContext(); + AnalyticsClient.with(app).applyConsent(); + if (OnlineConsent.isEnabled(app)) { + startCrashReports(app); + } else if (io.sentry.Sentry.isEnabled()) { + // close() flushes and waits for the transport (seconds): never on the main thread. + new Thread(io.sentry.Sentry::close, "sentry-close").start(); + } + } + + /** + * ADFA-4533: crash reports to GlitchTip (Sentry SDK) when the choice is on. No-op without a + * built-in DSN (the SDK stays inert); the manifest sets io.sentry.auto-init=false, so this is the + * only init path. Crash events only: no session tracking (it contacts GlitchTip at every start) + * and no client reports (counts of dropped events). beforeSend drops events once the choice is off. + * At app start this runs before K2GoUncaughtExceptionHandler is set, so that handler wraps + * Sentry; a later start (the user turns the choice on) wraps ours instead, and both still run. + */ + public static void startCrashReports(Context ctx) { + final Context app = ctx.getApplicationContext(); + if (!OnlineConsent.isEnabled(app) || io.sentry.Sentry.isEnabled()) return; + try { + io.sentry.android.core.SentryAndroid.init(app, options -> { + options.setEnableAutoSessionTracking(false); + options.setSendClientReports(false); + options.setBeforeSend((event, hint) -> OnlineConsent.isEnabled(app) ? event : null); + }); + } catch (Throwable t) { + Log.e(TAG, "Sentry init skipped", t); + } + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/delivery/data/AnalyticsConsent.java b/controller/app/src/main/java/org/appdevforall/k2go/delivery/data/AnalyticsConsent.java deleted file mode 100644 index 79ebf8d5f..000000000 --- a/controller/app/src/main/java/org/appdevforall/k2go/delivery/data/AnalyticsConsent.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.appdevforall.k2go.delivery.data; - -import android.content.Context; - -/** Opt-in flag for usage analytics. Default OFF (privacy-by-default). */ -public final class AnalyticsConsent { - - private static final String PREFS = "iiab_delivery"; - private static final String KEY = "analytics_opt_in"; - /** Whether the user has already been shown the one-time consent prompt (any flow). */ - private static final String KEY_ASKED = "analytics_enrollment_shown"; - - private AnalyticsConsent() { - } - - public static boolean isEnabled(Context ctx) { - return ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(KEY, false); - } - - public static void setEnabled(Context ctx, boolean enabled) { - ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEY, enabled).apply(); - } - - /** True once the consent prompt has been shown, so onboarding asks at most once. Shares the - * legacy key, so a user who already answered in the old flow is not asked again. */ - public static boolean wasAsked(Context ctx) { - return ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(KEY_ASKED, false); - } - - public static void markAsked(Context ctx) { - ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEY_ASKED, true).apply(); - } -} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/delivery/data/CrashReportConsent.java b/controller/app/src/main/java/org/appdevforall/k2go/delivery/data/CrashReportConsent.java deleted file mode 100644 index 2e4cc957d..000000000 --- a/controller/app/src/main/java/org/appdevforall/k2go/delivery/data/CrashReportConsent.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.appdevforall.k2go.delivery.data; - -import android.content.Context; - -/** - * Opt-in flag for crash / error reporting (GlitchTip via the Sentry SDK). Separate from - * {@link AnalyticsConsent} on purpose: error reports are operational (not behavioural - * telemetry) and carry no PII, so they can follow a different policy. Off until the user turns it - * on, in every build (K2GO-579): "Keep offline" must mean no outbound connection. - */ -public final class CrashReportConsent { - - private static final String PREFS = "iiab_delivery"; - private static final String KEY = "crash_reports_opt_in"; - - private CrashReportConsent() { - } - - public static boolean isEnabled(Context ctx) { - return ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE) - .getBoolean(KEY, false); - } - - public static void setEnabled(Context ctx, boolean enabled) { - ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEY, enabled).apply(); - } -} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/delivery/data/OnlineConsent.java b/controller/app/src/main/java/org/appdevforall/k2go/delivery/data/OnlineConsent.java new file mode 100644 index 000000000..16a9b7c6d --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/delivery/data/OnlineConsent.java @@ -0,0 +1,58 @@ +package org.appdevforall.k2go.delivery.data; + +import android.content.Context; +import android.content.SharedPreferences; + +/** + * K2GO-588: the one privacy choice. On = usage data (where the build has analytics), crash reports + * and automatic connections (catalog and update checks) on an unmetered network. Off ("Keep + * offline", the default) = none of them. The choice covers more than the old analytics and + * crash-report opt-ins, so their answers are dropped and every user is asked once again. + */ +public final class OnlineConsent { + + private static final String PREFS = "iiab_delivery"; + private static final String KEY = "online_choice"; + /** Whether the user has answered the one-time question (any flow). */ + private static final String KEY_ASKED = "online_choice_asked"; + /** The two opt-ins that this choice replaces (before K2GO-588). */ + private static final String[] OLD_KEYS = { + "analytics_opt_in", "analytics_enrollment_shown", "crash_reports_opt_in"}; + + private OnlineConsent() { + } + + private static SharedPreferences prefs(Context ctx) { + return ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } + + public static boolean isEnabled(Context ctx) { + return prefs(ctx).getBoolean(KEY, false); + } + + public static void setEnabled(Context ctx, boolean enabled) { + prefs(ctx).edit().putBoolean(KEY, enabled).apply(); + } + + /** True once the user has answered, so the question shows at most once. */ + public static boolean wasAsked(Context ctx) { + return prefs(ctx).getBoolean(KEY_ASKED, false); + } + + public static void markAsked(Context ctx) { + prefs(ctx).edit().putBoolean(KEY_ASKED, true).apply(); + } + + /** Removes the answers of the old opt-ins, once, so nothing reads them again. */ + public static void dropOldAnswers(Context ctx) { + SharedPreferences p = prefs(ctx); + SharedPreferences.Editor e = null; + for (String k : OLD_KEYS) { + if (p.contains(k)) { + if (e == null) e = p.edit(); + e.remove(k); + } + } + if (e != null) e.apply(); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/delivery/presentation/OnlineChoiceDialog.java b/controller/app/src/main/java/org/appdevforall/k2go/delivery/presentation/OnlineChoiceDialog.java new file mode 100644 index 000000000..9f32ddf72 --- /dev/null +++ b/controller/app/src/main/java/org/appdevforall/k2go/delivery/presentation/OnlineChoiceDialog.java @@ -0,0 +1,59 @@ +/* + * ============================================================================ + * Name : OnlineChoiceDialog.java + * Author : AppDevForAll + * Copyright : Copyright (c) 2026 AppDevForAll + * Description : K2GO-588. The one-time privacy question and the label of its switch. + * ============================================================================ + */ +package org.appdevforall.k2go.delivery.presentation; + +import android.app.Activity; + +import org.appdevforall.k2go.BuildConfig; +import org.appdevforall.k2go.R; +import org.appdevforall.k2go.delivery.OnlineChoiceEffects; +import org.appdevforall.k2go.delivery.data.OnlineConsent; +import org.appdevforall.k2go.ui.dialog.BrandDialog; + +/** + * K2GO-588: asked once in every build (F-Droid too: crash reports and online content). The wizard + * asks on a fresh install; Home asks an existing install after the update. + */ +public final class OnlineChoiceDialog { + + private OnlineChoiceDialog() {} + + /** The switch and button label: usage data only where the build has analytics (not F-Droid). */ + public static int choiceLabel() { + return BuildConfig.ANALYTICS_ENABLED + ? R.string.k2go_online_accept_usage + : R.string.k2go_online_accept_crash; + } + + /** The question text that matches {@link #choiceLabel()}. */ + public static int choiceBody() { + return BuildConfig.ANALYTICS_ENABLED + ? R.string.k2go_online_body_usage + : R.string.k2go_online_body_crash; + } + + /** Shows the question unless it was answered; runs {@code onDone} after the answer, or at once. */ + public static void askOnce(Activity activity, Runnable onDone) { + if (OnlineConsent.wasAsked(activity)) { onDone.run(); return; } + new BrandDialog(activity) + .setTitle(R.string.k2go_online_title) + .setMessage(activity.getString(choiceBody(), activity.getString(R.string.app_name))) + .setCancelable(false) + .setPositive(choiceLabel(), () -> answer(activity, true, onDone)) + .setNegative(R.string.analytics_enroll_decline, () -> answer(activity, false, onDone)) + .show(); + } + + private static void answer(Activity activity, boolean on, Runnable onDone) { + OnlineConsent.setEnabled(activity, on); + OnlineConsent.markAsked(activity); + OnlineChoiceEffects.apply(activity); + onDone.run(); + } +} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/diskguard/DiskGuard.java b/controller/app/src/main/java/org/appdevforall/k2go/diskguard/DiskGuard.java index ce1034944..178291528 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/diskguard/DiskGuard.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/diskguard/DiskGuard.java @@ -44,7 +44,7 @@ import org.appdevforall.k2go.R; import org.appdevforall.k2go.SystemStateEvaluator; -import org.appdevforall.k2go.delivery.data.CrashReportConsent; +import org.appdevforall.k2go.delivery.data.OnlineConsent; import org.appdevforall.k2go.diskguard.data.FirehoseSignalSource; import org.appdevforall.k2go.diskguard.domain.DiskGuardEscalation; import org.appdevforall.k2go.diskguard.domain.DiskGuardPolicy; @@ -310,7 +310,7 @@ private static File biggestLog(File dir) { /** * Report the event to developers, unattended. This is an OPERATIONAL diagnostic, not behavioural - * analytics, so it goes to GlitchTip via Sentry (CrashReportConsent, default off) -- NOT the + * analytics, so it goes to GlitchTip via Sentry (OnlineConsent, default off) -- NOT the * analytics backbone (opt-in, default off, which would silently drop it). A no-op when crash * reporting is off or Sentry has no DSN. See IIABApplication (ADFA-4533) and ADR-386 section 7. * The user-facing, user-sent report is a separate channel (the closing K2GO-386 ticket). @@ -318,7 +318,7 @@ private static File biggestLog(File dir) { private static void report(Context ctx, String source, String action, long floorBytes, boolean reaped, long reclaimed, int count, List paths) { try { - if (!CrashReportConsent.isEnabled(ctx)) return; + if (!OnlineConsent.isEnabled(ctx)) return; Sentry.withScope(scope -> { scope.setLevel(SentryLevel.WARNING); scope.setTag("event", "disk_guard"); diff --git a/controller/app/src/main/java/org/appdevforall/k2go/help/TooltipWiring.java b/controller/app/src/main/java/org/appdevforall/k2go/help/TooltipWiring.java index da0adb3a4..279b46cfb 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/help/TooltipWiring.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/help/TooltipWiring.java @@ -38,13 +38,6 @@ private TooltipWiring() {} // qr MAP.put(R.id.btn_flip_qr, TooltipTag.QR_FLIP); MAP.put(R.id.btn_close_qr, TooltipTag.QR_CLOSE); - // setup - MAP.put(R.id.btn_settings_done, TooltipTag.SETUP_DONE); - MAP.put(R.id.nav_setup, TooltipTag.SETUP_NAV_SETUP); - MAP.put(R.id.nav_feedback, TooltipTag.SETUP_NAV_FEEDBACK); - MAP.put(R.id.nav_about, TooltipTag.SETUP_NAV_ABOUT); - // about - MAP.put(R.id.switch_analytics_consent, TooltipTag.ABOUT_ANALYTICS_CONSENT); // ADFA-5192: the dashboard / deploy / sync / usage / main tooltip entries were removed with // the legacy tabbed UI (their controls and layouts no longer exist). The redesign wires its // own tooltips; this registry now covers only the surviving native surfaces below. @@ -52,16 +45,6 @@ private TooltipWiring() {} MAP.put(R.id.feedback_category, TooltipTag.FEEDBACK_CATEGORY); MAP.put(R.id.feedback_send, TooltipTag.FEEDBACK_SEND); MAP.put(R.id.feedback_force_crash, TooltipTag.FEEDBACK_FORCE_CRASH); - // setup_section - MAP.put(R.id.btn_setup_continue, TooltipTag.SETUP_SECTION_CONTINUE); - MAP.put(R.id.switch_perm_notifications, TooltipTag.SETUP_SECTION_PERM_NOTIFICATIONS); - MAP.put(R.id.switch_perm_storage, TooltipTag.SETUP_SECTION_PERM_STORAGE); - MAP.put(R.id.switch_perm_overlay, TooltipTag.SETUP_SECTION_PERM_OVERLAY); - MAP.put(R.id.switch_perm_battery, TooltipTag.SETUP_SECTION_PERM_BATTERY); - MAP.put(R.id.btn_manage_all, TooltipTag.SETUP_SECTION_MANAGE_ALL); - MAP.put(R.id.language_header, TooltipTag.SETUP_SECTION_LANGUAGE_HEADER); - MAP.put(R.id.spinner_app_language, TooltipTag.SETUP_SECTION_APP_LANGUAGE); - MAP.put(R.id.spinner_language, TooltipTag.SETUP_SECTION_CONTENT_LANGUAGE); } /** Attach tier-1/2 tooltips (long-press) to every mapped control found under {@code root}. */ diff --git a/controller/app/src/main/java/org/appdevforall/k2go/networkpolicy/data/NetworkCostAdmission.java b/controller/app/src/main/java/org/appdevforall/k2go/networkpolicy/data/NetworkCostAdmission.java index 889d6003a..e5dc2dbd7 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/networkpolicy/data/NetworkCostAdmission.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/networkpolicy/data/NetworkCostAdmission.java @@ -41,12 +41,14 @@ public static boolean allowsHeavyStartNow(@NonNull Context ctx) { } /** - * K2GO-580: may the app connect out on its own, with no user tap (an update check, a live - * catalog read)? Only on an unmetered network. Session consent does not count here: it covers - * what the user asked for, not traffic the user cannot see. A user tap goes through NetworkPolicyGate. + * K2GO-580 / K2GO-588: may the app connect out on its own, with no user tap (an update check, a + * live catalog read)? Only when the user chose to request online content (OnlineConsent) and the + * network is unmetered. Session consent does not count here: it covers what the user asked for, + * not traffic the user cannot see. A user tap goes through NetworkPolicyGate. */ public static boolean allowsAutomatic(@NonNull Context ctx) { - return AndroidNetworkClassifier.classify(ctx) + return org.appdevforall.k2go.delivery.data.OnlineConsent.isEnabled(ctx) + && AndroidNetworkClassifier.classify(ctx) == org.appdevforall.k2go.networkpolicy.domain.NetworkClass.UNMETERED; } } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/networkpolicy/domain/HostScope.java b/controller/app/src/main/java/org/appdevforall/k2go/networkpolicy/domain/HostScope.java index da50da5eb..07905b5a1 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/networkpolicy/domain/HostScope.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/networkpolicy/domain/HostScope.java @@ -24,6 +24,7 @@ public static boolean isLocal(String host) { if (h.startsWith("[") && h.endsWith("]")) h = h.substring(1, h.length() - 1); if (h.equals("localhost") || h.endsWith(".localhost") || h.endsWith(".local")) return true; if (h.indexOf(':') >= 0) return isLocalV6(h); + if (h.indexOf('.') < 0) return true; // a single label (box): a local name, never a domain String[] p = h.split("\\.", -1); if (p.length != 4) return false; // a domain name: the internet int[] o = new int[4]; diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/LibraryActivity.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/LibraryActivity.java index 27afd2b40..feb614778 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/redesign/LibraryActivity.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/LibraryActivity.java @@ -102,6 +102,7 @@ public class LibraryActivity extends AppCompatActivity // DownloadManager receiver via onResume/onPause and run one silent auto-check per launch. private org.appdevforall.k2go.update.presentation.UpdateController updateController; private boolean otaAutoChecked = false; + private boolean onlineChoiceAsking = false; // K2GO-588: the one-time question is showing /** K2GO-552: the admin-password notice runs once per launch, once the library is usable. */ private boolean authNoticeChecked = false; @@ -833,7 +834,7 @@ private void onServerReady() { // ADFA-4932: mount the feedback FAB only once the library is usable — never over the boot // gate / install progress. 88dp bottom margin clears the bottom nav. Idempotent. org.appdevforall.k2go.feedback.presentation.FeedbackFab.installOn(this, "library", 88); - if (reduceMotion()) { bootGate.setVisibility(View.GONE); maybeCheckAuthNotice(); return; } + if (reduceMotion()) { bootGate.setVisibility(View.GONE); askOnlineChoiceThenAuthNotice(); return; } bootGate.removeAllAnimatorListeners(); bootGate.setRepeatCount(0); bootGate.setMinAndMaxFrame("B_OPEN_FLIP"); @@ -843,7 +844,7 @@ public void onAnimationEnd(Animator animation) { if (bootGate != null) { bootGate.setVisibility(View.GONE); } - maybeCheckAuthNotice(); // K2GO-552: the notice comes after the gate is gone + askOnlineChoiceThenAuthNotice(); // K2GO-552/588: after the gate is gone } }); bootGate.playAnimation(); @@ -960,7 +961,7 @@ protected void onResume() { if (serverController != null) serverController.onResume(); if (updateController != null) updateController.registerDownloadReceiver(); maybeAutoCheckUpdate(); // ADFA-4984: deferred until the boot gate has opened - maybeCheckAuthNotice(); + askOnlineChoiceThenAuthNotice(); // K2GO-588, K2GO-552 maybeStartDiskGuardReport(); // K2GO-391 } @@ -992,6 +993,29 @@ protected void onPause() { if (updateController != null) updateController.unregisterDownloadReceiver(); } + /** K2GO-588: an install from before the one privacy choice is asked once, after the boot gate + * and never during a first install (the wizard asks then). Until the answer: Keep offline. + * Called when the gate opens (cold start) and from onResume (the gate was already open). */ + private void maybeAskOnlineChoice(Runnable after) { + if (onlineChoiceAsking || installing || !gateDismissed + || org.appdevforall.k2go.delivery.data.OnlineConsent.wasAsked(this)) { + if (!onlineChoiceAsking) after.run(); + return; + } + onlineChoiceAsking = true; + org.appdevforall.k2go.delivery.presentation.OnlineChoiceDialog.askOnce(this, () -> { + onlineChoiceAsking = false; + maybeAutoCheckUpdate(); + after.run(); + }); + } + + /** The gate is gone: first the one-time privacy question, then the admin-password notice, so + * the two dialogs never stack. */ + private void askOnlineChoiceThenAuthNotice() { + maybeAskOnlineChoice(this::maybeCheckAuthNotice); + } + /** ADFA-4984: exposed so Settings -> About can trigger a manual "Check for updates". */ public org.appdevforall.k2go.update.presentation.UpdateController updateController() { return updateController; diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/SettingsSubFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/SettingsSubFragment.java index 57220adc7..f4cc37e3d 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/redesign/SettingsSubFragment.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/SettingsSubFragment.java @@ -22,7 +22,7 @@ import org.appdevforall.k2go.applang.data.LanguageResolver; import org.appdevforall.k2go.applang.domain.AppLanguage; import org.appdevforall.k2go.applang.domain.SupportedAppLanguages; -import org.appdevforall.k2go.delivery.data.AnalyticsConsent; +import org.appdevforall.k2go.delivery.data.OnlineConsent; import android.view.Gravity; import android.widget.EditText; import android.widget.ImageView; @@ -197,21 +197,14 @@ private void buildAbout(Context ctx, LinearLayout list) { }); } SettingsUi.row(ctx, list, getString(R.string.k2go_settings_permissions), null, null, v -> openAppSettings(ctx)); - // ADFA-5337: hide the usage-statistics toggle when analytics is compiled out (no - // google-services.json), since there's nothing to share and the switch would do nothing. - if (org.appdevforall.k2go.BuildConfig.ANALYTICS_ENABLED) { - SettingsUi.toggle(ctx, list, getString(R.string.k2go_settings_usage_stats), AnalyticsConsent.isEnabled(ctx), checked -> { - AnalyticsConsent.setEnabled(ctx, checked); - org.appdevforall.k2go.analytics.AnalyticsClient.with(ctx).applyConsent(); - }); - } - // K2GO-401: crash reports (Sentry -> GlitchTip) are FOSS and unconditional, so the toggle - // always shows. Pref-only: DiskGuard honors it per capture (immediate); the startup-gated - // Sentry init applies on the next launch. (Immediate runtime apply was dropped: a mid-session - // Sentry re-init disturbs the uncaught-handler order IIABApplication establishes at startup.) - SettingsUi.toggle(ctx, list, getString(R.string.k2go_settings_crash_reports), - org.appdevforall.k2go.delivery.data.CrashReportConsent.isEnabled(ctx), - checked -> org.appdevforall.k2go.delivery.data.CrashReportConsent.setEnabled(ctx, checked)); + // K2GO-588: the one privacy choice (usage data where the build has analytics, crash reports, + // automatic connections). OnlineChoiceEffects applies a change at once. + SettingsUi.toggle(ctx, list, + getString(org.appdevforall.k2go.delivery.presentation.OnlineChoiceDialog.choiceLabel()), + OnlineConsent.isEnabled(ctx), checked -> { + OnlineConsent.setEnabled(ctx, checked); + org.appdevforall.k2go.delivery.OnlineChoiceEffects.apply(ctx); + }); SettingsUi.preview(ctx, list, getString(R.string.k2go_settings_licenses), null); } diff --git a/controller/app/src/main/java/org/appdevforall/k2go/redesign/WizardActivity.java b/controller/app/src/main/java/org/appdevforall/k2go/redesign/WizardActivity.java index b4d0106ba..c6a575d08 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/redesign/WizardActivity.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/redesign/WizardActivity.java @@ -15,13 +15,11 @@ import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.NotificationManagerCompat; import androidx.core.content.ContextCompat; -import org.appdevforall.k2go.ui.dialog.BrandDialog; import org.appdevforall.k2go.R; import org.appdevforall.k2go.applang.data.AppLocaleController; import org.appdevforall.k2go.applang.data.ContentLanguage; import org.appdevforall.k2go.applang.domain.AppLanguage; import org.appdevforall.k2go.applang.domain.SupportedAppLanguages; -import org.appdevforall.k2go.delivery.data.AnalyticsConsent; import java.util.Locale; /** @@ -156,6 +154,9 @@ protected void onCreate(Bundle b) { primary.setOnClickListener(v -> onPrimary()); back.setOnClickListener(v -> goBack()); render(); + // K2GO-588: a launch that resumes at the setup choice (permissions already granted) still + // asks the privacy question once; nothing below it may connect before the answer. + if (step == 3) maybeAskAnalytics(() -> { }); // ADFA-4797: on a recreate (e.g. right after a language change) fade the screen in // instead of a hard flash; first launch (b == null) stays instant. @@ -202,26 +203,9 @@ private void onPrimary() { } } - /** One-time usage-stats consent prompt; runs {@code onDone} after the choice (or immediately - * if already asked here or in the legacy flow). Reuses the analytics_enroll_* strings. */ + /** K2GO-588: the one-time privacy choice; runs {@code onDone} after it, or at once. */ private void maybeAskAnalytics(Runnable onDone) { - // ADFA-5337: no analytics compiled in (no google-services.json) → nothing to consent to; skip. - if (!org.appdevforall.k2go.BuildConfig.ANALYTICS_ENABLED) { onDone.run(); return; } - if (AnalyticsConsent.wasAsked(this)) { onDone.run(); return; } - new BrandDialog(this) - .setTitle(R.string.analytics_enroll_title) - .setMessage(getString(R.string.analytics_enroll_body, getString(R.string.app_name))) - .setCancelable(false) - .setPositive(R.string.analytics_enroll_accept, () -> setAnalytics(true, onDone)) - .setNegative(R.string.analytics_enroll_decline, () -> setAnalytics(false, onDone)) - .show(); - } - - private void setAnalytics(boolean on, Runnable onDone) { - AnalyticsConsent.setEnabled(this, on); - AnalyticsConsent.markAsked(this); - org.appdevforall.k2go.analytics.AnalyticsClient.with(this).applyConsent(); - onDone.run(); + org.appdevforall.k2go.delivery.presentation.OnlineChoiceDialog.askOnce(this, onDone); } private void goBack() { diff --git a/controller/app/src/main/java/org/appdevforall/k2go/rootfs/data/RootfsRemoteDataSource.java b/controller/app/src/main/java/org/appdevforall/k2go/rootfs/data/RootfsRemoteDataSource.java index 7fb3d4a3a..8d03fea0e 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/rootfs/data/RootfsRemoteDataSource.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/rootfs/data/RootfsRemoteDataSource.java @@ -49,7 +49,7 @@ public long fetchSizeBytes(String metaUrl) { try { URL url = new URL(metaUrl); conn = (HttpURLConnection) url.openConnection(); - conn.setRequestProperty("User-Agent", "Mozilla/5.0"); + conn.setConnectTimeout(TIMEOUT_MS); conn.setReadTimeout(TIMEOUT_MS); diff --git a/controller/app/src/main/java/org/appdevforall/k2go/settings/AboutFragment.java b/controller/app/src/main/java/org/appdevforall/k2go/settings/AboutFragment.java deleted file mode 100644 index 9db11b207..000000000 --- a/controller/app/src/main/java/org/appdevforall/k2go/settings/AboutFragment.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.appdevforall.k2go.settings; - -import android.content.pm.PackageManager; -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.appcompat.widget.SwitchCompat; -import androidx.fragment.app.Fragment; - -import org.appdevforall.k2go.R; -import org.appdevforall.k2go.delivery.data.AnalyticsConsent; - -/** About section: app name, version, the App Dev for All credit, and the anonymous - * usage-statistics opt-in toggle (mirrors the first-run enrollment choice). */ -public class AboutFragment extends Fragment { - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, - @Nullable Bundle savedInstanceState) { - return inflater.inflate(R.layout.fragment_about, container, false); - } - - @Override - public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - org.appdevforall.k2go.help.TooltipWiring.wireAll(view); - TextView versionView = view.findViewById(R.id.about_version); - versionView.setText(getString(R.string.about_version, appVersionName())); - - // ADFA-5337: no analytics compiled in (no google-services.json) → hide the whole opt-in block, - // since there's nothing to share and the switch would do nothing. - if (!org.appdevforall.k2go.BuildConfig.ANALYTICS_ENABLED) { - View row = view.findViewById(R.id.analytics_consent_row); - View desc = view.findViewById(R.id.analytics_consent_desc); - if (row != null) row.setVisibility(View.GONE); - if (desc != null) desc.setVisibility(View.GONE); - } else { - SwitchCompat analytics = view.findViewById(R.id.switch_analytics_consent); - analytics.setChecked(AnalyticsConsent.isEnabled(requireContext())); - analytics.setOnCheckedChangeListener( - (btn, checked) -> { - AnalyticsConsent.setEnabled(requireContext(), checked); - org.appdevforall.k2go.analytics.AnalyticsClient.with(requireContext()).applyConsent(); - }); - } - } - - private String appVersionName() { - try { - PackageManager pm = requireContext().getPackageManager(); - return pm.getPackageInfo(requireContext().getPackageName(), 0).versionName; - } catch (PackageManager.NameNotFoundException e) { - return ""; - } - } -} diff --git a/controller/app/src/main/java/org/appdevforall/k2go/util/ResilientWebViewClient.java b/controller/app/src/main/java/org/appdevforall/k2go/util/ResilientWebViewClient.java index b7a87bd2a..7a79d089a 100644 --- a/controller/app/src/main/java/org/appdevforall/k2go/util/ResilientWebViewClient.java +++ b/controller/app/src/main/java/org/appdevforall/k2go/util/ResilientWebViewClient.java @@ -71,18 +71,29 @@ public final boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail d } /** - * K2GO-580: a page's own sub-requests to the internet (map tiles, fonts, scripts) are dropped - * unless {@code NetworkCostAdmission.allowsAutomatic} allows them (Wi-Fi). Local hosts (the box, - * the local network) always pass, and so does a page the user opens (main frame). A subclass that + * K2GO-588: an in-app WebView shows the box and the app's own pages. Local hosts (the box, the + * local network) always load. An internet page (main frame) never opens here. A page's own + * internet sub-requests (map tiles, fonts) load only when {@code NetworkCostAdmission.allowsAutomatic} + * allows them: the privacy choice is on and the network is unmetered (K2GO-580). A subclass that * serves its own requests returns super for the rest. */ @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { - if (request.isForMainFrame() - || org.appdevforall.k2go.networkpolicy.domain.HostScope.isLocal(request.getUrl().getHost()) - || org.appdevforall.k2go.networkpolicy.data.NetworkCostAdmission.allowsAutomatic(view.getContext())) { + if (org.appdevforall.k2go.networkpolicy.domain.HostScope.isLocal(request.getUrl().getHost())) { return null; // load normally } + if (!request.isForMainFrame() + && org.appdevforall.k2go.networkpolicy.data.NetworkCostAdmission.allowsAutomatic(view.getContext())) { + return null; + } + if (request.isForMainFrame()) { + // An internet page in place of a blank screen: say why it does not open. + String msg = android.text.TextUtils.htmlEncode( + view.getContext().getString(org.appdevforall.k2go.R.string.k2go_webview_offline_page)); + byte[] html = ("" + msg + "") + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + return new WebResourceResponse("text/html", "utf-8", new java.io.ByteArrayInputStream(html)); + } return new WebResourceResponse("text/plain", "utf-8", 204, "No Content", null, new java.io.ByteArrayInputStream(new byte[0])); } diff --git a/controller/app/src/main/res/layout/activity_setup.xml b/controller/app/src/main/res/layout/activity_setup.xml deleted file mode 100644 index afebdadd5..000000000 --- a/controller/app/src/main/res/layout/activity_setup.xml +++ /dev/null @@ -1,111 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/controller/app/src/main/res/layout/fragment_about.xml b/controller/app/src/main/res/layout/fragment_about.xml deleted file mode 100644 index 3a47432d6..000000000 --- a/controller/app/src/main/res/layout/fragment_about.xml +++ /dev/null @@ -1,41 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/controller/app/src/main/res/layout/fragment_setup_section.xml b/controller/app/src/main/res/layout/fragment_setup_section.xml deleted file mode 100644 index 840a7156a..000000000 --- a/controller/app/src/main/res/layout/fragment_setup_section.xml +++ /dev/null @@ -1,221 +0,0 @@ - - - -