Example #1
0
 def handle(self, message):
     if handle_dongle_sms(message):
                 return True
     DHIS2_MESSAGE_PREFIXES = getattr(settings, 'DHIS2_MESSAGE_PREFIXES', ['mcd', 'pmtct'])
     if filter(message.text.strip().lower().startswith, DHIS2_MESSAGE_PREFIXES + [''])[0]:
         url = getattr(settings, 'DHIS2_SMSINPUT_URL', 'http://localhost:9090/dhis2_smsinput?')
         if url.find('?') < 0:
             c = '?'
         else:
             c = ''
         url = url + c + 'message=%s&sender=%s' % (message.text, message.connection.identity)
         try:
             urlopen(url)
         except:
             pass
         return True
     if message.connection.backend.name == getattr(settings, 'HOTLINE_BACKEND', 'console'):
         # anonymous_report = AnonymousReport.objects.create(connection=message.connection, message=message.db_message)
         # anonymous_report.save()
         # if anonymous report gets in and its time stamp is within the limit of 1hr
         # add this report to an existing AnonymousReportBatch object
         end_epoch = datetime.datetime.now()
         epoch = end_epoch - datetime.timedelta(seconds=3600 * 24 * 3)
         if AnonymousReport.objects.filter(date__gte=epoch, connection__in=Connection.objects.filter(id=message.connection.id)).exists():
             try:
                 anonymous_report = AnonymousReport.objects.filter(date__gte=epoch, connection__in=Connection.objects.filter(id=message.connection.id))[0]
                 anonymous_report.messages.add(message.db_message)
                 anonymous_report.save()
                 Message.objects.create(direction="O",
                     text="Thank you for your consistent feedback about this health facility.",
                     status='Q',
                     connection=message.connection,
                     in_response_to=message.db_message)
                 return True
             except IndexError:
                 pass
         else:
             anonymous_report = AnonymousReport.objects.create(connection=message.connection)
             anonymous_report.messages.add(message.db_message)
             anonymous_report.save()
             Message.objects.create(direction="O",
                 text="Thank you for your report, this report will be sent to relevant authorities. If this is an emergency, contact your nearest facility",
                 status='Q',
                 connection=message.connection,
                 in_response_to=message.db_message)
             return True
Example #2
0
    def handle (self, message):
        if handle_dongle_sms(message):
            return True

        if message.text.strip().lower() in [i.lower() for i in getattr(settings, 'OPT_OUT_WORDS', ['quit'])]:

            if Blacklist.objects.filter(connection=message.connection).exists():
                message.respond('You cannot send Quit to 6200 (EduTrac) more than once.')
                return True
            else:
                if ScriptProgress.objects.filter(connection=message.connection, script__slug='edtrac_autoreg').exists():
                    # user is attempting to quit before completing registration
                    message.respond('Your registration is not complete. You cannot quit at this point.')
                    return True

                Blacklist.objects.create(connection=message.connection)
                ScriptProgress.objects.filter(connection=message.connection).delete() # delete all script progress since the user has quit
                ScriptSession.objects.filter(connection=message.connection, end_time=None).delete() # the non closed out sessions need to be expunged as well
                if (message.connection.contact):
                    message.connection.contact.active = False
                    message.connection.contact.save()
                message.respond(getattr(settings, 'OPT_OUT_CONFIRMATION', 'Thank you for your contribution to EduTrac. To rejoin the system, send join to 6200'))
                return True

        elif message.text.strip().lower() in [i.lower() for i in getattr(settings, 'OPT_IN_WORDS', ['join'])]:

            if not message.connection.contact:
                if ScriptProgress.objects.filter(script__slug='edtrac_autoreg', connection=message.connection).count() == 0:
                    ScriptProgress.objects.create(script=Script.objects.get(slug="edtrac_autoreg"),\
                        connection=message.connection)
                else:
                    message.respond("Your registration is not complete yet, you do not need to 'Join' again.")
            elif Blacklist.objects.filter(connection=message.connection).exists():
                Blacklist.objects.filter(connection=message.connection).delete()
                if not ScriptProgress.objects.filter(script__slug='edtrac_autoreg', connection=message.connection).count():
                    ScriptProgress.objects.create(script=Script.objects.get(slug="edtrac_autoreg"),\
                        connection=message.connection)
            else:
                message.respond("You are already in the system and do not need to 'Join' again.")
            return True

        elif Blacklist.objects.filter(connection=message.connection).count():
            return True
            # when all else fails, quit!

        else:
            try:
                progress = ScriptProgress.objects.filter(connection=message.connection, time__lte=datetime.datetime.now()).order_by('-time')
                response_message_string = {"n":"The answer you have provided is not in the correct format. Use figures like 3 to answer the question",
                                 "t":"The answer you have provided is not in the correct format. Please follow instructions that were given to you"}
                if progress.count():
                    progress = progress[0]
                    script_last_step = ScriptStep.objects.filter(script=progress.script).order_by('-order')[0]
                    if progress.step and progress.step.order == script_last_step.order and progress.status == 'C':
                        return False
                    else:
                        response = incoming_progress(message)
                        if not progress.script.slug == 'edtrac_autoreg':
                            r = Response.objects.filter(contact__connection=message.connection,date__lte=datetime.datetime.now(),message__text=message.text).latest('date')
                            if r is not None:
                                if r.has_errors:
                                    progress.status = ScriptProgress.PENDING
                                    progress.save()
                                    Message.mass_text(response_message_string[r.poll.type], [message.connection])
                                    Message.mass_text(r.poll.question , [message.connection])
                        if response:
                            message.respond(gettext_db(response,progress.language))
                        return True
            except ScriptProgress.DoesNotExist:
                logger.debug("\nScript Progress object not found for message %s with connection %s" % (message,message.connection))
        return False
Example #3
0
    def handle (self, message):
        if handle_dongle_sms(message):
            return True

        if message.text.strip().lower() in [i.lower() for i in getattr(settings, 'OPT_OUT_WORDS', ['quit'])]:

            if Blacklist.objects.filter(connection=message.connection).exists():
                message.respond('You cannot send Quit to 6200 (EduTrac) more than once.')
                return True
            else:
                if ScriptProgress.objects.filter(connection=message.connection, script__slug='edtrac_autoreg').exists():
                    # user is attempting to quit before completing registration
                    message.respond('Your registration is not complete, you can not quit at this point')
                    return True

                Blacklist.objects.create(connection=message.connection)
                ScriptProgress.objects.filter(connection=message.connection).delete() # delete all script progress since the user has quit
                ScriptSession.objects.filter(connection=message.connection, end_time=None).delete() # the non closed out sessions need to be expunged as well
                if (message.connection.contact):
                    message.connection.contact.active = False
                    message.connection.contact.save()
                message.respond(getattr(settings, 'OPT_OUT_CONFIRMATION', 'Thank you for your contribution to EduTrac. To rejoin the system, send join to 6200'))
                return True

        elif message.text.strip().lower() in [i.lower() for i in getattr(settings, 'OPT_IN_WORDS', ['join'])]:

            if not message.connection.contact:
                if ScriptProgress.objects.filter(script__slug='edtrac_autoreg', connection=message.connection).count() == 0:
                    ScriptProgress.objects.create(script=Script.objects.get(slug="edtrac_autoreg"),\
                        connection=message.connection)
                else:
                    message.respond("Your registration is not complete yet, you do not need to 'Join' again.")
            elif Blacklist.objects.filter(connection=message.connection).exists():
                Blacklist.objects.filter(connection=message.connection).delete()
                if not ScriptProgress.objects.filter(script__slug='edtrac_autoreg', connection=message.connection).count():
                    ScriptProgress.objects.create(script=Script.objects.get(slug="edtrac_autoreg"),\
                        connection=message.connection)
            else:
                message.respond("You are already in the system and do not need to 'Join' again.")
            return True

        elif Blacklist.objects.filter(connection=message.connection).count():
            return True
            # when all else fails, quit!

        else:
            try:
                progress = ScriptProgress.objects.filter(connection=message.connection, time__lte=datetime.datetime.now()).order_by('-time')
                response_message_string = {"n":"The answer you have provided is not in the correct format. Use figures like 3 to answer the question",
                                 "t":"The answer you have provided is not in the correct format. Please follow instructions that were given to you"}
                if progress.count():
                    progress = progress[0]
                    script_last_step = ScriptStep.objects.filter(script=progress.script).order_by('-order')[0]
                    if progress.step and progress.step.order == script_last_step.order and progress.status == 'C':
                        return False
                    else:
                        response = incoming_progress(message)
                        if not progress.script.slug == 'edtrac_autoreg':
                            r = Response.objects.filter(contact__connection=message.connection,date__lte=datetime.datetime.now(),message__text=message.text).latest('date')
                            if r is not None:
                                if r.has_errors:
                                    progress.status = ScriptProgress.PENDING
                                    progress.save()
                                    Message.mass_text(response_message_string[r.poll.type], [message.connection])
                                    Message.mass_text(r.poll.question , [message.connection])
                        if response:
                            message.respond(gettext_db(response,progress.language))
                        return True
            except ScriptProgress.DoesNotExist:
                logger.debug("\nScript Progress object not found for message %s with connection %s" % (message,message.connection))
        return False
Example #4
0
    def handle(self, message):
        if handle_dongle_sms(message):
                    return True
        DHIS2_MESSAGE_PREFIXES = getattr(settings, 'DHIS2_MESSAGE_PREFIXES', ['mcd', 'pmtct'])
        if filter(message.text.strip().lower().startswith, DHIS2_MESSAGE_PREFIXES + [''])[0]:
            keyword = re.split('\W+', message.text.strip().lower())[0]
            keywordServerMappings = getattr(settings, 'KEYWORD_SERVER_MAPPINGS', {})

            if getattr(settings, 'USE_DISPATCHER', False):
                if keyword in getattr(settings, 'DISPATCHER_KEYWORDS', []):
                    url = getattr(settings, 'DHIS2_SMSINPUT_URL', 'http://localhost:9090/dhis2_smsinput?')
                    if url.find('?') < 0:
                        c = '?'
                    else:
                        c = ''
                    url = url + c + 'message=%s&originator=%s' % (quote_plus(message.text), message.connection.identity)
                    try:
                        urlopen(url)
                    except:
                        pass
                    return True

            # XXX please note that source and destination must be configured in dispatcher2
            destinationSever = keywordServerMappings.get(keyword, '')
            if destinationSever:
                # this time we're to queue requests in dispatcher2 with a POST request like so;
                # http://localhost:9191/queue?source=mtrack&destination=y&raw_msg=msg&is_qparam=t&
                msg_date = message.date.date()
                year, week = self.get_reporting_week(msg_date)
                queueEndpoint = getattr(
                    settings, 'DISPATCHER2_QUEUE_ENDPOINT', 'http://localhost:9191/queue?')
                payload = 'message=%s&originator=%s' % (quote_plus(message.text), message.connection.identity)
                params = {
                    'source': 'mtrack', 'destination': destinationSever,
                    'raw_msg': message.text, 'msisdn': message.connection.identity,
                    'ctype': 'text', 'is_qparams': 't',
                    'year': year, 'week': week,
                    'username': getattr(settings, 'DISPATCHER2_USERNAME', ''),
                    'password': getattr(settings, 'DISPATCHER2_PASSWORD', '')}
                try:
                    requests.post(
                        queueEndpoint, data=payload, params=params, headers={
                            'Content-type': 'text/plain'})
                except:
                    pass
                return True

        if message.connection.backend.name == getattr(settings, 'HOTLINE_BACKEND', 'console'):
            # anonymous_report = AnonymousReport.objects.create(connection=message.connection, message=message.db_message)
            # anonymous_report.save()
            # if anonymous report gets in and its time stamp is within the limit of 1hr
            # add this report to an existing AnonymousReportBatch object
            end_epoch = datetime.datetime.now()
            epoch = end_epoch - datetime.timedelta(seconds=3600 * 24 * 3)
            if AnonymousReport.objects.filter(date__gte=epoch, connection__in=Connection.objects.filter(id=message.connection.id)).exists():
                try:
                    anonymous_report = AnonymousReport.objects.filter(date__gte=epoch, connection__in=Connection.objects.filter(id=message.connection.id))[0]
                    anonymous_report.messages.add(message.db_message)
                    anonymous_report.save()
                    Message.objects.create(
                        direction="O",
                        text="Thank you for your consistent feedback about this health facility.",
                        status='Q',
                        connection=message.connection,
                        in_response_to=message.db_message)
                    return True
                except IndexError:
                    pass
            else:
                anonymous_report = AnonymousReport.objects.create(connection=message.connection)
                anonymous_report.messages.add(message.db_message)
                anonymous_report.save()
                Message.objects.create(
                    direction="O",
                    text=getattr(
                        settings, 'HOTLINE_DEFAULT_RESPONSE',
                        ("Your report has been sent to relevant authorities. You can also call Ministry "
                            "of Health on 0800100066 (toll free) for further help and inquires. "
                            "If this is an emergency contact your nearest facility")),
                    status='Q',
                    connection=message.connection,
                    in_response_to=message.db_message)
                return True