aboutsummaryrefslogtreecommitdiff
path: root/scripts/contacts.sh
blob: b13bdfbc810bba9f354c13b92e5864972aed899c (plain)
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
#!/usr/bin/env bash

export BEMENU_OPTS='--single-instance -i -n -H 26 --hp 10 --fn "InputSansCompressed Light 10" -p ">" --ff "#0f261F" --tf "#23C17C" --nf "#0f261F" --cf "#23C17C2" --af "#00140d" --hb "#23C17C" --hf "#DAE6E3" --nb "#DAE6E3" --tb "#DAE6E3" --fb "#DAE6E3" --cb "#DAE6E3" --ab "#DAE6E3"'

CACHE="$HOME/.cache/khard-contacts.tsv"
CACHE_MAX_AGE=30

if [[ ! -f "$CACHE" ]] || [[ -n "$(find "$CACHE" -mmin +"$CACHE_MAX_AGE" -print)" ]]; then
    khard list --parsable --fields uid,name --search-in-source-files | tail -n +2 > "$CACHE.tmp" \
        && mv "$CACHE.tmp" "$CACHE"
fi

declare -A contacts
while IFS=$'\t' read -r uid name; do
    contacts["$name"]="$uid"
done < "$CACHE"

name=$(printf '%s\n' "${!contacts[@]}" | sort | bemenu)
[[ -z "$name" ]] && exit 1

selection=$(
    khard show --format=yaml "uid:${contacts[$name]}" --search-in-source-files \
        | python3 -c '
import sys, yaml

data = yaml.safe_load(sys.stdin)
fields = [
    "Formatted name", "First name", "Last name",
    "Nickname", "Birthday", "Phone", "Email", "Address"
]

def leaves(val):
    if isinstance(val, dict):
        for v in val.values():
            yield from leaves(v)
    elif isinstance(val, list):
        for v in val:
            yield from leaves(v)
    else:
        if val is not None:
            yield str(val)

seen = set()
for key in fields:
    if key in data:
        for leaf in leaves(data[key]):
            leaf = leaf.strip()
            if leaf and leaf not in seen:
                seen.add(leaf)
                print(leaf)
' \
        | bemenu
)
[[ -z "$selection" ]] && exit 1

printf '%s' "$selection" | wl-copy
notify-send "Copied to clipboard" "$selection"