Codes divers: Check-in [cce3312fc0]

Divers bouts de code de ma composition

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

Overview
Comment:Another bug fix and improvement cycle on buddies.py
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:cce3312fc0e0bb3ef5d42d2387babfe8e485d351
User & Date: milouse 2019-12-19 19:03:15
Context
2020-02-25
19:33
Another improvement cycle on buddies.py check-in: cf6dbb4ff0 user: milouse tags: trunk
2019-12-19
19:03
Another bug fix and improvement cycle on buddies.py check-in: cce3312fc0 user: milouse tags: trunk
2019-12-18
23:20
Fix obvious bugs and display in buddies.py check-in: 6878617b04 user: milouse tags: trunk
Changes

Changes to buddies.py.

6
7
8
9
10
11
12



13




14
15
16

17
18
19
20
21
22
23
..
84
85
86
87
88
89
90
91
92
93
94
95
96



97
98
99
100
101
102
103
...
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
...
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
...
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
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
................................................................................
        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> {}"
................................................................................
        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, default=None):
        if isinstance(value, list):
            results = []
            for v in value:
                if isinstance(v[1], list):
                    val = ", ".join(v[1])
                else:
                    val = v[1]
                results.append((title, "{} ({})".format(v[0], val)))
            return results
        if value == "":
            if default is None:
                return []
            value = default
        return [(title, value)]

    def __str__(self):
        data = self._format_lines("id", self.get("uid"))
        data = self._format_lines("Nick", self.get("nickname"))
        data += self._format_lines("Phone", self.get("tel"))
        data += self._format_lines("Email", self.get("email"))
        if self.get("photo") == "":
            data += self._format_lines("Photo", "no")
        else:
            data += self._format_lines("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].ljust(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():
................................................................................


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, m.get("nickname")]
            ).strip()
            for qx in queryx:
................................................................................
        )
        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):
            answer = []
            for v in val:
                if "pref" in v[1]:
                    # There is a preferred value. Print only the first
                    # one found
                    print(template.format(name=name, email=v[0]))
                    return
                answer.append(template.format(name=name, email=v[0]))
            print("\n".join(answer))
        else:
            print(template.format(name=name, email=val[0]))

    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()







>
>
>

>
>
>
>

|

>







 







|





>
>
>







 







>
>
>
>
>
>
>
>
>



>
|
<
|
|
>
>
|



|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
<







|
|
>
>
>
>
>
>
>
>
>
>
>
>

>
|







 







|
|
>
>
>
>
>
|
|
>
>
>
|
|
|
|
<
>
>
>
|
|









>
>
>
>
>
>
>


|


<






|
|
|
|

>

|
>
>
>
>






|






|




|







 







>
>
>
>
|
<
<
<
<
>
>
>
>

>
>
>
>
>
>
>
>
>



>

<
|
<
<
<
<
<
<
<

<
<
<
<
>
>




|

>
|

|









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
..
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
...
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
...
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
...
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
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
................................................................................
        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> {}"
................................................................................
        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_kind(self, kind, cur_type, headers):
        if kind is None:
            return True
        if kind == "pref" and headers.get("pref") is not None:
            return True
        if isinstance(cur_type, list):
            return kind in cur_type
        return kind == cur_type

    def get(self, name):
        content = self.atoms.get(name.upper(), {})
        if isinstance(content, list):
            kind = self.context.get("kind")
            values = []

            for v in content:
                cur_type = v["headers"].get("type", "")
                if self._match_kind(kind, cur_type, v["headers"]):
                    values.append((v["value"], cur_type))
            return values
        return content.get("value", "")

    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"
        }
        lines += [
            self._format_lines(
                titlemap.get(term, term.capitalize()),
                self.get(term)
            ) for term in VCARD_TERMS[2:]
        ]
        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():
................................................................................


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("-t", "--type", dest="kind",
                            help="Display only this type of information, "
                            "when possible, instead of all possible kind.")
        mutu = parser.add_mutually_exclusive_group()
        mutu.add_argument("--edit", action="store_true",
                          help="Open corresponding vcf files in edition.")
        mutu.add_argument("--vcard", action="store_true",
                          help="Display the corresponding vcf files in "
                          "the console.")
        mutu.add_argument("--email", action="store_true",
                          help="Display only contact emails.")
        mutu.add_argument("--mutt", action="store_true",
                          help="Display only contact emails, formatted "

                          "to use with Mutt.")
        mutu.add_argument("--pine", action="store_true",
                          help="Convert to Pine addressbook format.")
        mutu.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)

        self.modifiers = {
            "format": "{name} <{email}>",
            "kind": args.kind
        }
        if args.mutt:
            self.modifiers["format"] = "{email}\t{name}"

        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.vcard:
            operation = self.show
        elif args.photo:
            operation = self.open_photo
        elif args.mutt:
            # Mutt imply email, thus it's checked first
            print()  # Mutt needs a first empty line
            operation = self.print_email
        elif args.email:
            operation = self.print_email
        elif args.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 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 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 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()