api_key_expire_mail.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. import pagure.config
  8. import pagure.lib.query
  9. import pagure.lib.notify
  10. import pagure.lib.model as model
  11. if 'PAGURE_CONFIG' not in os.environ \
  12. and os.path.exists('/etc/pagure/pagure.cfg'):
  13. print('Using configuration file `/etc/pagure/pagure.cfg`')
  14. os.environ['PAGURE_CONFIG'] = '/etc/pagure/pagure.cfg'
  15. _config = pagure.config.reload_config()
  16. def main(check=False, debug=False):
  17. ''' The function that actually sends the email
  18. in case the expiration date is near'''
  19. current_time = datetime.utcnow()
  20. day_diff_for_mail = [10, 5, 1]
  21. email_dates = [email_day.date() for email_day in \
  22. [current_time + timedelta(days=i) for i in day_diff_for_mail]]
  23. session = pagure.lib.query.create_session(_config['DB_URL'])
  24. tokens = session.query(model.Token).all()
  25. for token in tokens:
  26. if debug:
  27. print(token.id, token.expiration.date())
  28. if token.expiration.date() in email_dates:
  29. user = token.user
  30. username = user.fullname or user.username
  31. user_email = user.default_email
  32. project = token.project
  33. days_left = token.expiration.day - datetime.utcnow().day
  34. subject = 'Pagure API key expiration date is near!'
  35. text = '''Hi %s, \nYour Pagure API key for the project %s will expire
  36. in %s day(s). Please get a new key for non-interrupted service. \n
  37. Thanks, \nYour Pagure Admin. ''' % (username, project.name, days_left)
  38. if not check:
  39. msg = pagure.lib.notify.send_email(text, subject, user_email)
  40. else:
  41. print('Sending email to %s (%s) about key: %s' % (
  42. username, user_emailk, token.id))
  43. if debug:
  44. print('Sent mail to %s' % username)
  45. session.remove()
  46. if debug:
  47. print('Done')
  48. if __name__ == '__main__':
  49. parser = argparse.ArgumentParser(
  50. description='Script to send email before the api token expires')
  51. parser.add_argument(
  52. '--check', dest='check', action='store_true', default=False,
  53. help='Print the some output but does not send any email')
  54. parser.add_argument(
  55. '--debug', dest='debug', action='store_true', default=False,
  56. help='Print the debugging output')
  57. args = parser.parse_args()
  58. main(debug=args.debug)