File: export_emails.py

package info (click to toggle)
python-django-extensions 4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 2,820 kB
  • sloc: python: 18,601; javascript: 7,354; makefile: 108; xml: 17
file content (212 lines) | stat: -rw-r--r-- 6,314 bytes parent folder | download | duplicates (2)
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
# -*- coding: utf-8 -*-
import sys
import csv

from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand, CommandError

from django_extensions.management.utils import signalcommand


FORMATS = [
    "address",
    "emails",
    "google",
    "outlook",
    "linkedin",
    "vcard",
]


def full_name(**kwargs):
    """Return full name or username."""
    first_name = kwargs.get("first_name")
    last_name = kwargs.get("last_name")

    name = " ".join(n for n in [first_name, last_name] if n)
    if name:
        return name

    name = kwargs.get("name")
    if name:
        return name

    username = kwargs.get("username")
    if username:
        return username

    return ""


class Command(BaseCommand):
    help = "Export user email address list in one of a number of formats."
    args = "[output file]"
    label = "filename to save to"

    can_import_settings = True
    encoding = "utf-8"  # RED_FLAG: add as an option -DougN

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.UserModel = get_user_model()

    def add_arguments(self, parser):
        super().add_arguments(parser)
        (
            parser.add_argument(
                "--group",
                "-g",
                action="store",
                dest="group",
                default=None,
                help="Limit to users which are part of the supplied group name",
            ),
        )
        parser.add_argument(
            "--format",
            "-f",
            action="store",
            dest="format",
            default=FORMATS[0],
            help="output format. May be one of %s." % ", ".join(FORMATS),
        )

    def full_name(self, **kwargs):
        return getattr(settings, "EXPORT_EMAILS_FULL_NAME_FUNC", full_name)(**kwargs)

    @signalcommand
    def handle(self, *args, **options):
        if len(args) > 1:
            raise CommandError("extra arguments supplied")
        group = options["group"]
        if group and not Group.objects.filter(name=group).count() == 1:
            names = "', '".join(g["name"] for g in Group.objects.values("name"))
            if names:
                names = "'" + names + "'."
            raise CommandError(
                "Unknown group '" + group + "'. Valid group names are: " + names
            )

        UserModel = get_user_model()
        order_by = getattr(
            settings,
            "EXPORT_EMAILS_ORDER_BY",
            ["last_name", "first_name", "username", "email"],
        )
        fields = getattr(
            settings,
            "EXPORT_EMAILS_FIELDS",
            ["last_name", "first_name", "username", "email"],
        )

        qs = UserModel.objects.all().order_by(*order_by)
        if group:
            qs = qs.filter(groups__name=group).distinct()
        qs = qs.values(*fields)
        getattr(self, options["format"])(qs)

    def address(self, qs):
        """
        Single entry per line in the format of:
            "full name" <my@address.com>;
        """
        self.stdout.write(
            "\n".join(
                '"%s" <%s>;' % (self.full_name(**ent), ent.get("email", ""))
                for ent in qs
            )
        )
        self.stdout.write("\n")

    def emails(self, qs):
        """
        Single entry with email only in the format of:
            my@address.com,
        """
        self.stdout.write(",\n".join(ent["email"] for ent in qs if ent.get("email")))
        self.stdout.write("\n")

    def google(self, qs):
        """CSV format suitable for importing into google GMail"""
        csvf = csv.writer(sys.stdout)
        csvf.writerow(["Name", "Email"])
        for ent in qs:
            csvf.writerow([self.full_name(**ent), ent.get("email", "")])

    def linkedin(self, qs):
        """
        CSV format suitable for importing into linkedin Groups.
        perfect for pre-approving members of a linkedin group.
        """
        csvf = csv.writer(sys.stdout)
        csvf.writerow(["First Name", "Last Name", "Email"])
        for ent in qs:
            csvf.writerow(
                [
                    ent.get("first_name", ""),
                    ent.get("last_name", ""),
                    ent.get("email", ""),
                ]
            )

    def outlook(self, qs):
        """CSV format suitable for importing into outlook"""
        csvf = csv.writer(sys.stdout)
        columns = [
            "Name",
            "E-mail Address",
            "Notes",
            "E-mail 2 Address",
            "E-mail 3 Address",
            "Mobile Phone",
            "Pager",
            "Company",
            "Job Title",
            "Home Phone",
            "Home Phone 2",
            "Home Fax",
            "Home Address",
            "Business Phone",
            "Business Phone 2",
            "Business Fax",
            "Business Address",
            "Other Phone",
            "Other Fax",
            "Other Address",
        ]
        csvf.writerow(columns)
        empty = [""] * (len(columns) - 2)
        for ent in qs:
            csvf.writerow([self.full_name(**ent), ent.get("email", "")] + empty)

    def vcard(self, qs):
        """VCARD format."""
        try:
            import vobject
        except ImportError:
            print(
                self.style.ERROR(
                    "Please install vobject to use the vcard export format."
                )
            )
            sys.exit(1)

        out = sys.stdout
        for ent in qs:
            card = vobject.vCard()
            card.add("fn").value = self.full_name(**ent)
            if ent.get("last_name") and ent.get("first_name"):
                card.add("n").value = vobject.vcard.Name(
                    ent["last_name"], ent["first_name"]
                )
            else:
                # fallback to fullname, if both first and lastname are not declared
                card.add("n").value = vobject.vcard.Name(self.full_name(**ent))
            if ent.get("email"):
                emailpart = card.add("email")
                emailpart.value = ent["email"]
                emailpart.type_param = "INTERNET"

            out.write(card.serialize())