Commit 44bc915f authored by gouarin's avatar gouarin

add job notification for openshift

parent 694beb7d
Pipeline #4475 passed with stages
in 42 seconds
......@@ -10,3 +10,5 @@ maya
urllib3==1.24.2
requests
pelican
tweepy
gitpython
\ No newline at end of file
#!/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
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"
RECIPIENT_MAIL = "bureau.calcul@services.cnrs.fr"
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"
filepath = os.path.join(script_path, filename)
with open(filepath) as f:
s = f.read()
m = re.search(r"^Authors: (.*)$", s, re.MULTILINE)
self.author_name = m.group(1).title()
m = re.search(r"^Email: (.*)$", s, re.MULTILINE)
self.author_email = m.group(1)
m = re.search(r"^Job_Type: (.*)$", s, re.MULTILINE)
self.job_type = m.group(1).lower()
m = re.search(r"^Title: (.*)$", s, re.MULTILINE)
self.job_title = m.group(1)
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,
$JOB_AUTHOR vient de publier une offre de $JOB_TYPE concernant le poste intitulé "$JOB_TITLE".
Vous en retrouverez tous les détails sur $JOB_URL.
Cordialement,
$SIGNATURE
""")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.recipient_name = "Groupe Calcul"
if not self.recipient_email:
self.recipient_email = RECIPIENT_MAIL
self.subject = "Proposition de {}".format(self.job_type)
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
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():
notifiers = [AuthorMessage, ListMessage]
repo = git(GIT_REPO)
commit = repo.commit(os.environ["OPENSHIFT_BUILD_COMMIT"])
m = re.match("^Merge branch 'job_(.*)' into '(.*)'$", commit.message)
if m:
job_id = m.group(1)
publisher = commit.author.name
recipient_email = commit.author.email
for notifier in notifiers:
send_email(job_id=job_id, notifier=notifier,
recipient_email=recipient_email, publisher=publisher)
if __name__ == '__main__':
if os.environ["OPENSHIFT_BUILD_REFERENCE"] == 'master':
main()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment