Skip to content

Commit

Permalink
Add email receipt feature using Mailgun
Browse files Browse the repository at this point in the history
  • Loading branch information
danmichaelo committed May 5, 2016
1 parent 6aae964 commit 75c44d7
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 9 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ vocabulary=noubomn
skosmos_vocab=realfagstermer
user=FYLL INN NAVN
[mailgun]
api_key=FYLL INN API-NØKKEL
domain=FYLL INN AVSENDER-DOMENE
sender=FYLL INN AVSENDER-EPOST
recipient=FYLL INN MOTTAKER-EPOST
[nz_sandbox]
api_key=FYLL INN API-NØKKEL
api_region=eu
Expand Down
45 changes: 39 additions & 6 deletions lokar.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import argparse
import logging.handlers
from io import open
import io

import requests
import sys
Expand All @@ -23,12 +24,18 @@
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logging.getLogger('requests').setLevel(logging.WARNING)
formatter = logging.Formatter('[%(asctime)s %(levelname)s] %(message)s')
formatter = logging.Formatter('[%(asctime)s %(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%I:%S')

console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)

log_capture_string = io.StringIO()
capture_handler = logging.StreamHandler(log_capture_string)
capture_handler.setLevel(logging.DEBUG)
capture_handler.setFormatter(formatter)
logger.addHandler(capture_handler)

nsmap = {
'e20': 'http://explain.z3950.org/dtd/2.0/',
'e21': 'http://explain.z3950.org/dtd/2.1/',
Expand Down Expand Up @@ -220,6 +227,9 @@ def read_config(f, section):
for key in ['user', 'vocabulary', 'skosmos_vocab']:
config[key] = parser.get('general', key)

for key in ['domain', 'api_key', 'sender', 'recipient']:
config['mailgun.' + key] = parser.get('mailgun', key)

return config


Expand Down Expand Up @@ -292,6 +302,17 @@ def parse_args(args):
return args


def email(domain, api_key, sender, recipient, subject, body):
request_url = 'https://api.mailgun.net/v2/{0}/messages'.format(domain)
request = requests.post(request_url, auth=('api', api_key), data={
'from': sender,
'to': recipient,
'subject': subject,
'text': body
})
request.raise_for_status()


def main(config=None, args=None):

args = parse_args(args or sys.argv[1:])
Expand All @@ -312,7 +333,7 @@ def main(config=None, args=None):
old_term = normalize_term(args.old_term)
new_term = normalize_term(args.new_term)

logger.info('{:=^80}'.format(' LOKAR '))
logger.info('{:=^70}'.format(' Starter jobb '))
logger.info('[ Miljø: %s ] [ Vokabular: %s ] [ Tørrkjøring? %s ]'
% (args.env, config['vocabulary'], 'JA' if args.dry_run else 'NEI'))

Expand All @@ -332,15 +353,19 @@ def main(config=None, args=None):
if len(oc) == 2 and len(nc) == 2:
reporting_info['o2'] = oc[1]
reporting_info['n2'] = nc[1]
logger.info('Vil erstatte "$a %(o)s $x %(o2)s" med "$a %(n)s $x %(n2)s" i %(t)s-felt som har $2 %(v)s',
logger.info('Erstatter "$a %(o)s $x %(o2)s" med "$a %(n)s $x %(n2)s" i %(t)s-felt som har $2 %(v)s',
reporting_info)
elif len(oc) == 2 and len(nc) == 1:
logger.info('Vil erstatte "$a %(o)s $x %(o2)s" med "$a %(n)s" i %(t)s-felt som har $2 %(v)s"', reporting_info)
reporting_info['o2'] = oc[1]
if new_term == '':
logger.info('Fjerner %(t)s-felt som har "$a %(o)s $x %(o2)s $2 %(v)s"', reporting_info)
else:
logger.info('Erstatter "$a %(o)s $x %(o2)s" med "$a %(n)s" i %(t)s-felt som har $2 %(v)s"', reporting_info)
elif len(oc) == 1 and len(nc) == 1:
if new_term == '':
logger.info('Vil fjerne %(t)s-felt som har "$a %(o)s $2 %(v)s"', reporting_info)
logger.info('Fjerner %(t)s-felt som har "$a %(o)s $2 %(v)s"', reporting_info)
else:
logger.info('Vil erstatte "%(o)s" med "%(n)s" i $a og $x i %(t)s-felt som har $2 %(v)s', reporting_info)
logger.info('Erstatter "%(o)s" med "%(n)s" i $a og $x i %(t)s-felt som har $2 %(v)s', reporting_info)
else:
logger.error('Antall strengkomponenter i gammel eller ny term er ikke støttet')
return
Expand Down Expand Up @@ -394,6 +419,14 @@ def main(config=None, args=None):
if not args.dry_run:
bib.save()

logger.info('{:=^70}'.format(' Jobb ferdig '))

if not args.dry_run:
subject = '[{}] "{}" → "{}" endret i {:d} post(er)'.format(args.tag, old_term, new_term, len(valid_records))
body = log_capture_string.getvalue()
email(domain=config['mailgun.domain'], api_key=config['mailgun.api_key'], sender=config['mailgun.sender'],
recipient=config['mailgun.recipient'], subject=subject, body=body)

return valid_records


Expand Down
15 changes: 12 additions & 3 deletions tests/test_lokar.py
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,12 @@ def conf():
user=someuser
skosmos_vocab=realfagstermer
[mailgun]
domain=example.com
api_key=key
[email protected]
[email protected]
[test_env]
api_key=secret1
api_region=eu
Expand All @@ -456,10 +462,11 @@ def sru_search_mock(*args, **kwargs):
for n, rec in enumerate(recs):
yield n, len(recs), rec

@patch('lokar.email', autospec=True)
@patch('lokar.authorize_term', autospec=True)
@patch('lokar.sru_search', autospec=True)
@patch('lokar.Alma', autospec=True, spec_set=True)
def testMain(self, MockAlma, mock_sru, mock_authorize_term):
def testMain(self, MockAlma, mock_sru, mock_authorize_term, email):
old_term = 'Statistiske modeller'
new_term = 'Test æøå'
mock_sru.side_effect = TestLokar.sru_search_mock
Expand All @@ -475,10 +482,11 @@ def testMain(self, MockAlma, mock_sru, mock_authorize_term):

assert alma.bibs.call_count == 14

@patch('lokar.email', autospec=True)
@patch('lokar.authorize_term', autospec=True)
@patch('lokar.sru_search', autospec=True)
@patch('lokar.Alma', autospec=True, spec_set=True)
def testMainNoHits(self, MockAlma, mock_sru, mock_authorize_term):
def testMainNoHits(self, MockAlma, mock_sru, mock_authorize_term, email):
old_term = 'Something else'
new_term = 'Test æøå'
mock_sru.side_effect = TestLokar.sru_search_mock
Expand All @@ -494,10 +502,11 @@ def testMainNoHits(self, MockAlma, mock_sru, mock_authorize_term):

assert alma.bibs.call_count == 0

@patch('lokar.email', autospec=True)
@patch('lokar.authorize_term', autospec=True)
@patch('lokar.sru_search', autospec=True)
@patch('lokar.Alma', autospec=True, spec_set=True)
def testRemoveTerm(self, MockAlma, mock_sru, mock_authorize_term):
def testRemoveTerm(self, MockAlma, mock_sru, mock_authorize_term, mock_email):
old_term = 'Statistiske modeller'
mock_sru.side_effect = TestLokar.sru_search_mock
mock_authorize_term.return_value = {'localname': 'c030697'}
Expand Down

0 comments on commit 75c44d7

Please sign in to comment.