1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
|
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
# Copyright (c) 2023 Robin Jarry
"""
Query a CardDAV server for contact names and emails.
"""
import argparse
import base64
import configparser
import os
import re
import subprocess
import sys
import xml.etree.ElementTree as xml
from urllib import error, parse, request
def main():
try:
args = parse_args()
C = "urn:ietf:params:xml:ns:carddav"
D = "DAV:"
xml.register_namespace("C", C)
xml.register_namespace("D", D)
# perform the actual address book query
query = xml.Element(f"{{{C}}}addressbook-query")
prop = xml.SubElement(query, f"{{{D}}}prop")
xml.SubElement(prop, f"{{{D}}}getetag")
data = xml.SubElement(prop, f"{{{C}}}address-data")
xml.SubElement(data, f"{{{C}}}prop", name="FN")
xml.SubElement(data, f"{{{C}}}prop", name="EMAIL")
limit = xml.SubElement(query, f"{{{C}}}limit")
xml.SubElement(limit, f"{{{C}}}nresults").text = str(args.limit)
filtre = xml.SubElement(query, f"{{{C}}}filter", test="anyof")
for term in args.terms:
for attr in "FN", "EMAIL", "NICKNAME", "ORG", "TITLE":
prop = xml.SubElement(filtre, f"{{{C}}}prop-filter", name=attr)
match = xml.SubElement(
prop, f"{{{C}}}text-match", {"match-type": "contains"}
)
match.text = term
data = http_request_xml(
"REPORT",
args.server_url,
query,
username=args.username,
password=args.password,
debug=args.verbose,
Depth="1",
)
for vcard in data.iterfind(f".//{{{C}}}address-data"):
for name, email in parse_vcard(vcard.text.strip()):
print(f"{email}\t{name}")
except Exception as e:
if isinstance(e, error.HTTPError):
if args.verbose:
debug_response(e.fp)
e = e.fp.read().decode()
print(f"error: {e}", file=sys.stderr)
sys.exit(1)
def http_request_xml(
method: str,
url: str,
data: xml.Element,
username: str = None,
password: str = None,
debug: bool = False,
**headers,
) -> xml.Element:
req = request.Request(
url=url,
method=method,
headers={
"Content-Type": 'text/xml; charset="utf-8"',
**headers,
},
data=xml.tostring(data, encoding="utf-8", xml_declaration=True),
)
if username is not None and password is not None:
auth = f"{username}:{password}"
auth = base64.standard_b64encode(auth.encode("utf-8")).decode("ascii")
req.add_header("Authorization", f"Basic {auth}")
if debug:
uri = parse.urlparse(req.full_url)
print(f"> {req.method} {uri.path} HTTP/1.1", file=sys.stderr)
print(f"> Host: {uri.hostname}", file=sys.stderr)
for name, value in req.headers.items():
print(f"> {name}: {value}", file=sys.stderr)
print(f"{req.data.decode('utf-8')}\n", file=sys.stderr)
with request.urlopen(req) as resp:
data = resp.read().decode("utf-8")
if debug:
debug_response(resp)
print(f"{data}", file=sys.stderr)
return xml.fromstring(data)
def debug_response(resp):
print(f"< HTTP/1.1 {resp.code}", file=sys.stderr)
for name, value in resp.headers.items():
print(f"< {name}: {value}", file=sys.stderr)
def parse_vcard(txt):
lines = txt.splitlines()
if len(lines) < 4 or lines[0] != "BEGIN:VCARD" or lines[-1] != "END:VCARD":
return
name = None
emails = []
for line in lines[1:-1]:
if line.startswith("FN:"):
name = line[len("FN:") :].replace("\\,", ",")
continue
match = re.match(r"^(?:ITEM\d+\.)?EMAIL(?:;[\w-]+=[^;:]+)*:(.+@.+)$", line)
if match:
email = match.group(1).lower().replace("\\,", ",")
if email not in emails:
if "TYPE=pref" in line or "PREF=1" in line:
emails.insert(0, email)
else:
emails.append(email)
if name is not None:
for e in emails:
yield name, e
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"-l",
"--limit",
default=10,
type=int,
help="""
Maximum number of results returned by the server (default: 10).
If the server does not support limiting, this will be disregarded.
""",
)
parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="""
Print debug info on stderr.
""",
)
parser.add_argument(
"-c",
"--config-file",
metavar="FILE",
default=os.path.expanduser("~/.config/aerc/accounts.conf"),
help="""
INI configuration file from which to read the CardDAV URL endpoint
(default: ~/.config/aerc/accounts.conf).
""",
)
parser.add_argument(
"-S",
"--config-section",
metavar="SECTION",
help="""
INI configuration section where to find CONFIG_KEY. By default the
first section where CONFIG_KEY is found will be used.
""",
)
parser.add_argument(
"-k",
"--config-key-source",
metavar="KEY_SOURCE",
default="carddav-source",
help="""
INI configuration key to lookup in CONFIG_SECTION from CONFIG_FILE.
The value must respect the following format:
https?://USERNAME[:PASSWORD]@HOSTNAME/PATH/TO/ADDRESSBOOK.
Both USERNAME and PASSWORD must be percent encoded.
""",
)
parser.add_argument(
"-C",
"--config-key-cred-cmd",
metavar="KEY_CRED_CMD",
default="carddav-source-cred-cmd",
help="""
INI configuration key to lookup in CONFIG_SECTION from CONFIG_FILE. The
value is a command that will be used to determine PASSWORD if it is not
present in CONFIG_KEY_SOURCE.
""",
)
parser.add_argument(
"-s",
"--server-url",
help="""
CardDAV server URL endpoint. Overrides configuration file.
""",
)
parser.add_argument(
"-u",
"--username",
help="""
Username to authenticate on the server. Overrides configuration file.
""",
)
parser.add_argument(
"-p",
"--password",
help="""
Password for the specified user. Overrides configuration file.
""",
)
parser.add_argument(
"terms",
nargs="+",
metavar="TERM",
help="""
Search term. Will be used to search contacts from their FN (formatted
name), EMAIL, NICKNAME, ORG (company) and TITLE fields.
""",
)
args = parser.parse_args()
cfg = configparser.RawConfigParser(strict=False)
cfg.read([args.config_file])
source = cred_cmd = None
if args.config_section:
source = cfg.get(args.config_section, args.config_key_source, fallback=None)
cred_cmd = cfg.get(args.config_section, args.config_key_cred_cmd, fallback=None)
else:
for sec in cfg.sections():
source = cfg.get(sec, args.config_key_source, fallback=None)
if source is not None:
cred_cmd = cfg.get(sec, args.config_key_cred_cmd, fallback=None)
break
if source is not None:
try:
u = parse.urlparse(source)
if args.username is None:
args.username = u.username
if args.password is None:
args.password = u.password
if not args.password and cred_cmd is not None:
args.password = subprocess.check_output(
cred_cmd, shell=True, text=True, encoding="utf-8"
).strip()
if args.server_url is None:
args.server_url = f"{u.scheme}://{u.hostname}"
if u.port is not None:
args.server_url += f":{u.port}"
args.server_url += u.path
except ValueError as e:
parser.error(f"{args.config_file}: {e}")
if args.server_url is None:
parser.error("SERVER_URL is required")
return args
if __name__ == "__main__":
main()
|