<commit_before>"""
This resource enables you to publish a message using given mediums to subscribers with subscriptions 
to given topics. It is expected to hbe the primary function of meerkat hermes. 
"""

import uuid, boto3, uuid, json
import meerkat_hermes.util as util
from flask_restful import Resource, reqparse
from flask import current_app, Response
from boto3.dynamodb.conditions import Key, Attr
from meerkat_hermes.authentication import require_api_key

#This simple Emailer resource has just one method, which sends a given email message.
class Publish(Resource):

    #Require authentication
    decorators = [require_api_key]

    def __init__(self):
        #Load the database 
        db = boto3.resource('dynamodb')
        self.subscribers = db.Table(current_app.config['SUBSCRIBERS'])
        self.subscriptions = db.Table(current_app.config['SUBSCRIPTIONS'])

    def put(self):
        """
        Publish a method to a given topic set. 
        First parse the given arguments to check it is a valid email.
        !!!Remember that whilst still in AWS "Sandbox" we can only send to verified emails.

        PUT args:

            'id'*         - If another message with the same ID has been logged, this one won't send.
                            Returns a 400 Bad Request error if this is the case.
            'message'*    - The message.
            'topics'*     - The topics the message fits into (determines destination address/es).
                            Accepts array of multiple topics.
            'medium'      - The medium by which to publish the message (email, sms, etc...)
                            Defaults to email. Accepts array of multiple mediums.
            'sms-message' - The sms version of the message. Defaults to the same as 'message'
            'html-message'- The html version of the message. Defaults to the same as 'message'
            'subject'     - The e-mail subject. Defaults to "".
            'from'        - The address from which to send the message. 
                            Deafults to an emro address stored in the config.
    
 
        Returns:
            The amazon SES response.
        """

        #Define an argument parser for creating a valid email message.
        parser = reqparse.RequestParser()
        parser.add_argument('id', required=True, type=str, help='The message Id - must be unique.')
        parser.add_argument('message', required=True, type=str, help='The message to be sent')
        parser.add_argument('topics', required=True, action='append', type=str, 
                            help='The topics to publish to.')
        parser.add_argument('medium', required=False, action='append', type=str, 
                            help='The mediums by which to send the message.')
        parser.add_argument('html-message', required=False, type=str, 
                            help='If applicable, the message in html')
        parser.add_argument('sms-message', required=False, type=str, 
                            help='If applicable, the seperate sms message')
        parser.add_argument('subject', required=False, type=str, help='The email subject')
        parser.add_argument('from', required=False, type=str, 
                            help='The address from which to send the message')
        args = parser.parse_args()
        
        current_app.logger.warning( "Before defaults set: " + args['medium'] )

        #Check that the message hasn't already been sent.
        if util.id_valid( args['id'] ):

            #Set the default values for the non-required fields.
            if not args['medium']: 
                args['medium'] = ['email']
            if not args['html-message']:
                args['html-message'] = args['message']
            if not args['sms-message']:
                args['sms-message'] = args['message']
            if not args['from']: 
                args['from'] = current_app.config['SENDER']
    
            current_app.logger.warning( "After: " + args['medium'] )

            #Collect the subscriber IDs for all subscriptions to the given topics.
            subscribers = []
           
            for topic in args['topics']:
                query_response = self.subscriptions.query(
                    IndexName='topicID-index',
                    KeyConditionExpression=Key('topicID').eq(topic)
                )
                for item in query_response['Items']:
                    subscribers.append( item['subscriberID'] )
            
            #Record details about the sent messages.
            responses = []<commit_msg>Debugging publish resource<commit_after>"""
This resource enables you to publish a message using given mediums to subscribers with subscriptions 
to given topics. It is expected to hbe the primary function of meerkat hermes. 
"""

import uuid, boto3, uuid, json
import meerkat_hermes.util as util
from flask_restful import Resource, reqparse
from flask import current_app, Response
from boto3.dynamodb.conditions import Key, Attr
from meerkat_hermes.authentication import require_api_key

#This simple Emailer resource has just one method, which sends a given email message.
class Publish(Resource):

    #Require authentication
    decorators = [require_api_key]

    def __init__(self):
        #Load the database 
        db = boto3.resource('dynamodb')
        self.subscribers = db.Table(current_app.config['SUBSCRIBERS'])
        self.subscriptions = db.Table(current_app.config['SUBSCRIPTIONS'])

    def put(self):
        """
        Publish a method to a given topic set. 
        First parse the given arguments to check it is a valid email.
        !!!Remember that whilst still in AWS "Sandbox" we can only send to verified emails.

        PUT args:

            'id'*         - If another message with the same ID has been logged, this one won't send.
                            Returns a 400 Bad Request error if this is the case.
            'message'*    - The message.
            'topics'*     - The topics the message fits into (determines destination address/es).
                            Accepts array of multiple topics.
            'medium'      - The medium by which to publish the message (email, sms, etc...)
                            Defaults to email. Accepts array of multiple mediums.
            'sms-message' - The sms version of the message. Defaults to the same as 'message'
            'html-message'- The html version of the message. Defaults to the same as 'message'
            'subject'     - The e-mail subject. Defaults to "".
            'from'        - The address from which to send the message. 
                            Deafults to an emro address stored in the config.
    
 
        Returns:
            The amazon SES response.
        """

        #Define an argument parser for creating a valid email message.
        parser = reqparse.RequestParser()
        parser.add_argument('id', required=True, type=str, help='The message Id - must be unique.')
        parser.add_argument('message', required=True, type=str, help='The message to be sent')
        parser.add_argument('topics', required=True, action='append', type=str, 
                            help='The topics to publish to.')
        parser.add_argument('medium', required=False, action='append', type=str, 
                            help='The mediums by which to send the message.')
        parser.add_argument('html-message', required=False, type=str, 
                            help='If applicable, the message in html')
        parser.add_argument('sms-message', required=False, type=str, 
                            help='If applicable, the seperate sms message')
        parser.add_argument('subject', required=False, type=str, help='The email subject')
        parser.add_argument('from', required=False, type=str, 
                            help='The address from which to send the message')
        args = parser.parse_args()
        
        current_app.logger.warning( "Before defaults set: " + str(args['medium']) )

        #Check that the message hasn't already been sent.
        if util.id_valid( args['id'] ):

            #Set the default values for the non-required fields.
            if not args['medium']: 
                args['medium'] = ['email']
            if not args['html-message']:
                args['html-message'] = args['message']
            if not args['sms-message']:
                args['sms-message'] = args['message']
            if not args['from']: 
                args['from'] = current_app.config['SENDER']
    
            current_app.logger.warning( "After: " + str(args['medium']) )

            #Collect the subscriber IDs for all subscriptions to the given topics.
            subscribers = []
           
            for topic in args['topics']:
                query_response = self.subscriptions.query(
                    IndexName='topicID-index',
                    KeyConditionExpression=Key('topicID').eq(topic)
                )
                for item in query_response['Items']:
                    subscribers.append( item['subscriberID'] )
            
            #Record details about the sent messages.
            responses = []
{'fraction_non_alphanumeric': 0.09042725797728501, 'fraction_numerical': 0.0012979989183342347, 'mean_word_length': 2.0565289256198347, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '955728', 'n_tokens_mistral': 2386, 'n_tokens_neox': 2291, 'n_words': 828}