Metadata-Version: 2.4
Name: python-dbsync
Version: 0.3.1
Summary: Selective Dropbox folder sync for Linux and Windows: the folders you choose, one per running copy, with git underneath, rev-checked uploads that never overwrite a newer file, kept conflicts, a mass-delete guard, a daemon and a tray icon
Author-email: George Butiri <george@iseestudios.com>
License: MIT
Project-URL: Homepage, https://github.com/gbutiri/python-dbsync
Project-URL: Repository, https://github.com/gbutiri/python-dbsync
Project-URL: Issues, https://github.com/gbutiri/python-dbsync/issues
Keywords: dropbox,sync,selective sync,git,backup,daemon
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: No Input/Output (Daemon)
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: End Users/Desktop
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: POSIX :: Linux
Classifier: Operating System :: Microsoft :: Windows
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: System :: Archiving :: Mirroring
Classifier: Topic :: System :: Filesystems
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: dropbox>=12
Requires-Dist: python-dotenv>=1.0
Requires-Dist: requests>=2.28
Provides-Extra: windows
Requires-Dist: pystray>=0.19; extra == "windows"
Requires-Dist: Pillow>=10; extra == "windows"
Provides-Extra: test
Requires-Dist: pytest>=7.0; extra == "test"
Dynamic: license-file

# python-dbsync

**Selective Dropbox sync for the folders you choose, with git underneath.**

dbsync keeps the Dropbox folders you choose in step with local folders, on Linux and on Windows: one folder per running copy, and as many copies as you need. It uses the Dropbox API, not the Dropbox desktop client. It never downloads your whole Dropbox, never touches the official client's folder, and never overwrites a newer file without telling you. Every change on either side becomes a git commit, so nothing is lost and every conflict can be resolved with ordinary git.

It was built for machines that need a few folders from Dropbox and not the rest: a laptop with a small disk, a Chromebook, an AI agent's working folder that has to follow it from machine to machine. The official client starts by downloading everything (on the author's machine that was 1.6 TB), and its "selective sync" ignore flag deletes folders from the server when it is set the wrong way. dbsync was written so that neither can happen.

```bash
pip install python-dbsync
dbsync auth        # your own Dropbox app's key, secret and refresh token, saved, never printed
dbsync init        # after writing ~/.config/dbsync/config.toml: makes the folder a repo, first pull
dbsync daemon      # watches both sides and syncs, or run it as a service
```

## What It Does

- **Folders chosen explicitly.** For each copy you name one Dropbox path (at least two levels deep, such as `/Projects/notes`) and one local folder. `/`, an empty path or a single top-level folder is refused. Every API call is checked to stay inside the configured path.
- **Both directions, near real time.** Dropbox's longpoll tells dbsync when something changed remotely; a local scan every few seconds finds local changes. A change that has settled is pushed right away.
- **Never overwrites blind.** Every upload carries the last Dropbox revision dbsync saw. If the file changed on Dropbox since then, Dropbox refuses the upload, dbsync pulls the newer version and merges it instead.
- **Git underneath.** The local folder is a git repository. Remote changes land on a `dropbox` branch and are merged into `main`. A real conflict stops with both sides kept, the merge left in progress, and the tray showing "conflict", for you to resolve with `git add` and `git commit`.
- **Safe deletes.** A local delete is sent to Dropbox only with the matching revision, so a file someone changed elsewhere is never deleted. More than 20 deletions in one sync are refused until you say so. Deleted files stay recoverable in Dropbox's own history.
- **Renames are moves.** A local rename becomes a Dropbox move (not a delete and an upload), and a Dropbox rename becomes a `git mv`, so local edits carry over.
- **Growing files behave.** A log or a chat transcript that gets a line every second is uploaded at most every 10 minutes, and when it grew while uploading, the local side wins the conflicting lines.
- **Start-up files can be locked** (`protect`). A change made only in Dropbox to a listed file is kept aside, reported, and not applied. For an AI agent's instructions, a config, anything that should only change on the machine itself.
- **One-way mode** (`push_only`). Local to Dropbox only, for files that only this machine writes, such as live chat transcripts.
- **Several folders, one service each**, through one environment variable (see [Several Folders](#several-folders)).
- **A daemon, a tray icon and phone alerts.** A systemd user service (Linux) or a Task Scheduler task (Windows), a tray icon with the state and a menu, and an optional push to your phone on conflict or error.
- **No secrets in the code or the output.** Credentials live in a `.env` file you name. `dbsync auth` writes them without ever printing them.

## Install

Python 3.11 or newer and `git` on the PATH.

```bash
pip install python-dbsync
```

On Windows, with the tray icon:

```bash
pip install "python-dbsync[windows]"
```

The Linux tray uses the system's GTK bindings, not a pip package:

```bash
sudo apt install python3-gi gir1.2-ayatanaappindicator3-0.1 libnotify-bin
```

If dbsync is installed in a virtual environment that has no PyGObject, `dbsync tray` starts itself again with `/usr/bin/python3`: the tray needs only the standard library and `gi`.

## Quick Start

### 1. Make a Dropbox app

dbsync talks to Dropbox as an app that you own, so no one else's servers are involved.

1. Open the [Dropbox App Console](https://www.dropbox.com/developers/apps) and click **Create app**.
2. Choose **Scoped access** and **Full Dropbox** (dbsync limits itself to your folder; "App folder" would only let it see `/Apps/<name>`).
3. On the **Permissions** tab, tick `files.metadata.read`, `files.content.read` and `files.content.write`, then **Submit**.
4. On the **Settings** tab, note the **App key** and **App secret**.

### 2. Save the keys

```bash
dbsync auth
```

It asks for the app key, then the secret (hidden), opens Dropbox's **Allow** page, and asks for the code Dropbox shows (hidden). It saves `DROPBOX_APP_KEY`, `DROPBOX_APP_SECRET` and `DROPBOX_REFRESH_TOKEN` in `~/.config/secrets/api.env` with mode 600, keeps a copy of any earlier file, and tells you which permissions were granted. Nothing secret is printed. Use `--secrets <file>` for another file. Run it again whenever you change the app's permissions.

### 3. Write the config

Linux: `~/.config/dbsync/config.toml`. Windows: `%APPDATA%\dbsync\config.toml`.

```toml
[settings]
secrets_file = "~/.config/secrets/api.env"

[[folder]]
id = "notes"                    # short name for the state file, lock and log
remote = "/Projects/notes"      # must already exist in Dropbox
local = "~/notes"               # NOT inside the official Dropbox client's folder
```

The full example with every setting is in [`config/example.toml`](config/example.toml). With no config, `dbsync init` refuses, writes nothing, and prints the block to write. A config that still has the example's `CHANGE-ME` is refused by every command.

### 4. First sync

```bash
dbsync init      # makes ~/notes a git repo (if it is not one) and pulls the Dropbox folder
dbsync status    # what would happen next
dbsync push      # sends local changes (pulls first)
```

### 5. Keep it running

**Linux**, as a user service:

```bash
mkdir -p ~/.config/systemd/user ~/.config/autostart
cp config/systemd/dbsync.service ~/.config/systemd/user/      # edit ExecStart if `which dbsync` differs
cp config/autostart/dbsync-tray.desktop ~/.config/autostart/  # tray at login (optional)
systemctl --user daemon-reload
systemctl --user enable --now dbsync
loginctl enable-linger $USER                                  # keep syncing while logged out (optional)
```

The unit files are in this repository's `config/` folder (they are not inside the pip package).

**Windows**: run `dbsync daemon` and `dbsync tray` at logon through Task Scheduler, with `pythonw.exe` so no console window stays open, and "restart on failure" ticked. No administrator rights are needed.

## Commands

```
dbsync auth [--secrets FILE]                 get a Dropbox refresh token into the secrets file
dbsync init                                  set up the repo and do the first pull
dbsync status                                pending local and remote changes
dbsync pull  [--dry-run]                     bring Dropbox changes down and merge them
dbsync push  [--dry-run] [--allow-mass-delete]
                                             pull, then upload, move and delete
dbsync watch                                 foreground longpoll loop, pull only
dbsync daemon                                what the service runs: watch + auto-push + status + control
dbsync tray                                  tray icon for the running daemon
dbsync ctl status|sync-now|pause|resume|stop talk to the running daemon
```

Every command takes `--config FILE`. Exit codes: 0 ok, 1 error, 2 conflict. `dbsync ctl stop` makes the daemon write "stopped" and exit 0, so systemd's `Restart=on-failure` leaves it stopped.

## Settings

All under `[settings]` unless marked.

| Setting | Default | What it does |
|---|---|---|
| `secrets_file` | `~/.config/secrets/api.env` | The `.env` with the three Dropbox keys. |
| `longpoll_timeout` | 240 | Seconds per Dropbox longpoll (30 to 480). |
| `fallback_poll` | 30 | Retry interval when offline or in error, and the longest backoff. |
| `local_scan` | 10 | Seconds between local scans. |
| `auto_push` | true | Push settled local changes by itself. Off: the daemon only pulls; **Sync now** still pushes. |
| `settle_seconds` | 30 | A file changed more recently than this is "hot". |
| `hot_upload_interval` | 600 | A hot file goes up at most this often. |
| `local_wins` | `["logs/**"]` | After a push, conflicting lines in these paths keep the local side. |
| `propagate_local_deletes` | true | Send local deletes and renames to Dropbox. Off: they are only reported. |
| `max_deletes` | 20 | More deletions than this in one push are refused without `--allow-mass-delete`. |
| `extra_ignore` | `[]` | More paths to leave out, gitignore style (`"build/"`, `"tools/cache/"`). |
| `push_only` | false | One way, local to Dropbox. See below. |
| `ntfy_alerts` | true | Run `ntfy_script` on conflict or error. |
| `ntfy_script` | `""` | A script called as `script "<message>" "<title>" <priority> <tag>`. |
| `protect` (in `[[folder]]`) | `[]` | Files a Dropbox-only change may not replace. See below. |

Always left out: `.git/`, `.venv/`, `venv/`, `env_*/`, `node_modules/`, `__pycache__/`, `*.pyc`, `.dbsync/`. `.env` files **are** synced: Dropbox is meant to be the backup.

## How a Sync Works

```
           Dropbox /Projects/notes
                  |   ^
     longpoll,    |   |  rev-checked upload, move_v2, delete_v2 (parent_rev)
     download     v   |
   branch `dropbox` (a git worktree in the data folder: the last known state of Dropbox)
                  |   ^
           merge  v   |  the uploaded files are committed here too
   branch `main` = your folder ~/notes
```

- **Pull**: download what changed into the `dropbox` branch, commit any local changes on `main`, merge `dropbox` into `main`.
- **Push**: pull first. Then upload each changed file with the revision last seen (`update(rev)`), or as a new file (`add`, never renamed by Dropbox). A refused upload is a conflict: the newer remote version is pulled and merged, and you push again.
- **Conflicts**: a git conflict leaves the merge in progress on `main`. Resolve it in the folder (`git status`, edit, `git add`, `git commit`); the daemon notices and carries on.

### Deletes and renames

- **Local delete to Dropbox**: only for files dbsync has synced, with `parent_rev` set to the revision it last saw. If the file changed on Dropbox, the delete is refused, nothing is deleted, and the newer version comes back as a conflict.
- **Mass-delete guard**: more than `max_deletes` in one push are refused. A missing local folder or repository is refused outright, so an unplugged drive does not look like "everything was deleted".
- **Dropbox delete to local**: the local file is removed only if it is unchanged since the last sync. If you changed it, it is kept and reported.
- **Local rename** (a file gone and a new one with the same content): sent as a Dropbox move after checking the revision. If that fails, the new name is uploaded and the old one goes through the checked delete.
- **Dropbox rename**: a `git mv` on the `dropbox` branch, merged rename-aware, so your edits to the old name land in the new one.
- Empty folders are not synced.

### Growing files

A file modified less than `settle_seconds` ago is "hot" and is uploaded at most once per `hot_upload_interval`. A log written every two seconds goes up about every ten minutes; files that have settled go up at once. If a hot file grew while its snapshot was uploading, the paths in `local_wins` keep the local lines instead of stopping on a conflict. The repository packs its history automatically (`gc.auto = 100`), so a file that grows all day does not leave hundreds of full copies.

## Protecting Start-up Files

Without protection, a change made only in Dropbox reaches the machine quietly, which is what a sync is for. For some files that is the wrong thing: an AI agent's instruction files (`CLAUDE.md`, `NOTES.md`), a config, a script that runs at login. Anything that can write to that Dropbox folder could change what runs on the machine.

```toml
[[folder]]
id = "agent"
remote = "/Agents/agent"
local = "~/agent"
protect = ["CLAUDE.md", "PRINCIPLES.md", "NOTES.md", "config/*.toml"]
```

For a listed file:

- A change or a delete made **only in Dropbox** is not applied. The Dropbox version is kept beside the file as `<name>.remote-<YYYYmmdd-HHMMSS>`, and the local file goes back up on the next push.
- It is reported in `dbsync status` and push/pull output (`PROTECTED ...`), the log, the status file (`kept_remote`), and the tray's detail line.
- Local edits sync as usual. When both sides changed, the local side wins.
- Off by default (`protect = []`). Patterns are globs relative to the folder; a pattern without `/` also matches the file name in any folder.

## One-way Mode

```toml
[settings]
push_only = true
```

The whole folder goes one way, local to Dropbox, for files only this machine writes: live chat transcripts, logs, exported data.

- Dropbox-side edits and deletes never reach the local folder. Remote changes are still fetched into the `dropbox` branch, which keeps them, but they are never merged into `main`; the local copy is then uploaded over them.
- A file that exists only in Dropbox (added there by another machine) is left alone in Dropbox and not downloaded.
- A first sync against a Dropbox folder that already has older copies pulls nothing over a newer local file.

## Several Folders

Each running copy syncs one folder. For more folders, run one copy per folder, each with its own config and its own data folder:

```bash
cp config/systemd/dbsync@.service ~/.config/systemd/user/
# ~/.config/dbsync/photos.toml with its own [[folder]]
systemctl --user daemon-reload
systemctl --user enable --now dbsync@photos
```

`dbsync@photos` reads `~/.config/dbsync/photos.toml` and sets `DBSYNC_DATA_DIR=~/.local/share/dbsync-photos`, so its state, log, status file and control socket never meet another copy's. With `DBSYNC_DATA_DIR` unset, dbsync uses the single default data folder. From a shell: `DBSYNC_DATA_DIR=~/.local/share/dbsync-photos dbsync --config ~/.config/dbsync/photos.toml status`.

## The Daemon, the Tray and Alerts

- **States**: `synced`, `syncing`, `paused`, `conflict` (a git conflict, or Dropbox refused a write or a delete), `error` (rechecked every `fallback_poll` seconds), `offline` (retried), `stopped` (no daemon running).
- **Status file**: `status.json` in the data folder, with the state, message, last sync, conflicts, files kept by `protect`, the last result and a short history.
- **Control**: on Linux a unix socket (mode 600) at `$XDG_RUNTIME_DIR/dbsync.sock`; on Windows 127.0.0.1 on a random port with a token in the data folder. `dbsync ctl ...` uses it.
- **Tray**: the icon follows the state. Its menu has the status line, Sync now, Pause/Resume, Open folder, Open log and Quit tray. Desktop notifications only on conflict and error.
- **Phone alerts**: with `ntfy_alerts = true` and an `ntfy_script`, one push per change into conflict or error, and at most one error push per 15 minutes. The message holds the state, paths and the error type, never a secret.
- **Noisy accounts**: longpoll sometimes reports changes elsewhere in the account. Those wake-ups only move the cursor, with a growing backoff, so a busy Dropbox does not keep dbsync busy.

## Files

| | Linux | Windows |
|---|---|---|
| Config | `~/.config/dbsync/config.toml` | `%APPDATA%\dbsync\config.toml` |
| State, log, status, worktree | `~/.local/share/dbsync/` | `%LOCALAPPDATA%\dbsync\` |
| Credentials | the `secrets_file` you name | the same |

In the data folder: `<id>.db` (SQLite: each file's revision, hash, size and time, and the Dropbox cursor), `<id>.dropbox-worktree/` (the `dropbox` branch), `<id>.lock`, `dbsync.log`, `status.json`.

## Never Point It At

- the whole Dropbox (`/`) or a single top-level folder;
- a folder inside the official Dropbox client's folder (two programs syncing the same files);
- a folder another sync tool is also syncing.

## How It Is Built

```
src/dbsync/
  cli.py        commands
  auth.py       dbsync auth: OAuth code flow, writes the .env, prints no secret
  config.py     TOML config, folders, defaults, paths
  api.py        Dropbox API wrapper: every path checked against the configured roots
  sync.py       pull, push, merge, deletes and renames, protect, push_only
  gitops.py     git plumbing: repo and worktree setup, commits, merges
  state.py      SQLite state: revisions, hashes, cursor
  hashing.py    Dropbox content hash
  ignore.py     ignore rules (built-in + extra_ignore, gitignore style)
  daemon.py     longpoll thread, local scan, status file, control channel
  status.py     status.json read and write
  alerts.py     phone alerts, rate-limited
  plat/         the only platform-specific code: posix.py + linux_tray.py, windows.py + windows_tray.py
  assets/       tray icons
```

## Tests

```bash
pip install "python-dbsync[test]"
pytest tests
```

The suite uses a fake Dropbox API (`tests/fake_api.py`) and real git, with no network: 117 tests on Linux, 7 of them Windows-only and skipped there. It covers rev conflicts, merges, deletes, renames, the mass-delete guard, ignore rules, the daemon, `protect`, `push_only`, `auth` and the Windows platform code. The Windows build is tested on Windows 11 with Python 3.12.

## Status

v0.3.1: the license is now MIT (free for everyone, commercial use included). No code change.

v0.3.0: first public release. `protect` for start-up files; `push_only`; several copies per user (`DBSYNC_DATA_DIR`, `dbsync@.service`); automatic packing for growing files; `dbsync auth`; the tray finds its icons in an installed package. Fixed: in `push_only`, a file added only in Dropbox was deleted from Dropbox on the next push.

Earlier, unpublished: the Windows version (Task Scheduler, pystray tray, toasts, a token-checked local control port); anchored ignore paths such as `data/cache/`; `init` refusing to run without your own config; the daemon surviving `pythonw` with no console; the first versions with the daemon, tray, safe deletes and renames, rev-checked uploads and the git merge flow.

## License

[MIT](LICENSE). Free for everyone, commercial use included.

## Author

George Butiri, [george@iseestudios.com](mailto:george@iseestudios.com)
