Projet

Général

Profil

Demande #4691 » liste2vcf.py

Script pour générer le fichier .vcf - Frédéric Couchet, 24/09/2020 09:46

 
1
#!/usr/bin/env python3
2

    
3
import fileinput, sys, re
4

    
5
try:
6
    import vobject
7
except:
8
    print('apt install python3-vobject')
9
    exit(1)
10

    
11

    
12
def is_ascii(s):
13
    try:
14
        s.encode('ascii')
15
        return True
16
    except UnicodeEncodeError:
17
        return False
18

    
19
match_line = re.compile(r'^- (?P<prenom>[^\s]+)\s+(?P<nom>[^,]*)\s*(,\s+(?P<note>.*)\s+)?<(?P<email>[^>]+)>\s*$')
20

    
21
vcards = {}
22

    
23
for line in fileinput.input():
24
    matched = match_line.match(line)
25
    if not matched:
26
        print("Donnée mal formée: ", line, file=sys.stderr)
27
    else:
28
        card = matched.groupdict()
29
        already_seen = vcards.get((card["nom"], card["prenom"]), False)
30
        if already_seen:
31
            if hasattr(already_seen, 'note') and card['note']:
32
                v.add('note')
33
                v.note.value = card['note']
34
                print("Doublon probable (note mise à jour): ", card["prenom"], card["nom"], file=sys.stderr)
35
            else:
36
                print("Doublon probable (ignoré): ", card["prenom"], card["nom"], file=sys.stderr)
37
            continue
38

    
39
        v = vobject.vCard()
40

    
41
        v.add ('fn')
42
        v.fn.value = "{} {}".format(card["prenom"], card["nom"])
43
        if not is_ascii(v.fn.value):
44
            v.fn.charset_param = 'UTF-8'
45

    
46
        v.add ('n')
47
        v.n.value = vobject.vcard.Name(
48
            family = card["nom"],
49
            given = card["prenom"],
50
        )
51
        if not is_ascii(card["nom"] + card["prenom"]):
52
            v.n.charset_param = 'UTF-8'
53

    
54
        v.add('email')
55
        v.email.value = card["email"]
56
        v.email.type_param = 'HOME'
57
        if not is_ascii(v.email.value):
58
            v.email.charset_param = 'UTF-8'
59

    
60
        v.add('categories')
61
        v.categories.value = ["Personne invitée à Libre à vous !"]
62
        v.categories.charset_param = 'UTF-8'
63

    
64
        if card['note']:
65
            v.add('note')
66
            v.note.value = card['note']
67
            if not is_ascii(v.note.value):
68
                v.note.charset_param = 'UTF-8'
69

    
70
        vcards[(card["nom"], card["prenom"])] = v
71

    
72
for card in vcards.values():
73
        print(card.serialize())
    (1-1/1)