Codes divers: Check-in [cf6dbb4ff0]

Divers bouts de code de ma composition

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

Overview
Comment:Another improvement cycle on buddies.py
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1:cf6dbb4ff00091a6bb4887de3a08014245a517cd
User & Date: milouse 2020-02-25 19:33:24
Context
2020-03-11
08:21
Remove old unshorten.php code check-in: fe663be61d user: milouse tags: trunk
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
Changes

Changes to buddies.py.

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
...
181
182
183
184
185
186
187




188
189
190
191
192
193
194
195
196
197
198
199
...
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
...
315
316
317
318
319
320
321















322
323
324
325
326
327
328
...
339
340
341
342
343
344
345




346
347
348
349
350
351
352
        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)

................................................................................

        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 __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):
................................................................................
              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):
................................................................................
            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")







|
|

|


|
|




|



>
>
|



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>




|







 







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











>
|

<
<












>
>
|
>
>

|

|
|
>


|
>
>
>
>

|
>
>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







 







>
>
>
>







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
...
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
...
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
...
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
...
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
        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)

................................................................................

        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 __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):
................................................................................
              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):
................................................................................
            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")