Skip to content
danielkpl2Public

About

Two-way file sync between Android/iOS phones and Amazon S3: resumable multipart uploads and downloads that keep running in the background, conflict handling, and a web dashboard. Expo app + ASP.NET Core backend.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

42 Commits

Folders and files

Repository files navigation

FileSync

Reliable two-way file synchronisation between phones and Amazon S3, with a web dashboard.

Each device syncs with its own area in S3. Files upload from the phone and download to it, both resumable and in the background, and changes on either side are detected. Conflicts are never overwritten silently.

  • Mobile app (mobile/): React Native / Expo (SDK 54) for Android and iOS. Keeps a local inventory of files in SQLite and reports it to the backend. It uploads files directly to S3 as resumable multipart uploads, and downloads files from its cloud area with resumable transfers. Both keep running in the background.
  • Backend (backend/): ASP.NET Core (.NET 10) + SQLite. Password login, device registration and inventory. It owns the S3 multipart lifecycle (create, presigned part URLs, ListParts reconciliation, completion, verification, abort), keeps a cloud inventory with per-file versions (ETags), and issues presigned download URLs. File bytes never pass through it.
  • Dashboard (backend/web/): React + TypeScript, served by the backend. Shows devices, files, transfer progress, conflicts and S3 state. It uploads or replaces files in a device's cloud area, verifies files against S3, and deletes files on the device, in the cloud or both.

The full design, including status notes per section, is in s3-device-file-sync-design.md.

How it fits together

 Phone (Expo app)                     Backend (ASP.NET Core)                 Amazon S3
 ───────────────                      ──────────────────────                 ─────────
 SQLite inventory ── manifest ───────▶ devices, files, upload jobs (SQLite)
 Upload coordinator ── create/start ─▶ CreateMultipartUpload ──────────────▶
                    ◀─ presigned URLs ─ (per part, time-limited)
 Native uploader ──────────────── PUT part bytes ──────────────────────────▶ parts
                    ── ack / reconcile ▶ ListParts ◀──────────────────────────
                    ── complete ───────▶ CompleteMultipartUpload + HeadObject ▶ object
  • The backend owns the multipart lifecycle and chooses object keys (device-sync/{deviceId}/{fileId}/{filename}). Clients only ever receive presigned part upload URLs, never AWS credentials or delete URLs.
  • S3 is the source of truth for progress. After any interruption (app killed, network lost, phone rebooted), the app asks the backend to reconcile with ListParts and only re-sends missing parts.
  • A file is shown as synced only after the backend has verified the object in S3.
  • Deletions are explicit events with tombstones, never inferred from a missing file in a partial report.

Sync modes

Each device has two independent settings:

Setting Options
Direction To cloud (upload only, the default), To device (download only) or Both (two-way)
Trigger Auto (transfers start by themselves) or Manual (tap Upload / Download)

Wi-Fi only / Wi-Fi + mobile applies to both directions.

  • New files: with Auto, new local files upload (To cloud / Both), and files in the device's cloud area download (To device / Both). Cloud files come from the device's own uploads and from dashboard uploads. Downloads check free space first and never overwrite a different local file.
  • Changes: the backend records the S3 version each device last synced. If only the cloud copy changed (e.g. replaced from the dashboard), the device downloads the new version. If only the local copy changed, it uploads it.
  • Conflicts: a file changed on both sides is marked ⚠ Conflict and isn't transferred until resolved.
    • Keep this device's: uploads over the cloud copy.
    • Keep cloud's: downloads over the local copy.
    • Keep both: the cloud version is copied to "name (cloud copy)" and downloaded; the local version is uploaded.
    • A per-device default (Ask / Keep both / Newest wins) applies automatically.
  • Deletions always ask: from device, from cloud, or everywhere, in the app and the dashboard.
    • A file deleted only on the device becomes cloud-only and isn't downloaded again automatically.
    • A file deleted only in the cloud stays on the device and isn't uploaded again.
  • Cancelling an upload or download stops it, and it isn't restarted automatically.

Repository layout

Path What
backend/FileSync.Api API: Auth/, Devices/, Uploads/, Storage/, Data/ (EF Core + migrations)
backend/FileSync.Api.Tests xUnit unit and integration tests (in-memory fake S3, temp SQLite)
backend/web Dashboard (Vite, Vitest, Playwright in e2e/)
backend/scripts/simulate-device.py Fake device for exercising the backend against real S3
mobile/src App: Expo Router screens (app/), sync logic (lib/), headless background task (background/)
mobile/modules/background-uploader Local Expo native module: Kotlin (WorkManager) and Swift (URLSession) background uploads and downloads
deploy/ Linux server setup (systemd, Caddy), deploy script

Getting started

Prerequisites

  • .NET SDK 10 (pinned by backend/global.json), Node 20+.
  • For the app: Android SDK and/or Xcode 16.x. The app uses native code, so it runs as a development build, not in Expo Go.
  • An S3 bucket and an IAM user limited to a prefix (see section 24.1 of the design spec). A lifecycle rule that aborts incomplete multipart uploads after a couple of days is recommended.

Backend and dashboard

cp backend/.env.example backend/.env       # then fill in APP_PASSWORD, JWT_SIGNING_KEY, AWS_* and S3_*
cd backend/web && npm install && npm run build   # builds the dashboard into the API's wwwroot
cd backend && dotnet run --project FileSync.Api # http://localhost:5080

Open http://localhost:5080 and sign in with APP_PASSWORD.

Mobile app

cd mobile && npm install
npx expo run:android            # or: npx expo run:ios

On the login screen, use http://10.0.2.2:5080 on the Android emulator, http://localhost:5080 on the iOS simulator, or the computer's LAN address on a real phone. Background sync without the app open (the periodic task) requires a release build, e.g. npx expo run:android --variant release.

Deploying to a Linux server

deploy/ contains everything for an Ubuntu 24.04 (x86-64) server:

  • the backend runs as a systemd service under its own filesync user, on 127.0.0.1:5080 only;
  • Caddy serves HTTPS with automatic Let's Encrypt certificates (an sslip.io hostname until a domain exists);
  • ufw allows only SSH, HTTP and HTTPS;
  • the SQLite database is backed up nightly (14 days kept).
cp deploy/.env.example deploy/.env      # set DEPLOY_HOST and PUBLIC_HOSTNAME (gitignored)
set -a; . deploy/.env; set +a
rsync -az deploy/ "$DEPLOY_HOST:/root/filesync-deploy/"
ssh "$DEPLOY_HOST" bash /root/filesync-deploy/setup-server.sh   # once; idempotent
# Secrets go in /etc/filesync/filesync.env (mode 640 root:filesync): APP_PASSWORD, JWT_SIGNING_KEY, AWS_*, S3_*.
deploy/deploy.sh                        # every release

deploy.sh builds the dashboard and a self-contained linux-x64 backend locally, so the server needs no .NET installation. It uploads the build as a new release, switches to it, restarts the service, checks health and keeps the last 5 releases. For dashboard uploads, add the public URL to the S3 bucket's CORS AllowedOrigins.

Android releases

cd mobile && scripts/release-android.sh            # signed production APK in mobile/dist/
cd mobile && scripts/release-android.sh --publish  # also creates GitHub release v<version> (needs `gh auth login`)
  • Builds are signed with a release keystore kept outside the repo (~/.config/filesync/android-release.env + keystore). Back both up: Android only installs updates signed with the same key.
  • Production builds only connect over HTTPS. Users enter the server URL on the login screen.
  • Bump version in mobile/app.config.ts for each release; the Android versionCode is derived from it.
  • Requirements: Android 7.0 (API 24) or later. Install by allowing "Install unknown apps" for the browser or file manager.
  • iOS isn't published: installing outside the App Store needs an Apple Developer account (Ad Hoc / TestFlight).

Tests

cd backend && dotnet test                                 # backend (no AWS needed)
cd backend/web && npm run typecheck && npm test           # dashboard unit tests
cd backend/web && npm run build && npm run e2e            # dashboard E2E (Playwright; own backend on :5099)
cd mobile && npx tsc --noEmit && npx jest && npx expo lint

Background transfers

Foreground and background uploads use one pipeline. Upload work is split into two layers:

  1. Orchestration (TypeScript, mobile/src/lib/uploadCoordinator.ts): decides what to upload, creates the job, fetches presigned URLs, reconciles with S3 and completes. It keeps no essential state in memory; everything is in SQLite, the backend and S3. So it can be recreated at any time (after a relaunch, or headlessly by the background task) and continue where things stand.
  2. Byte transfer (TransferExecutor): PUTs each part's byte range to its presigned URL. The app uses the native executor (mobile/modules/background-uploader) even while it is open, so an upload started in the foreground simply keeps going when the app is closed: there is nothing to hand over. A JavaScript executor exists for tests and Expo Go.

All missing parts are handed to the operating system up front, together with a job-scoped completion token issued by the backend. The native code can therefore finish the whole upload, including the final complete call, while the app's JavaScript is frozen or not running at all. The token can only complete that one job, and the backend still verifies the object in S3.

Android: WorkManager, the foreground service and the hand-off

Each part is a WorkManager job (PartUploadWorker). Parts are spread over three sequential lanes per file, so at most three parts upload at once instead of WorkManager running them all in parallel.

Foreground service. Android 14+ defers and throttles ordinary background jobs of an app the user isn't looking at. So each worker immediately asks WorkManager to run it as a foreground service of type dataSync. Android then shows an ongoing notification ("Uploading clip.mp4 — Part 3", or "Waiting for network…") and lets the upload run at full speed in the background, with the screen locked, and after the app is swiped away. The notification disappears when the upload finishes.

Why the worker manages the network itself. Android 12+ only lets an app start a foreground service while the app is in the foreground. That has two consequences:

  • WorkManager network constraints aren't used. With a constraint, WorkManager stops a running worker the moment the network drops, and the restarted worker would then be in the background and could no longer become a foreground service.
  • Instead, a worker that loses the network stays alive in the foreground, shows "Waiting for network…" (or "Waiting for Wi-Fi…" under the Wi-Fi only setting), and resumes as soon as Android reports a suitable network. Only after 30 minutes without network does it hand back to WorkManager to retry later.

Hand-off when the app is opened. Some parts can still end up as ordinary, deferrable background jobs. For example, the periodic background sync task may start a new upload while the app is closed, where Android doesn't allow a foreground service. When the app comes to the foreground, it takes these over:

  • parts that are sending promote themselves, because each worker retries the foreground request about once a second and that succeeds once the app is visible;
  • parts that are waiting or in retry back-off are cancelled and immediately re-queued with fresh URLs, so they start as foreground-service jobs right away.

Because the foreground service keeps running until the upload finishes, the upload continues at full speed after you leave the app again.

Other Android behaviour

  • Force stop in Android's settings stops all of the app's work until it is opened again; apps can't prevent this. Swiping the app away does not stop uploads.
  • Some manufacturers' battery savers (e.g. Samsung, Xiaomi) can add their own restrictions.
  • Notification permission (Android 13+) is requested at sign-in. Without it uploads still run, but the notification is hidden.
  • Emulator quirk: the Android emulator can't rejoin Wi-Fi while the screen is off, so screen-off Wi-Fi-only tests need a real phone.

iOS: background URLSession

Each part's byte range is copied to a temporary file and handed to a background URLSession; iOS only supports background uploads from files. iOS performs the transfers itself while the app is suspended or after it was terminated by the system, and wakes the app when they finish. The last part triggers the completion call. Two iOS rules to be aware of:

  • Force-quit: if the user swipes the app away in the app switcher, iOS cancels its background transfers. Parts already uploaded are kept in S3, and the next launch reconciles and sends only the missing ones.
  • Scheduling: iOS decides when the periodic background task (expo-background-task) runs.

Downloads

Downloads use the same native layer: on Android a WorkManager job per file, as a dataSync foreground service with a "Downloading…" notification, and on iOS a background URLSession download task.

  • Safe downloads: data goes to a temporary file, resumes with HTTP Range after interruptions, and the file is moved into place only when complete, so a partial download never appears in the sync folder.
  • Recorded before it starts: the app writes a pending local record with the cloud file's ID first. The file is then recognised as already synced even if the download finishes while the app is closed, and is never uploaded again.
  • Wi-Fi only: downloads follow the same Wi-Fi only rule and network waiting as uploads.
  • Opening the app takes over queued downloads, the same as for uploads.

Periodic background sync

mobile/src/background/syncTask.ts runs about every 15 minutes when the OS allows it. It rescans files, reports deletions and the inventory, completes uploads whose parts all arrived, and in Auto mode hands new uploads and downloads to the native layer.

While uploads are in progress, the backend also refreshes their progress from S3 every 10 seconds, so the dashboard shows real progress even when the app is frozen.

License

MIT © 2026 Daniel Kasprowicz

About

Two-way file sync between Android/iOS phones and Amazon S3: resumable multipart uploads and downloads that keep running in the background, conflict handling, and a web dashboard. Expo app + ASP.NET Core backend.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages