Codes divers: Check-in [fa1a1fa487]

Divers bouts de code de ma composition

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Add a new script, which allow to browse contacts in a vdir collection
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:fa1a1fa4874768bb1a2df4a23c992eec790590e8
User & Date: milouse 2019-12-18 21:10:03
Context
2019-12-18
23:20
Fix obvious bugs and display in buddies.py check-in: 6878617b04 user: milouse tags: trunk
21:10
Add a new script, which allow to browse contacts in a vdir collection check-in: fa1a1fa487 user: milouse tags: trunk
2019-11-12
16:23
Upgrade betterodoo check-in: 43e3dea217 user: milouse tags: trunk
Changes

Added buddies.py.







































































































































































































































































































































































































































































































































































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import os
import re
import sys
import glob
import base64
import subprocess
from argparse import ArgumentParser


__version__ = "0.1.0"


class VCardParser:
    def __init__(self, filepath):
        self.filepath = filepath
        self.atoms = {}
        self.parse()

    def parse(self):
        with open(self.filepath, "r") as f:
            lines = f.readlines()
        self._last_atom = None
        self._last_data = None
        for line in lines:
            stripped = line.strip()
            if stripped in ["", "BEGIN:VCARD", "END:VCARD"]:
                # Ignore some useless values
                continue
            if line.startswith(" "):
                if self._last_atom is None:
                    raise SyntaxError(
                        "Continuation line found without open atom in {}"
                        .format(self.filepath)
                    )
                # This is a continuation line
                self._last_data["value"] += line.strip()
            else:
                # This is a new atom
                if self._last_atom is not None:
                    # Append last opened atom to self.atoms
                    self._write_atom()
                # Now process the current line
                self._extract_atom(line)
        # Do it for the last loop step
        self._write_atom()

    def _extract_atom(self, line):
        data = line.split(":", 1)
        headers = data[0].split(";")
        last_atom = headers.pop(0)
        # Warning: Provide empty metadata to the extract headers method
        # to avoid pollution through methods calls and variable stored
        # by references
        meta_data = self._extract_headers(headers, {})
        content = {"headers": meta_data, "value": data[1].strip()}
        self._last_atom = last_atom
        self._last_data = content

    def _extract_headers(self, headers, meta_data):
        for meta in headers:
            if meta == "":
                # Ignore empty cells
                continue
            name = meta.lower().split("=")
            if len(name) == 1:
                meta_data.setdefault("others", [])
                meta_data["others"].append(name[0])
            else:
                cur_val = meta_data.get(name[0])
                if cur_val is None:
                    meta_data[name[0]] = name[1]
                elif isinstance(cur_val, list):
                    meta_data[name[0]].append(name[1])
                else:
                    meta_data[name[0]] = [cur_val, name[1]]
        return meta_data

    def _handle_photo_field(self):
        new_val = self._last_data["value"].split(",", 1)
        if len(new_val) <= 1:
            return
        self._last_data["value"] = new_val[1]
        new_meta = self._extract_headers(
            new_val[0].split(";"),
            self._last_data["headers"]
        )
        self._last_data["headers"] = new_meta

    def _write_atom(self):
        if self._last_atom in ["PRODID", "VERSION"]:
            self._last_atom = None
            self._last_data = None
            return
        if self._last_atom == "PHOTO":
            self._handle_photo_field()
        else:
            new_val = self._last_data["value"].split(";")
            if len(new_val) > 1:
                self._last_data["value"] = [v for v in new_val if v != ""]
        cur_val = self.atoms.get(self._last_atom)
        if self._last_atom == "UID" and cur_val is not None:
            print("WARNING: This card has 2 UID!\n> {}"
                  .format(self.filepath), file=sys.stderr)
        if cur_val is None:
            self.atoms[self._last_atom] = self._last_data
        elif isinstance(cur_val, list):
            self.atoms[self._last_atom].append(self._last_data)
        else:
            self.atoms[self._last_atom] = [cur_val, self._last_data]
        self._last_atom = None
        self._last_data = None

    def get(self, name):
        content = self.atoms.get(name.upper(), {})
        if isinstance(content, list):
            values = [
                (v["value"], v["headers"].get("type", "other"))
                for v in content
            ]
            return list(values)
        return content.get("value", "")

    def _format_lines(self, title, value):
        if isinstance(value, list):
            results = []
            for v in value:
                if isinstance(v[1], list):
                    val = ", ".join(v[1])
                else:
                    val = v[1]
                results.append(("{}[{}]".format(title, val), v[0]))
            return results
        return [(title, value)]

    def __str__(self):
        data = self._format_lines("id", self.get("uid"))
        data += self._format_lines("Phone", self.get("tel"))
        data += self._format_lines("Email", self.get("email"))
        if self.get("photo") == "":
            data += self._format_lines("Has Photo", "no")
        else:
            data += self._format_lines("Has Photo", "yes")

        max_len = 0
        for line in data:
            n = len(line[0])
            if n > max_len:
                max_len = n

        name = self.get("fn")
        if name == "":
            lines = ["Anonymous"]
        else:
            lines = [name]
        lines.append("-" * len(lines[0]))

        for line in data:
            lines.append("{}: {}".format(line[0].rjust(max_len), line[1]))
        lines.append("")
        return "\n".join(lines)

    def __repr__(self):
        return "[" + ", ".join(self.atoms.keys()) + "]"

    def __getattr__(self, name):
        uname = name.upper()
        if uname in self.atoms.keys():
            return self.atoms[uname]
        raise AttributeError("No such attribute: {}".format(uname))


class Buddies:
    def __init__(self):
        parser = ArgumentParser()
        parser.add_argument("-v", "--version", action="store_true",
                            help="Display version information and exit.")
        parser.add_argument("-f", "--filepath", action="store_true",
                            help="Parse one file and exit.")
        parser.add_argument("--edit", action="store_true",
                            help="Open corresponding vcf file in edition.")
        parser.add_argument("--email", action="store_true",
                            help="Display only contact email.")
        parser.add_argument("--mutt", action="store_true",
                            help="Display only contact email, formatted "
                            "to use it in Mutt (imply --email).")
        parser.add_argument("--photo", action="store_true",
                            help="Display only contact photo, if any.")
        parser.add_argument("query_or_file", nargs="+",
                            help="Query or file to parse.")

        args = parser.parse_args()

        if args.version:
            print("Buddies - v{}".format(__version__))
            sys.exit(0)

        if args.filepath:
            vcards = [
                VCardParser(os.path.expanduser(f))
                for f in args.query_or_file
            ]

        else:
            vcards = self.search(args.query_or_file)

        if args.edit:
            # vCards will be edited one after the other
            operation = self.edit
        elif args.photo:
            operation = self.open_photo
        elif args.email:
            operation = self.print_email
        elif args.mutt:
            print()  # Mutt needs a first empty line
            operation = self.print_mutt
        else:
            operation = print
        for card in vcards:
            operation(card)

    def search(self, query):
        addressbooks = ["~/.vdirsyncer/addressbooks"]
        vcf_files = []
        for book in addressbooks:
            vcf_files += glob.glob(
                os.path.join(os.path.expanduser(book), "**/*.vcf")
            )
        if "all" in query:
            return [VCardParser(m) for m in vcf_files]
        vcards = []
        # Compile regexp once for all
        queryx = [re.compile(q, re.I) for q in query]
        for mate in vcf_files:
            m = VCardParser(mate)
            email = m.get("email")
            if isinstance(email, list):
                email = " ".join([e[0] for e in email])
            data = " ".join([m.get("fn"), email]).strip()
            for qx in queryx:
                if qx.search(data) is None:
                    continue
                vcards.append(m)
                # One match is sufficient
                break
        return vcards

    def edit(self, card):
        p = subprocess.run(
            [os.getenv("EDITOR", "nano"), card.filepath]
        )
        if p.returncode == 0:
            return
        print("Error while editing {}".format(card.filepath),
              file=sys.stderr)
        sys.exit(p.returncode)

    def print_email(self, card, for_mutt=False):
        if for_mutt:
            template = "{email}\t{name}"
        else:
            template = "{name} <{email}>"
        name = card.get("fn")
        val = card.get("email")
        if val == "":
            return
        if isinstance(val, list):
            for v in val:
                print(template.format(name=name, email=v))
        else:
            print(template.format(name=name, email=val))

    def print_mutt(self, card):
        self.print_email(card, True)

    def open_photo(self, card):
        photo = card.get("photo")
        if photo == "":
            print("No photo for {}".format(card.fn), file=sys.stderr)
            return
        with open("/tmp/picture", "wb") as f:
            f.write(base64.b64decode(photo))
        p = subprocess.run(["gio", "open", "/tmp/picture"])
        if p.returncode == 0:
            return
        print("Error while opening photo from {}".format(card.filepath),
              file=sys.stderr)
        sys.exit(p.returncode)


if __name__ == "__main__":
    Buddies()