Codes divers: Check-in [f8e33b603a]

Divers bouts de code de ma composition

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

Overview
Comment:Remove buddies.py as it is now hosted in its own repository
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:f8e33b603ab578fcff41edc57dd336cc705a4b98
User & Date: milouse 2020-03-13 22:01:35
Context
2020-03-26
08:50
Fix program name in mail_status.py about dialog check-in: dd64db9664 user: milouse tags: trunk
2020-03-13
22:01
Remove buddies.py as it is now hosted in its own repository check-in: f8e33b603a user: milouse tags: trunk
2020-03-11
08:21
Remove old unshorten.php code check-in: fe663be61d user: milouse tags: trunk
Changes

Deleted 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
#!/usr/bin/env python
import os
import re
import sys
import glob
import base64
import subprocess
from argparse import ArgumentParser


__version__ = "0.1.0"

VCARD_TECHNICAL_TERMS = ["PRODID", "VERSION", "REV", "N"]
VCARD_TERMS = ["FN", "PHOTO", "UID", "NICKNAME", "TEL", "EMAIL", "IMPP",
               "ADR", "BDAY", "URL", "TITLE", "ORG", "NOTE", "RELATED"]

ALLOWED_TERMS = ["X-DEPARTMENT", "X-GENDER"]
ADDRESSBOOKS = ["~/.vdirsyncer/addressbooks"]


class VCardParser:
    def __init__(self, filepath, context={}):
        self.filepath = filepath
        self.context = context
        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 VCARD_TECHNICAL_TERMS:
            self._last_atom = None
            self._last_data = None
            return
        if self._last_atom == "PHOTO":
            self._handle_photo_field()
        elif self._last_atom not in VCARD_TERMS + ALLOWED_TERMS:
            print("WARNING: This card use a non standard term {}!\n> {}"
                  .format(self._last_atom, self.filepath), file=sys.stderr)
        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 _match_property_type(self, prop_type, cur_type, headers):
        if prop_type is None:
            return True
        if prop_type == "pref" and headers.get("pref") is not None:
            return True
        if isinstance(cur_type, list):
            return prop_type in cur_type
        return prop_type == cur_type

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

    def print_org_contact(self):
        lines = []
        name = self.get("fn")
        if name == "":
            name = "Anonymous"
        lines.append("* " + name)
        lines.append(":PROPERTIES:")

        def linefmt(title, value):
            if isinstance(value, str):
                val = value
            elif isinstance(value, list):
                new_list = [v[0] if isinstance(v, tuple) else v
                            for v in value]
                val = ", ".join(new_list)
            if val == "":
                return ""
            return ":{title}: {value}".format(
                title=title.upper(), value=val
            )

        email = linefmt("email", self.get("email"))
        if email != "":
            lines.append(email)
        phone = linefmt("phone", self.get("tel"))
        if phone != "":
            lines.append(phone)
        nick = linefmt("nickname", self.get("nickname"))
        if nick != "":
            lines.append(nick)
        adr = linefmt("address", self.get("adr"))
        if adr != "":
            lines.append(adr)
        bday = linefmt("birthday", self.get("bday"))
        if bday != "":
            lines.append(bday)

        lines.append(":END:")
        return "\n".join(lines)

    def _format_lines(self, title, value, default=None):
        max_len = 8  # len of longest possible vcard term (birthday)
        title = title.ljust(max_len)
        if isinstance(value, list):
            first = value.pop(0)

            def linefmt(title, value):
                if isinstance(value, str):
                    return "{title} {value}".format(
                        title=title, value=value
                    )
                if isinstance(value[1], list):
                    val = ", ".join(value[1])
                else:
                    val = value[1]
                return "{title} {value} ({info})".format(
                    title=title, value=value[0], info=val
                )

            results = [linefmt(title + " :", first)]
            results += [linefmt(" " * (max_len + 2), v) for v in value]
            return "\n".join(results)
        if value == "":
            if default is None:
                return None
            value = default
        return "{title} : {val}".format(title=title, val=value)

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

        titlemap = {
            "NICKNAME": "Nick",
            "BDAY": "Birthday",
            "IMPP": "IM",
            "ADR": "Address"
        }
        if self.context.get("show_uid"):
            terms_iter = VCARD_TERMS[2:]
        else:
            terms_iter = VCARD_TERMS[3:]
        lines += [
            self._format_lines(
                titlemap.get(term, term.capitalize()),
                self.get(term)
            ) for term in terms_iter
        ]
        if self.get("photo") != "":
            lines.append(self._format_lines("Photo", "yes"))
        lines.append("")

        return "\n".join([l for l in lines if l is not None])

    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", "--file", action="store_true",
                            dest="filepath", help="Expect given query "
                            "to be vcard file paths.")
        parser.add_argument("-o", "--only", dest="property_type",
                            help="When a property have different "
                            "possible types (e.g. home or work email), "
                            "display only this type. (Only relevant "
                            "for --show and --clip mode)")
        parser.add_argument("-u", "--uid", action="store_true",
                            help="Add vcard uid in displayed fields. "
                            "(Only relevant for --show mode)")
        mutu = parser.add_mutually_exclusive_group()
        mutu.add_argument("-c", "--clip", choices=["email", "tel"],
                          help="Do not print anything, but instead "
                          "copy the given property value in the "
                          "clipboard using xclip.")
        mutu.add_argument("-e", "--edit", action="store_true",
                          help="Open corresponding vcf files in edition.")
        mutu.add_argument("-s", "--show", default="fancy",
                          choices=["email", "fancy", "mu", "mutt",
                                   "org-contact", "photo", "pine",
                                   "vcard"],
                          help="Use this format to display information. "
                          "The default value is `fancy'.")
        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)

        self.modifiers = {
            "format": "{name} <{email}>",
            "prop_type": args.property_type,
            "show_uid": args.uid
        }

        if args.filepath:
            vcards = [
                VCardParser(os.path.expanduser(f), self.modifiers)
                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.clip == "email":
            operation = self.clip_email
        elif args.clip == "tel":
            operation = self.clip_tel
        elif args.show == "vcard":
            operation = self.show
        elif args.show == "photo":
            operation = self.open_photo
        elif args.show == "mutt":
            # Mutt imply email, thus it's checked before email
            self.modifiers["format"] = "{email}\t{name}"
            print()  # Mutt needs a first empty line
            operation = self.print_email
        elif args.show == "mu":
            # Mu imply email, thus it's checked before email too
            magenta_name = "\x1b[35m{}\x1b[0m".format("{name}")
            green_email = "\x1b[32m{}\x1b[0m".format("{email}")
            self.modifiers["format"] = magenta_name + " " + green_email
            operation = self.print_email
        elif args.show == "email":
            operation = self.print_email
        elif args.show == "org-contact":
            operation = self.convert_org
        elif args.show == "pine":
            operation = self.convert_pine
        else:
            operation = print
        for card in vcards:
            operation(card)

    def search(self, query):
        addressbooks = 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, self.modifiers) 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, self.modifiers)
            email = m.get("email")
            if isinstance(email, list):
                email = " ".join([e[0] for e in email])
            data = " ".join(
                [m.get("fn"), email, m.get("nickname")]
            ).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 show(self, card):
        with open(card.filepath, "r") as f:
            print(f.read())

    def clip_data(self, value):
        if value == "":
            return
        if isinstance(value, list):
            value = ", ".join([v[0] for v in value])
        cmd = subprocess.Popen(["xclip", "-selection", "primary"],
                               stdin=subprocess.PIPE)
        cmd.communicate(value.encode())

    def clip_email(self, card):
        self.clip_data(card.get("email"))

    def clip_tel(self, card):
        self.clip_data(card.get("tel"))

    def print_email(self, card):
        val = card.get("email")
        if val == "":
            return
        template = self.modifiers.get("format")
        name = card.get("fn")
        if isinstance(val, list):
            print("\n".join([
                template.format(name=name, email=v[0])
                for v in val
            ]))
        else:
            print(template.format(name=name, email=val))

    def convert_pine(self, card):
        val = card.get("email")
        if val == "":
            return
        line = [card.get("nickname"), card.get("fn")]
        if isinstance(val, list):
            line.append("({})".format(",".join([v[0] for v in val])))
        else:
            line.append(val)
        print("\t".join(line))

    def convert_org(self, card):
        print(card.print_org_contact())
        print()

    def open_photo(self, card):
        photo = card.get("photo")
        if photo == "":
            print("No photo for {}".format(card.get("fn")), file=sys.stderr)
            return
        tmp_pic_path = "/tmp/picture_" + card.get("uid")
        with open(tmp_pic_path, "wb") as f:
            f.write(base64.b64decode(photo))
        p = subprocess.run(["gio", "open", tmp_pic_path])
        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()
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<