notify_job_offer_openshift.py 5.92 KB
Newer Older
gouarin's avatar
gouarin committed
1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python3
"""Email confirmation to job offer author"""

import smtplib
import git
from email.message import EmailMessage
from email.headerregistry import Address
from string import Template
import os
import re
import datetime
12
import html
gouarin's avatar
gouarin committed
13
14
15
16
17
18
19
20
21
22
23
import locale
locale.setlocale(locale.LC_TIME, '')

# Email
SITEURL = "https://calcul.math.cnrs.fr"
SMTP_SERVER = "172.16.101.1"
GIT_REPO = os.environ["ATTACHMENTS"]
SENDER_MAIL = "calcul-contact@math.cnrs.fr"
SENDER_NAME = "Bureau du groupe Calcul"
SENDER_ACCOUNT_DISPLAY = "calcul-contact"
SENDER_DOMAIN = "math.cnrs.fr"
gouarin's avatar
gouarin committed
24
RECIPIENT_MAIL = "calcul@listes.math.cnrs.fr"
gouarin's avatar
gouarin committed
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


class Message:
    """Abstract class for message"""

    subject = ""
    template = Template("")

    def __init__(self, job_id, recipient_email=None, publisher=None):
        self.job_id = job_id
        self.parse_job_offer_file()
        self.recipient_name = None
        self.recipient_email = recipient_email

        job_url = "{}/job_{}.html".format(SITEURL, self.job_id)
        self.d = {'JOB_URL': job_url}
        if publisher:
            self.d['SIGNATURE'] = "{}, pour le bureau du groupe Calcul".format(publisher.title())
        else:
            self.d['SIGNATURE'] = 'Le bureau du groupe Calcul'


    def parse_job_offer_file(self):
        filename = f"{GIT_REPO}/content/job_offers/job_{self.job_id}.md"

gouarin's avatar
gouarin committed
50
        with open(filename) as f:
gouarin's avatar
gouarin committed
51
52
            s = f.read()
            m = re.search(r"^Authors: (.*)$", s, re.MULTILINE)
53
            self.author_name = html.unescape(m.group(1)).title()
gouarin's avatar
gouarin committed
54
            m = re.search(r"^Email: (.*)$", s, re.MULTILINE)
55
            self.author_email = html.unescape(m.group(1))
gouarin's avatar
gouarin committed
56
            m = re.search(r"^Job_Type: (.*)$", s, re.MULTILINE)
57
58
59
            self.job_type = html.unescape(m.group(1)).lower()
            m = re.search(r"^Job_Duration: (.*)$", s, re.MULTILINE)
            self.job_duration = html.unescape(m.group(1)).lower()
gouarin's avatar
gouarin committed
60
            m = re.search(r"^Title: (.*)$", s, re.MULTILINE)
61
            self.job_title = html.unescape(m.group(1))
gouarin's avatar
gouarin committed
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
            m = re.search(r"^Expiration_Date: (.*)$", s, re.MULTILINE)
            if m:
                self.expire_date = datetime.datetime.strptime(m.group(1), '%Y-%m-%d')
            else:
                self.expire_date = datetime.date.today() + datetime.timedelta(days=90)

    def get_email_body(self):
        """Virtual function"""
        pass

    def get_msg(self):
        """Get a message object for job_id"""
        body = self.get_email_body()
        msg = EmailMessage()
        msg['Subject'] = self.subject
        msg['From'] = Address(SENDER_NAME, SENDER_ACCOUNT_DISPLAY, SENDER_DOMAIN)
        msg['To'] = self.recipient_email

        print(f">>> Sending notification to {self.recipient_name} <{self.recipient_email}>")
        print(body)
        msg.set_content(body)

        return msg


class AuthorMessage(Message):
    """A class to notify job offer authors"""

    subject = "Votre annonce d'offre d'emploi a été validée"
    template = Template("""\
Bonjour,

Merci d'avoir déposé une annonce d'offre d'emploi sur le site web du groupe Calcul.
Cette annonce a été validée par le bureau du groupe Calcul et vient d'être :
  - publiée sur $JOB_URL
  - diffusée sur la liste calcul@listes.math.cnrs.fr.

Sans demande de votre part, elle restera en ligne jusqu'au $EXPIRE_DATE.

Cordialement,

$SIGNATURE
""")

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

        self.recipient_name = self.author_name
        if not self.recipient_email:
            self.recipient_email = self.author_email

    def get_email_body(self):
        """Return email body from template"""

        self.d['EXPIRE_DATE'] = '{d.day} {d:%B} {d.year}'.format(d=self.expire_date)
        body = self.template.substitute(self.d)
        return body


class ListMessage(Message):
    """A class to notify diffusion list"""

    template = Template("""\
Bonjour,

127
$JOB_AUTHOR vient de publier une offre de $JOB_TYPE$JOB_DURATION concernant le poste intitulé "$JOB_TITLE".
gouarin's avatar
gouarin committed
128

129
Vous en retrouverez tous les détails sur $JOB_URL
gouarin's avatar
gouarin committed
130
131
132
133

Cordialement,

$SIGNATURE
134
135

---
Matthieu Boileau's avatar
Matthieu Boileau committed
136
Pour déposer une annonce d'offre d'emploi sur notre site, rendez-vous sur ${SITEURL}/job_offers/add_job_offer.
137

gouarin's avatar
gouarin committed
138
139
140
141
142
143
144
145
""")

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

        self.recipient_name = "Groupe Calcul"
        if not self.recipient_email:
            self.recipient_email = RECIPIENT_MAIL
146
147
148
149
150
151

        self.subject = "Offre de {}{}: {}".format(
            self.job_type,
            " de {}".format(self.job_duration) if self.job_duration else "",
            self.job_title
        )
gouarin's avatar
gouarin committed
152
153
154
155
156
157
158

    def get_email_body(self):
        """Return email body from template"""

        self.d['JOB_AUTHOR'] = self.author_name
        self.d['JOB_TYPE'] = self.job_type
        self.d['JOB_TITLE'] = self.job_title
159
        self.d['JOB_DURATION'] = " ({})".format(self.job_duration) if self.job_duration else ""
Matthieu Boileau's avatar
Matthieu Boileau committed
160
        self.d['SITEURL'] = SITEURL
gouarin's avatar
gouarin committed
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180

        body = self.template.substitute(self.d)

        return body


def send_email(job_id=None, notifier=None, recipient_email=None, publisher=None):
    """Send notification email using smtplib"""

    message = notifier(job_id, recipient_email, publisher)
    msg = message.get_msg()

    try:
        smtpObj = smtplib.SMTP(SMTP_SERVER)
        smtpObj.sendmail(SENDER_MAIL, msg['To'], msg.as_string())
        print("Successfully sent email")
    except SMTPException:
        print("Error: unable to send email")

def main():
gouarin's avatar
gouarin committed
181
    repo = git.Repo(GIT_REPO)
gouarin's avatar
gouarin committed
182
183
    commit = repo.commit(os.environ["OPENSHIFT_BUILD_COMMIT"])

gouarin's avatar
gouarin committed
184
    m = re.match("^Merge branch 'job_(.*)' into '(.*)'", commit.message)
gouarin's avatar
gouarin committed
185
186
187
188
    if m:
        job_id = m.group(1)
        publisher = commit.author.name

189
190
        send_email(job_id=job_id, notifier=AuthorMessage, publisher=publisher)
        send_email(job_id=job_id, notifier=ListMessage, publisher=publisher)
gouarin's avatar
gouarin committed
191
192
193
194
195


if __name__ == '__main__':
    if os.environ["OPENSHIFT_BUILD_REFERENCE"] == 'master':
        main()