1#!/usr/bin/env python3
  2
  3"""Distribute Report widget. Takes an report.html, converts it to a PDF format and distributes to an e-mail address 
  4and or an ftp location. 
  5"""
  6
  7import os
  8import ftplib
  9
 10import logging
 11import shlex, subprocess
 12from collections import OrderedDict
 13
 14from chart.project import settings
 15import chart.alg.settings
 16
 17from chart.common.util import nvl
 18from chart.cmd.report import convert_dir_to_pdf
 19from chart.common import sendmail
 20from chart.reports.widget import Widget
 21
 22
 23def pdf_upload_ftp(report_name, ftp_to):
 24    """Upload report to ftp destination."""
 25
 26    # name of file to ftp
 27    report = report_name + '.pdf'
 28
 29    # send to individual ftp locations
 30    for rec in ftp_to:
 31        ftp_params = settings.FTP_RECIPIENT[rec['ftpname']]
 32
 33        server = ftp_params['location']
 34        username = ftp_params['username']
 35<<<hidden due to potential security issue>>>
 36        destination_dir =  ftp_params['destination_dir']
 37
 38<<<hidden due to potential security issue>>>
 39
 40        # changing to destination directory
 41        myFTP.cwd(destination_dir)
 42
 43        # send the file
 44        if os.path.isfile(report):
 45            fh = open(report, 'rb')
 46            myFTP.storbinary('STOR ' + str(report), fh)
 47            fh.close()
 48
 49        else:
 50            logging.warning("Source Report File {f}, does not exist".format(f=report))
 51
 52
 53def pdf_sendmail(report_name, email_to, start_time):
 54    """Send the report to an email destination, as an attachment."""
 55
 56    # name of file to attach
 57    attachment = report_name + '.pdf'
 58
 59    # email individual digests
 60    for rec in email_to:
 61        name = '{first} {last}'.format(first=nvl(rec['forename']),
 62                                       last=nvl(rec['surname']))
 63        email = rec['forename'] + '.' +  rec['surname'] + '@eumetsat.int'
 64
 65        sendmail.sendmail_pdf_attachment(
 66                from_address=(settings.EMAIL_NAME.format('digest'),
 67                              settings.EMAIL_ADDRESS.format('digest')),
 68                to_addresses=((name, email),),
 69                subject='{r} Report attached for {d}'.format(r=report_name, d=start_time.date()),
 70                report_name=report_name,
 71                attachment=attachment)
 72
 73
 74class distribute_report(Widget):
 75    """Create a PDF Report to disseminate."""
 76
 77    name = 'distribute-report'
 78
 79    thumbnail = "pdf_sendmail.png"
 80
 81    options = OrderedDict([    ('name', {'type': 'string', 'optional': True}),
 82                            ('html', {'type': 'string', 'optional': True}),
 83                            ('email-recipient', {'description': 'Receivers of email',
 84                                                'multiple': True,
 85                                                'type': OrderedDict([('forename', {'type': 'string'}),
 86                                                                     ('surname', {'type': 'string'}),
 87                                                                    ])}), 
 88                            ('ftp-recipient', {'description': 'ftp details to send report',
 89                                                'multiple': True,
 90                                                'type': OrderedDict([('ftpname', {'type': 'string'}),
 91                                                                    ])}) 
 92                          ])
 93
 94
 95    def __str__(self):
 96        return 'distribute_reportWidget {' + self.config.get('name', '') + '}'
 97
 98
 99    def __init__(self):
100        super(distribute_report, self).__init__()
101
102
103    def html(self, document):
104        """Render ourselves."""
105
106        # This widget does not update the report at all, only creates a pdf report from the current report
107
108        c = self.config
109
110        dc = document.config
111        start_time = dc['sensing_start']
112
113        # allow substitutions such as {scid} and {gs}
114        replacements = {'sid': dc['sid'], 'env': settings.INGEST_GS_ENV}
115        report_name = c['name'].format(**replacements).format(document=dc)
116
117        if 'html' in c:
118            # use the name supplied as basis of report to be converted
119            tmp_filename = c['html'] + '.html'
120
121        else:
122            # copy current report into temp report, and add html tail
123            tmp_filename = 'pdf_' + str(chart.alg.settings.REPORT_FILENAME)
124
125        # write current contents of document.html to temp file
126        with open(tmp_filename, 'w') as handle:
127            for h in document.htmls:
128                if isinstance(h, str):
129                    handle.write(h)
130
131                else:
132                    handle.write(h.getvalue())
133
134
135        # use this command to covert to pdf format
136        cmd = [os.path.expanduser(i) for i in settings.PDF_CONVERTER_COMMAND]
137        command = cmd + [
138               tmp_filename,
139               str(report_name)+ '.pdf']
140
141        logging.debug('Converting using {cmd}'.format(cmd=' '.join(command)))
142
143        child = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
144        out, err = child.communicate()
145        if child.returncode != 0:
146            logging.warning('PDF converter returned a error code {code}. Command was: {cmd}'.format(
147                code=child.returncode, cmd=' '.join(command)))
148            logging.debug('current dir is ' + os.getcwd())
149            logging.debug('stdout was {out}'.format(out=out))
150            logging.debug('stderr was {err}'.format(err=err))
151
152
153        # now distribute the pdf report
154        if 'email-recipient' in c:
155            # send resulting pdf file as email
156            pdf_sendmail(report_name, c['email-recipient'], start_time)
157
158        if 'ftp-recipient' in c:
159            # send resulting pdf file to ftp recipient
160            pdf_upload_ftp(report_name, c['ftp-recipient'])
161
162
163        # include pdf into final report archive
164        document.aux_files.append(report_name + '.pdf')