jmapvault 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- jmapvault/__init__.py +0 -0
- jmapvault/changes.py +91 -0
- jmapvault/cli.py +533 -0
- jmapvault/config.py +161 -0
- jmapvault/credentials.py +187 -0
- jmapvault/discovery.py +123 -0
- jmapvault/discovery_view.py +31 -0
- jmapvault/engine.py +297 -0
- jmapvault/errors.py +43 -0
- jmapvault/exit_codes.py +7 -0
- jmapvault/export/__init__.py +13 -0
- jmapvault/export/common.py +109 -0
- jmapvault/export/containers.py +77 -0
- jmapvault/export/mail.py +257 -0
- jmapvault/export/pim.py +125 -0
- jmapvault/export/view.py +26 -0
- jmapvault/ical.py +347 -0
- jmapvault/lock.py +32 -0
- jmapvault/logging_setup.py +59 -0
- jmapvault/meta.py +43 -0
- jmapvault/oauth.py +95 -0
- jmapvault/progress.py +176 -0
- jmapvault/retry.py +197 -0
- jmapvault/runreport.py +54 -0
- jmapvault/runreport_view.py +67 -0
- jmapvault/session.py +29 -0
- jmapvault/state.py +432 -0
- jmapvault/status_view.py +108 -0
- jmapvault/store.py +227 -0
- jmapvault/syncers/__init__.py +19 -0
- jmapvault/syncers/calendars.py +36 -0
- jmapvault/syncers/consistency.py +148 -0
- jmapvault/syncers/contacts.py +34 -0
- jmapvault/syncers/mail.py +380 -0
- jmapvault/syncers/objects.py +328 -0
- jmapvault/syncers/retire.py +39 -0
- jmapvault/syncers/settings.py +82 -0
- jmapvault/syncers/sieve.py +152 -0
- jmapvault/vcard.py +290 -0
- jmapvault/verify.py +236 -0
- jmapvault/verify_view.py +62 -0
- jmapvault-0.1.0.dist-info/METADATA +396 -0
- jmapvault-0.1.0.dist-info/RECORD +46 -0
- jmapvault-0.1.0.dist-info/WHEEL +4 -0
- jmapvault-0.1.0.dist-info/entry_points.txt +3 -0
- jmapvault-0.1.0.dist-info/licenses/LICENSE +661 -0
jmapvault/__init__.py
ADDED
|
File without changes
|
jmapvault/changes.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
|
|
3
|
+
from jmap.aio import AsyncJMAPClient
|
|
4
|
+
from jmap.core.errors import MethodError
|
|
5
|
+
from jmap.core.ids import Id
|
|
6
|
+
|
|
7
|
+
from jmapvault.errors import JmapvaultError
|
|
8
|
+
|
|
9
|
+
CANNOT_CALCULATE_CHANGES = "cannotCalculateChanges"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ResyncRequired(JmapvaultError):
|
|
13
|
+
"""The server cannot compute changes since the stored state; list everything again."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class ChangeSet:
|
|
18
|
+
"""Net effect of one or more ``/changes`` pages, in server order.
|
|
19
|
+
|
|
20
|
+
The latest page wins: an id created then updated stays "created", one destroyed
|
|
21
|
+
after being created or updated is "destroyed" (it may already be stored from a
|
|
22
|
+
listing beyond the stored state; tombstoning an unknown id is a no-op), and one
|
|
23
|
+
created or updated after being destroyed is live again.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
new_state: str
|
|
27
|
+
created: dict[str, None] = field(default_factory=dict)
|
|
28
|
+
updated: dict[str, None] = field(default_factory=dict)
|
|
29
|
+
destroyed: dict[str, None] = field(default_factory=dict)
|
|
30
|
+
|
|
31
|
+
def absorb(
|
|
32
|
+
self, created: list[str], updated: list[str], destroyed: list[str], new_state: str
|
|
33
|
+
) -> None:
|
|
34
|
+
self.new_state = new_state
|
|
35
|
+
for item_id in created:
|
|
36
|
+
self.destroyed.pop(item_id, None)
|
|
37
|
+
self.updated.pop(item_id, None)
|
|
38
|
+
self.created[item_id] = None
|
|
39
|
+
for item_id in updated:
|
|
40
|
+
self.destroyed.pop(item_id, None)
|
|
41
|
+
if item_id not in self.created:
|
|
42
|
+
self.updated[item_id] = None
|
|
43
|
+
for item_id in destroyed:
|
|
44
|
+
self.created.pop(item_id, None)
|
|
45
|
+
self.updated.pop(item_id, None)
|
|
46
|
+
self.destroyed[item_id] = None
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def is_empty(self) -> bool:
|
|
50
|
+
return not (self.created or self.updated or self.destroyed)
|
|
51
|
+
|
|
52
|
+
def summary(self) -> str:
|
|
53
|
+
return (
|
|
54
|
+
f"{len(self.created)} new, {len(self.updated)} updated, {len(self.destroyed)} deleted"
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
async def collect_changes(
|
|
59
|
+
client: AsyncJMAPClient,
|
|
60
|
+
account_id: Id,
|
|
61
|
+
data_type: str,
|
|
62
|
+
since_state: str,
|
|
63
|
+
max_changes: int,
|
|
64
|
+
) -> ChangeSet:
|
|
65
|
+
"""Page ``<data_type>/changes`` from ``since_state`` until ``hasMoreChanges`` is false.
|
|
66
|
+
|
|
67
|
+
Raises ``ResyncRequired`` on ``cannotCalculateChanges``. Every JMAP type with
|
|
68
|
+
``/changes`` (ContactCard, CalendarEvent, ...) can reuse this unchanged.
|
|
69
|
+
"""
|
|
70
|
+
changes = ChangeSet(new_state=since_state)
|
|
71
|
+
since = since_state
|
|
72
|
+
while True:
|
|
73
|
+
try:
|
|
74
|
+
page = await client.call(
|
|
75
|
+
f"{data_type}/changes",
|
|
76
|
+
{"sinceState": since, "maxChanges": max_changes},
|
|
77
|
+
account_id=account_id,
|
|
78
|
+
)
|
|
79
|
+
except MethodError as error:
|
|
80
|
+
if error.type == CANNOT_CALCULATE_CHANGES:
|
|
81
|
+
raise ResyncRequired(
|
|
82
|
+
f"{data_type}: cannot calculate changes since {since}"
|
|
83
|
+
) from error
|
|
84
|
+
raise
|
|
85
|
+
new_state = page.new_state or since
|
|
86
|
+
if page.has_more_changes and new_state == since:
|
|
87
|
+
raise JmapvaultError(f"{data_type}/changes made no progress at state {since}")
|
|
88
|
+
changes.absorb(page.created, page.updated, page.destroyed, new_state)
|
|
89
|
+
if not page.has_more_changes:
|
|
90
|
+
return changes
|
|
91
|
+
since = new_state
|
jmapvault/cli.py
ADDED
|
@@ -0,0 +1,533 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import sqlite3
|
|
3
|
+
import sys
|
|
4
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from enum import StrEnum
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Annotated, get_args
|
|
9
|
+
|
|
10
|
+
import anyio
|
|
11
|
+
import httpx
|
|
12
|
+
import typer
|
|
13
|
+
from jmap import JMAPError
|
|
14
|
+
from jmap.aio import AsyncJMAPClient
|
|
15
|
+
from jmap.core.session import Session
|
|
16
|
+
from rich.console import Console
|
|
17
|
+
|
|
18
|
+
from jmapvault.config import (
|
|
19
|
+
AuthMethod,
|
|
20
|
+
Config,
|
|
21
|
+
DataType,
|
|
22
|
+
ProfileConfig,
|
|
23
|
+
default_config_path,
|
|
24
|
+
load_config,
|
|
25
|
+
parse_config,
|
|
26
|
+
save_config,
|
|
27
|
+
select_profile,
|
|
28
|
+
)
|
|
29
|
+
from jmapvault.credentials import KeyringTokenStore, build_auth, store_secret
|
|
30
|
+
from jmapvault.discovery import discover_session
|
|
31
|
+
from jmapvault.discovery_view import render_report
|
|
32
|
+
from jmapvault.engine import run_backup
|
|
33
|
+
from jmapvault.errors import CredentialError, JmapvaultError
|
|
34
|
+
from jmapvault.exit_codes import ExitCode
|
|
35
|
+
from jmapvault.export import (
|
|
36
|
+
ExportFormat,
|
|
37
|
+
ExportResult,
|
|
38
|
+
export_calendars,
|
|
39
|
+
export_contacts,
|
|
40
|
+
export_mail,
|
|
41
|
+
)
|
|
42
|
+
from jmapvault.export.view import render_export_result
|
|
43
|
+
from jmapvault.logging_setup import LogFormat, configure_logging
|
|
44
|
+
from jmapvault.meta import ensure_meta
|
|
45
|
+
from jmapvault.oauth import login_oauth
|
|
46
|
+
from jmapvault.progress import ProgressMode, choose_reporter
|
|
47
|
+
from jmapvault.runreport import RunReport, run_report_path
|
|
48
|
+
from jmapvault.runreport_view import render_run_report
|
|
49
|
+
from jmapvault.session import connect
|
|
50
|
+
from jmapvault.state import StateDB, state_db_path
|
|
51
|
+
from jmapvault.status_view import render_status
|
|
52
|
+
from jmapvault.verify import verify_backup
|
|
53
|
+
from jmapvault.verify_view import render_verify_report
|
|
54
|
+
|
|
55
|
+
DEFAULT_PROFILE_NAME = "default"
|
|
56
|
+
|
|
57
|
+
app = typer.Typer(help="Back up a JMAP account.", no_args_is_help=True)
|
|
58
|
+
auth_app = typer.Typer(help="Check or update credentials.", no_args_is_help=True)
|
|
59
|
+
app.add_typer(auth_app, name="auth")
|
|
60
|
+
export_app = typer.Typer(
|
|
61
|
+
help="Convert the stored backup to standard formats (offline).", no_args_is_help=True
|
|
62
|
+
)
|
|
63
|
+
app.add_typer(export_app, name="export")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class Options:
|
|
68
|
+
config_path: Path
|
|
69
|
+
profile_name: str | None
|
|
70
|
+
console: Console
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _options(ctx: typer.Context) -> Options:
|
|
74
|
+
return ctx.obj
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@app.callback()
|
|
78
|
+
def main(
|
|
79
|
+
ctx: typer.Context,
|
|
80
|
+
config: Annotated[
|
|
81
|
+
Path | None,
|
|
82
|
+
typer.Option("--config", help="Config file (env: JMAPVAULT_CONFIG)."),
|
|
83
|
+
] = None,
|
|
84
|
+
profile: Annotated[str | None, typer.Option("--profile", help="Profile name.")] = None,
|
|
85
|
+
verbose: Annotated[bool, typer.Option("--verbose", "-v", help="Debug logging.")] = False,
|
|
86
|
+
log_format: Annotated[
|
|
87
|
+
LogFormat,
|
|
88
|
+
typer.Option("--log-format", help="Log format on stderr; json is one object per line."),
|
|
89
|
+
] = LogFormat.text,
|
|
90
|
+
) -> None:
|
|
91
|
+
console = Console(stderr=True)
|
|
92
|
+
configure_logging(log_format, verbose, console)
|
|
93
|
+
ctx.obj = Options(config or default_config_path(), profile, console)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _fail(message: str) -> typer.Exit:
|
|
97
|
+
typer.echo(f"error: {message}", err=True)
|
|
98
|
+
return typer.Exit(ExitCode.FATAL)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _fail_unexpected(error: Exception) -> typer.Exit:
|
|
102
|
+
logging.getLogger(__name__).debug("unexpected failure", exc_info=error)
|
|
103
|
+
return _fail(str(error))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@app.command()
|
|
107
|
+
def discover(
|
|
108
|
+
ctx: typer.Context,
|
|
109
|
+
as_json: Annotated[bool, typer.Option("--json", help="Print the report as JSON.")] = False,
|
|
110
|
+
) -> None:
|
|
111
|
+
"""Report server capabilities and what can be backed up."""
|
|
112
|
+
report = _with_session(_options(ctx), discover_session)
|
|
113
|
+
if as_json:
|
|
114
|
+
typer.echo(report.model_dump_json(indent=2))
|
|
115
|
+
else:
|
|
116
|
+
render_report(report, Console())
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@app.command()
|
|
120
|
+
def backup(
|
|
121
|
+
ctx: typer.Context,
|
|
122
|
+
only: Annotated[
|
|
123
|
+
str | None,
|
|
124
|
+
typer.Option(help="Comma-separated data types to back up (default: all configured)."),
|
|
125
|
+
] = None,
|
|
126
|
+
dry_run: Annotated[
|
|
127
|
+
bool, typer.Option("--dry-run", help="Show what would change; write nothing.")
|
|
128
|
+
] = False,
|
|
129
|
+
concurrency: Annotated[
|
|
130
|
+
int | None,
|
|
131
|
+
typer.Option(min=1, help="Parallel downloads (overrides the profile)."),
|
|
132
|
+
] = None,
|
|
133
|
+
progress: Annotated[
|
|
134
|
+
ProgressMode,
|
|
135
|
+
typer.Option(help="Progress display: rich bars on a terminal, log lines otherwise."),
|
|
136
|
+
] = ProgressMode.auto,
|
|
137
|
+
all_profiles: Annotated[
|
|
138
|
+
bool,
|
|
139
|
+
typer.Option("--all-profiles", help="Back up every profile in turn, sorted by name."),
|
|
140
|
+
] = False,
|
|
141
|
+
) -> None:
|
|
142
|
+
"""Run a backup."""
|
|
143
|
+
options = _options(ctx)
|
|
144
|
+
requested = _parse_types(only)
|
|
145
|
+
if not all_profiles:
|
|
146
|
+
profile = _load_profile(options)
|
|
147
|
+
raise typer.Exit(
|
|
148
|
+
_backup_profile(options, profile, requested, concurrency, dry_run, progress)
|
|
149
|
+
)
|
|
150
|
+
if options.profile_name is not None:
|
|
151
|
+
raise _fail("--all-profiles cannot be combined with --profile")
|
|
152
|
+
config = _load_config(options)
|
|
153
|
+
if not config.profiles:
|
|
154
|
+
raise _fail("no profiles configured; run `jmapvault init`")
|
|
155
|
+
exit_code = ExitCode.OK
|
|
156
|
+
for name in sorted(config.profiles):
|
|
157
|
+
Console().print(f"== Profile {name} ==", markup=False, highlight=False)
|
|
158
|
+
profile = config.profiles[name]
|
|
159
|
+
try:
|
|
160
|
+
code = _backup_profile(options, profile, requested, concurrency, dry_run, progress)
|
|
161
|
+
except typer.Exit as fatal:
|
|
162
|
+
code = fatal.exit_code
|
|
163
|
+
exit_code = max(exit_code, code)
|
|
164
|
+
raise typer.Exit(exit_code)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _backup_profile(
|
|
168
|
+
options: Options,
|
|
169
|
+
profile: ProfileConfig,
|
|
170
|
+
requested: set[str] | None,
|
|
171
|
+
concurrency: int | None,
|
|
172
|
+
dry_run: bool,
|
|
173
|
+
progress: ProgressMode,
|
|
174
|
+
) -> int:
|
|
175
|
+
if concurrency is not None:
|
|
176
|
+
profile = profile.model_copy(update={"concurrency": concurrency})
|
|
177
|
+
reporter = choose_reporter(progress, options.console)
|
|
178
|
+
|
|
179
|
+
async def run(client: AsyncJMAPClient) -> RunReport:
|
|
180
|
+
return await run_backup(profile, client, only=requested, dry_run=dry_run, reporter=reporter)
|
|
181
|
+
|
|
182
|
+
try:
|
|
183
|
+
if not dry_run:
|
|
184
|
+
ensure_meta(profile.destination, server=profile.server, user=profile.user)
|
|
185
|
+
with reporter:
|
|
186
|
+
report = _connect_and_run(profile, run)
|
|
187
|
+
except (OSError, sqlite3.Error) as error:
|
|
188
|
+
raise _fail_unexpected(error) from error
|
|
189
|
+
except JmapvaultError as error:
|
|
190
|
+
raise _fail(str(error)) from error
|
|
191
|
+
report_path = None if dry_run else run_report_path(profile.destination, report.started_at)
|
|
192
|
+
render_run_report(report, Console(), report_path)
|
|
193
|
+
return report.exit_code
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _parse_types(value: str | None) -> set[str] | None:
|
|
197
|
+
if value is None:
|
|
198
|
+
return None
|
|
199
|
+
requested = {name.strip() for name in value.split(",") if name.strip()}
|
|
200
|
+
known = set(get_args(DataType))
|
|
201
|
+
unknown = sorted(requested - known)
|
|
202
|
+
if unknown:
|
|
203
|
+
raise _fail(
|
|
204
|
+
f"unknown data type(s) {', '.join(unknown)}; choose from {', '.join(sorted(known))}"
|
|
205
|
+
)
|
|
206
|
+
return requested
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
@app.command()
|
|
210
|
+
def status(ctx: typer.Context) -> None:
|
|
211
|
+
"""Show the state of the backup."""
|
|
212
|
+
profile = _load_profile(_options(ctx))
|
|
213
|
+
db_path = state_db_path(profile.destination)
|
|
214
|
+
console = Console()
|
|
215
|
+
if not db_path.exists():
|
|
216
|
+
console.print("No runs recorded yet.")
|
|
217
|
+
return
|
|
218
|
+
try:
|
|
219
|
+
with StateDB(db_path) as db:
|
|
220
|
+
render_status(db, console)
|
|
221
|
+
except (OSError, sqlite3.Error) as error:
|
|
222
|
+
raise _fail_unexpected(error) from error
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
@app.command()
|
|
226
|
+
def verify(
|
|
227
|
+
ctx: typer.Context,
|
|
228
|
+
deep: Annotated[bool, typer.Option("--deep", help="Re-hash stored content.")] = False,
|
|
229
|
+
as_json: Annotated[bool, typer.Option("--json", help="Print the report as JSON.")] = False,
|
|
230
|
+
) -> None:
|
|
231
|
+
"""Check the backup files against the state database (offline)."""
|
|
232
|
+
profile = _load_profile(_options(ctx))
|
|
233
|
+
try:
|
|
234
|
+
report = verify_backup(profile.destination, deep=deep)
|
|
235
|
+
except (OSError, sqlite3.Error) as error:
|
|
236
|
+
raise _fail_unexpected(error) from error
|
|
237
|
+
except JmapvaultError as error:
|
|
238
|
+
raise _fail(str(error)) from error
|
|
239
|
+
if as_json:
|
|
240
|
+
typer.echo(report.model_dump_json(indent=2))
|
|
241
|
+
else:
|
|
242
|
+
render_verify_report(report, Console())
|
|
243
|
+
raise typer.Exit(report.exit_code)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
OutputOption = Annotated[
|
|
247
|
+
Path, typer.Option("--output", help="Directory to write to (must be empty or absent).")
|
|
248
|
+
]
|
|
249
|
+
AccountOption = Annotated[
|
|
250
|
+
str | None, typer.Option("--account", help="Account id (needed when several have data).")
|
|
251
|
+
]
|
|
252
|
+
ForceOption = Annotated[
|
|
253
|
+
bool, typer.Option("--force", help="Export into a non-empty output directory.")
|
|
254
|
+
]
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
class ContactsFormat(StrEnum):
|
|
258
|
+
vcf = "vcf"
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
class CalendarsFormat(StrEnum):
|
|
262
|
+
ics = "ics"
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
@export_app.command("mail")
|
|
266
|
+
def export_mail_command(
|
|
267
|
+
ctx: typer.Context,
|
|
268
|
+
format: Annotated[
|
|
269
|
+
ExportFormat, typer.Option("--format", help="maildir (Maildir++ folders) or mbox (mboxrd).")
|
|
270
|
+
],
|
|
271
|
+
output: OutputOption,
|
|
272
|
+
account: AccountOption = None,
|
|
273
|
+
mailbox: Annotated[
|
|
274
|
+
list[str] | None,
|
|
275
|
+
typer.Option("--mailbox", help="Mailbox name, path (A/B) or id; repeatable."),
|
|
276
|
+
] = None,
|
|
277
|
+
include_deleted: Annotated[
|
|
278
|
+
bool, typer.Option("--include-deleted", help="Also export emails deleted on the server.")
|
|
279
|
+
] = False,
|
|
280
|
+
force: ForceOption = False,
|
|
281
|
+
) -> None:
|
|
282
|
+
"""Export backed-up email to Maildir or mbox."""
|
|
283
|
+
destination = _load_profile(_options(ctx)).destination
|
|
284
|
+
_run_export(
|
|
285
|
+
lambda: export_mail(
|
|
286
|
+
destination,
|
|
287
|
+
output,
|
|
288
|
+
format,
|
|
289
|
+
account=account,
|
|
290
|
+
mailboxes=mailbox or [],
|
|
291
|
+
include_deleted=include_deleted,
|
|
292
|
+
force=force,
|
|
293
|
+
),
|
|
294
|
+
item_noun="message",
|
|
295
|
+
container_noun="mailbox",
|
|
296
|
+
)
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
@export_app.command("contacts")
|
|
300
|
+
def export_contacts_command(
|
|
301
|
+
ctx: typer.Context,
|
|
302
|
+
output: OutputOption,
|
|
303
|
+
format: Annotated[ContactsFormat, typer.Option("--format", help="Output format.")] = (
|
|
304
|
+
ContactsFormat.vcf
|
|
305
|
+
),
|
|
306
|
+
account: AccountOption = None,
|
|
307
|
+
force: ForceOption = False,
|
|
308
|
+
) -> None:
|
|
309
|
+
"""Export backed-up contacts to a single contacts.vcf."""
|
|
310
|
+
destination = _load_profile(_options(ctx)).destination
|
|
311
|
+
_run_export(
|
|
312
|
+
lambda: export_contacts(destination, output, account=account, force=force),
|
|
313
|
+
item_noun="contact",
|
|
314
|
+
container_noun="file",
|
|
315
|
+
)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
@export_app.command("calendars")
|
|
319
|
+
def export_calendars_command(
|
|
320
|
+
ctx: typer.Context,
|
|
321
|
+
output: OutputOption,
|
|
322
|
+
format: Annotated[CalendarsFormat, typer.Option("--format", help="Output format.")] = (
|
|
323
|
+
CalendarsFormat.ics
|
|
324
|
+
),
|
|
325
|
+
account: AccountOption = None,
|
|
326
|
+
force: ForceOption = False,
|
|
327
|
+
) -> None:
|
|
328
|
+
"""Export backed-up calendars to one .ics file per calendar."""
|
|
329
|
+
destination = _load_profile(_options(ctx)).destination
|
|
330
|
+
_run_export(
|
|
331
|
+
lambda: export_calendars(destination, output, account=account, force=force),
|
|
332
|
+
item_noun="event",
|
|
333
|
+
container_noun="calendar",
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _run_export(run: Callable[[], ExportResult], *, item_noun: str, container_noun: str) -> None:
|
|
338
|
+
try:
|
|
339
|
+
result = run()
|
|
340
|
+
except (OSError, sqlite3.Error) as error:
|
|
341
|
+
raise _fail_unexpected(error) from error
|
|
342
|
+
except JmapvaultError as error:
|
|
343
|
+
raise _fail(str(error)) from error
|
|
344
|
+
render_export_result(result, Console(), item_noun=item_noun, container_noun=container_noun)
|
|
345
|
+
raise typer.Exit(result.exit_code)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
@app.command()
|
|
349
|
+
def init(
|
|
350
|
+
ctx: typer.Context,
|
|
351
|
+
server: Annotated[str | None, typer.Option(help="JMAP server URL.")] = None,
|
|
352
|
+
user: Annotated[str | None, typer.Option(help="Account login (email address).")] = None,
|
|
353
|
+
auth: Annotated[AuthMethod | None, typer.Option(help="Authentication method.")] = None,
|
|
354
|
+
destination: Annotated[Path | None, typer.Option(help="Backup directory.")] = None,
|
|
355
|
+
password_command: Annotated[
|
|
356
|
+
str | None, typer.Option(help="Command that prints the password.")
|
|
357
|
+
] = None,
|
|
358
|
+
store_in_keyring: Annotated[
|
|
359
|
+
bool,
|
|
360
|
+
typer.Option("--store-in-keyring", help="Prompt for the secret and store it."),
|
|
361
|
+
] = False,
|
|
362
|
+
) -> None:
|
|
363
|
+
"""Create or update a profile and prepare its backup directory."""
|
|
364
|
+
options = _options(ctx)
|
|
365
|
+
name = options.profile_name or DEFAULT_PROFILE_NAME
|
|
366
|
+
try:
|
|
367
|
+
config = _existing_config(options.config_path)
|
|
368
|
+
changes = {
|
|
369
|
+
"server": server,
|
|
370
|
+
"user": user,
|
|
371
|
+
"auth": auth,
|
|
372
|
+
"destination": str(destination) if destination else None,
|
|
373
|
+
"password_command": password_command,
|
|
374
|
+
"credential": "keyring" if store_in_keyring else None,
|
|
375
|
+
}
|
|
376
|
+
profile = _merged_profile(config, name, changes, options.config_path)
|
|
377
|
+
ensure_meta(profile.destination, server=profile.server, user=profile.user)
|
|
378
|
+
if store_in_keyring:
|
|
379
|
+
secret = typer.prompt("Secret", hide_input=True, confirmation_prompt=True)
|
|
380
|
+
store_secret(profile, secret)
|
|
381
|
+
config.profiles[name] = profile
|
|
382
|
+
save_config(config, options.config_path)
|
|
383
|
+
except (OSError, sqlite3.Error) as error:
|
|
384
|
+
raise _fail_unexpected(error) from error
|
|
385
|
+
except JmapvaultError as error:
|
|
386
|
+
raise _fail(str(error)) from error
|
|
387
|
+
typer.echo(f"Profile {name!r} saved to {options.config_path}")
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _existing_config(path: Path) -> Config:
|
|
391
|
+
return load_config(path) if path.exists() else Config()
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _merged_profile(
|
|
395
|
+
config: Config, name: str, changes: Mapping[str, object], source: Path
|
|
396
|
+
) -> ProfileConfig:
|
|
397
|
+
existing = config.profiles.get(name)
|
|
398
|
+
values = existing.model_dump(mode="json", exclude_unset=True) if existing else {}
|
|
399
|
+
values.update({key: value for key, value in changes.items() if value is not None})
|
|
400
|
+
for required in ("user", "destination"):
|
|
401
|
+
if required not in values:
|
|
402
|
+
values[required] = typer.prompt(required.capitalize())
|
|
403
|
+
parsed = parse_config({"profiles": {name: values}}, source)
|
|
404
|
+
return parsed.profiles[name]
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
@auth_app.command("set")
|
|
408
|
+
def auth_set(
|
|
409
|
+
ctx: typer.Context,
|
|
410
|
+
from_stdin: Annotated[
|
|
411
|
+
bool, typer.Option("--stdin", help="Read the secret from stdin instead of prompting.")
|
|
412
|
+
] = False,
|
|
413
|
+
) -> None:
|
|
414
|
+
"""Store the profile's secret in the system keyring."""
|
|
415
|
+
options = _options(ctx)
|
|
416
|
+
try:
|
|
417
|
+
config = load_config(options.config_path)
|
|
418
|
+
name, profile = select_profile(config, options.profile_name)
|
|
419
|
+
if profile.auth == "oauth2":
|
|
420
|
+
raise CredentialError(
|
|
421
|
+
f"profile {name!r} uses OAuth2; run `jmapvault auth login` instead of `auth set`"
|
|
422
|
+
)
|
|
423
|
+
secret = _read_secret_from_stdin() if from_stdin else _prompt_secret()
|
|
424
|
+
store_secret(profile, secret)
|
|
425
|
+
config.profiles[name] = _merged_profile(
|
|
426
|
+
config, name, {"credential": "keyring"}, options.config_path
|
|
427
|
+
)
|
|
428
|
+
save_config(config, options.config_path)
|
|
429
|
+
except JmapvaultError as error:
|
|
430
|
+
raise _fail(str(error)) from error
|
|
431
|
+
typer.echo(f"Secret for profile {name!r} stored in the keyring")
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def _prompt_secret() -> str:
|
|
435
|
+
return typer.prompt("Secret", hide_input=True, confirmation_prompt=True)
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _read_secret_from_stdin() -> str:
|
|
439
|
+
secret = sys.stdin.read().rstrip("\r\n")
|
|
440
|
+
if not secret:
|
|
441
|
+
raise CredentialError("no secret received on stdin")
|
|
442
|
+
return secret
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
@auth_app.command("login")
|
|
446
|
+
def auth_login(ctx: typer.Context) -> None:
|
|
447
|
+
"""Authorize with OAuth2 and store the token in the system keyring."""
|
|
448
|
+
options = _options(ctx)
|
|
449
|
+
try:
|
|
450
|
+
name, profile = select_profile(load_config(options.config_path), options.profile_name)
|
|
451
|
+
_require_oauth2(name, profile)
|
|
452
|
+
login_oauth(profile, typer.echo)
|
|
453
|
+
except JmapvaultError as error:
|
|
454
|
+
raise _fail(str(error)) from error
|
|
455
|
+
typer.echo(f"Logged in; token for profile {name!r} stored in the keyring")
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
@auth_app.command("logout")
|
|
459
|
+
def auth_logout(ctx: typer.Context) -> None:
|
|
460
|
+
"""Delete the stored OAuth2 token."""
|
|
461
|
+
options = _options(ctx)
|
|
462
|
+
try:
|
|
463
|
+
name, profile = select_profile(load_config(options.config_path), options.profile_name)
|
|
464
|
+
_require_oauth2(name, profile)
|
|
465
|
+
removed = KeyringTokenStore(profile.user).delete()
|
|
466
|
+
except JmapvaultError as error:
|
|
467
|
+
raise _fail(str(error)) from error
|
|
468
|
+
typer.echo(
|
|
469
|
+
f"Token for profile {name!r} deleted" if removed else f"No stored token for {name!r}"
|
|
470
|
+
)
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _require_oauth2(name: str, profile: ProfileConfig) -> None:
|
|
474
|
+
if profile.auth != "oauth2":
|
|
475
|
+
raise CredentialError(f'profile {name!r} does not use auth = "oauth2"')
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
@auth_app.command("test")
|
|
479
|
+
def auth_test(ctx: typer.Context) -> None:
|
|
480
|
+
"""Connect to the server and show the session."""
|
|
481
|
+
_with_session(_options(ctx), _print_session)
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def _load_config(options: Options) -> Config:
|
|
485
|
+
try:
|
|
486
|
+
return load_config(options.config_path)
|
|
487
|
+
except JmapvaultError as error:
|
|
488
|
+
raise _fail(str(error)) from error
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def _load_profile(options: Options) -> ProfileConfig:
|
|
492
|
+
try:
|
|
493
|
+
_, profile = select_profile(load_config(options.config_path), options.profile_name)
|
|
494
|
+
except JmapvaultError as error:
|
|
495
|
+
raise _fail(str(error)) from error
|
|
496
|
+
return profile
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def _with_session[T](options: Options, use: Callable[[Session], T]) -> T:
|
|
500
|
+
async def run(client: AsyncJMAPClient) -> T:
|
|
501
|
+
return use(client.session)
|
|
502
|
+
|
|
503
|
+
return _connect_and_run(_load_profile(options), run)
|
|
504
|
+
|
|
505
|
+
|
|
506
|
+
def _connect_and_run[T](
|
|
507
|
+
profile: ProfileConfig, use: Callable[[AsyncJMAPClient], Awaitable[T]]
|
|
508
|
+
) -> T:
|
|
509
|
+
try:
|
|
510
|
+
auth = build_auth(profile)
|
|
511
|
+
return anyio.run(_in_client, profile, auth, use)
|
|
512
|
+
except JmapvaultError as error:
|
|
513
|
+
raise _fail(str(error)) from error
|
|
514
|
+
except (JMAPError, ValueError) as error:
|
|
515
|
+
raise _fail(f"connection failed: {error}") from error
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
async def _in_client[T](
|
|
519
|
+
profile: ProfileConfig,
|
|
520
|
+
auth: httpx.Auth,
|
|
521
|
+
use: Callable[[AsyncJMAPClient], Awaitable[T]],
|
|
522
|
+
) -> T:
|
|
523
|
+
client = await connect(profile, auth)
|
|
524
|
+
async with client:
|
|
525
|
+
return await use(client)
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def _print_session(session: Session) -> None:
|
|
529
|
+
typer.echo(f"Authenticated as {session.username}")
|
|
530
|
+
for account in session.accounts.values():
|
|
531
|
+
kind = "personal" if account.is_personal else "shared"
|
|
532
|
+
access = "read-only" if account.is_read_only else "read-write"
|
|
533
|
+
typer.echo(f" {account.id} {account.name} ({kind}, {access})")
|