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