api_key_expire_mail.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. import os
  4. import argparse
  5. from datetime import datetime, timedelta
  6. from sqlalchemy.exc import SQLAlchemyError
  7. if 'PAGURE_CONFIG' not in os.environ \
  8. and os.path.exists('/etc/pagure/pagure.cfg'):
  9. print('Using configuration file `/etc/pagure/pagure.cfg`')
  10. os.environ['PAGURE_CONFIG'] = '/etc/pagure/pagure.cfg'
  11. import pagure
  12. from pagure import SESSION
  13. from pagure.lib import model
  14. def main(debug=False):
  15. ''' The function that actually sends the email
  16. in case the expiration date is near'''
  17. current_time = datetime.utcnow()
  18. day_diff_for_mail = [5, 3, 1]
  19. email_dates = [email_day.date() for email_day in \
  20. [current_time + timedelta(days=i) for i in day_diff_for_mail]]
  21. tokens = SESSION.query(model.Token).all()
  22. for token in tokens:
  23. if token.expiration.date() in email_dates:
  24. user = token.user
  25. user_email = user.default_email
  26. project = token.project
  27. days_left = token.expiration.day - datetime.utcnow().day
  28. subject = 'Pagure API key expiration date is near!'
  29. text = '''Hi %s, \nYour Pagure API key for the project %s will expire
  30. in %s day(s). Please get a new key for non-interrupted service. \n
  31. Thanks, \nYour Pagure Admin. ''' % (user.fullname, project.name, days_left)
  32. msg = pagure.lib.notify.send_email(text, subject, user_email)
  33. if debug:
  34. print('Sent mail to %s' % user.fullname)
  35. if debug:
  36. print('Done')
  37. if __name__ == '__main__':
  38. parser = argparse.ArgumentParser(
  39. description='Script to send email before the api token expires')
  40. parser.add_argument(
  41. '--debug', dest='debug', action='store_true', default=False,
  42. help='Print the debugging output')
  43. args = parser.parse_args()
  44. main(debug=args.debug)