mirror of
https://github.com/rustdesk/rustdesk.git
synced 2026-11-03 16:32:22 +00:00
* feat(android): transfer files directly through SAF folders Let Android users choose folders in the existing file-transfer browser and stream documents through provider descriptors without workspace copies. Keep local browsing separate from host sharing, and restrict new peer document requests to the current shared folder. Preserve traversal checks, overwrite protection, cancellation, empty files, and provider errors through completion. Run Android provider IO on blocking workers and reuse the native directory-listing bridge. Retain the existing workspace import/export flow and non-Android file-transfer behavior. Validation: all 11 base tests pass, including shared-root confinement, document IO, cancellation, provider failures, and resume cleanup. macOS Rust checking and isolated Kotlin compilation pass. Flutter analysis reports no errors, with existing warnings. Full Android builds and device tests remain unperformed. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): group storage locations in the file menu Replace the standalone folder icon and ambiguous RustDesk entry with adjacent RustDesk storage and Other folders actions in the existing menu. Reuse the current storage handlers and register the two localized labels. Validation: targeted Flutter analysis reports no errors and six existing diagnostics. Translation consistency and git diff checks pass. Android device interaction was not tested. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(file-transfer): keep batch deletion running across refreshes Snapshot selected files before awaiting deletion confirmations so directory refreshes cannot invalidate the batch iterator. Defer refreshes for awaited file deletions until the batch finishes, while retaining refreshes for late completions. Retain one regression test for completing all three confirmations after selection reconciliation. All nine file-model tests pass; focused analysis reports no errors and one existing informational diagnostic. Android visual behavior was not tested on a device. Signed-off-by: fufesou <linlong1266@gmail.com> * refactor(android): narrow SAF scope and move folder selection to settings Move shared-folder selection from Share screen permissions to Settings > Transfer file, preserving live connection locking and managed settings visibility. Trim optional SAF resume and thread-identity assertions while retaining transfer and authorization regressions. Split the independent batch-deletion fix into commit 06313a9aa on fix/file-transfer-batch-deletion. Validation: 19 base unit tests and 11 Flutter file-model/download-path tests passed. Focused Flutter analysis reports only existing informational diagnostics. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): clean up failed SAF transfers and reset navigation Cancel pending SAF writes when the client receives a transfer error or the connection manager handles WriteError. Log cleanup failures without replacing the original transfer error or discarding data retained after publication fails. Clear local navigation history after successfully selecting a storage root, so Back does not attempt to return to the previous workspace. Validation: 19 base unit tests and 11 Flutter file-model/download-path tests passed. macOS cargo check passed; focused Flutter analysis reports only existing diagnostics. Android build and device validation were not performed. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): guard SAF overwrites and clean up interrupted receives Require matching per-file confirmation before SAF downloads replace an existing destination, including transfers from peers without overwrite detection. Enforce the policy before creating a temporary document. Cancel unfinished SAF receives when the Android client session exits. Delete newly created temporary documents if opening them fails, preserving the original error and reporting cleanup failures. Keep publication-failure recovery and non-Android transfer paths unchanged. Validation: 19 base unit tests and macOS cargo check --lib --features flutter passed. The document storage Kotlin modules compiled against Android SDK 35. Full Android builds and device validation were not performed. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): clean up SAF uploads on host disconnect Cancel pending SAF receives after the Android connection manager removes a closed connection, including receiver EOF. Log cleanup failures without preventing cleanup of other jobs. Preserve publication-failure recovery. Validation: 19 base unit tests and macOS cargo check --lib --features flutter passed. Android host disconnect behavior still requires device validation. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): restore storage root after failed folder selection Restore the previous local home when opening a selected SAF folder or the RustDesk workspace fails or throws. Preserve navigation history on failure and retain existing error reporting. Keep the home assignment before the asynchronous read so superseded read completions cannot overwrite a newer storage selection. Validation: 11 existing file-model/download-path Flutter tests passed. Focused analysis reports no errors and six pre-existing diagnostics. Changed-method formatting and whitespace checks passed. Android device validation of overlapping storage switches remains pending. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): enforce shared storage and protect SAF overwrites Authorize peer filesystem requests against the currently shared root so remembered workspace paths cannot bypass a selected SAF folder. Offer text-only RustDesk storage and Other folders choices under Change path, including an explicit switch back to the application workspace. Reject SAF host overwrites from peers without overwrite-detection support, while preserving modern senders' existing confirmation flow. Cover legacy creation, rejected replacement, and modern replacement in the Rust fixture. Validation: 19 base tests, 11 Flutter tests, focused Dart analysis, Android Rust/APK builds, and whitespace checks passed. Device checks verified storage switching, cancellation, old-path rejection, and Android-initiated three-file overwrite/Skip batches against macOS. The separate legacy-host overwrite guard was verified by Rust tests and was not in the device APK. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): reject partial SAF listings and restore folder roots Reject provider cursors reporting loading or errors before using their cached rows as a complete directory listing. Propagate the error through the existing folder-transfer initialization and browsing paths. After restoring a local SAF directory, derive its navigation root from the displayed document path so Home and breadcrumbs use the selected tree independently of the host's shared-folder setting. Validation: Kotlin storage modules compile; an Android runtime cursor check covers complete, loading, and error results. Eleven existing Flutter tests and three temporary reconnect checks pass. Focused Dart analysis reports only the existing setter lint; diff checks pass. Cloud-provider transfers and navigation in a rebuilt APK were not tested. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): discard pending SAF writes after block errors Cancel pending document receives when a data-block write fails, removing temporary data before cancellation or disconnect. Preserve the original write error and throttle cleanup-error logging. Keep publication-failure retention unchanged. Extend the existing provider tests with a real descriptor I/O failure and a cleanup-failure case. Validation: - Regression failed before the fix. - cargo test --offline -p base --lib: 19 passed within 60 seconds. - Rustfmt and git diff --check passed. - No Android build or on-device storage-exhaustion test was performed. Signed-off-by: fufesou <linlong1266@gmail.com> * feat(android): guide first-time file transfer folder setup Prompt users to choose the folder remote devices may access when first opening File transfer, manually starting the service, or enabling file transfer. Offer RustDesk storage and the existing SAF picker, and explain where to change the shared folder later in Settings. Remember successful setup or explicit Skip, while allowing canceled setup to be retried. Honor existing settings and permission restrictions. Use the native translation placeholder convention for the settings path. Validation: - Two onboarding widget tests pass, including the breadcrumb regression. - Flutter analysis and Dart formatting checks pass for the new files. - Staged diff whitespace checks pass. Android system-picker and service integration were not tested on a device. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): group file transfer folder choices Replace plain list rows with an indented group of full-width outlined buttons. Tighten spacing while preserving the standard Android touch target and allowing labels to wrap. Validation: both existing onboarding widget tests, scoped Flutter analysis, Dart formatting, and diff whitespace checks pass. Android visual validation was not performed on a device. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): clean up SAF finalization and guard source resume Discard temporary documents when flushing, syncing, or closing a receive fails before publication. Attempt discard even when cancellation cannot close the descriptor, and retain both errors when cleanup also fails. Keep recovery documents after publication failures. Reject nonzero source offsets when the SAF modification time is unknown, so same-size changes cannot combine with a previous partial download. Report that the transfer must restart; fresh sends remain supported. Validation: all 19 base library tests pass, including finalization and cancellation cleanup, combined provider errors, unknown-timestamp resume, fresh sends, and failed-publication retention. Tests used a 60-second limit. Rustfmt and diff whitespace checks pass. Android device/provider failure testing and a rebuilt APK were not performed. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(file-transfer): restore reliable batch deletion Snapshot selected entries before awaiting deletion confirmations so refreshes cannot invalidate the batch iterator. Defer refreshes for awaited file deletions until the batch finishes, while preserving refreshes for late completions. Completing the batch lets the existing mobile delete handler clear the selection and exit selection mode. Restore the previously split fix on the SAF branch with one five-file regression test. Validation: all nine file-model tests pass. The regression reproduced Concurrent modification during iteration before the fix. Focused Flutter analysis has no errors or warnings, with one existing setter-style informational diagnostic. Formatting and diff checks pass. Android device deletion and selection-mode rendering were not tested. Signed-off-by: fufesou <linlong1266@gmail.com> * feat(android): store logs in app media storage Write release logs to Android/media/com.carriez.flutter_hbb/RustDesk, using Android's package-specific media directory and the existing logger. Include this directory in Export Logs alongside legacy logs and recordings, and restrict the added export access to the canonical log directory. Suggest Android/media for the first SAF folder selection on API 26+. Validation: Android ARM64 release cargo check and Kotlin compilation passed. Focused Flutter analysis found no new diagnostics; git diff --check passed. Full APK linking is blocked by missing libvpx.a in the build environment. On-device log writing, export, and initial picker location remain unverified. Signed-off-by: fufesou <linlong1266@gmail.com> * feat(android): keep logs in a user-authorized shared folder Write release logs through SAF in Android/media/RustDesk instead of the package-owned media directory. Require the independent log-folder grant before starting the service, and include these logs in Export Logs while retaining export of existing logs and recordings. Keep daily/size rotation and bounded retention within the log backend. Report provider failures explicitly and route JNI lifetime diagnostics directly to logcat to avoid re-entering JNI during native thread teardown. Allow a deleted log folder to be selected and created again. Validation: Android ARM64 release cargo check, Kotlin compilation, and two existing Flutter setup tests passed. A temporary real-JVM reproduction using the production writer passed native thread exit at debug and trace levels after reproducing the earlier crash. Full Rust/APK builds passed before the final JNI and missing-folder fixes; those fixes passed Rust and Kotlin checks. The final APK and folder authorization, rotation, export, and uninstall retention have not been tested on an Android device. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): validate SAF parent names and restore workspace navigation Reject a newly created SAF parent when the provider changes its display name, before receiving data into that directory. This prevents sanitized names from splitting one source folder into multiple destination folders while reporting success. An adjusted empty directory can remain. Restore the local navigation root for saved paths inside the actual app workspace before checking the saved directory. Keep that choice separate from the host's shared SAF root and leave peer access checks unchanged. Validation: 12 tracked Flutter file-model/download-path tests passed. Three temporary controller tests passed for workspace root/subfolder restoration, local SAF restoration, and workspace-prefix rejection; the workspace case failed before the fix. Kotlin compilation, focused Dart analysis, and diff checks passed, with one existing analysis info. No rebuilt APK or device provider-name/navigation test was performed. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): authorize log storage before outgoing connections Require the existing log-folder authorization before opening an Android remote-control, file-transfer, camera, or terminal session. Canceling or failing authorization leaves the connection unstarted; check that the page is still mounted before navigation. Validation: two temporary authorization regression tests and two existing setup widget tests passed. Focused analysis reported only unchanged diagnostics, and git diff --check passed. No rebuilt APK or device validation. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): clear terminal admin intent on canceled log setup Clear IS_TERMINAL_ADMIN when the Android log-folder authorization guard aborts a terminal launch. A canceled administrator-terminal attempt can no longer pass its one-shot intent to a later ordinary terminal connection. Successful authorization keeps the existing session initialization behavior. Validation: the temporary regression test reproduced the stale flag before the fix; all three temporary widget tests pass after it, including successful administrator intent preservation. Focused Dart analysis reports only unchanged diagnostics, and git diff --check passes. Android authentication dialogs were not tested on a device. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): clarify log setup and default folder selection Show a concise log-directory prompt before opening the picker, and skip the prompt when existing log access is ready. Start first file-transfer folder selection in Documents, excluding the separate log grant from the check for previous transfer-folder selections. Validation: - Focused Flutter analysis, locale consistency, and diff checks passed. - Six temporary authorization/dialog tests passed during implementation. - The review rerun of existing setup tests timed out while loading (60s). - Kotlin/APK builds and Android device validation were not performed. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): check log readiness before boot hosting Run the log-directory preflight off the receiver thread before creating the hosting service. Abort startup with an explicit error when logging is unavailable, and finish the asynchronous broadcast on every path. Validation: four temporary JVM startup tests, Android Kotlin compilation, and git diff --check passed. Release APK reboot and provider validation were not performed. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): simplify log setup and preserve reconnect paths Use a single Choose folder action with clearer log-storage guidance and request Android/media/RustDesk as the initial picker location. Reuse the existing directory ID and add the button label to the locale maps. Restore the workspace root before opening each Android local reconnect candidate, preserving the currently browsed directory ahead of saved locations while retaining the existing fallback order. Validation: 14 existing Flutter tests and two temporary Android-controller regression tests passed. Scoped Dart analysis and git diff --check passed, with only the existing setter-style informational diagnostic. Android compilation and device validation were not performed for these changes. The initial picker location remains a system hint and can be ignored if the directory does not exist. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): prioritize log setup and separate picker defaults Authorize log storage before showing first-use file-transfer setup. Always request Documents for transfer folder selection, independently of previously granted folders. Request Android/media/RustDesk for logs when accessible, otherwise use Android/media so the existing authorization flow can create the child. Remove the obsolete log-grant classifier. Validation: two temporary setup-order tests, three temporary JVM picker tests, and two existing Flutter setup tests passed. Scoped Dart analysis, Android Kotlin compilation, and git diff --check passed. Actual picker behavior was not tested on a device. Initial locations remain system hints supported from API 26. Signed-off-by: fufesou <linlong1266@gmail.com> * refact: translation Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): preserve default logs and simplify folder setup Limit folder setup prompts to hosting startup and remember successful manual shared-folder selections. Outgoing sessions and file-transfer permission toggles no longer request folder configuration. Keep release logs in Config::log_path() until public storage is authorized, and use that original directory when public writes fail. A failed default writer must not prevent logging to a working public folder. Report the fallback explicitly and retain both errors when neither destination works. Use Android/media/<installed AppName>/Logs for public logs. Resolve and create only authorized descendants, verify provider-created directory names, and update picker and startup messages. Keep hosting authorization and the Documents transfer-picker default unchanged. Validation: - Two focused Rust regressions using the real writer and flexi_logger with a supplied Android bridge: default/public routing, fallback and failures. - Five temporary Flutter checks and two existing folder-setup widget tests. - Two temporary Kotlin checks for standard/custom app names, authorized directory creation and independent picker defaults. - Android :app:compileDebugKotlin -Ptarget-platform=android-arm64 passed. - Scoped Dart analysis matches HEAD's existing diagnostics; rustfmt and git diff --check passed. The temporary checks supply Android APIs; release APK logging, permission revocation, fallback and reboot behavior have not been verified on device. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): simplify log folder selection errors Show "Please select Android/media." when a log-folder selection is invalid. Display the platform error message instead of the full PlatformException, while keeping the complete error in debug output. Directory validation and permission handling are unchanged. Validation: scoped Dart analysis, both existing folder-setup widget tests, and git diff --check passed. No APK rebuild or device verification. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): simplify the log folder picker location Always request Android/media as the initial log authorization location and show the same short path in the picker title. Keep creating and using <AppName>/Logs internally. Remove the obsolete filesystem probe for an existing Logs directory. Preserve accepted grants, logging policy and the Documents default for the separate file-transfer picker. Validation: two temporary picker checks with supplied Android APIs, Android :app:compileDebugKotlin -Ptarget-platform=android-arm64, and git diff --check passed. Actual system-picker positioning has not been verified on a device. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): keep hosting independent of log access Restore boot and native service startup without requiring public log folder authorization. The existing logger uses the original directory when public logging is unconfigured or fails. Removing the early service stops also avoids the foreground-service startup failure path. Keep log and shared-folder setup on deliberate hosting startup, but allow hosting confirmation after cancellation or setup failure. Request log setup once, before shared-folder setup. Route Android SAF AllFiles requests through the existing CM enumeration and result channel so the connection loop can continue processing messages. Preserve path validation, file-count limits and ordinary filesystem paths. Validation: - Android Kotlin compilation and ARM64 release cargo check passed. - Focused Dart analysis and both existing folder-setup tests passed. - Temporary source-based startup, cancellation, log fallback and SAF dispatch checks passed using supplied platform/provider APIs. - git diff --check passed; no new rustfmt differences from HEAD. The CM unit test timed out during dependency compilation at the 60-second limit and did not execute. No APK/device reboot, revocation or slow-provider validation was performed. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): reject SAF root deletion before traversal Reject the selected SAF tree root before recursive enumeration or deletion, so a failed root-deletion request cannot remove its empty subdirectories. Keep ordinary subdirectory deletion on the existing path and strengthen one existing root-rejection assertion. Validation: - cargo test -p base --lib fs::android (2 passed) - Three temporary source-backed filesystem checks passed for root preservation, ordinary subtree deletion and nonempty subtree rejection - rustfmt --check and git diff --check passed - No Android device validation performed Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): reject stale SAF source metadata Check provider size and modification time after opening a SAF source against its listed metadata. Reject changed sources before advertising a stale digest, preventing resumed downloads from combining old and new file contents. Treat negative provider timestamps as unknown instead of rejecting the entire listing. Offset resume remains disallowed for sources with unknown timestamps. Validation: - cargo test -p base --lib: 20 tests passed. - Standalone Rust transfer checks: reject a changed source, restart with the current contents, and preserve resume for an unchanged source. - rustfmt --check and git diff --check passed. - No Android APK build or device validation performed. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): move shared folder selection under permissions Place Change Path below Transfer file on the Share screen page, retaining custom-client visibility and active-session permission restrictions. Remove the Settings entry and shorten the first-use sharing prompt. Keep the existing translation key and update its English and Chinese display text. Adjust the existing setup widget test to match. Validation: - Existing setup widget tests: 2 passed. - Focused Dart analysis: no errors or warnings; existing page deprecation notices remain. - Locale consistency, Dart formatting, and git diff --check passed. - No Android APK build or device layout validation. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): tidy shared folder option layout Render Change Path as a compact, full-width sub-option below Transfer file, with one directional inset and a trailing chevron. This removes the extra mobile text-button padding while preserving permission locking. Validation: - Focused Dart analysis: no errors or warnings; three existing deprecation notices remain. - Dart formatting and git diff --check passed. - No new tests for this presentation-only change; updated device layout has not been validated on Android. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): authorize legacy public logs without a folder picker On Android versions below 8, request the system storage permission and write configured public logs to Android/media/<AppName>/Logs. Limit WRITE_EXTERNAL_STORAGE to API 25; keep the existing SAF flow on newer Android versions. General storage permission alone does not redirect logs before explicit setup. Keep the original log destination before setup and on public-write errors. Permission denial completes promptly and does not prevent hosting. Retain log rotation and export, and reopen the writer during readiness checks if the fixed directory has been moved or removed. Validation: - Nox Android 7.1.2: permission grant/denial, original-log fallback, fixed public destination, persisted setup, and actual Rust logs after restart. - Isolated device regression: exported public logs match the source bytes; moved-directory readiness fails before the fix and passes afterward. - Full ARMv7 Flutter debug APK with the release Rust library built and installed successfully. - Two Flutter setup tests, scoped Dart analysis, whitespace checks, and a fresh CodeRabbit review passed. Android 5/6 and Android 8+ device testing was not performed. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): restore SAF log setup and surface folder errors Use SAF for public logs on all supported Android versions. Remove the legacy direct writer and WRITE_EXTERNAL_STORAGE permission, preserving the original logging fallback and normal picker cancellation. Keep log-folder errors visible until acknowledged, then exit the current manual hosting setup instead of advancing to file-transfer setup. Translate the error text, add Chinese translations, and register the missing key in the language catalogs. Boot startup and existing services are unchanged. Validation: - Two existing Flutter file-transfer setup tests passed. - Focused Flutter analysis and git diff --check passed. - Built the release ARMv7 Rust library and Flutter debug APK. - On Nox Android 7.1.2, invalid-root selection showed the persistent Chinese error; acknowledgement exited setup without starting hosting. - Ordinary picker cancellation continued the existing optional setup flow. - APK inspection found no READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE, or MANAGE_EXTERNAL_STORAGE permissions. Device validation used the debug APK on Nox; other Android versions and a full release APK were not device-tested for this change. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): bind SAF digests to opened files and simplify setup Read size and modification time from the opened document descriptor so replacing a source path cannot pair old data with a newer resume digest. Refresh stale metadata for regular files and keep streams non-resumable while preserving fresh sequential sends. Shorten the shared-folder setup prompt and direct log-folder selection to Android/media. Remove obsolete app-media log-directory queries and export allowances; retain SAF logs, original app-data logs, and recordings export. Validation: - Focused base Android tests: 3 passed; the replacement regression failed before the descriptor fix and passed afterward. - Existing Flutter setup and file-model tests: 11 passed. - ARMv7 release Rust library and Flutter debug APK builds passed. - Scoped CodeRabbit re-review: 0 findings; git diff --check passed. No Android device validation was performed for this revision. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): avoid blocking log callers during folder setup Bypass per-record JSON/JNI dispatch after discovering that public logging is unconfigured. Publish routing changes from the application-owned Kotlin logger so a late fallback response cannot undo successful folder setup. Return contended public writes to the existing original-directory writer instead of waiting for provider operations. Keep the JNI callback available in debug Android builds without changing their logcat logger, and remove the unused English tree-picker title. Validation: - ARMv7 release Rust build and full Flutter debug APK packaging passed. - Android 7 provider contention check reproduced the wait before the fix and passed with the rebuilt Kotlin code and native library. - Temporary native routing test passed: one initial backend lookup, subsequent bypass, re-enabling, and all records in the fallback file. - Formatting and diff checks passed; scoped CodeRabbit findings were reviewed against the Rust fallback and picker callers. The full APK was built but not installed for this change. Device checks used the existing isolated probe; full release-app end-to-end validation remains pending. No permanent test infrastructure was added. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): allow slower SAF empty-directory scans Use the existing 30-second remote-directory timeout only for SAF scans. Ordinary filesystem scans keep the two-second timeout, and the request lifecycle is unchanged. Add a regression for a SAF response arriving after three seconds. The file-model suite passes all 10 tests. Targeted analysis reports only the existing setter lint; Android device validation was not performed. Scans exceeding 30 seconds can still time out. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): isolate SAF empty-directory scan lifecycles Only remove an empty-directory request when its timeout still owns the registered completer. Cancel pending SAF scans when the remote session changes so the same directory can be retried immediately. Ordinary filesystem reconnect behavior and timeout durations remain unchanged. Share regression coverage for completed and reconnected scans, keeping each retry pending across the previous timer deadline without adding production state. Validation: all 11 file-model tests pass. Test-file analysis and whitespace checks pass; targeted production analysis reports only the existing setter lint. No Android build or device validation was performed for this change. Signed-off-by: fufesou <linlong1266@gmail.com> * refactor(android): deduplicate SAF helpers and test setup Share local storage navigation, tree-picker Intent construction, and provider listing readiness checks. Preserve independent picker defaults, error messages, failed-navigation rollback, and authorization lifecycles. Reuse Rust transfer-test fixtures and remove text-only setup assertions while retaining behavioral regression coverage. Reduce the branch diff by 78 lines without changing transfer or logging policy. Validation: - Focused Rust SAF tests: 3 passed. - Four focused Flutter suites: 20 passed; the two setup tests were rerun successfully after removing text-only assertions. - Kotlin 2.1.21 / Android SDK 36 compilation passed for all six document integration sources in an isolated Linux directory. - git diff --check passed. No APK build or device validation this round. Signed-off-by: fufesou <linlong1266@gmail.com> * chore(android): organize SAF tests and complete zh-TW label Move the two SAF test files into libs/base/src/fs/tests and update the module path, preserving their contents and module hierarchy. Fill the missing Traditional Chinese translation for Choose folder. Validation: cargo test -p base --lib fs::android passed (3 tests). Verified both moved files are byte-identical and all six new SAF/logging keys have nonempty Traditional Chinese translations. Diff check passed. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): keep hosting available and reject stale SAF scans Keep the log-folder error dialog, skip remaining folder setup after an error, and continue to the existing hosting confirmation. Public-log failures retain the existing default-directory logging fallback. Reject remote SAF empty-directory requests if the session changes while awaiting bridge dispatch. Reuse the existing session generation and leave ordinary filesystem requests unchanged. Extend the existing lifecycle test to cover reconnecting during dispatch. Validation: 21 focused Flutter tests passed. A temporary startup-flow check passed for setup error, success and cancellation. Analysis reports only the existing setter-return-type info. Diff check passed; CodeRabbit review completed with no findings. No Android device validation. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): avoid logging raw folder setup errors Log fixed status messages for Android log-folder setup failures instead of provider-derived exception text. Preserve detailed errors in the dialog and keep the existing folder setup and hosting flow unchanged. Validation: focused Flutter analysis and both existing folder-setup widget tests passed. Diff check passed. No Android device validation. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): offload access checks and restore identical-file hints Run Android peer-path authorization on blocking workers for initial folders, file actions and rename destinations. Preserve fail-closed access decisions and the existing non-Android path. Set the SAF identical-file hint only for matching sizes and known, matching modification times. Keep overwrite confirmation and reject receive resume. Extend the existing transfer test to cover the hint. Validation: - cargo test -p base --lib fs::android: 3 passed. - Android ARMv7 API 21 release cargo check with flutter,hwcodec passed using an isolated copy of HEAD plus these changes, verified by SHA256. - macOS cargo check --lib --features flutter passed for the access fix. - Temporary scheduling check failed before the fix and passed afterward. - Scoped CodeRabbit reviews and diff checks passed. No APK build or device testing was performed for this follow-up. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): limit SAF dispatch and clarify log exports Use blocking workers only for document-backed file operations. Keep ordinary Android filesystem calls on their original execution path and retain asynchronous peer-path authorization checks. Report success and failure counts when log export succeeds only partly. Skip the destination picker when there are no default log sources and no public-folder permission. Preserve public-log permission errors. Validation: - cargo test -p base --lib fs::: 19 passed. - Flutter file-model and Android setup suites: 14 passed. - Android ARMv7 API 21 release cargo check with flutter,hwcodec passed against an isolated source copy, verified by SHA256. - Temporary Dart feedback and Kotlin export-handler checks failed before the fix and passed afterward. - Focused Dart analysis found only existing diagnostics; diff checks passed. No APK build or device testing was performed for this follow-up. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): allow longer SAF deletion scans Use the existing 30-second deadline when recursively scanning SAF folders before deletion. Keep the two-second timeout for ordinary filesystem paths, with request handling and deletion behavior unchanged. Validation: - Existing Flutter file-model and Android setup suites: 14 passed. - Targeted Dart analysis found no new diagnostics. - git diff --check passed. No Android APK build or device testing was performed for this fix. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): keep public logging active after cleanup failures Log a warning when deleting an expired log fails, and continue writing to the newly opened public log. Keep creation, open, and write failures on the existing fallback path. Failed deletions may leave extra old logs. Validation: - Four temporary Kotlin checks passed: deletion false/exception, normal rotation, and propagation of a genuine log-open failure. - Actual document-storage Kotlin sources compiled against Android API 36. - git diff --check passed. No APK build or device test performed. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): keep accepted SAF download file lists immutable Reject replacement of an accepted generic SAF download file list before any mutation, so per-file overwrite approval cannot be redirected to a different destination. Preserve the ordinary download and upload paths. Extend the existing overwrite test and construct each receive fixture with its initial file list only once. Validation: - The added assertion failed before the fix; all 19 filesystem tests passed afterward: cargo test --offline -p base --lib fs::. - Scoped CodeRabbit review completed with no findings. - No new rustfmt differences; git diff --check passed. - No Android build or device test performed for this fix. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): preserve secondary document-transfer exceptions Attach cleanup and backup-restore exceptions to the original error before wrapping it in IOException. Preserve the existing error messages, primary cause, and transfer control flow. Validation: - Confirmed the diff contains only the two addSuppressed calls. - git diff --check passed. - No Android build or device test performed for this diagnostic change. Signed-off-by: fufesou <linlong1266@gmail.com> * fix(android): log authorization failures with throttling Report document access-check errors at warning level and blocking-task failures at error level. Throttle each site to one record per minute while preserving existing deny decisions and failure messages. Validation: - Existing hbb_common log_throttle tests: 4 passed. - Rust formatting and git diff --check passed. - Android target build and device testing not performed. Signed-off-by: fufesou <linlong1266@gmail.com> --------- Signed-off-by: fufesou <linlong1266@gmail.com>
952 lines
28 KiB
Dart
952 lines
28 KiB
Dart
import 'dart:async';
|
|
import 'dart:convert';
|
|
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter_hbb/consts.dart';
|
|
import 'package:flutter_hbb/main.dart';
|
|
import 'package:flutter_hbb/mobile/pages/settings_page.dart';
|
|
import 'package:flutter_hbb/models/chat_model.dart';
|
|
import 'package:flutter_hbb/models/platform_model.dart';
|
|
import 'package:get/get.dart';
|
|
import 'package:window_manager/window_manager.dart';
|
|
|
|
import '../common.dart';
|
|
import '../common/formatter/id_formatter.dart';
|
|
import '../desktop/pages/server_page.dart' as desktop;
|
|
import '../desktop/widgets/tabbar_widget.dart';
|
|
import '../mobile/pages/server_page.dart';
|
|
import '../mobile/widgets/android_file_transfer_setup.dart';
|
|
import '../utils/android_documents.dart';
|
|
import 'model.dart';
|
|
|
|
const kLoginDialogTag = "LOGIN";
|
|
|
|
const kUseTemporaryPassword = "use-temporary-password";
|
|
const kUsePermanentPassword = "use-permanent-password";
|
|
const kUseBothPasswords = "use-both-passwords";
|
|
|
|
class ServerModel with ChangeNotifier {
|
|
bool _isStart = false; // Android MainService status
|
|
bool _mediaOk = false;
|
|
bool _inputOk = false;
|
|
bool _audioOk = false;
|
|
bool _fileOk = false;
|
|
bool _clipboardOk = false;
|
|
bool _showElevation = false;
|
|
bool hideCm = false;
|
|
int _connectStatus = 0; // Rendezvous Server status
|
|
String _verificationMethod = "";
|
|
String _temporaryPasswordLength = "";
|
|
bool _allowNumericOneTimePassword = false;
|
|
String _approveMode = "";
|
|
int _zeroClientLengthCounter = 0;
|
|
|
|
late String _emptyIdShow;
|
|
late final IDTextEditingController _serverId;
|
|
final _serverPasswd =
|
|
TextEditingController(text: translate("Generating ..."));
|
|
|
|
final tabController = DesktopTabController(tabType: DesktopTabType.cm);
|
|
|
|
final List<Client> _clients = [];
|
|
|
|
Timer? cmHiddenTimer;
|
|
|
|
final _wakelockKey = UniqueKey();
|
|
|
|
bool get isStart => _isStart;
|
|
|
|
bool get mediaOk => _mediaOk;
|
|
|
|
bool get inputOk => _inputOk;
|
|
|
|
bool get audioOk => _audioOk;
|
|
|
|
bool get fileOk => _fileOk;
|
|
|
|
bool get clipboardOk => _clipboardOk;
|
|
|
|
bool get showElevation => _showElevation;
|
|
|
|
int get connectStatus => _connectStatus;
|
|
|
|
String get verificationMethod {
|
|
final index = [
|
|
kUseTemporaryPassword,
|
|
kUsePermanentPassword,
|
|
kUseBothPasswords
|
|
].indexOf(_verificationMethod);
|
|
if (index < 0) {
|
|
return kUseBothPasswords;
|
|
}
|
|
return _verificationMethod;
|
|
}
|
|
|
|
String get approveMode => _approveMode;
|
|
|
|
setVerificationMethod(String method) async {
|
|
await bind.mainSetOption(key: kOptionVerificationMethod, value: method);
|
|
/*
|
|
if (method != kUsePermanentPassword) {
|
|
await bind.mainSetOption(
|
|
key: 'allow-hide-cm', value: bool2option('allow-hide-cm', false));
|
|
}
|
|
*/
|
|
}
|
|
|
|
String get temporaryPasswordLength {
|
|
final lengthIndex = ["6", "8", "10"].indexOf(_temporaryPasswordLength);
|
|
if (lengthIndex < 0) {
|
|
return "6";
|
|
}
|
|
return _temporaryPasswordLength;
|
|
}
|
|
|
|
setTemporaryPasswordLength(String length) async {
|
|
await bind.mainSetOption(key: "temporary-password-length", value: length);
|
|
}
|
|
|
|
setApproveMode(String mode) async {
|
|
await bind.mainSetOption(key: kOptionApproveMode, value: mode);
|
|
/*
|
|
if (mode != 'password') {
|
|
await bind.mainSetOption(
|
|
key: 'allow-hide-cm', value: bool2option('allow-hide-cm', false));
|
|
}
|
|
*/
|
|
}
|
|
|
|
bool get allowNumericOneTimePassword => _allowNumericOneTimePassword;
|
|
switchAllowNumericOneTimePassword() async {
|
|
await mainSetBoolOption(
|
|
kOptionAllowNumericOneTimePassword, !_allowNumericOneTimePassword);
|
|
}
|
|
|
|
TextEditingController get serverId => _serverId;
|
|
|
|
TextEditingController get serverPasswd => _serverPasswd;
|
|
|
|
List<Client> get clients => _clients;
|
|
|
|
final controller = ScrollController();
|
|
|
|
WeakReference<FFI> parent;
|
|
|
|
ServerModel(this.parent) {
|
|
_emptyIdShow = translate("Generating ...");
|
|
_serverId = IDTextEditingController(text: _emptyIdShow);
|
|
|
|
/*
|
|
// initital _hideCm at startup
|
|
final verificationMethod =
|
|
bind.mainGetOptionSync(key: kOptionVerificationMethod);
|
|
final approveMode = bind.mainGetOptionSync(key: kOptionApproveMode);
|
|
_hideCm = option2bool(
|
|
'allow-hide-cm', bind.mainGetOptionSync(key: 'allow-hide-cm'));
|
|
if (!(approveMode == 'password' &&
|
|
verificationMethod == kUsePermanentPassword)) {
|
|
_hideCm = false;
|
|
}
|
|
*/
|
|
|
|
timerCallback() async {
|
|
final connectionStatus =
|
|
jsonDecode(await bind.mainGetConnectStatus()) as Map<String, dynamic>;
|
|
final statusNum = connectionStatus['status_num'] as int;
|
|
if (statusNum != _connectStatus) {
|
|
_connectStatus = statusNum;
|
|
notifyListeners();
|
|
}
|
|
|
|
if (desktopType == DesktopType.cm) {
|
|
final res = await bind.cmCheckClientsLength(length: _clients.length);
|
|
if (res != null) {
|
|
debugPrint("clients not match!");
|
|
updateClientState(res);
|
|
} else {
|
|
if (_clients.isEmpty) {
|
|
hideCmWindow();
|
|
if (_zeroClientLengthCounter++ == 12) {
|
|
// 6 second
|
|
windowManager.close();
|
|
}
|
|
} else {
|
|
_zeroClientLengthCounter = 0;
|
|
if (!hideCm) showCmWindow();
|
|
}
|
|
}
|
|
}
|
|
|
|
updatePasswordModel();
|
|
}
|
|
|
|
if (!isTest) {
|
|
Future.delayed(Duration.zero, () async {
|
|
if (await bind.optionSynced()) {
|
|
await timerCallback();
|
|
}
|
|
});
|
|
Timer.periodic(Duration(milliseconds: 500), (timer) async {
|
|
await timerCallback();
|
|
});
|
|
}
|
|
|
|
// Initial keyboard status is off on mobile
|
|
if (isMobile) {
|
|
bind.mainSetOption(key: kOptionEnableKeyboard, value: 'N');
|
|
}
|
|
}
|
|
|
|
/// 1. check android permission
|
|
/// 2. check config
|
|
/// audio true by default (if permission on) (false default < Android 10)
|
|
/// file true by default (if permission on)
|
|
checkAndroidPermission() async {
|
|
// audio
|
|
if (androidVersion < 30 ||
|
|
!await AndroidPermissionManager.check(kRecordAudio)) {
|
|
_audioOk = false;
|
|
bind.mainSetOption(key: kOptionEnableAudio, value: "N");
|
|
} else {
|
|
final audioOption = await bind.mainGetOption(key: kOptionEnableAudio);
|
|
_audioOk = audioOption != 'N';
|
|
}
|
|
|
|
// Android file transfer is confined to app-specific storage. Files enter
|
|
// and leave the workspace through Android's system document picker.
|
|
final fileOption = await bind.mainGetOption(key: kOptionEnableFileTransfer);
|
|
_fileOk = fileOption != 'N';
|
|
|
|
// clipboard
|
|
final clipOption = await bind.mainGetOption(key: kOptionEnableClipboard);
|
|
_clipboardOk = clipOption != 'N';
|
|
|
|
notifyListeners();
|
|
}
|
|
|
|
updatePasswordModel() async {
|
|
var update = false;
|
|
final temporaryPassword = await bind.mainGetTemporaryPassword();
|
|
final verificationMethod =
|
|
await bind.mainGetOption(key: kOptionVerificationMethod);
|
|
final temporaryPasswordLength =
|
|
await bind.mainGetOption(key: "temporary-password-length");
|
|
final approveMode = await bind.mainGetOption(key: kOptionApproveMode);
|
|
final numericOneTimePassword =
|
|
await mainGetBoolOption(kOptionAllowNumericOneTimePassword);
|
|
/*
|
|
var hideCm = option2bool(
|
|
'allow-hide-cm', await bind.mainGetOption(key: 'allow-hide-cm'));
|
|
if (!(approveMode == 'password' &&
|
|
verificationMethod == kUsePermanentPassword)) {
|
|
hideCm = false;
|
|
}
|
|
*/
|
|
if (_approveMode != approveMode) {
|
|
_approveMode = approveMode;
|
|
update = true;
|
|
}
|
|
var stopped = await mainGetBoolOption(kOptionStopService);
|
|
final oldPwdText = _serverPasswd.text;
|
|
if (stopped ||
|
|
verificationMethod == kUsePermanentPassword ||
|
|
_approveMode == 'click') {
|
|
_serverPasswd.text = '-';
|
|
} else {
|
|
if (_serverPasswd.text != temporaryPassword &&
|
|
temporaryPassword.isNotEmpty) {
|
|
_serverPasswd.text = temporaryPassword;
|
|
}
|
|
}
|
|
if (oldPwdText != _serverPasswd.text) {
|
|
update = true;
|
|
}
|
|
if (_verificationMethod != verificationMethod) {
|
|
_verificationMethod = verificationMethod;
|
|
update = true;
|
|
}
|
|
if (_temporaryPasswordLength != temporaryPasswordLength) {
|
|
if (_temporaryPasswordLength.isNotEmpty) {
|
|
bind.mainUpdateTemporaryPassword();
|
|
}
|
|
_temporaryPasswordLength = temporaryPasswordLength;
|
|
update = true;
|
|
}
|
|
if (_allowNumericOneTimePassword != numericOneTimePassword) {
|
|
_allowNumericOneTimePassword = numericOneTimePassword;
|
|
update = true;
|
|
}
|
|
/*
|
|
if (_hideCm != hideCm) {
|
|
_hideCm = hideCm;
|
|
if (desktopType == DesktopType.cm) {
|
|
if (hideCm) {
|
|
await hideCmWindow();
|
|
} else {
|
|
await showCmWindow();
|
|
}
|
|
}
|
|
update = true;
|
|
}
|
|
*/
|
|
if (update) {
|
|
notifyListeners();
|
|
}
|
|
}
|
|
|
|
toggleAudio() async {
|
|
if (clients.any((c) => !c.disconnected)) {
|
|
await showClientsMayNotBeChangedAlert(parent.target);
|
|
}
|
|
if (!_audioOk && !await AndroidPermissionManager.check(kRecordAudio)) {
|
|
final res = await AndroidPermissionManager.request(kRecordAudio);
|
|
if (!res) {
|
|
showToast(translate('Failed'));
|
|
return;
|
|
}
|
|
}
|
|
|
|
_audioOk = !_audioOk;
|
|
bind.mainSetOption(
|
|
key: kOptionEnableAudio, value: _audioOk ? defaultOptionYes : 'N');
|
|
notifyListeners();
|
|
}
|
|
|
|
toggleFile() async {
|
|
if (clients.any((c) => !c.disconnected)) {
|
|
await showClientsMayNotBeChangedAlert(parent.target);
|
|
}
|
|
_fileOk = !_fileOk;
|
|
bind.mainSetOption(
|
|
key: kOptionEnableFileTransfer,
|
|
value: _fileOk ? defaultOptionYes : 'N');
|
|
notifyListeners();
|
|
}
|
|
|
|
toggleClipboard() async {
|
|
_clipboardOk = !clipboardOk;
|
|
bind.mainSetOption(
|
|
key: kOptionEnableClipboard,
|
|
value: clipboardOk ? defaultOptionYes : 'N');
|
|
notifyListeners();
|
|
}
|
|
|
|
toggleInput() async {
|
|
if (clients.any((c) => !c.disconnected)) {
|
|
await showClientsMayNotBeChangedAlert(parent.target);
|
|
}
|
|
if (_inputOk) {
|
|
parent.target?.invokeMethod("stop_input");
|
|
bind.mainSetOption(key: kOptionEnableKeyboard, value: 'N');
|
|
} else {
|
|
if (parent.target != null) {
|
|
/// the result of toggle-on depends on user actions in the settings page.
|
|
/// handle result, see [ServerModel.changeStatue]
|
|
showInputWarnAlert(parent.target!);
|
|
}
|
|
}
|
|
}
|
|
|
|
Future<bool> checkRequestNotificationPermission() async {
|
|
debugPrint("androidVersion $androidVersion");
|
|
if (androidVersion < 33) {
|
|
return true;
|
|
}
|
|
if (await AndroidPermissionManager.check(kAndroid13Notification)) {
|
|
debugPrint("notification permission already granted");
|
|
return true;
|
|
}
|
|
var res = await AndroidPermissionManager.request(kAndroid13Notification);
|
|
debugPrint("notification permission request result: $res");
|
|
return res;
|
|
}
|
|
|
|
Future<bool> checkFloatingWindowPermission() async {
|
|
debugPrint("androidVersion $androidVersion");
|
|
if (androidVersion < 23) {
|
|
return false;
|
|
}
|
|
if (await AndroidPermissionManager.check(kSystemAlertWindow)) {
|
|
debugPrint("alert window permission already granted");
|
|
return true;
|
|
}
|
|
var res = await AndroidPermissionManager.request(kSystemAlertWindow);
|
|
debugPrint("alert window permission request result: $res");
|
|
return res;
|
|
}
|
|
|
|
/// Toggle the screen sharing service.
|
|
toggleService() async {
|
|
if (_isStart) {
|
|
final res = await parent.target?.dialogManager
|
|
.show<bool>((setState, close, context) {
|
|
submit() => close(true);
|
|
return CustomAlertDialog(
|
|
title: Row(children: [
|
|
const Icon(Icons.warning_amber_sharp,
|
|
color: Colors.redAccent, size: 28),
|
|
const SizedBox(width: 10),
|
|
Text(translate("Warning")),
|
|
]),
|
|
content: Text(translate("android_stop_service_tip")),
|
|
actions: [
|
|
TextButton(onPressed: close, child: Text(translate("Cancel"))),
|
|
TextButton(onPressed: submit, child: Text(translate("OK"))),
|
|
],
|
|
onSubmit: submit,
|
|
onCancel: close,
|
|
);
|
|
});
|
|
if (res == true) {
|
|
stopService();
|
|
}
|
|
} else {
|
|
if (isAndroid) {
|
|
try {
|
|
await AndroidDocuments.requireLogFolder();
|
|
await showAndroidFileTransferSetup(gFFI);
|
|
} catch (_) {
|
|
debugPrint('Folder setup failed; continuing service startup');
|
|
}
|
|
}
|
|
await checkRequestNotificationPermission();
|
|
if (bind.mainGetLocalOption(key: kOptionDisableFloatingWindow) != 'Y') {
|
|
await checkFloatingWindowPermission();
|
|
}
|
|
final res = await parent.target?.dialogManager
|
|
.show<bool>((setState, close, context) {
|
|
submit() => close(true);
|
|
return CustomAlertDialog(
|
|
title: Row(children: [
|
|
const Icon(Icons.warning_amber_sharp,
|
|
color: Colors.redAccent, size: 28),
|
|
const SizedBox(width: 10),
|
|
Text(translate("Warning")),
|
|
]),
|
|
content: Text(translate("android_service_will_start_tip")),
|
|
actions: [
|
|
dialogButton("Cancel", onPressed: close, isOutline: true),
|
|
dialogButton("OK", onPressed: submit),
|
|
],
|
|
onSubmit: submit,
|
|
onCancel: close,
|
|
);
|
|
});
|
|
if (res == true) {
|
|
startService();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Start the screen sharing service.
|
|
Future<void> startService() async {
|
|
_isStart = true;
|
|
notifyListeners();
|
|
parent.target?.ffiModel.updateEventListener(parent.target!.sessionId, "");
|
|
await parent.target?.invokeMethod("init_service");
|
|
// ugly is here, because for desktop, below is useless
|
|
await bind.mainStartService();
|
|
updateClientState();
|
|
if (isAndroid) {
|
|
androidUpdatekeepScreenOn();
|
|
}
|
|
}
|
|
|
|
/// Stop the screen sharing service.
|
|
Future<void> stopService() async {
|
|
_isStart = false;
|
|
closeAll();
|
|
await parent.target?.invokeMethod("stop_service");
|
|
await bind.mainStopService();
|
|
notifyListeners();
|
|
// for androidUpdatekeepScreenOn only
|
|
WakelockManager.disable(_wakelockKey);
|
|
}
|
|
|
|
fetchID() async {
|
|
final id = await bind.mainGetMyId();
|
|
if (id != _serverId.id) {
|
|
_serverId.id = id;
|
|
notifyListeners();
|
|
}
|
|
}
|
|
|
|
changeStatue(String name, bool value) {
|
|
debugPrint("changeStatue value $value");
|
|
switch (name) {
|
|
case "media":
|
|
_mediaOk = value;
|
|
if (value && !_isStart) {
|
|
startService();
|
|
}
|
|
break;
|
|
case "input":
|
|
if (_inputOk != value) {
|
|
bind.mainSetOption(
|
|
key: kOptionEnableKeyboard,
|
|
value: value ? defaultOptionYes : 'N');
|
|
}
|
|
_inputOk = value;
|
|
break;
|
|
default:
|
|
return;
|
|
}
|
|
notifyListeners();
|
|
}
|
|
|
|
// force
|
|
updateClientState([String? json]) async {
|
|
if (isTest) return;
|
|
var res = await bind.cmGetClientsState();
|
|
List<dynamic> clientsJson;
|
|
try {
|
|
clientsJson = jsonDecode(res);
|
|
} catch (e) {
|
|
debugPrint("Failed to decode clientsJson: '$res', error $e");
|
|
return;
|
|
}
|
|
|
|
final oldClientLenght = _clients.length;
|
|
_clients.clear();
|
|
tabController.state.value.tabs.clear();
|
|
|
|
for (var clientJson in clientsJson) {
|
|
try {
|
|
final client = Client.fromJson(clientJson);
|
|
_clients.add(client);
|
|
_addTab(client);
|
|
} catch (e) {
|
|
debugPrint("Failed to decode clientJson '$clientJson', error $e");
|
|
}
|
|
}
|
|
if (desktopType == DesktopType.cm) {
|
|
if (_clients.isEmpty) {
|
|
hideCmWindow();
|
|
} else if (!hideCm) {
|
|
showCmWindow();
|
|
}
|
|
}
|
|
if (_clients.length != oldClientLenght) {
|
|
notifyListeners();
|
|
if (isAndroid) androidUpdatekeepScreenOn();
|
|
}
|
|
}
|
|
|
|
void addConnection(Map<String, dynamic> evt) {
|
|
try {
|
|
final client = Client.fromJson(jsonDecode(evt["client"]));
|
|
if (client.authorized) {
|
|
parent.target?.dialogManager.dismissByTag(getLoginDialogTag(client.id));
|
|
final index = _clients.indexWhere((c) => c.id == client.id);
|
|
if (index < 0) {
|
|
_clients.add(client);
|
|
} else {
|
|
if (_clients[index].authorized) {
|
|
_clients[index].privacyMode = client.privacyMode;
|
|
notifyListeners();
|
|
return;
|
|
}
|
|
_clients[index].authorized = true;
|
|
_clients[index].privacyMode = client.privacyMode;
|
|
}
|
|
} else {
|
|
final index = _clients.indexWhere((c) => c.id == client.id);
|
|
if (index >= 0) {
|
|
_clients[index].privacyMode = client.privacyMode;
|
|
notifyListeners();
|
|
return;
|
|
}
|
|
_clients.add(client);
|
|
}
|
|
_addTab(client);
|
|
// remove disconnected
|
|
final index_disconnected = _clients
|
|
.indexWhere((c) => c.disconnected && c.peerId == client.peerId);
|
|
if (index_disconnected >= 0) {
|
|
_clients.removeAt(index_disconnected);
|
|
tabController.remove(index_disconnected);
|
|
}
|
|
if (desktopType == DesktopType.cm && !hideCm) {
|
|
showCmWindow();
|
|
}
|
|
scrollToBottom();
|
|
notifyListeners();
|
|
if (isAndroid && !client.authorized) showLoginDialog(client);
|
|
if (isAndroid) androidUpdatekeepScreenOn();
|
|
} catch (e) {
|
|
debugPrint("Failed to call loginRequest,error:$e");
|
|
}
|
|
}
|
|
|
|
void _addTab(Client client) {
|
|
tabController.add(TabInfo(
|
|
key: client.id.toString(),
|
|
label: client.name,
|
|
closable: false,
|
|
onTap: () {},
|
|
page: desktop.buildConnectionCard(client)));
|
|
Future.delayed(Duration.zero, () async {
|
|
if (!hideCm) windowOnTop(null);
|
|
});
|
|
// Only do the hidden task when on Desktop.
|
|
if (client.authorized && isDesktop) {
|
|
cmHiddenTimer = Timer(const Duration(seconds: 3), () {
|
|
if (!hideCm) windowManager.minimize();
|
|
cmHiddenTimer = null;
|
|
});
|
|
}
|
|
parent.target?.chatModel
|
|
.updateConnIdOfKey(MessageKey(client.peerId, client.id));
|
|
}
|
|
|
|
void showLoginDialog(Client client) {
|
|
showClientDialog(
|
|
client,
|
|
client.isFileTransfer
|
|
? "Transfer file"
|
|
: client.isViewCamera
|
|
? "View camera"
|
|
: client.isTerminal
|
|
? "Terminal"
|
|
: "Share screen",
|
|
'Do you accept?',
|
|
'android_new_connection_tip',
|
|
() => sendLoginResponse(client, false),
|
|
() => sendLoginResponse(client, true),
|
|
);
|
|
}
|
|
|
|
handleVoiceCall(Client client, bool accept) {
|
|
parent.target?.invokeMethod("cancel_notification", client.id);
|
|
bind.cmHandleIncomingVoiceCall(id: client.id, accept: accept);
|
|
}
|
|
|
|
showVoiceCallDialog(Client client) {
|
|
showClientDialog(
|
|
client,
|
|
'Voice call',
|
|
'Do you accept?',
|
|
'android_new_voice_call_tip',
|
|
() => handleVoiceCall(client, false),
|
|
() => handleVoiceCall(client, true),
|
|
);
|
|
}
|
|
|
|
showClientDialog(Client client, String title, String contentTitle,
|
|
String content, VoidCallback onCancel, VoidCallback onSubmit) {
|
|
parent.target?.dialogManager.show((setState, close, context) {
|
|
cancel() {
|
|
onCancel();
|
|
close();
|
|
}
|
|
|
|
submit() {
|
|
onSubmit();
|
|
close();
|
|
}
|
|
|
|
return CustomAlertDialog(
|
|
title:
|
|
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
|
|
Text(translate(title)),
|
|
IconButton(onPressed: close, icon: const Icon(Icons.close))
|
|
]),
|
|
content: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
mainAxisAlignment: MainAxisAlignment.center,
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(translate(contentTitle)),
|
|
ClientInfo(client),
|
|
Text(
|
|
translate(content),
|
|
style: Theme.of(globalKey.currentContext!).textTheme.bodyMedium,
|
|
),
|
|
],
|
|
),
|
|
actions: [
|
|
dialogButton("Dismiss", onPressed: cancel, isOutline: true),
|
|
if (approveMode != 'password')
|
|
dialogButton("Accept", onPressed: submit),
|
|
],
|
|
onSubmit: submit,
|
|
onCancel: cancel,
|
|
);
|
|
}, tag: getLoginDialogTag(client.id));
|
|
}
|
|
|
|
scrollToBottom() {
|
|
if (isDesktop) return;
|
|
Future.delayed(Duration(milliseconds: 200), () {
|
|
controller.animateTo(controller.position.maxScrollExtent,
|
|
duration: Duration(milliseconds: 200),
|
|
curve: Curves.fastLinearToSlowEaseIn);
|
|
});
|
|
}
|
|
|
|
void sendLoginResponse(Client client, bool res) async {
|
|
if (res) {
|
|
bind.cmLoginRes(connId: client.id, res: res);
|
|
if (!client.isFileTransfer && !client.isTerminal) {
|
|
parent.target?.invokeMethod("start_capture");
|
|
}
|
|
parent.target?.invokeMethod("cancel_notification", client.id);
|
|
client.authorized = true;
|
|
notifyListeners();
|
|
} else {
|
|
bind.cmLoginRes(connId: client.id, res: res);
|
|
parent.target?.invokeMethod("cancel_notification", client.id);
|
|
final index = _clients.indexOf(client);
|
|
tabController.remove(index);
|
|
_clients.remove(client);
|
|
if (isAndroid) androidUpdatekeepScreenOn();
|
|
}
|
|
}
|
|
|
|
void onClientRemove(Map<String, dynamic> evt) {
|
|
try {
|
|
final id = int.parse(evt['id'] as String);
|
|
final close = (evt['close'] as String) == 'true';
|
|
if (_clients.any((c) => c.id == id)) {
|
|
final index = _clients.indexWhere((client) => client.id == id);
|
|
if (index >= 0) {
|
|
if (close) {
|
|
_clients.removeAt(index);
|
|
tabController.remove(index);
|
|
} else {
|
|
_clients[index].disconnected = true;
|
|
}
|
|
}
|
|
parent.target?.dialogManager.dismissByTag(getLoginDialogTag(id));
|
|
parent.target?.invokeMethod("cancel_notification", id);
|
|
}
|
|
if (desktopType == DesktopType.cm && _clients.isEmpty) {
|
|
hideCmWindow();
|
|
}
|
|
if (isAndroid) androidUpdatekeepScreenOn();
|
|
notifyListeners();
|
|
} catch (e) {
|
|
debugPrint("onClientRemove failed,error:$e");
|
|
}
|
|
}
|
|
|
|
/// `byOperator` false means the CM's window went away rather than a person asking for the
|
|
/// peers to go. The sessions end either way; only the close reason differs, and with it
|
|
/// whether the peer is allowed to reconnect. See `ipc::Data::CmWindowClosed`.
|
|
Future<void> closeAll({bool byOperator = true}) async {
|
|
await Future.wait(_clients.map((client) => byOperator
|
|
? bind.cmCloseConnection(connId: client.id)
|
|
: bind.cmCloseConnectionWindow(connId: client.id)));
|
|
_clients.clear();
|
|
tabController.state.value.tabs.clear();
|
|
if (isAndroid) androidUpdatekeepScreenOn();
|
|
}
|
|
|
|
void jumpTo(int id) {
|
|
final index = _clients.indexWhere((client) => client.id == id);
|
|
tabController.jumpTo(index);
|
|
}
|
|
|
|
void setShowElevation(bool show) {
|
|
if (_showElevation != show) {
|
|
_showElevation = show;
|
|
notifyListeners();
|
|
}
|
|
}
|
|
|
|
void updateVoiceCallState(Map<String, dynamic> evt) {
|
|
try {
|
|
final client = Client.fromJson(jsonDecode(evt["client"]));
|
|
final index = _clients.indexWhere((element) => element.id == client.id);
|
|
if (index != -1) {
|
|
_clients[index].inVoiceCall = client.inVoiceCall;
|
|
_clients[index].incomingVoiceCall = client.incomingVoiceCall;
|
|
if (client.incomingVoiceCall) {
|
|
if (isAndroid) {
|
|
showVoiceCallDialog(client);
|
|
} else {
|
|
// Has incoming phone call, let's set the window on top.
|
|
Future.delayed(Duration.zero, () {
|
|
windowOnTop(null);
|
|
});
|
|
}
|
|
}
|
|
notifyListeners();
|
|
}
|
|
} catch (e) {
|
|
debugPrint("updateVoiceCallState failed: $e");
|
|
}
|
|
}
|
|
|
|
void androidUpdatekeepScreenOn() async {
|
|
if (!isAndroid) return;
|
|
var floatingWindowDisabled =
|
|
bind.mainGetLocalOption(key: kOptionDisableFloatingWindow) == "Y" ||
|
|
!await AndroidPermissionManager.check(kSystemAlertWindow);
|
|
final keepScreenOn = floatingWindowDisabled
|
|
? KeepScreenOn.never
|
|
: optionToKeepScreenOn(
|
|
bind.mainGetLocalOption(key: kOptionKeepScreenOn));
|
|
final on = ((keepScreenOn == KeepScreenOn.serviceOn) && _isStart) ||
|
|
(keepScreenOn == KeepScreenOn.duringControlled &&
|
|
_clients.map((e) => !e.disconnected).isNotEmpty);
|
|
if (on) {
|
|
WakelockManager.enable(_wakelockKey, isServer: true);
|
|
} else {
|
|
WakelockManager.disable(_wakelockKey);
|
|
}
|
|
}
|
|
}
|
|
|
|
enum ClientType {
|
|
remote,
|
|
file,
|
|
camera,
|
|
portForward,
|
|
terminal,
|
|
}
|
|
|
|
class Client {
|
|
int id = 0; // client connections inner count id
|
|
bool authorized = false;
|
|
bool isFileTransfer = false;
|
|
bool isViewCamera = false;
|
|
bool isTerminal = false;
|
|
String portForward = "";
|
|
String name = "";
|
|
String avatar = "";
|
|
String peerId = ""; // peer user's id,show at app
|
|
bool keyboard = false;
|
|
bool clipboard = false;
|
|
bool audio = false;
|
|
bool file = false;
|
|
bool restart = false;
|
|
bool recording = false;
|
|
bool blockInput = false;
|
|
bool privacyMode = false;
|
|
bool disconnected = false;
|
|
bool fromSwitch = false;
|
|
bool inVoiceCall = false;
|
|
bool incomingVoiceCall = false;
|
|
|
|
RxInt unreadChatMessageCount = 0.obs;
|
|
|
|
Client(this.id, this.authorized, this.isFileTransfer, this.isViewCamera,
|
|
this.name, this.peerId, this.keyboard, this.clipboard, this.audio);
|
|
|
|
Client.fromJson(Map<String, dynamic> json) {
|
|
id = json['id'];
|
|
authorized = json['authorized'];
|
|
isFileTransfer = json['is_file_transfer'];
|
|
// TODO: no entry then default.
|
|
isViewCamera = json['is_view_camera'];
|
|
isTerminal = json['is_terminal'] ?? false;
|
|
portForward = json['port_forward'];
|
|
name = json['name'];
|
|
avatar = json['avatar'] ?? '';
|
|
peerId = json['peer_id'];
|
|
keyboard = json['keyboard'];
|
|
clipboard = json['clipboard'];
|
|
audio = json['audio'];
|
|
file = json['file'];
|
|
restart = json['restart'];
|
|
recording = json['recording'];
|
|
blockInput = json['block_input'];
|
|
privacyMode = json['privacy_mode'] ?? privacyMode;
|
|
disconnected = json['disconnected'];
|
|
fromSwitch = json['from_switch'];
|
|
inVoiceCall = json['in_voice_call'];
|
|
incomingVoiceCall = json['incoming_voice_call'];
|
|
}
|
|
|
|
Map<String, dynamic> toJson() {
|
|
final Map<String, dynamic> data = <String, dynamic>{};
|
|
data['id'] = id;
|
|
data['authorized'] = authorized;
|
|
data['is_file_transfer'] = isFileTransfer;
|
|
data['is_view_camera'] = isViewCamera;
|
|
data['is_terminal'] = isTerminal;
|
|
data['port_forward'] = portForward;
|
|
data['name'] = name;
|
|
data['avatar'] = avatar;
|
|
data['peer_id'] = peerId;
|
|
data['keyboard'] = keyboard;
|
|
data['clipboard'] = clipboard;
|
|
data['audio'] = audio;
|
|
data['file'] = file;
|
|
data['restart'] = restart;
|
|
data['recording'] = recording;
|
|
data['block_input'] = blockInput;
|
|
data['privacy_mode'] = privacyMode;
|
|
data['disconnected'] = disconnected;
|
|
data['from_switch'] = fromSwitch;
|
|
data['in_voice_call'] = inVoiceCall;
|
|
data['incoming_voice_call'] = incomingVoiceCall;
|
|
return data;
|
|
}
|
|
|
|
ClientType type_() {
|
|
if (isFileTransfer) {
|
|
return ClientType.file;
|
|
} else if (isViewCamera) {
|
|
return ClientType.camera;
|
|
} else if (isTerminal) {
|
|
return ClientType.terminal;
|
|
} else if (portForward.isNotEmpty) {
|
|
return ClientType.portForward;
|
|
} else {
|
|
return ClientType.remote;
|
|
}
|
|
}
|
|
}
|
|
|
|
String getLoginDialogTag(int id) {
|
|
return kLoginDialogTag + id.toString();
|
|
}
|
|
|
|
showInputWarnAlert(FFI ffi) {
|
|
ffi.dialogManager.show((setState, close, context) {
|
|
submit() {
|
|
AndroidPermissionManager.startAction(kActionAccessibilitySettings);
|
|
close();
|
|
}
|
|
|
|
return CustomAlertDialog(
|
|
title: Text(translate("How to get Android input permission?")),
|
|
content: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Text(translate("android_input_permission_tip1")),
|
|
const SizedBox(height: 10),
|
|
Text(translate("android_input_permission_tip2")),
|
|
],
|
|
),
|
|
actions: [
|
|
dialogButton("Cancel", onPressed: close, isOutline: true),
|
|
dialogButton("Open System Setting", onPressed: submit),
|
|
],
|
|
onSubmit: submit,
|
|
onCancel: close,
|
|
);
|
|
});
|
|
}
|
|
|
|
Future<void> showClientsMayNotBeChangedAlert(FFI? ffi) async {
|
|
await ffi?.dialogManager.show((setState, close, context) {
|
|
return CustomAlertDialog(
|
|
title: Text(translate("Permissions")),
|
|
content: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Text(translate("android_permission_may_not_change_tip")),
|
|
],
|
|
),
|
|
actions: [
|
|
dialogButton("OK", onPressed: close),
|
|
],
|
|
onSubmit: close,
|
|
onCancel: close,
|
|
);
|
|
});
|
|
}
|